From 41afa951293381a9ac21504018326607ac5413e3 Mon Sep 17 00:00:00 2001 From: Chris Makler Date: Wed, 24 Jul 2024 10:53:54 -0400 Subject: [PATCH] updating code to make it work with local url --- _config.yml | 3 +- _layouts/default.html | 27 +- static/css/kg-tufte.0.3.2.css | 178 + static/css/kg-tufte.css | 5 + static/css/kg.0.3.2.css | 176 + static/js/kg.0.3.2.js | 71401 +++++++++++++++++++++++++++++++ static/js/kg3d.0.3.2.js | 71435 ++++++++++++++++++++++++++++++++ 7 files changed, 143213 insertions(+), 12 deletions(-) create mode 100644 static/css/kg-tufte.0.3.2.css create mode 100644 static/css/kg-tufte.css create mode 100644 static/css/kg.0.3.2.css create mode 100644 static/js/kg.0.3.2.js create mode 100644 static/js/kg3d.0.3.2.js diff --git a/_config.yml b/_config.yml index 85d887b..a6fd81e 100644 --- a/_config.yml +++ b/_config.yml @@ -18,12 +18,13 @@ email: cmakler@stanford.edu description: >- # this means to ignore newlines until "baseurl:" A template repository for creating standalone KineticGraphs repository: "graph-template" # the name of your repository -baseurl: "graph-template" # the subpath of your site, e.g. /blog +baseurl: "/graph-template" # the subpath of your site, e.g. /blog url: "" # the base hostname & protocol for your site, e.g. http://example.com github_username: cmakler # Build settings markdown: kramdown +theme: minima plugins: - jekyll-feed diff --git a/_layouts/default.html b/_layouts/default.html index fd9a97d..cc2ab61 100644 --- a/_layouts/default.html +++ b/_layouts/default.html @@ -5,36 +5,41 @@ Graph -
+
(loading. please wait)
- + \ No newline at end of file diff --git a/static/css/kg-tufte.0.3.2.css b/static/css/kg-tufte.0.3.2.css new file mode 100644 index 0000000..0fca852 --- /dev/null +++ b/static/css/kg-tufte.0.3.2.css @@ -0,0 +1,178 @@ +@font-face{font-family:KaTeX_AMS;src:url(fonts/KaTeX_AMS-Regular.woff2) format("woff2"),url(fonts/KaTeX_AMS-Regular.woff) format("woff"),url(fonts/KaTeX_AMS-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Caligraphic;src:url(fonts/KaTeX_Caligraphic-Bold.woff2) format("woff2"),url(fonts/KaTeX_Caligraphic-Bold.woff) format("woff"),url(fonts/KaTeX_Caligraphic-Bold.ttf) format("truetype");font-weight:700;font-style:normal}@font-face{font-family:KaTeX_Caligraphic;src:url(fonts/KaTeX_Caligraphic-Regular.woff2) format("woff2"),url(fonts/KaTeX_Caligraphic-Regular.woff) format("woff"),url(fonts/KaTeX_Caligraphic-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Fraktur;src:url(fonts/KaTeX_Fraktur-Bold.woff2) format("woff2"),url(fonts/KaTeX_Fraktur-Bold.woff) format("woff"),url(fonts/KaTeX_Fraktur-Bold.ttf) format("truetype");font-weight:700;font-style:normal}@font-face{font-family:KaTeX_Fraktur;src:url(fonts/KaTeX_Fraktur-Regular.woff2) format("woff2"),url(fonts/KaTeX_Fraktur-Regular.woff) format("woff"),url(fonts/KaTeX_Fraktur-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-Bold.woff2) format("woff2"),url(fonts/KaTeX_Main-Bold.woff) format("woff"),url(fonts/KaTeX_Main-Bold.ttf) format("truetype");font-weight:700;font-style:normal}@font-face{font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-BoldItalic.woff2) format("woff2"),url(fonts/KaTeX_Main-BoldItalic.woff) format("woff"),url(fonts/KaTeX_Main-BoldItalic.ttf) format("truetype");font-weight:700;font-style:italic}@font-face{font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-Italic.woff2) format("woff2"),url(fonts/KaTeX_Main-Italic.woff) format("woff"),url(fonts/KaTeX_Main-Italic.ttf) format("truetype");font-weight:400;font-style:italic}@font-face{font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-Regular.woff2) format("woff2"),url(fonts/KaTeX_Main-Regular.woff) format("woff"),url(fonts/KaTeX_Main-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Math;src:url(fonts/KaTeX_Math-BoldItalic.woff2) format("woff2"),url(fonts/KaTeX_Math-BoldItalic.woff) format("woff"),url(fonts/KaTeX_Math-BoldItalic.ttf) format("truetype");font-weight:700;font-style:italic}@font-face{font-family:KaTeX_Math;src:url(fonts/KaTeX_Math-Italic.woff2) format("woff2"),url(fonts/KaTeX_Math-Italic.woff) format("woff"),url(fonts/KaTeX_Math-Italic.ttf) format("truetype");font-weight:400;font-style:italic}@font-face{font-family:"KaTeX_SansSerif";src:url(fonts/KaTeX_SansSerif-Bold.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Bold.woff) format("woff"),url(fonts/KaTeX_SansSerif-Bold.ttf) format("truetype");font-weight:700;font-style:normal}@font-face{font-family:"KaTeX_SansSerif";src:url(fonts/KaTeX_SansSerif-Italic.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Italic.woff) format("woff"),url(fonts/KaTeX_SansSerif-Italic.ttf) format("truetype");font-weight:400;font-style:italic}@font-face{font-family:"KaTeX_SansSerif";src:url(fonts/KaTeX_SansSerif-Regular.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Regular.woff) format("woff"),url(fonts/KaTeX_SansSerif-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Script;src:url(fonts/KaTeX_Script-Regular.woff2) format("woff2"),url(fonts/KaTeX_Script-Regular.woff) format("woff"),url(fonts/KaTeX_Script-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Size1;src:url(fonts/KaTeX_Size1-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size1-Regular.woff) format("woff"),url(fonts/KaTeX_Size1-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Size2;src:url(fonts/KaTeX_Size2-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size2-Regular.woff) format("woff"),url(fonts/KaTeX_Size2-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Size3;src:url(fonts/KaTeX_Size3-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size3-Regular.woff) format("woff"),url(fonts/KaTeX_Size3-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Size4;src:url(fonts/KaTeX_Size4-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size4-Regular.woff) format("woff"),url(fonts/KaTeX_Size4-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Typewriter;src:url(fonts/KaTeX_Typewriter-Regular.woff2) format("woff2"),url(fonts/KaTeX_Typewriter-Regular.woff) format("woff"),url(fonts/KaTeX_Typewriter-Regular.ttf) format("truetype");font-weight:400;font-style:normal}.katex{font:normal 1.21em KaTeX_Main,Times New Roman,serif;line-height:1.2;text-indent:0;text-rendering:auto}.katex *{-ms-high-contrast-adjust:none!important}.katex .katex-version:after{content:"0.11.0"}.katex .katex-mathml{position:absolute;clip:rect(1px,1px,1px,1px);padding:0;border:0;height:1px;width:1px;overflow:hidden}.katex .katex-html>.newline{display:block}.katex .base{position:relative;white-space:nowrap;width:min-content}.katex .base,.katex .strut{display:inline-block}.katex .textbf{font-weight:700}.katex .textit{font-style:italic}.katex .textrm{font-family:KaTeX_Main}.katex .textsf{font-family:KaTeX_SansSerif}.katex .texttt{font-family:KaTeX_Typewriter}.katex .mathdefault{font-family:KaTeX_Math;font-style:italic}.katex .mathit{font-family:KaTeX_Main;font-style:italic}.katex .mathrm{font-style:normal}.katex .mathbf{font-family:KaTeX_Main;font-weight:700}.katex .boldsymbol{font-family:KaTeX_Math;font-weight:700;font-style:italic}.katex .amsrm,.katex .mathbb,.katex .textbb{font-family:KaTeX_AMS}.katex .mathcal{font-family:KaTeX_Caligraphic}.katex .mathfrak,.katex .textfrak{font-family:KaTeX_Fraktur}.katex .mathtt{font-family:KaTeX_Typewriter}.katex .mathscr,.katex .textscr{font-family:KaTeX_Script}.katex .mathsf,.katex .textsf{font-family:KaTeX_SansSerif}.katex .mathboldsf,.katex .textboldsf{font-family:KaTeX_SansSerif;font-weight:700}.katex .mathitsf,.katex .textitsf{font-family:KaTeX_SansSerif;font-style:italic}.katex .mainrm{font-family:KaTeX_Main;font-style:normal}.katex .vlist-t{display:inline-table;table-layout:fixed}.katex .vlist-r{display:table-row}.katex .vlist{display:table-cell;vertical-align:bottom;position:relative}.katex .vlist>span{display:block;height:0;position:relative}.katex .vlist>span>span{display:inline-block}.katex .vlist>span>.pstrut{overflow:hidden;width:0}.katex .vlist-t2{margin-right:-2px}.katex .vlist-s{display:table-cell;vertical-align:bottom;font-size:1px;width:2px;min-width:2px}.katex .msupsub{text-align:left}.katex .mfrac>span>span{text-align:center}.katex .mfrac .frac-line{display:inline-block;width:100%;border-bottom-style:solid}.katex .hdashline,.katex .hline,.katex .mfrac .frac-line,.katex .overline .overline-line,.katex .rule,.katex .underline .underline-line{min-height:1px}.katex .mspace{display:inline-block}.katex .clap,.katex .llap,.katex .rlap{width:0;position:relative}.katex .clap>.inner,.katex .llap>.inner,.katex .rlap>.inner{position:absolute}.katex .clap>.fix,.katex .llap>.fix,.katex .rlap>.fix{display:inline-block}.katex .llap>.inner{right:0}.katex .clap>.inner,.katex .rlap>.inner{left:0}.katex .clap>.inner>span{margin-left:-50%;margin-right:50%}.katex .rule{display:inline-block;border:0 solid;position:relative}.katex .hline,.katex .overline .overline-line,.katex .underline .underline-line{display:inline-block;width:100%;border-bottom-style:solid}.katex .hdashline{display:inline-block;width:100%;border-bottom-style:dashed}.katex .sqrt>.root{margin-left:.27777778em;margin-right:-.55555556em}.katex .fontsize-ensurer.reset-size1.size1,.katex .sizing.reset-size1.size1{font-size:1em}.katex .fontsize-ensurer.reset-size1.size2,.katex .sizing.reset-size1.size2{font-size:1.2em}.katex .fontsize-ensurer.reset-size1.size3,.katex .sizing.reset-size1.size3{font-size:1.4em}.katex .fontsize-ensurer.reset-size1.size4,.katex .sizing.reset-size1.size4{font-size:1.6em}.katex .fontsize-ensurer.reset-size1.size5,.katex .sizing.reset-size1.size5{font-size:1.8em}.katex .fontsize-ensurer.reset-size1.size6,.katex .sizing.reset-size1.size6{font-size:2em}.katex .fontsize-ensurer.reset-size1.size7,.katex .sizing.reset-size1.size7{font-size:2.4em}.katex .fontsize-ensurer.reset-size1.size8,.katex .sizing.reset-size1.size8{font-size:2.88em}.katex .fontsize-ensurer.reset-size1.size9,.katex .sizing.reset-size1.size9{font-size:3.456em}.katex .fontsize-ensurer.reset-size1.size10,.katex .sizing.reset-size1.size10{font-size:4.148em}.katex .fontsize-ensurer.reset-size1.size11,.katex .sizing.reset-size1.size11{font-size:4.976em}.katex .fontsize-ensurer.reset-size2.size1,.katex .sizing.reset-size2.size1{font-size:.83333333em}.katex .fontsize-ensurer.reset-size2.size2,.katex .sizing.reset-size2.size2{font-size:1em}.katex .fontsize-ensurer.reset-size2.size3,.katex .sizing.reset-size2.size3{font-size:1.16666667em}.katex .fontsize-ensurer.reset-size2.size4,.katex .sizing.reset-size2.size4{font-size:1.33333333em}.katex .fontsize-ensurer.reset-size2.size5,.katex .sizing.reset-size2.size5{font-size:1.5em}.katex .fontsize-ensurer.reset-size2.size6,.katex .sizing.reset-size2.size6{font-size:1.66666667em}.katex .fontsize-ensurer.reset-size2.size7,.katex .sizing.reset-size2.size7{font-size:2em}.katex .fontsize-ensurer.reset-size2.size8,.katex .sizing.reset-size2.size8{font-size:2.4em}.katex .fontsize-ensurer.reset-size2.size9,.katex .sizing.reset-size2.size9{font-size:2.88em}.katex .fontsize-ensurer.reset-size2.size10,.katex .sizing.reset-size2.size10{font-size:3.45666667em}.katex .fontsize-ensurer.reset-size2.size11,.katex .sizing.reset-size2.size11{font-size:4.14666667em}.katex .fontsize-ensurer.reset-size3.size1,.katex .sizing.reset-size3.size1{font-size:.71428571em}.katex .fontsize-ensurer.reset-size3.size2,.katex .sizing.reset-size3.size2{font-size:.85714286em}.katex .fontsize-ensurer.reset-size3.size3,.katex .sizing.reset-size3.size3{font-size:1em}.katex .fontsize-ensurer.reset-size3.size4,.katex .sizing.reset-size3.size4{font-size:1.14285714em}.katex .fontsize-ensurer.reset-size3.size5,.katex .sizing.reset-size3.size5{font-size:1.28571429em}.katex .fontsize-ensurer.reset-size3.size6,.katex .sizing.reset-size3.size6{font-size:1.42857143em}.katex .fontsize-ensurer.reset-size3.size7,.katex .sizing.reset-size3.size7{font-size:1.71428571em}.katex .fontsize-ensurer.reset-size3.size8,.katex .sizing.reset-size3.size8{font-size:2.05714286em}.katex .fontsize-ensurer.reset-size3.size9,.katex .sizing.reset-size3.size9{font-size:2.46857143em}.katex .fontsize-ensurer.reset-size3.size10,.katex .sizing.reset-size3.size10{font-size:2.96285714em}.katex .fontsize-ensurer.reset-size3.size11,.katex .sizing.reset-size3.size11{font-size:3.55428571em}.katex .fontsize-ensurer.reset-size4.size1,.katex .sizing.reset-size4.size1{font-size:.625em}.katex .fontsize-ensurer.reset-size4.size2,.katex .sizing.reset-size4.size2{font-size:.75em}.katex .fontsize-ensurer.reset-size4.size3,.katex .sizing.reset-size4.size3{font-size:.875em}.katex .fontsize-ensurer.reset-size4.size4,.katex .sizing.reset-size4.size4{font-size:1em}.katex .fontsize-ensurer.reset-size4.size5,.katex .sizing.reset-size4.size5{font-size:1.125em}.katex .fontsize-ensurer.reset-size4.size6,.katex .sizing.reset-size4.size6{font-size:1.25em}.katex .fontsize-ensurer.reset-size4.size7,.katex .sizing.reset-size4.size7{font-size:1.5em}.katex .fontsize-ensurer.reset-size4.size8,.katex .sizing.reset-size4.size8{font-size:1.8em}.katex .fontsize-ensurer.reset-size4.size9,.katex .sizing.reset-size4.size9{font-size:2.16em}.katex .fontsize-ensurer.reset-size4.size10,.katex .sizing.reset-size4.size10{font-size:2.5925em}.katex .fontsize-ensurer.reset-size4.size11,.katex .sizing.reset-size4.size11{font-size:3.11em}.katex .fontsize-ensurer.reset-size5.size1,.katex .sizing.reset-size5.size1{font-size:.55555556em}.katex .fontsize-ensurer.reset-size5.size2,.katex .sizing.reset-size5.size2{font-size:.66666667em}.katex .fontsize-ensurer.reset-size5.size3,.katex .sizing.reset-size5.size3{font-size:.77777778em}.katex .fontsize-ensurer.reset-size5.size4,.katex .sizing.reset-size5.size4{font-size:.88888889em}.katex .fontsize-ensurer.reset-size5.size5,.katex .sizing.reset-size5.size5{font-size:1em}.katex .fontsize-ensurer.reset-size5.size6,.katex .sizing.reset-size5.size6{font-size:1.11111111em}.katex .fontsize-ensurer.reset-size5.size7,.katex .sizing.reset-size5.size7{font-size:1.33333333em}.katex .fontsize-ensurer.reset-size5.size8,.katex .sizing.reset-size5.size8{font-size:1.6em}.katex .fontsize-ensurer.reset-size5.size9,.katex .sizing.reset-size5.size9{font-size:1.92em}.katex .fontsize-ensurer.reset-size5.size10,.katex .sizing.reset-size5.size10{font-size:2.30444444em}.katex .fontsize-ensurer.reset-size5.size11,.katex .sizing.reset-size5.size11{font-size:2.76444444em}.katex .fontsize-ensurer.reset-size6.size1,.katex .sizing.reset-size6.size1{font-size:.5em}.katex .fontsize-ensurer.reset-size6.size2,.katex .sizing.reset-size6.size2{font-size:.6em}.katex .fontsize-ensurer.reset-size6.size3,.katex .sizing.reset-size6.size3{font-size:.7em}.katex .fontsize-ensurer.reset-size6.size4,.katex .sizing.reset-size6.size4{font-size:.8em}.katex .fontsize-ensurer.reset-size6.size5,.katex .sizing.reset-size6.size5{font-size:.9em}.katex .fontsize-ensurer.reset-size6.size6,.katex .sizing.reset-size6.size6{font-size:1em}.katex .fontsize-ensurer.reset-size6.size7,.katex .sizing.reset-size6.size7{font-size:1.2em}.katex .fontsize-ensurer.reset-size6.size8,.katex .sizing.reset-size6.size8{font-size:1.44em}.katex .fontsize-ensurer.reset-size6.size9,.katex .sizing.reset-size6.size9{font-size:1.728em}.katex .fontsize-ensurer.reset-size6.size10,.katex .sizing.reset-size6.size10{font-size:2.074em}.katex .fontsize-ensurer.reset-size6.size11,.katex .sizing.reset-size6.size11{font-size:2.488em}.katex .fontsize-ensurer.reset-size7.size1,.katex .sizing.reset-size7.size1{font-size:.41666667em}.katex .fontsize-ensurer.reset-size7.size2,.katex .sizing.reset-size7.size2{font-size:.5em}.katex .fontsize-ensurer.reset-size7.size3,.katex .sizing.reset-size7.size3{font-size:.58333333em}.katex .fontsize-ensurer.reset-size7.size4,.katex .sizing.reset-size7.size4{font-size:.66666667em}.katex .fontsize-ensurer.reset-size7.size5,.katex .sizing.reset-size7.size5{font-size:.75em}.katex .fontsize-ensurer.reset-size7.size6,.katex .sizing.reset-size7.size6{font-size:.83333333em}.katex .fontsize-ensurer.reset-size7.size7,.katex .sizing.reset-size7.size7{font-size:1em}.katex .fontsize-ensurer.reset-size7.size8,.katex .sizing.reset-size7.size8{font-size:1.2em}.katex .fontsize-ensurer.reset-size7.size9,.katex .sizing.reset-size7.size9{font-size:1.44em}.katex .fontsize-ensurer.reset-size7.size10,.katex .sizing.reset-size7.size10{font-size:1.72833333em}.katex .fontsize-ensurer.reset-size7.size11,.katex .sizing.reset-size7.size11{font-size:2.07333333em}.katex .fontsize-ensurer.reset-size8.size1,.katex .sizing.reset-size8.size1{font-size:.34722222em}.katex .fontsize-ensurer.reset-size8.size2,.katex .sizing.reset-size8.size2{font-size:.41666667em}.katex .fontsize-ensurer.reset-size8.size3,.katex .sizing.reset-size8.size3{font-size:.48611111em}.katex .fontsize-ensurer.reset-size8.size4,.katex .sizing.reset-size8.size4{font-size:.55555556em}.katex .fontsize-ensurer.reset-size8.size5,.katex .sizing.reset-size8.size5{font-size:.625em}.katex .fontsize-ensurer.reset-size8.size6,.katex .sizing.reset-size8.size6{font-size:.69444444em}.katex .fontsize-ensurer.reset-size8.size7,.katex .sizing.reset-size8.size7{font-size:.83333333em}.katex .fontsize-ensurer.reset-size8.size8,.katex .sizing.reset-size8.size8{font-size:1em}.katex .fontsize-ensurer.reset-size8.size9,.katex .sizing.reset-size8.size9{font-size:1.2em}.katex .fontsize-ensurer.reset-size8.size10,.katex .sizing.reset-size8.size10{font-size:1.44027778em}.katex .fontsize-ensurer.reset-size8.size11,.katex .sizing.reset-size8.size11{font-size:1.72777778em}.katex .fontsize-ensurer.reset-size9.size1,.katex .sizing.reset-size9.size1{font-size:.28935185em}.katex .fontsize-ensurer.reset-size9.size2,.katex .sizing.reset-size9.size2{font-size:.34722222em}.katex .fontsize-ensurer.reset-size9.size3,.katex .sizing.reset-size9.size3{font-size:.40509259em}.katex .fontsize-ensurer.reset-size9.size4,.katex .sizing.reset-size9.size4{font-size:.46296296em}.katex .fontsize-ensurer.reset-size9.size5,.katex .sizing.reset-size9.size5{font-size:.52083333em}.katex .fontsize-ensurer.reset-size9.size6,.katex .sizing.reset-size9.size6{font-size:.5787037em}.katex .fontsize-ensurer.reset-size9.size7,.katex .sizing.reset-size9.size7{font-size:.69444444em}.katex .fontsize-ensurer.reset-size9.size8,.katex .sizing.reset-size9.size8{font-size:.83333333em}.katex .fontsize-ensurer.reset-size9.size9,.katex .sizing.reset-size9.size9{font-size:1em}.katex .fontsize-ensurer.reset-size9.size10,.katex .sizing.reset-size9.size10{font-size:1.20023148em}.katex .fontsize-ensurer.reset-size9.size11,.katex .sizing.reset-size9.size11{font-size:1.43981481em}.katex .fontsize-ensurer.reset-size10.size1,.katex .sizing.reset-size10.size1{font-size:.24108004em}.katex .fontsize-ensurer.reset-size10.size2,.katex .sizing.reset-size10.size2{font-size:.28929605em}.katex .fontsize-ensurer.reset-size10.size3,.katex .sizing.reset-size10.size3{font-size:.33751205em}.katex .fontsize-ensurer.reset-size10.size4,.katex .sizing.reset-size10.size4{font-size:.38572806em}.katex .fontsize-ensurer.reset-size10.size5,.katex .sizing.reset-size10.size5{font-size:.43394407em}.katex .fontsize-ensurer.reset-size10.size6,.katex .sizing.reset-size10.size6{font-size:.48216008em}.katex .fontsize-ensurer.reset-size10.size7,.katex .sizing.reset-size10.size7{font-size:.57859209em}.katex .fontsize-ensurer.reset-size10.size8,.katex .sizing.reset-size10.size8{font-size:.69431051em}.katex .fontsize-ensurer.reset-size10.size9,.katex .sizing.reset-size10.size9{font-size:.83317261em}.katex .fontsize-ensurer.reset-size10.size10,.katex .sizing.reset-size10.size10{font-size:1em}.katex .fontsize-ensurer.reset-size10.size11,.katex .sizing.reset-size10.size11{font-size:1.19961427em}.katex .fontsize-ensurer.reset-size11.size1,.katex .sizing.reset-size11.size1{font-size:.20096463em}.katex .fontsize-ensurer.reset-size11.size2,.katex .sizing.reset-size11.size2{font-size:.24115756em}.katex .fontsize-ensurer.reset-size11.size3,.katex .sizing.reset-size11.size3{font-size:.28135048em}.katex .fontsize-ensurer.reset-size11.size4,.katex .sizing.reset-size11.size4{font-size:.32154341em}.katex .fontsize-ensurer.reset-size11.size5,.katex .sizing.reset-size11.size5{font-size:.36173633em}.katex .fontsize-ensurer.reset-size11.size6,.katex .sizing.reset-size11.size6{font-size:.40192926em}.katex .fontsize-ensurer.reset-size11.size7,.katex .sizing.reset-size11.size7{font-size:.48231511em}.katex .fontsize-ensurer.reset-size11.size8,.katex .sizing.reset-size11.size8{font-size:.57877814em}.katex .fontsize-ensurer.reset-size11.size9,.katex .sizing.reset-size11.size9{font-size:.69453376em}.katex .fontsize-ensurer.reset-size11.size10,.katex .sizing.reset-size11.size10{font-size:.83360129em}.katex .fontsize-ensurer.reset-size11.size11,.katex .sizing.reset-size11.size11{font-size:1em}.katex .delimsizing.size1{font-family:KaTeX_Size1}.katex .delimsizing.size2{font-family:KaTeX_Size2}.katex .delimsizing.size3{font-family:KaTeX_Size3}.katex .delimsizing.size4{font-family:KaTeX_Size4}.katex .delimsizing.mult .delim-size1>span{font-family:KaTeX_Size1}.katex .delimsizing.mult .delim-size4>span{font-family:KaTeX_Size4}.katex .nulldelimiter{display:inline-block;width:.12em}.katex .delimcenter,.katex .op-symbol{position:relative}.katex .op-symbol.small-op{font-family:KaTeX_Size1}.katex .op-symbol.large-op{font-family:KaTeX_Size2}.katex .op-limits>.vlist-t{text-align:center}.katex .accent>.vlist-t{text-align:center}.katex .accent .accent-body{position:relative}.katex .accent .accent-body:not(.accent-full){width:0}.katex .overlay{display:block}.katex .mtable .vertical-separator{display:inline-block;min-width:1px}.katex .mtable .arraycolsep{display:inline-block}.katex .mtable .col-align-c>.vlist-t{text-align:center}.katex .mtable .col-align-l>.vlist-t{text-align:left}.katex .mtable .col-align-r>.vlist-t{text-align:right}.katex .svg-align{text-align:left}.katex svg{display:block;position:absolute;width:100%;height:inherit;fill:currentColor;stroke:currentColor;fill-rule:nonzero;fill-opacity:1;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1}.katex svg path{stroke:none}.katex img{border-style:none;min-width:0;min-height:0;max-width:none;max-height:none}.katex .stretchy{width:100%;display:block;position:relative;overflow:hidden}.katex .stretchy:after,.katex .stretchy:before{content:""}.katex .hide-tail{width:100%;position:relative;overflow:hidden}.katex .halfarrow-left{position:absolute;left:0;width:50.2%;overflow:hidden}.katex .halfarrow-right{position:absolute;right:0;width:50.2%;overflow:hidden}.katex .brace-left{position:absolute;left:0;width:25.1%;overflow:hidden}.katex .brace-center{position:absolute;left:25%;width:50%;overflow:hidden}.katex .brace-right{position:absolute;right:0;width:25.1%;overflow:hidden}.katex .x-arrow-pad{padding:0 .5em}.katex .mover,.katex .munder,.katex .x-arrow{text-align:center}.katex .boxpad{padding:0 .3em}.katex .fbox,.katex .fcolorbox{box-sizing:border-box;border:.04em solid}.katex .cancel-pad{padding:0 .2em}.katex .cancel-lap{margin-left:-.2em;margin-right:-.2em}.katex .sout{border-bottom-style:solid;border-bottom-width:.08em}.katex-display{display:block;margin:1em 0;text-align:center}.katex-display>.katex{display:block;text-align:center;white-space:nowrap}.katex-display>.katex>.katex-html{display:block;position:relative}.katex-display>.katex>.katex-html>.tag{position:absolute;right:0}.katex-display.leqno>.katex>.katex-html>.tag{left:0;right:auto}.katex-display.fleqn>.katex{text-align:left} + + +@charset "UTF-8";@font-face{font-family:et-book;src:url(et-book/et-book-roman-line-figures/et-book-roman-line-figures.eot);src:url(et-book/et-book-roman-line-figures/et-book-roman-line-figures.eot?#iefix) format("embedded-opentype"),url(et-book/et-book-roman-line-figures/et-book-roman-line-figures.woff) format("woff"),url(et-book/et-book-roman-line-figures/et-book-roman-line-figures.ttf) format("truetype"),url(et-book/et-book-roman-line-figures/et-book-roman-line-figures.svg#etbookromanosf) format("svg");font-weight:400;font-style:normal}@font-face{font-family:et-book;src:url(et-book/et-book-display-italic-old-style-figures/et-book-display-italic-old-style-figures.eot);src:url(et-book/et-book-display-italic-old-style-figures/et-book-display-italic-old-style-figures.eot?#iefix) format("embedded-opentype"),url(et-book/et-book-display-italic-old-style-figures/et-book-display-italic-old-style-figures.woff) format("woff"),url(et-book/et-book-display-italic-old-style-figures/et-book-display-italic-old-style-figures.ttf) format("truetype"),url(et-book/et-book-display-italic-old-style-figures/et-book-display-italic-old-style-figures.svg#etbookromanosf) format("svg");font-weight:400;font-style:italic}@font-face{font-family:et-book;src:url(et-book/et-book-bold-line-figures/et-book-bold-line-figures.eot);src:url(et-book/et-book-bold-line-figures/et-book-bold-line-figures.eot?#iefix) format("embedded-opentype"),url(et-book/et-book-bold-line-figures/et-book-bold-line-figures.woff) format("woff"),url(et-book/et-book-bold-line-figures/et-book-bold-line-figures.ttf) format("truetype"),url(et-book/et-book-bold-line-figures/et-book-bold-line-figures.svg#etbookromanosf) format("svg");font-weight:700;font-style:normal}@font-face{font-family:et-book-roman-old-style;src:url(et-book/et-book-roman-old-style-figures/et-book-roman-old-style-figures.eot);src:url(et-book/et-book-roman-old-style-figures/et-book-roman-old-style-figures.eot?#iefix) format("embedded-opentype"),url(et-book/et-book-roman-old-style-figures/et-book-roman-old-style-figures.woff) format("woff"),url(et-book/et-book-roman-old-style-figures/et-book-roman-old-style-figures.ttf) format("truetype"),url(et-book/et-book-roman-old-style-figures/et-book-roman-old-style-figures.svg#etbookromanosf) format("svg");font-weight:400;font-style:normal}html{font-size:15px}body{width:87.5%;margin-left:auto;margin-right:auto;padding-left:12.5%;font-family:et-book,Palatino,"Palatino Linotype","Palatino LT STD","Book Antiqua",Georgia,serif;background-color:#fffff8;color:#111;max-width:1400px;counter-reset:sidenote-counter}h1{font-weight:400;margin-top:4rem;margin-bottom:1.5rem;font-size:3.2rem;line-height:1}h2{font-style:italic;font-weight:400;margin-top:2.1rem;margin-bottom:1.4rem;font-size:2.2rem;line-height:1}h3{font-style:italic;font-weight:400;font-size:1.7rem;margin-top:2rem;margin-bottom:1.4rem;line-height:1}hr{display:block;height:1px;width:55%;border:0;border-top:1px solid #ccc;margin:1em 0;padding:0}p.subtitle{font-style:italic;margin-top:1rem;margin-bottom:1rem;font-size:1.8rem;display:block;line-height:1}.numeral{font-family:et-book-roman-old-style}.danger{color:red}article{padding:5rem 0}section{padding-top:1rem;padding-bottom:1rem}ol,p,ul{font-size:1.4rem;line-height:2rem}p{margin-top:1.4rem;margin-bottom:1.4rem;padding-right:0;vertical-align:baseline}div.epigraph{margin:5em 0}div.epigraph>blockquote{margin-top:3em;margin-bottom:3em}div.epigraph>blockquote,div.epigraph>blockquote>p{font-style:italic}div.epigraph>blockquote>footer{font-style:normal}div.epigraph>blockquote>footer>cite{font-style:italic}blockquote{font-size:1.4rem}blockquote p{width:55%;margin-right:40px}blockquote footer{width:55%;font-size:1.1rem;text-align:right}section>footer,section>p,section>table{width:55%}section>ol,section>ul{width:50%;-webkit-padding-start:5%}li:not(:first-child){margin-top:.25rem}figure{padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline;max-width:55%;-webkit-margin-start:0;-webkit-margin-end:0;margin:0 0 3em 0}figcaption{float:right;clear:right;margin-top:0;margin-bottom:0;font-size:1.1rem;line-height:1.6;vertical-align:baseline;position:relative;max-width:40%}figure.fullwidth figcaption{margin-right:24%}a:link,a:visited{color:inherit}a:link{text-decoration:none;background:-webkit-linear-gradient(#fffff8,#fffff8),-webkit-linear-gradient(#fffff8,#fffff8),-webkit-linear-gradient(currentColor,currentColor);background:linear-gradient(#fffff8,#fffff8),linear-gradient(#fffff8,#fffff8),linear-gradient(currentColor,currentColor);-webkit-background-size:.05em 1px,.05em 1px,1px 1px;-moz-background-size:.05em 1px,.05em 1px,1px 1px;background-size:.05em 1px,.05em 1px,1px 1px;background-repeat:no-repeat,no-repeat,repeat-x;text-shadow:.03em 0 #fffff8,-.03em 0 #fffff8,0 .03em #fffff8,0 -.03em #fffff8,.06em 0 #fffff8,-.06em 0 #fffff8,.09em 0 #fffff8,-.09em 0 #fffff8,.12em 0 #fffff8,-.12em 0 #fffff8,.15em 0 #fffff8,-.15em 0 #fffff8;background-position:0 93%,100% 93%,0 93%}@media screen and (-webkit-min-device-pixel-ratio:0){a:link{background-position-y:87%,87%,87%}}a:link::selection{text-shadow:.03em 0 #b4d5fe,-.03em 0 #b4d5fe,0 .03em #b4d5fe,0 -.03em #b4d5fe,.06em 0 #b4d5fe,-.06em 0 #b4d5fe,.09em 0 #b4d5fe,-.09em 0 #b4d5fe,.12em 0 #b4d5fe,-.12em 0 #b4d5fe,.15em 0 #b4d5fe,-.15em 0 #b4d5fe;background:#b4d5fe}a:link::-moz-selection{text-shadow:.03em 0 #b4d5fe,-.03em 0 #b4d5fe,0 .03em #b4d5fe,0 -.03em #b4d5fe,.06em 0 #b4d5fe,-.06em 0 #b4d5fe,.09em 0 #b4d5fe,-.09em 0 #b4d5fe,.12em 0 #b4d5fe,-.12em 0 #b4d5fe,.15em 0 #b4d5fe,-.15em 0 #b4d5fe;background:#b4d5fe}img{max-width:100%}.marginnote,.sidenote{float:right;clear:right;margin-right:-60%;width:50%;margin-top:0;margin-bottom:0;font-size:1.1rem;line-height:1.3;vertical-align:baseline;position:relative}.sidenote-number{counter-increment:sidenote-counter}.sidenote-number:after,.sidenote:before{font-family:et-book-roman-old-style;position:relative;vertical-align:baseline}.sidenote-number:after{content:counter(sidenote-counter);font-size:1rem;top:-.5rem;left:.1rem}.sidenote:before{content:counter(sidenote-counter) " ";font-size:1rem;top:-.5rem}blockquote .marginnote,blockquote .sidenote{margin-right:-82%;min-width:59%;text-align:left}div.fullwidth,table.fullwidth{width:100%}div.table-wrapper{overflow-x:auto;font-family:"Trebuchet MS","Gill Sans","Gill Sans MT",sans-serif}.sans{font-family:"Gill Sans","Gill Sans MT",Calibri,sans-serif;letter-spacing:.03em}code{font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace;font-size:1rem;line-height:1.42;-webkit-text-size-adjust:100%}.sans>code{font-size:1.2rem}h1>code,h2>code,h3>code{font-size:.8em}.marginnote>code,.sidenote>code{font-size:1rem}pre.code{font-size:.9rem;width:52.5%;margin-left:2.5%;overflow-x:auto}pre.code.fullwidth{width:90%}.fullwidth{max-width:90%;clear:both}span.newthought{font-variant:small-caps;font-size:1.2em}input.margin-toggle{display:none}label.sidenote-number{display:inline}label.margin-toggle:not(.sidenote-number){display:none}.iframe-wrapper{position:relative;padding-bottom:56.25%;padding-top:25px;height:0}.iframe-wrapper iframe{position:absolute;top:0;left:0;width:100%;height:100%}@media (max-width:760px){body{width:84%;padding-left:8%;padding-right:8%}hr,section>footer,section>p,section>table{width:100%}pre.code{width:97%}section>ol{width:90%}section>ul{width:90%}figure{max-width:90%}figcaption,figure.fullwidth figcaption{margin-right:0;max-width:none}blockquote{margin-left:1.5em;margin-right:0}blockquote footer,blockquote p{width:100%}label.margin-toggle:not(.sidenote-number){display:inline}.marginnote,.sidenote{display:none}.margin-toggle:checked+.marginnote,.margin-toggle:checked+.sidenote{display:block;float:left;left:1rem;clear:both;width:95%;margin:1rem 2.5%;vertical-align:baseline;position:relative}label{cursor:pointer}div.table-wrapper,table{width:85%}img{width:100%}} + +::-webkit-scrollbar { + width: 0px; + background: transparent; /* make scrollbar transparent */ +} + +.documentation { + width: 100%; + padding-left: 20px; + max-width: 1200px; + margin-left: 0px; +} + +.documentation p { + width: 1000px; +} + +div.kg-container text { + cursor: default; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +div.kg-container text::selection { + background: none; +} + +text { + font-size: 10px; +} + +input { + font-family: KaTeX_Main; +} + +.katex { + font-size: 1em; +} + +.watermark { + position: fixed; + bottom: 5px; + right: 5px; + opacity: 0.5; + z-index: 99; + color: lightgray; +} + +.watermark a { + color: lightgray; +} + +.tick text { + fill: gray; +} + +.tick line { + stroke: gray; +} + +.tick { + font-size: 5pt; + color: red; +} + +table.gameMatrix { + border-collapse: collapse; + width: 100%; +} + +table.gameMatrix tr td { + border: 2px solid #999; + padding: 1rem; + text-align: center; + font-size: 14pt; +} + +table.gameMatrix tr td.player1 { + color: #3182bd; +} + +table.gameMatrix tr td.player2 { + color: #d62728; +} + +table.gameMatrix tr td.empty { + border: 0; +} + +table.gameMatrix tr td.player1.payoff { + border-right: 0; +} + +table.gameMatrix tr td.player2.payoff { + border-left: 0; +} + +table.gameMatrix tr td.strategy { + font-weight: bolder; +} + +.kg-container:fullscreen { + background-color: white; +} + +.contents { + position: absolute; + margin-left: 0; + width: 180px; + top: 40px; + left: 0px; + border-right: thin lightgrey dotted; + padding: 20px; +} + +.kgjs-title { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 36px; + position: absolute; + left: 72px; + top: 18px; + letter-spacing: 0px; + font-weight: 500; + margin-block-end: 10px; + color: #666666; +} + + +.contents-category { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 12px; + font-weight: 700; + color: #959595; + text-transform: uppercase; + letter-spacing: 1px; + margin-top: 2em; + margin-bottom: 0.5em; +} + +.contents-category a { + background: none; +} + +.contents p { + margin-left: 10px; + margin-top: 0; + margin-bottom: 0; + line-height: 1; +} + +.contents p a { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 1rem; + padding: 3px; + background: none; + color: rgb(31, 119, 180); +} + +.spacer { + margin-top: 20px; +} + +.subtitle { + padding-top: 20px; + padding-bottom: 10px; + font-size: 12px; + font-weight: 700; + color: #959595; + text-transform: uppercase; + letter-spacing: 1px; +} + diff --git a/static/css/kg-tufte.css b/static/css/kg-tufte.css new file mode 100644 index 0000000..10175cc --- /dev/null +++ b/static/css/kg-tufte.css @@ -0,0 +1,5 @@ +@font-face{font-family:KaTeX_AMS;src:url(fonts/KaTeX_AMS-Regular.woff2) format("woff2"),url(fonts/KaTeX_AMS-Regular.woff) format("woff"),url(fonts/KaTeX_AMS-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Caligraphic;src:url(fonts/KaTeX_Caligraphic-Bold.woff2) format("woff2"),url(fonts/KaTeX_Caligraphic-Bold.woff) format("woff"),url(fonts/KaTeX_Caligraphic-Bold.ttf) format("truetype");font-weight:700;font-style:normal}@font-face{font-family:KaTeX_Caligraphic;src:url(fonts/KaTeX_Caligraphic-Regular.woff2) format("woff2"),url(fonts/KaTeX_Caligraphic-Regular.woff) format("woff"),url(fonts/KaTeX_Caligraphic-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Fraktur;src:url(fonts/KaTeX_Fraktur-Bold.woff2) format("woff2"),url(fonts/KaTeX_Fraktur-Bold.woff) format("woff"),url(fonts/KaTeX_Fraktur-Bold.ttf) format("truetype");font-weight:700;font-style:normal}@font-face{font-family:KaTeX_Fraktur;src:url(fonts/KaTeX_Fraktur-Regular.woff2) format("woff2"),url(fonts/KaTeX_Fraktur-Regular.woff) format("woff"),url(fonts/KaTeX_Fraktur-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-Bold.woff2) format("woff2"),url(fonts/KaTeX_Main-Bold.woff) format("woff"),url(fonts/KaTeX_Main-Bold.ttf) format("truetype");font-weight:700;font-style:normal}@font-face{font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-BoldItalic.woff2) format("woff2"),url(fonts/KaTeX_Main-BoldItalic.woff) format("woff"),url(fonts/KaTeX_Main-BoldItalic.ttf) format("truetype");font-weight:700;font-style:italic}@font-face{font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-Italic.woff2) format("woff2"),url(fonts/KaTeX_Main-Italic.woff) format("woff"),url(fonts/KaTeX_Main-Italic.ttf) format("truetype");font-weight:400;font-style:italic}@font-face{font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-Regular.woff2) format("woff2"),url(fonts/KaTeX_Main-Regular.woff) format("woff"),url(fonts/KaTeX_Main-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Math;src:url(fonts/KaTeX_Math-BoldItalic.woff2) format("woff2"),url(fonts/KaTeX_Math-BoldItalic.woff) format("woff"),url(fonts/KaTeX_Math-BoldItalic.ttf) format("truetype");font-weight:700;font-style:italic}@font-face{font-family:KaTeX_Math;src:url(fonts/KaTeX_Math-Italic.woff2) format("woff2"),url(fonts/KaTeX_Math-Italic.woff) format("woff"),url(fonts/KaTeX_Math-Italic.ttf) format("truetype");font-weight:400;font-style:italic}@font-face{font-family:"KaTeX_SansSerif";src:url(fonts/KaTeX_SansSerif-Bold.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Bold.woff) format("woff"),url(fonts/KaTeX_SansSerif-Bold.ttf) format("truetype");font-weight:700;font-style:normal}@font-face{font-family:"KaTeX_SansSerif";src:url(fonts/KaTeX_SansSerif-Italic.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Italic.woff) format("woff"),url(fonts/KaTeX_SansSerif-Italic.ttf) format("truetype");font-weight:400;font-style:italic}@font-face{font-family:"KaTeX_SansSerif";src:url(fonts/KaTeX_SansSerif-Regular.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Regular.woff) format("woff"),url(fonts/KaTeX_SansSerif-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Script;src:url(fonts/KaTeX_Script-Regular.woff2) format("woff2"),url(fonts/KaTeX_Script-Regular.woff) format("woff"),url(fonts/KaTeX_Script-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Size1;src:url(fonts/KaTeX_Size1-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size1-Regular.woff) format("woff"),url(fonts/KaTeX_Size1-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Size2;src:url(fonts/KaTeX_Size2-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size2-Regular.woff) format("woff"),url(fonts/KaTeX_Size2-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Size3;src:url(fonts/KaTeX_Size3-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size3-Regular.woff) format("woff"),url(fonts/KaTeX_Size3-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Size4;src:url(fonts/KaTeX_Size4-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size4-Regular.woff) format("woff"),url(fonts/KaTeX_Size4-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Typewriter;src:url(fonts/KaTeX_Typewriter-Regular.woff2) format("woff2"),url(fonts/KaTeX_Typewriter-Regular.woff) format("woff"),url(fonts/KaTeX_Typewriter-Regular.ttf) format("truetype");font-weight:400;font-style:normal}.katex{font:normal 1.21em KaTeX_Main,Times New Roman,serif;line-height:1.2;text-indent:0;text-rendering:auto}.katex *{-ms-high-contrast-adjust:none!important}.katex .katex-version:after{content:"0.11.0"}.katex .katex-mathml{position:absolute;clip:rect(1px,1px,1px,1px);padding:0;border:0;height:1px;width:1px;overflow:hidden}.katex .katex-html>.newline{display:block}.katex .base{position:relative;white-space:nowrap;width:min-content}.katex .base,.katex .strut{display:inline-block}.katex .textbf{font-weight:700}.katex .textit{font-style:italic}.katex .textrm{font-family:KaTeX_Main}.katex .textsf{font-family:KaTeX_SansSerif}.katex .texttt{font-family:KaTeX_Typewriter}.katex .mathdefault{font-family:KaTeX_Math;font-style:italic}.katex .mathit{font-family:KaTeX_Main;font-style:italic}.katex .mathrm{font-style:normal}.katex .mathbf{font-family:KaTeX_Main;font-weight:700}.katex .boldsymbol{font-family:KaTeX_Math;font-weight:700;font-style:italic}.katex .amsrm,.katex .mathbb,.katex .textbb{font-family:KaTeX_AMS}.katex .mathcal{font-family:KaTeX_Caligraphic}.katex .mathfrak,.katex .textfrak{font-family:KaTeX_Fraktur}.katex .mathtt{font-family:KaTeX_Typewriter}.katex .mathscr,.katex .textscr{font-family:KaTeX_Script}.katex .mathsf,.katex .textsf{font-family:KaTeX_SansSerif}.katex .mathboldsf,.katex .textboldsf{font-family:KaTeX_SansSerif;font-weight:700}.katex .mathitsf,.katex .textitsf{font-family:KaTeX_SansSerif;font-style:italic}.katex .mainrm{font-family:KaTeX_Main;font-style:normal}.katex .vlist-t{display:inline-table;table-layout:fixed}.katex .vlist-r{display:table-row}.katex .vlist{display:table-cell;vertical-align:bottom;position:relative}.katex .vlist>span{display:block;height:0;position:relative}.katex .vlist>span>span{display:inline-block}.katex .vlist>span>.pstrut{overflow:hidden;width:0}.katex .vlist-t2{margin-right:-2px}.katex .vlist-s{display:table-cell;vertical-align:bottom;font-size:1px;width:2px;min-width:2px}.katex .msupsub{text-align:left}.katex .mfrac>span>span{text-align:center}.katex .mfrac .frac-line{display:inline-block;width:100%;border-bottom-style:solid}.katex .hdashline,.katex .hline,.katex .mfrac .frac-line,.katex .overline .overline-line,.katex .rule,.katex .underline .underline-line{min-height:1px}.katex .mspace{display:inline-block}.katex .clap,.katex .llap,.katex .rlap{width:0;position:relative}.katex .clap>.inner,.katex .llap>.inner,.katex .rlap>.inner{position:absolute}.katex .clap>.fix,.katex .llap>.fix,.katex .rlap>.fix{display:inline-block}.katex .llap>.inner{right:0}.katex .clap>.inner,.katex .rlap>.inner{left:0}.katex .clap>.inner>span{margin-left:-50%;margin-right:50%}.katex .rule{display:inline-block;border:0 solid;position:relative}.katex .hline,.katex .overline .overline-line,.katex .underline .underline-line{display:inline-block;width:100%;border-bottom-style:solid}.katex .hdashline{display:inline-block;width:100%;border-bottom-style:dashed}.katex .sqrt>.root{margin-left:.27777778em;margin-right:-.55555556em}.katex .fontsize-ensurer.reset-size1.size1,.katex .sizing.reset-size1.size1{font-size:1em}.katex .fontsize-ensurer.reset-size1.size2,.katex .sizing.reset-size1.size2{font-size:1.2em}.katex .fontsize-ensurer.reset-size1.size3,.katex .sizing.reset-size1.size3{font-size:1.4em}.katex .fontsize-ensurer.reset-size1.size4,.katex .sizing.reset-size1.size4{font-size:1.6em}.katex .fontsize-ensurer.reset-size1.size5,.katex .sizing.reset-size1.size5{font-size:1.8em}.katex .fontsize-ensurer.reset-size1.size6,.katex .sizing.reset-size1.size6{font-size:2em}.katex .fontsize-ensurer.reset-size1.size7,.katex .sizing.reset-size1.size7{font-size:2.4em}.katex .fontsize-ensurer.reset-size1.size8,.katex .sizing.reset-size1.size8{font-size:2.88em}.katex .fontsize-ensurer.reset-size1.size9,.katex .sizing.reset-size1.size9{font-size:3.456em}.katex .fontsize-ensurer.reset-size1.size10,.katex .sizing.reset-size1.size10{font-size:4.148em}.katex .fontsize-ensurer.reset-size1.size11,.katex .sizing.reset-size1.size11{font-size:4.976em}.katex .fontsize-ensurer.reset-size2.size1,.katex .sizing.reset-size2.size1{font-size:.83333333em}.katex .fontsize-ensurer.reset-size2.size2,.katex .sizing.reset-size2.size2{font-size:1em}.katex .fontsize-ensurer.reset-size2.size3,.katex .sizing.reset-size2.size3{font-size:1.16666667em}.katex .fontsize-ensurer.reset-size2.size4,.katex .sizing.reset-size2.size4{font-size:1.33333333em}.katex .fontsize-ensurer.reset-size2.size5,.katex .sizing.reset-size2.size5{font-size:1.5em}.katex .fontsize-ensurer.reset-size2.size6,.katex .sizing.reset-size2.size6{font-size:1.66666667em}.katex .fontsize-ensurer.reset-size2.size7,.katex .sizing.reset-size2.size7{font-size:2em}.katex .fontsize-ensurer.reset-size2.size8,.katex .sizing.reset-size2.size8{font-size:2.4em}.katex .fontsize-ensurer.reset-size2.size9,.katex .sizing.reset-size2.size9{font-size:2.88em}.katex .fontsize-ensurer.reset-size2.size10,.katex .sizing.reset-size2.size10{font-size:3.45666667em}.katex .fontsize-ensurer.reset-size2.size11,.katex .sizing.reset-size2.size11{font-size:4.14666667em}.katex .fontsize-ensurer.reset-size3.size1,.katex .sizing.reset-size3.size1{font-size:.71428571em}.katex .fontsize-ensurer.reset-size3.size2,.katex .sizing.reset-size3.size2{font-size:.85714286em}.katex .fontsize-ensurer.reset-size3.size3,.katex .sizing.reset-size3.size3{font-size:1em}.katex .fontsize-ensurer.reset-size3.size4,.katex .sizing.reset-size3.size4{font-size:1.14285714em}.katex .fontsize-ensurer.reset-size3.size5,.katex .sizing.reset-size3.size5{font-size:1.28571429em}.katex .fontsize-ensurer.reset-size3.size6,.katex .sizing.reset-size3.size6{font-size:1.42857143em}.katex .fontsize-ensurer.reset-size3.size7,.katex .sizing.reset-size3.size7{font-size:1.71428571em}.katex .fontsize-ensurer.reset-size3.size8,.katex .sizing.reset-size3.size8{font-size:2.05714286em}.katex .fontsize-ensurer.reset-size3.size9,.katex .sizing.reset-size3.size9{font-size:2.46857143em}.katex .fontsize-ensurer.reset-size3.size10,.katex .sizing.reset-size3.size10{font-size:2.96285714em}.katex .fontsize-ensurer.reset-size3.size11,.katex .sizing.reset-size3.size11{font-size:3.55428571em}.katex .fontsize-ensurer.reset-size4.size1,.katex .sizing.reset-size4.size1{font-size:.625em}.katex .fontsize-ensurer.reset-size4.size2,.katex .sizing.reset-size4.size2{font-size:.75em}.katex .fontsize-ensurer.reset-size4.size3,.katex .sizing.reset-size4.size3{font-size:.875em}.katex .fontsize-ensurer.reset-size4.size4,.katex .sizing.reset-size4.size4{font-size:1em}.katex .fontsize-ensurer.reset-size4.size5,.katex .sizing.reset-size4.size5{font-size:1.125em}.katex .fontsize-ensurer.reset-size4.size6,.katex .sizing.reset-size4.size6{font-size:1.25em}.katex .fontsize-ensurer.reset-size4.size7,.katex .sizing.reset-size4.size7{font-size:1.5em}.katex .fontsize-ensurer.reset-size4.size8,.katex .sizing.reset-size4.size8{font-size:1.8em}.katex .fontsize-ensurer.reset-size4.size9,.katex .sizing.reset-size4.size9{font-size:2.16em}.katex .fontsize-ensurer.reset-size4.size10,.katex .sizing.reset-size4.size10{font-size:2.5925em}.katex .fontsize-ensurer.reset-size4.size11,.katex .sizing.reset-size4.size11{font-size:3.11em}.katex .fontsize-ensurer.reset-size5.size1,.katex .sizing.reset-size5.size1{font-size:.55555556em}.katex .fontsize-ensurer.reset-size5.size2,.katex .sizing.reset-size5.size2{font-size:.66666667em}.katex .fontsize-ensurer.reset-size5.size3,.katex .sizing.reset-size5.size3{font-size:.77777778em}.katex .fontsize-ensurer.reset-size5.size4,.katex .sizing.reset-size5.size4{font-size:.88888889em}.katex .fontsize-ensurer.reset-size5.size5,.katex .sizing.reset-size5.size5{font-size:1em}.katex .fontsize-ensurer.reset-size5.size6,.katex .sizing.reset-size5.size6{font-size:1.11111111em}.katex .fontsize-ensurer.reset-size5.size7,.katex .sizing.reset-size5.size7{font-size:1.33333333em}.katex .fontsize-ensurer.reset-size5.size8,.katex .sizing.reset-size5.size8{font-size:1.6em}.katex .fontsize-ensurer.reset-size5.size9,.katex .sizing.reset-size5.size9{font-size:1.92em}.katex .fontsize-ensurer.reset-size5.size10,.katex .sizing.reset-size5.size10{font-size:2.30444444em}.katex .fontsize-ensurer.reset-size5.size11,.katex .sizing.reset-size5.size11{font-size:2.76444444em}.katex .fontsize-ensurer.reset-size6.size1,.katex .sizing.reset-size6.size1{font-size:.5em}.katex .fontsize-ensurer.reset-size6.size2,.katex .sizing.reset-size6.size2{font-size:.6em}.katex .fontsize-ensurer.reset-size6.size3,.katex .sizing.reset-size6.size3{font-size:.7em}.katex .fontsize-ensurer.reset-size6.size4,.katex .sizing.reset-size6.size4{font-size:.8em}.katex .fontsize-ensurer.reset-size6.size5,.katex .sizing.reset-size6.size5{font-size:.9em}.katex .fontsize-ensurer.reset-size6.size6,.katex .sizing.reset-size6.size6{font-size:1em}.katex .fontsize-ensurer.reset-size6.size7,.katex .sizing.reset-size6.size7{font-size:1.2em}.katex .fontsize-ensurer.reset-size6.size8,.katex .sizing.reset-size6.size8{font-size:1.44em}.katex .fontsize-ensurer.reset-size6.size9,.katex .sizing.reset-size6.size9{font-size:1.728em}.katex .fontsize-ensurer.reset-size6.size10,.katex .sizing.reset-size6.size10{font-size:2.074em}.katex .fontsize-ensurer.reset-size6.size11,.katex .sizing.reset-size6.size11{font-size:2.488em}.katex .fontsize-ensurer.reset-size7.size1,.katex .sizing.reset-size7.size1{font-size:.41666667em}.katex .fontsize-ensurer.reset-size7.size2,.katex .sizing.reset-size7.size2{font-size:.5em}.katex .fontsize-ensurer.reset-size7.size3,.katex .sizing.reset-size7.size3{font-size:.58333333em}.katex .fontsize-ensurer.reset-size7.size4,.katex .sizing.reset-size7.size4{font-size:.66666667em}.katex .fontsize-ensurer.reset-size7.size5,.katex .sizing.reset-size7.size5{font-size:.75em}.katex .fontsize-ensurer.reset-size7.size6,.katex .sizing.reset-size7.size6{font-size:.83333333em}.katex .fontsize-ensurer.reset-size7.size7,.katex .sizing.reset-size7.size7{font-size:1em}.katex .fontsize-ensurer.reset-size7.size8,.katex .sizing.reset-size7.size8{font-size:1.2em}.katex .fontsize-ensurer.reset-size7.size9,.katex .sizing.reset-size7.size9{font-size:1.44em}.katex .fontsize-ensurer.reset-size7.size10,.katex .sizing.reset-size7.size10{font-size:1.72833333em}.katex .fontsize-ensurer.reset-size7.size11,.katex .sizing.reset-size7.size11{font-size:2.07333333em}.katex .fontsize-ensurer.reset-size8.size1,.katex .sizing.reset-size8.size1{font-size:.34722222em}.katex .fontsize-ensurer.reset-size8.size2,.katex .sizing.reset-size8.size2{font-size:.41666667em}.katex .fontsize-ensurer.reset-size8.size3,.katex .sizing.reset-size8.size3{font-size:.48611111em}.katex .fontsize-ensurer.reset-size8.size4,.katex .sizing.reset-size8.size4{font-size:.55555556em}.katex .fontsize-ensurer.reset-size8.size5,.katex .sizing.reset-size8.size5{font-size:.625em}.katex .fontsize-ensurer.reset-size8.size6,.katex .sizing.reset-size8.size6{font-size:.69444444em}.katex .fontsize-ensurer.reset-size8.size7,.katex .sizing.reset-size8.size7{font-size:.83333333em}.katex .fontsize-ensurer.reset-size8.size8,.katex .sizing.reset-size8.size8{font-size:1em}.katex .fontsize-ensurer.reset-size8.size9,.katex .sizing.reset-size8.size9{font-size:1.2em}.katex .fontsize-ensurer.reset-size8.size10,.katex .sizing.reset-size8.size10{font-size:1.44027778em}.katex .fontsize-ensurer.reset-size8.size11,.katex .sizing.reset-size8.size11{font-size:1.72777778em}.katex .fontsize-ensurer.reset-size9.size1,.katex .sizing.reset-size9.size1{font-size:.28935185em}.katex .fontsize-ensurer.reset-size9.size2,.katex .sizing.reset-size9.size2{font-size:.34722222em}.katex .fontsize-ensurer.reset-size9.size3,.katex .sizing.reset-size9.size3{font-size:.40509259em}.katex .fontsize-ensurer.reset-size9.size4,.katex .sizing.reset-size9.size4{font-size:.46296296em}.katex .fontsize-ensurer.reset-size9.size5,.katex .sizing.reset-size9.size5{font-size:.52083333em}.katex .fontsize-ensurer.reset-size9.size6,.katex .sizing.reset-size9.size6{font-size:.5787037em}.katex .fontsize-ensurer.reset-size9.size7,.katex .sizing.reset-size9.size7{font-size:.69444444em}.katex .fontsize-ensurer.reset-size9.size8,.katex .sizing.reset-size9.size8{font-size:.83333333em}.katex .fontsize-ensurer.reset-size9.size9,.katex .sizing.reset-size9.size9{font-size:1em}.katex .fontsize-ensurer.reset-size9.size10,.katex .sizing.reset-size9.size10{font-size:1.20023148em}.katex .fontsize-ensurer.reset-size9.size11,.katex .sizing.reset-size9.size11{font-size:1.43981481em}.katex .fontsize-ensurer.reset-size10.size1,.katex .sizing.reset-size10.size1{font-size:.24108004em}.katex .fontsize-ensurer.reset-size10.size2,.katex .sizing.reset-size10.size2{font-size:.28929605em}.katex .fontsize-ensurer.reset-size10.size3,.katex .sizing.reset-size10.size3{font-size:.33751205em}.katex .fontsize-ensurer.reset-size10.size4,.katex .sizing.reset-size10.size4{font-size:.38572806em}.katex .fontsize-ensurer.reset-size10.size5,.katex .sizing.reset-size10.size5{font-size:.43394407em}.katex .fontsize-ensurer.reset-size10.size6,.katex .sizing.reset-size10.size6{font-size:.48216008em}.katex .fontsize-ensurer.reset-size10.size7,.katex .sizing.reset-size10.size7{font-size:.57859209em}.katex .fontsize-ensurer.reset-size10.size8,.katex .sizing.reset-size10.size8{font-size:.69431051em}.katex .fontsize-ensurer.reset-size10.size9,.katex .sizing.reset-size10.size9{font-size:.83317261em}.katex .fontsize-ensurer.reset-size10.size10,.katex .sizing.reset-size10.size10{font-size:1em}.katex .fontsize-ensurer.reset-size10.size11,.katex .sizing.reset-size10.size11{font-size:1.19961427em}.katex .fontsize-ensurer.reset-size11.size1,.katex .sizing.reset-size11.size1{font-size:.20096463em}.katex .fontsize-ensurer.reset-size11.size2,.katex .sizing.reset-size11.size2{font-size:.24115756em}.katex .fontsize-ensurer.reset-size11.size3,.katex .sizing.reset-size11.size3{font-size:.28135048em}.katex .fontsize-ensurer.reset-size11.size4,.katex .sizing.reset-size11.size4{font-size:.32154341em}.katex .fontsize-ensurer.reset-size11.size5,.katex .sizing.reset-size11.size5{font-size:.36173633em}.katex .fontsize-ensurer.reset-size11.size6,.katex .sizing.reset-size11.size6{font-size:.40192926em}.katex .fontsize-ensurer.reset-size11.size7,.katex .sizing.reset-size11.size7{font-size:.48231511em}.katex .fontsize-ensurer.reset-size11.size8,.katex .sizing.reset-size11.size8{font-size:.57877814em}.katex .fontsize-ensurer.reset-size11.size9,.katex .sizing.reset-size11.size9{font-size:.69453376em}.katex .fontsize-ensurer.reset-size11.size10,.katex .sizing.reset-size11.size10{font-size:.83360129em}.katex .fontsize-ensurer.reset-size11.size11,.katex .sizing.reset-size11.size11{font-size:1em}.katex .delimsizing.size1{font-family:KaTeX_Size1}.katex .delimsizing.size2{font-family:KaTeX_Size2}.katex .delimsizing.size3{font-family:KaTeX_Size3}.katex .delimsizing.size4{font-family:KaTeX_Size4}.katex .delimsizing.mult .delim-size1>span{font-family:KaTeX_Size1}.katex .delimsizing.mult .delim-size4>span{font-family:KaTeX_Size4}.katex .nulldelimiter{display:inline-block;width:.12em}.katex .delimcenter,.katex .op-symbol{position:relative}.katex .op-symbol.small-op{font-family:KaTeX_Size1}.katex .op-symbol.large-op{font-family:KaTeX_Size2}.katex .op-limits>.vlist-t{text-align:center}.katex .accent>.vlist-t{text-align:center}.katex .accent .accent-body{position:relative}.katex .accent .accent-body:not(.accent-full){width:0}.katex .overlay{display:block}.katex .mtable .vertical-separator{display:inline-block;min-width:1px}.katex .mtable .arraycolsep{display:inline-block}.katex .mtable .col-align-c>.vlist-t{text-align:center}.katex .mtable .col-align-l>.vlist-t{text-align:left}.katex .mtable .col-align-r>.vlist-t{text-align:right}.katex .svg-align{text-align:left}.katex svg{display:block;position:absolute;width:100%;height:inherit;fill:currentColor;stroke:currentColor;fill-rule:nonzero;fill-opacity:1;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1}.katex svg path{stroke:none}.katex img{border-style:none;min-width:0;min-height:0;max-width:none;max-height:none}.katex .stretchy{width:100%;display:block;position:relative;overflow:hidden}.katex .stretchy:after,.katex .stretchy:before{content:""}.katex .hide-tail{width:100%;position:relative;overflow:hidden}.katex .halfarrow-left{position:absolute;left:0;width:50.2%;overflow:hidden}.katex .halfarrow-right{position:absolute;right:0;width:50.2%;overflow:hidden}.katex .brace-left{position:absolute;left:0;width:25.1%;overflow:hidden}.katex .brace-center{position:absolute;left:25%;width:50%;overflow:hidden}.katex .brace-right{position:absolute;right:0;width:25.1%;overflow:hidden}.katex .x-arrow-pad{padding:0 .5em}.katex .mover,.katex .munder,.katex .x-arrow{text-align:center}.katex .boxpad{padding:0 .3em}.katex .fbox,.katex .fcolorbox{box-sizing:border-box;border:.04em solid}.katex .cancel-pad{padding:0 .2em}.katex .cancel-lap{margin-left:-.2em;margin-right:-.2em}.katex .sout{border-bottom-style:solid;border-bottom-width:.08em}.katex-display{display:block;margin:1em 0;text-align:center}.katex-display>.katex{display:block;text-align:center;white-space:nowrap}.katex-display>.katex>.katex-html{display:block;position:relative}.katex-display>.katex>.katex-html>.tag{position:absolute;right:0}.katex-display.leqno>.katex>.katex-html>.tag{left:0;right:auto}.katex-display.fleqn>.katex{text-align:left} + + +@charset "UTF-8";@font-face{font-family:et-book;src:url(et-book/et-book-roman-line-figures/et-book-roman-line-figures.eot);src:url(et-book/et-book-roman-line-figures/et-book-roman-line-figures.eot?#iefix) format("embedded-opentype"),url(et-book/et-book-roman-line-figures/et-book-roman-line-figures.woff) format("woff"),url(et-book/et-book-roman-line-figures/et-book-roman-line-figures.ttf) format("truetype"),url(et-book/et-book-roman-line-figures/et-book-roman-line-figures.svg#etbookromanosf) format("svg");font-weight:400;font-style:normal}@font-face{font-family:et-book;src:url(et-book/et-book-display-italic-old-style-figures/et-book-display-italic-old-style-figures.eot);src:url(et-book/et-book-display-italic-old-style-figures/et-book-display-italic-old-style-figures.eot?#iefix) format("embedded-opentype"),url(et-book/et-book-display-italic-old-style-figures/et-book-display-italic-old-style-figures.woff) format("woff"),url(et-book/et-book-display-italic-old-style-figures/et-book-display-italic-old-style-figures.ttf) format("truetype"),url(et-book/et-book-display-italic-old-style-figures/et-book-display-italic-old-style-figures.svg#etbookromanosf) format("svg");font-weight:400;font-style:italic}@font-face{font-family:et-book;src:url(et-book/et-book-bold-line-figures/et-book-bold-line-figures.eot);src:url(et-book/et-book-bold-line-figures/et-book-bold-line-figures.eot?#iefix) format("embedded-opentype"),url(et-book/et-book-bold-line-figures/et-book-bold-line-figures.woff) format("woff"),url(et-book/et-book-bold-line-figures/et-book-bold-line-figures.ttf) format("truetype"),url(et-book/et-book-bold-line-figures/et-book-bold-line-figures.svg#etbookromanosf) format("svg");font-weight:700;font-style:normal}@font-face{font-family:et-book-roman-old-style;src:url(et-book/et-book-roman-old-style-figures/et-book-roman-old-style-figures.eot);src:url(et-book/et-book-roman-old-style-figures/et-book-roman-old-style-figures.eot?#iefix) format("embedded-opentype"),url(et-book/et-book-roman-old-style-figures/et-book-roman-old-style-figures.woff) format("woff"),url(et-book/et-book-roman-old-style-figures/et-book-roman-old-style-figures.ttf) format("truetype"),url(et-book/et-book-roman-old-style-figures/et-book-roman-old-style-figures.svg#etbookromanosf) format("svg");font-weight:400;font-style:normal}html{font-size:15px}body{width:87.5%;margin-left:auto;margin-right:auto;padding-left:12.5%;font-family:et-book,Palatino,"Palatino Linotype","Palatino LT STD","Book Antiqua",Georgia,serif;background-color:#fffff8;color:#111;max-width:1400px;counter-reset:sidenote-counter}h1{font-weight:400;margin-top:4rem;margin-bottom:1.5rem;font-size:3.2rem;line-height:1}h2{font-style:italic;font-weight:400;margin-top:2.1rem;margin-bottom:1.4rem;font-size:2.2rem;line-height:1}h3{font-style:italic;font-weight:400;font-size:1.7rem;margin-top:2rem;margin-bottom:1.4rem;line-height:1}hr{display:block;height:1px;width:55%;border:0;border-top:1px solid #ccc;margin:1em 0;padding:0}p.subtitle{font-style:italic;margin-top:1rem;margin-bottom:1rem;font-size:1.8rem;display:block;line-height:1}.numeral{font-family:et-book-roman-old-style}.danger{color:red}article{padding:5rem 0}section{padding-top:1rem;padding-bottom:1rem}ol,p,ul{font-size:1.4rem;line-height:2rem}p{margin-top:1.4rem;margin-bottom:1.4rem;padding-right:0;vertical-align:baseline}div.epigraph{margin:5em 0}div.epigraph>blockquote{margin-top:3em;margin-bottom:3em}div.epigraph>blockquote,div.epigraph>blockquote>p{font-style:italic}div.epigraph>blockquote>footer{font-style:normal}div.epigraph>blockquote>footer>cite{font-style:italic}blockquote{font-size:1.4rem}blockquote p{width:55%;margin-right:40px}blockquote footer{width:55%;font-size:1.1rem;text-align:right}section>footer,section>p,section>table{width:55%}section>ol,section>ul{width:50%;-webkit-padding-start:5%}li:not(:first-child){margin-top:.25rem}figure{padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline;max-width:55%;-webkit-margin-start:0;-webkit-margin-end:0;margin:0 0 3em 0}figcaption{float:right;clear:right;margin-top:0;margin-bottom:0;font-size:1.1rem;line-height:1.6;vertical-align:baseline;position:relative;max-width:40%}figure.fullwidth figcaption{margin-right:24%}a:link,a:visited{color:inherit}a:link{text-decoration:none;background:-webkit-linear-gradient(#fffff8,#fffff8),-webkit-linear-gradient(#fffff8,#fffff8),-webkit-linear-gradient(currentColor,currentColor);background:linear-gradient(#fffff8,#fffff8),linear-gradient(#fffff8,#fffff8),linear-gradient(currentColor,currentColor);-webkit-background-size:.05em 1px,.05em 1px,1px 1px;-moz-background-size:.05em 1px,.05em 1px,1px 1px;background-size:.05em 1px,.05em 1px,1px 1px;background-repeat:no-repeat,no-repeat,repeat-x;text-shadow:.03em 0 #fffff8,-.03em 0 #fffff8,0 .03em #fffff8,0 -.03em #fffff8,.06em 0 #fffff8,-.06em 0 #fffff8,.09em 0 #fffff8,-.09em 0 #fffff8,.12em 0 #fffff8,-.12em 0 #fffff8,.15em 0 #fffff8,-.15em 0 #fffff8;background-position:0 93%,100% 93%,0 93%}@media screen and (-webkit-min-device-pixel-ratio:0){a:link{background-position-y:87%,87%,87%}}a:link::selection{text-shadow:.03em 0 #b4d5fe,-.03em 0 #b4d5fe,0 .03em #b4d5fe,0 -.03em #b4d5fe,.06em 0 #b4d5fe,-.06em 0 #b4d5fe,.09em 0 #b4d5fe,-.09em 0 #b4d5fe,.12em 0 #b4d5fe,-.12em 0 #b4d5fe,.15em 0 #b4d5fe,-.15em 0 #b4d5fe;background:#b4d5fe}a:link::-moz-selection{text-shadow:.03em 0 #b4d5fe,-.03em 0 #b4d5fe,0 .03em #b4d5fe,0 -.03em #b4d5fe,.06em 0 #b4d5fe,-.06em 0 #b4d5fe,.09em 0 #b4d5fe,-.09em 0 #b4d5fe,.12em 0 #b4d5fe,-.12em 0 #b4d5fe,.15em 0 #b4d5fe,-.15em 0 #b4d5fe;background:#b4d5fe}img{max-width:100%}.marginnote,.sidenote{float:right;clear:right;margin-right:-60%;width:50%;margin-top:0;margin-bottom:0;font-size:1.1rem;line-height:1.3;vertical-align:baseline;position:relative}.sidenote-number{counter-increment:sidenote-counter}.sidenote-number:after,.sidenote:before{font-family:et-book-roman-old-style;position:relative;vertical-align:baseline}.sidenote-number:after{content:counter(sidenote-counter);font-size:1rem;top:-.5rem;left:.1rem}.sidenote:before{content:counter(sidenote-counter) " ";font-size:1rem;top:-.5rem}blockquote .marginnote,blockquote .sidenote{margin-right:-82%;min-width:59%;text-align:left}div.fullwidth,table.fullwidth{width:100%}div.table-wrapper{overflow-x:auto;font-family:"Trebuchet MS","Gill Sans","Gill Sans MT",sans-serif}.sans{font-family:"Gill Sans","Gill Sans MT",Calibri,sans-serif;letter-spacing:.03em}code{font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace;font-size:1rem;line-height:1.42;-webkit-text-size-adjust:100%}.sans>code{font-size:1.2rem}h1>code,h2>code,h3>code{font-size:.8em}.marginnote>code,.sidenote>code{font-size:1rem}pre.code{font-size:.9rem;width:52.5%;margin-left:2.5%;overflow-x:auto}pre.code.fullwidth{width:90%}.fullwidth{max-width:90%;clear:both}span.newthought{font-variant:small-caps;font-size:1.2em}input.margin-toggle{display:none}label.sidenote-number{display:inline}label.margin-toggle:not(.sidenote-number){display:none}.iframe-wrapper{position:relative;padding-bottom:56.25%;padding-top:25px;height:0}.iframe-wrapper iframe{position:absolute;top:0;left:0;width:100%;height:100%}@media (max-width:760px){body{width:84%;padding-left:8%;padding-right:8%}hr,section>footer,section>p,section>table{width:100%}pre.code{width:97%}section>ol{width:90%}section>ul{width:90%}figure{max-width:90%}figcaption,figure.fullwidth figcaption{margin-right:0;max-width:none}blockquote{margin-left:1.5em;margin-right:0}blockquote footer,blockquote p{width:100%}label.margin-toggle:not(.sidenote-number){display:inline}.marginnote,.sidenote{display:none}.margin-toggle:checked+.marginnote,.margin-toggle:checked+.sidenote{display:block;float:left;left:1rem;clear:both;width:95%;margin:1rem 2.5%;vertical-align:baseline;position:relative}label{cursor:pointer}div.table-wrapper,table{width:85%}img{width:100%}} + diff --git a/static/css/kg.0.3.2.css b/static/css/kg.0.3.2.css new file mode 100644 index 0000000..29d861a --- /dev/null +++ b/static/css/kg.0.3.2.css @@ -0,0 +1,176 @@ +@font-face{font-family:KaTeX_AMS;src:url(fonts/KaTeX_AMS-Regular.woff2) format("woff2"),url(fonts/KaTeX_AMS-Regular.woff) format("woff"),url(fonts/KaTeX_AMS-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Caligraphic;src:url(fonts/KaTeX_Caligraphic-Bold.woff2) format("woff2"),url(fonts/KaTeX_Caligraphic-Bold.woff) format("woff"),url(fonts/KaTeX_Caligraphic-Bold.ttf) format("truetype");font-weight:700;font-style:normal}@font-face{font-family:KaTeX_Caligraphic;src:url(fonts/KaTeX_Caligraphic-Regular.woff2) format("woff2"),url(fonts/KaTeX_Caligraphic-Regular.woff) format("woff"),url(fonts/KaTeX_Caligraphic-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Fraktur;src:url(fonts/KaTeX_Fraktur-Bold.woff2) format("woff2"),url(fonts/KaTeX_Fraktur-Bold.woff) format("woff"),url(fonts/KaTeX_Fraktur-Bold.ttf) format("truetype");font-weight:700;font-style:normal}@font-face{font-family:KaTeX_Fraktur;src:url(fonts/KaTeX_Fraktur-Regular.woff2) format("woff2"),url(fonts/KaTeX_Fraktur-Regular.woff) format("woff"),url(fonts/KaTeX_Fraktur-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-Bold.woff2) format("woff2"),url(fonts/KaTeX_Main-Bold.woff) format("woff"),url(fonts/KaTeX_Main-Bold.ttf) format("truetype");font-weight:700;font-style:normal}@font-face{font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-BoldItalic.woff2) format("woff2"),url(fonts/KaTeX_Main-BoldItalic.woff) format("woff"),url(fonts/KaTeX_Main-BoldItalic.ttf) format("truetype");font-weight:700;font-style:italic}@font-face{font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-Italic.woff2) format("woff2"),url(fonts/KaTeX_Main-Italic.woff) format("woff"),url(fonts/KaTeX_Main-Italic.ttf) format("truetype");font-weight:400;font-style:italic}@font-face{font-family:KaTeX_Main;src:url(fonts/KaTeX_Main-Regular.woff2) format("woff2"),url(fonts/KaTeX_Main-Regular.woff) format("woff"),url(fonts/KaTeX_Main-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Math;src:url(fonts/KaTeX_Math-BoldItalic.woff2) format("woff2"),url(fonts/KaTeX_Math-BoldItalic.woff) format("woff"),url(fonts/KaTeX_Math-BoldItalic.ttf) format("truetype");font-weight:700;font-style:italic}@font-face{font-family:KaTeX_Math;src:url(fonts/KaTeX_Math-Italic.woff2) format("woff2"),url(fonts/KaTeX_Math-Italic.woff) format("woff"),url(fonts/KaTeX_Math-Italic.ttf) format("truetype");font-weight:400;font-style:italic}@font-face{font-family:"KaTeX_SansSerif";src:url(fonts/KaTeX_SansSerif-Bold.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Bold.woff) format("woff"),url(fonts/KaTeX_SansSerif-Bold.ttf) format("truetype");font-weight:700;font-style:normal}@font-face{font-family:"KaTeX_SansSerif";src:url(fonts/KaTeX_SansSerif-Italic.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Italic.woff) format("woff"),url(fonts/KaTeX_SansSerif-Italic.ttf) format("truetype");font-weight:400;font-style:italic}@font-face{font-family:"KaTeX_SansSerif";src:url(fonts/KaTeX_SansSerif-Regular.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Regular.woff) format("woff"),url(fonts/KaTeX_SansSerif-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Script;src:url(fonts/KaTeX_Script-Regular.woff2) format("woff2"),url(fonts/KaTeX_Script-Regular.woff) format("woff"),url(fonts/KaTeX_Script-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Size1;src:url(fonts/KaTeX_Size1-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size1-Regular.woff) format("woff"),url(fonts/KaTeX_Size1-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Size2;src:url(fonts/KaTeX_Size2-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size2-Regular.woff) format("woff"),url(fonts/KaTeX_Size2-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Size3;src:url(fonts/KaTeX_Size3-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size3-Regular.woff) format("woff"),url(fonts/KaTeX_Size3-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Size4;src:url(fonts/KaTeX_Size4-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size4-Regular.woff) format("woff"),url(fonts/KaTeX_Size4-Regular.ttf) format("truetype");font-weight:400;font-style:normal}@font-face{font-family:KaTeX_Typewriter;src:url(fonts/KaTeX_Typewriter-Regular.woff2) format("woff2"),url(fonts/KaTeX_Typewriter-Regular.woff) format("woff"),url(fonts/KaTeX_Typewriter-Regular.ttf) format("truetype");font-weight:400;font-style:normal}.katex{font:normal 1.21em KaTeX_Main,Times New Roman,serif;line-height:1.2;text-indent:0;text-rendering:auto}.katex *{-ms-high-contrast-adjust:none!important}.katex .katex-version:after{content:"0.11.0"}.katex .katex-mathml{position:absolute;clip:rect(1px,1px,1px,1px);padding:0;border:0;height:1px;width:1px;overflow:hidden}.katex .katex-html>.newline{display:block}.katex .base{position:relative;white-space:nowrap;width:min-content}.katex .base,.katex .strut{display:inline-block}.katex .textbf{font-weight:700}.katex .textit{font-style:italic}.katex .textrm{font-family:KaTeX_Main}.katex .textsf{font-family:KaTeX_SansSerif}.katex .texttt{font-family:KaTeX_Typewriter}.katex .mathdefault{font-family:KaTeX_Math;font-style:italic}.katex .mathit{font-family:KaTeX_Main;font-style:italic}.katex .mathrm{font-style:normal}.katex .mathbf{font-family:KaTeX_Main;font-weight:700}.katex .boldsymbol{font-family:KaTeX_Math;font-weight:700;font-style:italic}.katex .amsrm,.katex .mathbb,.katex .textbb{font-family:KaTeX_AMS}.katex .mathcal{font-family:KaTeX_Caligraphic}.katex .mathfrak,.katex .textfrak{font-family:KaTeX_Fraktur}.katex .mathtt{font-family:KaTeX_Typewriter}.katex .mathscr,.katex .textscr{font-family:KaTeX_Script}.katex .mathsf,.katex .textsf{font-family:KaTeX_SansSerif}.katex .mathboldsf,.katex .textboldsf{font-family:KaTeX_SansSerif;font-weight:700}.katex .mathitsf,.katex .textitsf{font-family:KaTeX_SansSerif;font-style:italic}.katex .mainrm{font-family:KaTeX_Main;font-style:normal}.katex .vlist-t{display:inline-table;table-layout:fixed}.katex .vlist-r{display:table-row}.katex .vlist{display:table-cell;vertical-align:bottom;position:relative}.katex .vlist>span{display:block;height:0;position:relative}.katex .vlist>span>span{display:inline-block}.katex .vlist>span>.pstrut{overflow:hidden;width:0}.katex .vlist-t2{margin-right:-2px}.katex .vlist-s{display:table-cell;vertical-align:bottom;font-size:1px;width:2px;min-width:2px}.katex .msupsub{text-align:left}.katex .mfrac>span>span{text-align:center}.katex .mfrac .frac-line{display:inline-block;width:100%;border-bottom-style:solid}.katex .hdashline,.katex .hline,.katex .mfrac .frac-line,.katex .overline .overline-line,.katex .rule,.katex .underline .underline-line{min-height:1px}.katex .mspace{display:inline-block}.katex .clap,.katex .llap,.katex .rlap{width:0;position:relative}.katex .clap>.inner,.katex .llap>.inner,.katex .rlap>.inner{position:absolute}.katex .clap>.fix,.katex .llap>.fix,.katex .rlap>.fix{display:inline-block}.katex .llap>.inner{right:0}.katex .clap>.inner,.katex .rlap>.inner{left:0}.katex .clap>.inner>span{margin-left:-50%;margin-right:50%}.katex .rule{display:inline-block;border:0 solid;position:relative}.katex .hline,.katex .overline .overline-line,.katex .underline .underline-line{display:inline-block;width:100%;border-bottom-style:solid}.katex .hdashline{display:inline-block;width:100%;border-bottom-style:dashed}.katex .sqrt>.root{margin-left:.27777778em;margin-right:-.55555556em}.katex .fontsize-ensurer.reset-size1.size1,.katex .sizing.reset-size1.size1{font-size:1em}.katex .fontsize-ensurer.reset-size1.size2,.katex .sizing.reset-size1.size2{font-size:1.2em}.katex .fontsize-ensurer.reset-size1.size3,.katex .sizing.reset-size1.size3{font-size:1.4em}.katex .fontsize-ensurer.reset-size1.size4,.katex .sizing.reset-size1.size4{font-size:1.6em}.katex .fontsize-ensurer.reset-size1.size5,.katex .sizing.reset-size1.size5{font-size:1.8em}.katex .fontsize-ensurer.reset-size1.size6,.katex .sizing.reset-size1.size6{font-size:2em}.katex .fontsize-ensurer.reset-size1.size7,.katex .sizing.reset-size1.size7{font-size:2.4em}.katex .fontsize-ensurer.reset-size1.size8,.katex .sizing.reset-size1.size8{font-size:2.88em}.katex .fontsize-ensurer.reset-size1.size9,.katex .sizing.reset-size1.size9{font-size:3.456em}.katex .fontsize-ensurer.reset-size1.size10,.katex .sizing.reset-size1.size10{font-size:4.148em}.katex .fontsize-ensurer.reset-size1.size11,.katex .sizing.reset-size1.size11{font-size:4.976em}.katex .fontsize-ensurer.reset-size2.size1,.katex .sizing.reset-size2.size1{font-size:.83333333em}.katex .fontsize-ensurer.reset-size2.size2,.katex .sizing.reset-size2.size2{font-size:1em}.katex .fontsize-ensurer.reset-size2.size3,.katex .sizing.reset-size2.size3{font-size:1.16666667em}.katex .fontsize-ensurer.reset-size2.size4,.katex .sizing.reset-size2.size4{font-size:1.33333333em}.katex .fontsize-ensurer.reset-size2.size5,.katex .sizing.reset-size2.size5{font-size:1.5em}.katex .fontsize-ensurer.reset-size2.size6,.katex .sizing.reset-size2.size6{font-size:1.66666667em}.katex .fontsize-ensurer.reset-size2.size7,.katex .sizing.reset-size2.size7{font-size:2em}.katex .fontsize-ensurer.reset-size2.size8,.katex .sizing.reset-size2.size8{font-size:2.4em}.katex .fontsize-ensurer.reset-size2.size9,.katex .sizing.reset-size2.size9{font-size:2.88em}.katex .fontsize-ensurer.reset-size2.size10,.katex .sizing.reset-size2.size10{font-size:3.45666667em}.katex .fontsize-ensurer.reset-size2.size11,.katex .sizing.reset-size2.size11{font-size:4.14666667em}.katex .fontsize-ensurer.reset-size3.size1,.katex .sizing.reset-size3.size1{font-size:.71428571em}.katex .fontsize-ensurer.reset-size3.size2,.katex .sizing.reset-size3.size2{font-size:.85714286em}.katex .fontsize-ensurer.reset-size3.size3,.katex .sizing.reset-size3.size3{font-size:1em}.katex .fontsize-ensurer.reset-size3.size4,.katex .sizing.reset-size3.size4{font-size:1.14285714em}.katex .fontsize-ensurer.reset-size3.size5,.katex .sizing.reset-size3.size5{font-size:1.28571429em}.katex .fontsize-ensurer.reset-size3.size6,.katex .sizing.reset-size3.size6{font-size:1.42857143em}.katex .fontsize-ensurer.reset-size3.size7,.katex .sizing.reset-size3.size7{font-size:1.71428571em}.katex .fontsize-ensurer.reset-size3.size8,.katex .sizing.reset-size3.size8{font-size:2.05714286em}.katex .fontsize-ensurer.reset-size3.size9,.katex .sizing.reset-size3.size9{font-size:2.46857143em}.katex .fontsize-ensurer.reset-size3.size10,.katex .sizing.reset-size3.size10{font-size:2.96285714em}.katex .fontsize-ensurer.reset-size3.size11,.katex .sizing.reset-size3.size11{font-size:3.55428571em}.katex .fontsize-ensurer.reset-size4.size1,.katex .sizing.reset-size4.size1{font-size:.625em}.katex .fontsize-ensurer.reset-size4.size2,.katex .sizing.reset-size4.size2{font-size:.75em}.katex .fontsize-ensurer.reset-size4.size3,.katex .sizing.reset-size4.size3{font-size:.875em}.katex .fontsize-ensurer.reset-size4.size4,.katex .sizing.reset-size4.size4{font-size:1em}.katex .fontsize-ensurer.reset-size4.size5,.katex .sizing.reset-size4.size5{font-size:1.125em}.katex .fontsize-ensurer.reset-size4.size6,.katex .sizing.reset-size4.size6{font-size:1.25em}.katex .fontsize-ensurer.reset-size4.size7,.katex .sizing.reset-size4.size7{font-size:1.5em}.katex .fontsize-ensurer.reset-size4.size8,.katex .sizing.reset-size4.size8{font-size:1.8em}.katex .fontsize-ensurer.reset-size4.size9,.katex .sizing.reset-size4.size9{font-size:2.16em}.katex .fontsize-ensurer.reset-size4.size10,.katex .sizing.reset-size4.size10{font-size:2.5925em}.katex .fontsize-ensurer.reset-size4.size11,.katex .sizing.reset-size4.size11{font-size:3.11em}.katex .fontsize-ensurer.reset-size5.size1,.katex .sizing.reset-size5.size1{font-size:.55555556em}.katex .fontsize-ensurer.reset-size5.size2,.katex .sizing.reset-size5.size2{font-size:.66666667em}.katex .fontsize-ensurer.reset-size5.size3,.katex .sizing.reset-size5.size3{font-size:.77777778em}.katex .fontsize-ensurer.reset-size5.size4,.katex .sizing.reset-size5.size4{font-size:.88888889em}.katex .fontsize-ensurer.reset-size5.size5,.katex .sizing.reset-size5.size5{font-size:1em}.katex .fontsize-ensurer.reset-size5.size6,.katex .sizing.reset-size5.size6{font-size:1.11111111em}.katex .fontsize-ensurer.reset-size5.size7,.katex .sizing.reset-size5.size7{font-size:1.33333333em}.katex .fontsize-ensurer.reset-size5.size8,.katex .sizing.reset-size5.size8{font-size:1.6em}.katex .fontsize-ensurer.reset-size5.size9,.katex .sizing.reset-size5.size9{font-size:1.92em}.katex .fontsize-ensurer.reset-size5.size10,.katex .sizing.reset-size5.size10{font-size:2.30444444em}.katex .fontsize-ensurer.reset-size5.size11,.katex .sizing.reset-size5.size11{font-size:2.76444444em}.katex .fontsize-ensurer.reset-size6.size1,.katex .sizing.reset-size6.size1{font-size:.5em}.katex .fontsize-ensurer.reset-size6.size2,.katex .sizing.reset-size6.size2{font-size:.6em}.katex .fontsize-ensurer.reset-size6.size3,.katex .sizing.reset-size6.size3{font-size:.7em}.katex .fontsize-ensurer.reset-size6.size4,.katex .sizing.reset-size6.size4{font-size:.8em}.katex .fontsize-ensurer.reset-size6.size5,.katex .sizing.reset-size6.size5{font-size:.9em}.katex .fontsize-ensurer.reset-size6.size6,.katex .sizing.reset-size6.size6{font-size:1em}.katex .fontsize-ensurer.reset-size6.size7,.katex .sizing.reset-size6.size7{font-size:1.2em}.katex .fontsize-ensurer.reset-size6.size8,.katex .sizing.reset-size6.size8{font-size:1.44em}.katex .fontsize-ensurer.reset-size6.size9,.katex .sizing.reset-size6.size9{font-size:1.728em}.katex .fontsize-ensurer.reset-size6.size10,.katex .sizing.reset-size6.size10{font-size:2.074em}.katex .fontsize-ensurer.reset-size6.size11,.katex .sizing.reset-size6.size11{font-size:2.488em}.katex .fontsize-ensurer.reset-size7.size1,.katex .sizing.reset-size7.size1{font-size:.41666667em}.katex .fontsize-ensurer.reset-size7.size2,.katex .sizing.reset-size7.size2{font-size:.5em}.katex .fontsize-ensurer.reset-size7.size3,.katex .sizing.reset-size7.size3{font-size:.58333333em}.katex .fontsize-ensurer.reset-size7.size4,.katex .sizing.reset-size7.size4{font-size:.66666667em}.katex .fontsize-ensurer.reset-size7.size5,.katex .sizing.reset-size7.size5{font-size:.75em}.katex .fontsize-ensurer.reset-size7.size6,.katex .sizing.reset-size7.size6{font-size:.83333333em}.katex .fontsize-ensurer.reset-size7.size7,.katex .sizing.reset-size7.size7{font-size:1em}.katex .fontsize-ensurer.reset-size7.size8,.katex .sizing.reset-size7.size8{font-size:1.2em}.katex .fontsize-ensurer.reset-size7.size9,.katex .sizing.reset-size7.size9{font-size:1.44em}.katex .fontsize-ensurer.reset-size7.size10,.katex .sizing.reset-size7.size10{font-size:1.72833333em}.katex .fontsize-ensurer.reset-size7.size11,.katex .sizing.reset-size7.size11{font-size:2.07333333em}.katex .fontsize-ensurer.reset-size8.size1,.katex .sizing.reset-size8.size1{font-size:.34722222em}.katex .fontsize-ensurer.reset-size8.size2,.katex .sizing.reset-size8.size2{font-size:.41666667em}.katex .fontsize-ensurer.reset-size8.size3,.katex .sizing.reset-size8.size3{font-size:.48611111em}.katex .fontsize-ensurer.reset-size8.size4,.katex .sizing.reset-size8.size4{font-size:.55555556em}.katex .fontsize-ensurer.reset-size8.size5,.katex .sizing.reset-size8.size5{font-size:.625em}.katex .fontsize-ensurer.reset-size8.size6,.katex .sizing.reset-size8.size6{font-size:.69444444em}.katex .fontsize-ensurer.reset-size8.size7,.katex .sizing.reset-size8.size7{font-size:.83333333em}.katex .fontsize-ensurer.reset-size8.size8,.katex .sizing.reset-size8.size8{font-size:1em}.katex .fontsize-ensurer.reset-size8.size9,.katex .sizing.reset-size8.size9{font-size:1.2em}.katex .fontsize-ensurer.reset-size8.size10,.katex .sizing.reset-size8.size10{font-size:1.44027778em}.katex .fontsize-ensurer.reset-size8.size11,.katex .sizing.reset-size8.size11{font-size:1.72777778em}.katex .fontsize-ensurer.reset-size9.size1,.katex .sizing.reset-size9.size1{font-size:.28935185em}.katex .fontsize-ensurer.reset-size9.size2,.katex .sizing.reset-size9.size2{font-size:.34722222em}.katex .fontsize-ensurer.reset-size9.size3,.katex .sizing.reset-size9.size3{font-size:.40509259em}.katex .fontsize-ensurer.reset-size9.size4,.katex .sizing.reset-size9.size4{font-size:.46296296em}.katex .fontsize-ensurer.reset-size9.size5,.katex .sizing.reset-size9.size5{font-size:.52083333em}.katex .fontsize-ensurer.reset-size9.size6,.katex .sizing.reset-size9.size6{font-size:.5787037em}.katex .fontsize-ensurer.reset-size9.size7,.katex .sizing.reset-size9.size7{font-size:.69444444em}.katex .fontsize-ensurer.reset-size9.size8,.katex .sizing.reset-size9.size8{font-size:.83333333em}.katex .fontsize-ensurer.reset-size9.size9,.katex .sizing.reset-size9.size9{font-size:1em}.katex .fontsize-ensurer.reset-size9.size10,.katex .sizing.reset-size9.size10{font-size:1.20023148em}.katex .fontsize-ensurer.reset-size9.size11,.katex .sizing.reset-size9.size11{font-size:1.43981481em}.katex .fontsize-ensurer.reset-size10.size1,.katex .sizing.reset-size10.size1{font-size:.24108004em}.katex .fontsize-ensurer.reset-size10.size2,.katex .sizing.reset-size10.size2{font-size:.28929605em}.katex .fontsize-ensurer.reset-size10.size3,.katex .sizing.reset-size10.size3{font-size:.33751205em}.katex .fontsize-ensurer.reset-size10.size4,.katex .sizing.reset-size10.size4{font-size:.38572806em}.katex .fontsize-ensurer.reset-size10.size5,.katex .sizing.reset-size10.size5{font-size:.43394407em}.katex .fontsize-ensurer.reset-size10.size6,.katex .sizing.reset-size10.size6{font-size:.48216008em}.katex .fontsize-ensurer.reset-size10.size7,.katex .sizing.reset-size10.size7{font-size:.57859209em}.katex .fontsize-ensurer.reset-size10.size8,.katex .sizing.reset-size10.size8{font-size:.69431051em}.katex .fontsize-ensurer.reset-size10.size9,.katex .sizing.reset-size10.size9{font-size:.83317261em}.katex .fontsize-ensurer.reset-size10.size10,.katex .sizing.reset-size10.size10{font-size:1em}.katex .fontsize-ensurer.reset-size10.size11,.katex .sizing.reset-size10.size11{font-size:1.19961427em}.katex .fontsize-ensurer.reset-size11.size1,.katex .sizing.reset-size11.size1{font-size:.20096463em}.katex .fontsize-ensurer.reset-size11.size2,.katex .sizing.reset-size11.size2{font-size:.24115756em}.katex .fontsize-ensurer.reset-size11.size3,.katex .sizing.reset-size11.size3{font-size:.28135048em}.katex .fontsize-ensurer.reset-size11.size4,.katex .sizing.reset-size11.size4{font-size:.32154341em}.katex .fontsize-ensurer.reset-size11.size5,.katex .sizing.reset-size11.size5{font-size:.36173633em}.katex .fontsize-ensurer.reset-size11.size6,.katex .sizing.reset-size11.size6{font-size:.40192926em}.katex .fontsize-ensurer.reset-size11.size7,.katex .sizing.reset-size11.size7{font-size:.48231511em}.katex .fontsize-ensurer.reset-size11.size8,.katex .sizing.reset-size11.size8{font-size:.57877814em}.katex .fontsize-ensurer.reset-size11.size9,.katex .sizing.reset-size11.size9{font-size:.69453376em}.katex .fontsize-ensurer.reset-size11.size10,.katex .sizing.reset-size11.size10{font-size:.83360129em}.katex .fontsize-ensurer.reset-size11.size11,.katex .sizing.reset-size11.size11{font-size:1em}.katex .delimsizing.size1{font-family:KaTeX_Size1}.katex .delimsizing.size2{font-family:KaTeX_Size2}.katex .delimsizing.size3{font-family:KaTeX_Size3}.katex .delimsizing.size4{font-family:KaTeX_Size4}.katex .delimsizing.mult .delim-size1>span{font-family:KaTeX_Size1}.katex .delimsizing.mult .delim-size4>span{font-family:KaTeX_Size4}.katex .nulldelimiter{display:inline-block;width:.12em}.katex .delimcenter,.katex .op-symbol{position:relative}.katex .op-symbol.small-op{font-family:KaTeX_Size1}.katex .op-symbol.large-op{font-family:KaTeX_Size2}.katex .op-limits>.vlist-t{text-align:center}.katex .accent>.vlist-t{text-align:center}.katex .accent .accent-body{position:relative}.katex .accent .accent-body:not(.accent-full){width:0}.katex .overlay{display:block}.katex .mtable .vertical-separator{display:inline-block;min-width:1px}.katex .mtable .arraycolsep{display:inline-block}.katex .mtable .col-align-c>.vlist-t{text-align:center}.katex .mtable .col-align-l>.vlist-t{text-align:left}.katex .mtable .col-align-r>.vlist-t{text-align:right}.katex .svg-align{text-align:left}.katex svg{display:block;position:absolute;width:100%;height:inherit;fill:currentColor;stroke:currentColor;fill-rule:nonzero;fill-opacity:1;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1}.katex svg path{stroke:none}.katex img{border-style:none;min-width:0;min-height:0;max-width:none;max-height:none}.katex .stretchy{width:100%;display:block;position:relative;overflow:hidden}.katex .stretchy:after,.katex .stretchy:before{content:""}.katex .hide-tail{width:100%;position:relative;overflow:hidden}.katex .halfarrow-left{position:absolute;left:0;width:50.2%;overflow:hidden}.katex .halfarrow-right{position:absolute;right:0;width:50.2%;overflow:hidden}.katex .brace-left{position:absolute;left:0;width:25.1%;overflow:hidden}.katex .brace-center{position:absolute;left:25%;width:50%;overflow:hidden}.katex .brace-right{position:absolute;right:0;width:25.1%;overflow:hidden}.katex .x-arrow-pad{padding:0 .5em}.katex .mover,.katex .munder,.katex .x-arrow{text-align:center}.katex .boxpad{padding:0 .3em}.katex .fbox,.katex .fcolorbox{box-sizing:border-box;border:.04em solid}.katex .cancel-pad{padding:0 .2em}.katex .cancel-lap{margin-left:-.2em;margin-right:-.2em}.katex .sout{border-bottom-style:solid;border-bottom-width:.08em}.katex-display{display:block;margin:1em 0;text-align:center}.katex-display>.katex{display:block;text-align:center;white-space:nowrap}.katex-display>.katex>.katex-html{display:block;position:relative}.katex-display>.katex>.katex-html>.tag{position:absolute;right:0}.katex-display.leqno>.katex>.katex-html>.tag{left:0;right:auto}.katex-display.fleqn>.katex{text-align:left} + + +::-webkit-scrollbar { + width: 0px; + background: transparent; /* make scrollbar transparent */ +} + +.documentation { + width: 100%; + padding-left: 20px; + max-width: 1200px; + margin-left: 0px; +} + +.documentation p { + width: 1000px; +} + +div.kg-container text { + cursor: default; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +div.kg-container text::selection { + background: none; +} + +text { + font-size: 10px; +} + +input { + font-family: KaTeX_Main; +} + +.katex { + font-size: 1em; +} + +.watermark { + position: fixed; + bottom: 5px; + right: 5px; + opacity: 0.5; + z-index: 99; + color: lightgray; +} + +.watermark a { + color: lightgray; +} + +.tick text { + fill: gray; +} + +.tick line { + stroke: gray; +} + +.tick { + font-size: 5pt; + color: red; +} + +table.gameMatrix { + border-collapse: collapse; + width: 100%; +} + +table.gameMatrix tr td { + border: 2px solid #999; + padding: 1rem; + text-align: center; + font-size: 14pt; +} + +table.gameMatrix tr td.player1 { + color: #3182bd; +} + +table.gameMatrix tr td.player2 { + color: #d62728; +} + +table.gameMatrix tr td.empty { + border: 0; +} + +table.gameMatrix tr td.player1.payoff { + border-right: 0; +} + +table.gameMatrix tr td.player2.payoff { + border-left: 0; +} + +table.gameMatrix tr td.strategy { + font-weight: bolder; +} + +.kg-container:fullscreen { + background-color: white; +} + +.contents { + position: absolute; + margin-left: 0; + width: 180px; + top: 40px; + left: 0px; + border-right: thin lightgrey dotted; + padding: 20px; +} + +.kgjs-title { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 36px; + position: absolute; + left: 72px; + top: 18px; + letter-spacing: 0px; + font-weight: 500; + margin-block-end: 10px; + color: #666666; +} + + +.contents-category { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 12px; + font-weight: 700; + color: #959595; + text-transform: uppercase; + letter-spacing: 1px; + margin-top: 2em; + margin-bottom: 0.5em; +} + +.contents-category a { + background: none; +} + +.contents p { + margin-left: 10px; + margin-top: 0; + margin-bottom: 0; + line-height: 1; +} + +.contents p a { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 1rem; + padding: 3px; + background: none; + color: rgb(31, 119, 180); +} + +.spacer { + margin-top: 20px; +} + +.subtitle { + padding-top: 20px; + padding-bottom: 10px; + font-size: 12px; + font-weight: 700; + color: #959595; + text-transform: uppercase; + letter-spacing: 1px; +} + diff --git a/static/js/kg.0.3.2.js b/static/js/kg.0.3.2.js new file mode 100644 index 0000000..ee88202 --- /dev/null +++ b/static/js/kg.0.3.2.js @@ -0,0 +1,71401 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.katex=e():t.katex=e()}("undefined"!=typeof self?self:this,function(){return function(t){var e={};function r(a){if(e[a])return e[a].exports;var n=e[a]={i:a,l:!1,exports:{}};return t[a].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=t,r.c=e,r.d=function(t,e,a){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:a})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var a=Object.create(null);if(r.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var n in t)r.d(a,n,function(e){return t[e]}.bind(null,n));return a},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=1)}([function(t,e,r){},function(t,e,r){"use strict";r.r(e);r(0);var a=function(){function t(t,e,r){this.lexer=void 0,this.start=void 0,this.end=void 0,this.lexer=t,this.start=e,this.end=r}return t.range=function(e,r){return r?e&&e.loc&&r.loc&&e.loc.lexer===r.loc.lexer?new t(e.loc.lexer,e.loc.start,r.loc.end):null:e&&e.loc},t}(),n=function(){function t(t,e){this.text=void 0,this.loc=void 0,this.text=t,this.loc=e}return t.prototype.range=function(e,r){return new t(r,a.range(this,e))},t}(),i=function t(e,r){this.position=void 0;var a,n="KaTeX parse error: "+e,i=r&&r.loc;if(i&&i.start<=i.end){var o=i.lexer.input;a=i.start;var s=i.end;a===o.length?n+=" at end of input: ":n+=" at position "+(a+1)+": ";var h=o.slice(a,s).replace(/[^]/g,"$&\u0332");n+=(a>15?"\u2026"+o.slice(a-15,a):o.slice(0,a))+h+(s+15":">","<":"<",'"':""","'":"'"},l=/[&><"']/g;var m=function t(e){return"ordgroup"===e.type?1===e.body.length?t(e.body[0]):e:"color"===e.type?1===e.body.length?t(e.body[0]):e:"font"===e.type?t(e.body):e},c={contains:function(t,e){return-1!==t.indexOf(e)},deflt:function(t,e){return void 0===t?e:t},escape:function(t){return String(t).replace(l,function(t){return h[t]})},hyphenate:function(t){return t.replace(s,"-$1").toLowerCase()},getBaseElem:m,isCharacterBox:function(t){var e=m(t);return"mathord"===e.type||"textord"===e.type||"atom"===e.type},protocolFromUrl:function(t){var e=/^\s*([^\\\/#]*?)(?::|�*58|�*3a)/i.exec(t);return null!=e?e[1]:"_relative"}},u=function(){function t(t){this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void 0,this.errorColor=void 0,this.macros=void 0,this.minRuleThickness=void 0,this.colorIsTextColor=void 0,this.strict=void 0,this.trust=void 0,this.maxSize=void 0,this.maxExpand=void 0,t=t||{},this.displayMode=c.deflt(t.displayMode,!1),this.output=c.deflt(t.output,"htmlAndMathml"),this.leqno=c.deflt(t.leqno,!1),this.fleqn=c.deflt(t.fleqn,!1),this.throwOnError=c.deflt(t.throwOnError,!0),this.errorColor=c.deflt(t.errorColor,"#cc0000"),this.macros=t.macros||{},this.minRuleThickness=Math.max(0,c.deflt(t.minRuleThickness,0)),this.colorIsTextColor=c.deflt(t.colorIsTextColor,!1),this.strict=c.deflt(t.strict,"warn"),this.trust=c.deflt(t.trust,!1),this.maxSize=Math.max(0,c.deflt(t.maxSize,1/0)),this.maxExpand=Math.max(0,c.deflt(t.maxExpand,1e3))}var e=t.prototype;return e.reportNonstrict=function(t,e,r){var a=this.strict;if("function"==typeof a&&(a=a(t,e,r)),a&&"ignore"!==a){if(!0===a||"error"===a)throw new o("LaTeX-incompatible input and strict mode is set to 'error': "+e+" ["+t+"]",r);"warn"===a?"undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+e+" ["+t+"]"):"undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to unrecognized '"+a+"': "+e+" ["+t+"]")}},e.useStrictBehavior=function(t,e,r){var a=this.strict;if("function"==typeof a)try{a=a(t,e,r)}catch(t){a="error"}return!(!a||"ignore"===a)&&(!0===a||"error"===a||("warn"===a?("undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+e+" ["+t+"]"),!1):("undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to unrecognized '"+a+"': "+e+" ["+t+"]"),!1)))},e.isTrusted=function(t){t.url&&!t.protocol&&(t.protocol=c.protocolFromUrl(t.url));var e="function"==typeof this.trust?this.trust(t):this.trust;return Boolean(e)},t}(),p=function(){function t(t,e,r){this.id=void 0,this.size=void 0,this.cramped=void 0,this.id=t,this.size=e,this.cramped=r}var e=t.prototype;return e.sup=function(){return d[f[this.id]]},e.sub=function(){return d[g[this.id]]},e.fracNum=function(){return d[x[this.id]]},e.fracDen=function(){return d[v[this.id]]},e.cramp=function(){return d[b[this.id]]},e.text=function(){return d[y[this.id]]},e.isTight=function(){return this.size>=2},t}(),d=[new p(0,0,!1),new p(1,0,!0),new p(2,1,!1),new p(3,1,!0),new p(4,2,!1),new p(5,2,!0),new p(6,3,!1),new p(7,3,!0)],f=[4,5,4,5,6,7,6,7],g=[5,5,5,5,7,7,7,7],x=[2,3,4,5,6,7,6,7],v=[3,3,5,5,7,7,7,7],b=[1,1,3,3,5,5,7,7],y=[0,1,2,3,2,3,2,3],w={DISPLAY:d[0],TEXT:d[2],SCRIPT:d[4],SCRIPTSCRIPT:d[6]},k=[{name:"latin",blocks:[[256,591],[768,879]]},{name:"cyrillic",blocks:[[1024,1279]]},{name:"brahmic",blocks:[[2304,4255]]},{name:"georgian",blocks:[[4256,4351]]},{name:"cjk",blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:"hangul",blocks:[[44032,55215]]}];var S=[];function M(t){for(var e=0;e=S[e]&&t<=S[e+1])return!0;return!1}k.forEach(function(t){return t.blocks.forEach(function(t){return S.push.apply(S,t)})});var z={doubleleftarrow:"M262 157\nl10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3\n 0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28\n 14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5\nc2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5\n 157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87\n-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7\n-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z\nm8 0v40h399730v-40zm0 194v40h399730v-40z",doublerightarrow:"M399738 392l\n-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5\n 14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88\n-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68\n-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18\n-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782\nc-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3\n-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z",leftarrow:"M400000 241H110l3-3c68.7-52.7 113.7-120\n 135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8\n-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247\nc-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208\n 490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3\n 1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202\n l-3-3h399890zM100 241v40h399900v-40z",leftbrace:"M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117\n-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7\n 5-6 9-10 13-.7 1-7.3 1-20 1H6z",leftbraceunder:"M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13\n 35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688\n 0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7\n-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z",leftgroup:"M400000 80\nH435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0\n 435 0h399565z",leftgroupunder:"M400000 262\nH435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219\n 435 219h399565z",leftharpoon:"M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3\n-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5\n-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7\n-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z",leftharpoonplus:"M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5\n 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3\n-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7\n-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z\nm0 0v40h400000v-40z",leftharpoondown:"M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333\n 5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5\n 1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667\n-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z",leftharpoondownplus:"M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12\n 10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7\n-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0\nv40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z",lefthook:"M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5\n-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3\n-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21\n 71.5 23h399859zM103 281v-40h399897v40z",leftlinesegment:"M40 281 V428 H0 V94 H40 V241 H400000 v40z\nM40 281 V428 H0 V94 H40 V241 H400000 v40z",leftmapsto:"M40 281 V448H0V74H40V241H400000v40z\nM40 281 V448H0V74H40V241H400000v40z",leftToFrom:"M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23\n-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8\nc28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3\n 68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z",longequal:"M0 50 h400000 v40H0z m0 194h40000v40H0z\nM0 50 h400000 v40H0z m0 194h40000v40H0z",midbrace:"M200428 334\nc-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14\n-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7\n 311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11\n 12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z",midbraceunder:"M199572 214\nc100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14\n 53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3\n 11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0\n-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z",oiintSize1:"M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6\n-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z\nm368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8\n60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z",oiintSize2:"M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8\n-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z\nm502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2\nc0 110 84 276 504 276s502.4-166 502.4-276z",oiiintSize1:"M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6\n-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z\nm525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0\n85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z",oiiintSize2:"M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8\n-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z\nm770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1\nc0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z",rightarrow:"M0 241v40h399891c-47.3 35.3-84 78-110 128\n-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20\n 11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7\n 39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85\n-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n 151.7 139 205zm0 0v40h399900v-40z",rightbrace:"M400000 542l\n-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5\ns-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1\nc124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z",rightbraceunder:"M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3\n 28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237\n-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z",rightgroup:"M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0\n 3-1 3-3v-38c-76-158-257-219-435-219H0z",rightgroupunder:"M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18\n 0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z",rightharpoon:"M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3\n-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2\n-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58\n 69.2 92 94.5zm0 0v40h399900v-40z",rightharpoonplus:"M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11\n-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7\n 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z\nm0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z",rightharpoondown:"M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8\n 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5\n-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95\n-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z",rightharpoondownplus:"M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8\n 15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3\n 8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3\n-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z\nm0-194v40h400000v-40zm0 0v40h400000v-40z",righthook:"M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3\n 15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0\n-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21\n 66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z",rightlinesegment:"M399960 241 V94 h40 V428 h-40 V281 H0 v-40z\nM399960 241 V94 h40 V428 h-40 V281 H0 v-40z",rightToFrom:"M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23\n 1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32\n-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142\n-167z M100 147v40h399900v-40zM0 341v40h399900v-40z",twoheadleftarrow:"M0 167c68 40\n 115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69\n-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3\n-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19\n-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101\n 10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z",twoheadrightarrow:"M400000 167\nc-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3\n 41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42\n 18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333\n-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70\n 101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z",tilde1:"M200 55.538c-77 0-168 73.953-177 73.953-3 0-7\n-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0\n 114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0\n 4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128\n-68.267.847-113-73.952-191-73.952z",tilde2:"M344 55.266c-142 0-300.638 81.316-311.5 86.418\n-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9\n 31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114\nc1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751\n 181.476 676 181.476c-149 0-189-126.21-332-126.21z",tilde3:"M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457\n-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0\n 411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697\n 16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696\n -338 0-409-156.573-744-156.573z",tilde4:"M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345\n-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409\n 177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9\n 14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409\n -175.236-744-175.236z",vec:"M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5\n3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11\n10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63\n-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1\n-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59\nH213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359\nc-16-25.333-24-45-24-59z",widehat1:"M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22\nc-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z",widehat2:"M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widehat3:"M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widehat4:"M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widecheck1:"M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1,\n-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z",widecheck2:"M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",widecheck3:"M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",widecheck4:"M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",baraboveleftarrow:"M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202\nc4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5\nc-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130\ns-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47\n121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6\ns2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11\nc0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z\nM100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z",rightarrowabovebar:"M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32\n-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0\n13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39\n-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5\n-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z",baraboveshortleftharpoon:"M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17\nc2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21\nc-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40\nc-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z\nM0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z",rightharpoonaboveshortbar:"M0,241 l0,40c399126,0,399993,0,399993,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z",shortbaraboveleftharpoon:"M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9,\n1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7,\n-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z\nM93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z",shortrightharpoonabovebar:"M53,241l0,40c398570,0,399437,0,399437,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z"},T=function(){function t(t){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=t,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}var e=t.prototype;return e.hasClass=function(t){return c.contains(this.classes,t)},e.toNode=function(){for(var t=document.createDocumentFragment(),e=0;e"},N=function(){function t(t,e,r,a){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,B.call(this,t,r,a),this.children=e||[]}var e=t.prototype;return e.setAttribute=function(t,e){this.attributes[t]=e},e.hasClass=function(t){return c.contains(this.classes,t)},e.toNode=function(){return C.call(this,"span")},e.toMarkup=function(){return q.call(this,"span")},t}(),I=function(){function t(t,e,r,a){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,B.call(this,e,a),this.children=r||[],this.setAttribute("href",t)}var e=t.prototype;return e.setAttribute=function(t,e){this.attributes[t]=e},e.hasClass=function(t){return c.contains(this.classes,t)},e.toNode=function(){return C.call(this,"a")},e.toMarkup=function(){return q.call(this,"a")},t}(),R=function(){function t(t,e,r){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=e,this.src=t,this.classes=["mord"],this.style=r}var e=t.prototype;return e.hasClass=function(t){return c.contains(this.classes,t)},e.toNode=function(){var t=document.createElement("img");for(var e in t.src=this.src,t.alt=this.alt,t.className="mord",this.style)this.style.hasOwnProperty(e)&&(t.style[e]=this.style[e]);return t},e.toMarkup=function(){var t=""+this.alt+"=n[0]&&t<=n[1])return r.name}return null}(this.text.charCodeAt(0));h&&this.classes.push(h+"_fallback"),/[\xee\xef\xed\xec]/.test(this.text)&&(this.text=O[this.text])}var e=t.prototype;return e.hasClass=function(t){return c.contains(this.classes,t)},e.toNode=function(){var t=document.createTextNode(this.text),e=null;for(var r in this.italic>0&&((e=document.createElement("span")).style.marginRight=this.italic+"em"),this.classes.length>0&&((e=e||document.createElement("span")).className=A(this.classes)),this.style)this.style.hasOwnProperty(r)&&((e=e||document.createElement("span")).style[r]=this.style[r]);return e?(e.appendChild(t),e):t},e.toMarkup=function(){var t=!1,e="0&&(r+="margin-right:"+this.italic+"em;"),this.style)this.style.hasOwnProperty(a)&&(r+=c.hyphenate(a)+":"+this.style[a]+";");r&&(t=!0,e+=' style="'+c.escape(r)+'"');var n=c.escape(this.text);return t?(e+=">",e+=n,e+=""):n},t}(),L=function(){function t(t,e){this.children=void 0,this.attributes=void 0,this.children=t||[],this.attributes=e||{}}var e=t.prototype;return e.toNode=function(){var t=document.createElementNS("http://www.w3.org/2000/svg","svg");for(var e in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,e)&&t.setAttribute(e,this.attributes[e]);for(var r=0;r":""},t}(),P=function(){function t(t){this.attributes=void 0,this.attributes=t||{}}var e=t.prototype;return e.toNode=function(){var t=document.createElementNS("http://www.w3.org/2000/svg","line");for(var e in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,e)&&t.setAttribute(e,this.attributes[e]);return t},e.toMarkup=function(){var t="",">"),j("math",$,tt,":",":"),j("math",$,tt,"\u2248","\\approx",!0),j("math",$,tt,"\u2245","\\cong",!0),j("math",$,tt,"\u2265","\\ge"),j("math",$,tt,"\u2265","\\geq",!0),j("math",$,tt,"\u2190","\\gets"),j("math",$,tt,">","\\gt"),j("math",$,tt,"\u2208","\\in",!0),j("math",$,tt,"\ue020","\\@not"),j("math",$,tt,"\u2282","\\subset",!0),j("math",$,tt,"\u2283","\\supset",!0),j("math",$,tt,"\u2286","\\subseteq",!0),j("math",$,tt,"\u2287","\\supseteq",!0),j("math",Z,tt,"\u2288","\\nsubseteq",!0),j("math",Z,tt,"\u2289","\\nsupseteq",!0),j("math",$,tt,"\u22a8","\\models"),j("math",$,tt,"\u2190","\\leftarrow",!0),j("math",$,tt,"\u2264","\\le"),j("math",$,tt,"\u2264","\\leq",!0),j("math",$,tt,"<","\\lt"),j("math",$,tt,"\u2192","\\rightarrow",!0),j("math",$,tt,"\u2192","\\to"),j("math",Z,tt,"\u2271","\\ngeq",!0),j("math",Z,tt,"\u2270","\\nleq",!0),j("math",$,"spacing","\xa0","\\ "),j("math",$,"spacing","\xa0","~"),j("math",$,"spacing","\xa0","\\space"),j("math",$,"spacing","\xa0","\\nobreakspace"),j("text",$,"spacing","\xa0","\\ "),j("text",$,"spacing","\xa0","~"),j("text",$,"spacing","\xa0","\\space"),j("text",$,"spacing","\xa0","\\nobreakspace"),j("math",$,"spacing",null,"\\nobreak"),j("math",$,"spacing",null,"\\allowbreak"),j("math",$,"punct",",",","),j("math",$,"punct",";",";"),j("math",Z,K,"\u22bc","\\barwedge",!0),j("math",Z,K,"\u22bb","\\veebar",!0),j("math",$,K,"\u2299","\\odot",!0),j("math",$,K,"\u2295","\\oplus",!0),j("math",$,K,"\u2297","\\otimes",!0),j("math",$,"textord","\u2202","\\partial",!0),j("math",$,K,"\u2298","\\oslash",!0),j("math",Z,K,"\u229a","\\circledcirc",!0),j("math",Z,K,"\u22a1","\\boxdot",!0),j("math",$,K,"\u25b3","\\bigtriangleup"),j("math",$,K,"\u25bd","\\bigtriangledown"),j("math",$,K,"\u2020","\\dagger"),j("math",$,K,"\u22c4","\\diamond"),j("math",$,K,"\u22c6","\\star"),j("math",$,K,"\u25c3","\\triangleleft"),j("math",$,K,"\u25b9","\\triangleright"),j("math",$,"open","{","\\{"),j("text",$,"textord","{","\\{"),j("text",$,"textord","{","\\textbraceleft"),j("math",$,"close","}","\\}"),j("text",$,"textord","}","\\}"),j("text",$,"textord","}","\\textbraceright"),j("math",$,"open","{","\\lbrace"),j("math",$,"close","}","\\rbrace"),j("math",$,"open","[","\\lbrack"),j("text",$,"textord","[","\\lbrack"),j("math",$,"close","]","\\rbrack"),j("text",$,"textord","]","\\rbrack"),j("math",$,"open","(","\\lparen"),j("math",$,"close",")","\\rparen"),j("text",$,"textord","<","\\textless"),j("text",$,"textord",">","\\textgreater"),j("math",$,"open","\u230a","\\lfloor",!0),j("math",$,"close","\u230b","\\rfloor",!0),j("math",$,"open","\u2308","\\lceil",!0),j("math",$,"close","\u2309","\\rceil",!0),j("math",$,"textord","\\","\\backslash"),j("math",$,"textord","\u2223","|"),j("math",$,"textord","\u2223","\\vert"),j("text",$,"textord","|","\\textbar"),j("math",$,"textord","\u2225","\\|"),j("math",$,"textord","\u2225","\\Vert"),j("text",$,"textord","\u2225","\\textbardbl"),j("text",$,"textord","~","\\textasciitilde"),j("text",$,"textord","\\","\\textbackslash"),j("text",$,"textord","^","\\textasciicircum"),j("math",$,tt,"\u2191","\\uparrow",!0),j("math",$,tt,"\u21d1","\\Uparrow",!0),j("math",$,tt,"\u2193","\\downarrow",!0),j("math",$,tt,"\u21d3","\\Downarrow",!0),j("math",$,tt,"\u2195","\\updownarrow",!0),j("math",$,tt,"\u21d5","\\Updownarrow",!0),j("math",$,Q,"\u2210","\\coprod"),j("math",$,Q,"\u22c1","\\bigvee"),j("math",$,Q,"\u22c0","\\bigwedge"),j("math",$,Q,"\u2a04","\\biguplus"),j("math",$,Q,"\u22c2","\\bigcap"),j("math",$,Q,"\u22c3","\\bigcup"),j("math",$,Q,"\u222b","\\int"),j("math",$,Q,"\u222b","\\intop"),j("math",$,Q,"\u222c","\\iint"),j("math",$,Q,"\u222d","\\iiint"),j("math",$,Q,"\u220f","\\prod"),j("math",$,Q,"\u2211","\\sum"),j("math",$,Q,"\u2a02","\\bigotimes"),j("math",$,Q,"\u2a01","\\bigoplus"),j("math",$,Q,"\u2a00","\\bigodot"),j("math",$,Q,"\u222e","\\oint"),j("math",$,Q,"\u222f","\\oiint"),j("math",$,Q,"\u2230","\\oiiint"),j("math",$,Q,"\u2a06","\\bigsqcup"),j("math",$,Q,"\u222b","\\smallint"),j("text",$,"inner","\u2026","\\textellipsis"),j("math",$,"inner","\u2026","\\mathellipsis"),j("text",$,"inner","\u2026","\\ldots",!0),j("math",$,"inner","\u2026","\\ldots",!0),j("math",$,"inner","\u22ef","\\@cdots",!0),j("math",$,"inner","\u22f1","\\ddots",!0),j("math",$,"textord","\u22ee","\\varvdots"),j("math",$,"accent-token","\u02ca","\\acute"),j("math",$,"accent-token","\u02cb","\\grave"),j("math",$,"accent-token","\xa8","\\ddot"),j("math",$,"accent-token","~","\\tilde"),j("math",$,"accent-token","\u02c9","\\bar"),j("math",$,"accent-token","\u02d8","\\breve"),j("math",$,"accent-token","\u02c7","\\check"),j("math",$,"accent-token","^","\\hat"),j("math",$,"accent-token","\u20d7","\\vec"),j("math",$,"accent-token","\u02d9","\\dot"),j("math",$,"accent-token","\u02da","\\mathring"),j("math",$,J,"\u0131","\\imath",!0),j("math",$,J,"\u0237","\\jmath",!0),j("text",$,"textord","\u0131","\\i",!0),j("text",$,"textord","\u0237","\\j",!0),j("text",$,"textord","\xdf","\\ss",!0),j("text",$,"textord","\xe6","\\ae",!0),j("text",$,"textord","\xe6","\\ae",!0),j("text",$,"textord","\u0153","\\oe",!0),j("text",$,"textord","\xf8","\\o",!0),j("text",$,"textord","\xc6","\\AE",!0),j("text",$,"textord","\u0152","\\OE",!0),j("text",$,"textord","\xd8","\\O",!0),j("text",$,"accent-token","\u02ca","\\'"),j("text",$,"accent-token","\u02cb","\\`"),j("text",$,"accent-token","\u02c6","\\^"),j("text",$,"accent-token","\u02dc","\\~"),j("text",$,"accent-token","\u02c9","\\="),j("text",$,"accent-token","\u02d8","\\u"),j("text",$,"accent-token","\u02d9","\\."),j("text",$,"accent-token","\u02da","\\r"),j("text",$,"accent-token","\u02c7","\\v"),j("text",$,"accent-token","\xa8",'\\"'),j("text",$,"accent-token","\u02dd","\\H"),j("text",$,"accent-token","\u25ef","\\textcircled");var et={"--":!0,"---":!0,"``":!0,"''":!0};j("text",$,"textord","\u2013","--"),j("text",$,"textord","\u2013","\\textendash"),j("text",$,"textord","\u2014","---"),j("text",$,"textord","\u2014","\\textemdash"),j("text",$,"textord","\u2018","`"),j("text",$,"textord","\u2018","\\textquoteleft"),j("text",$,"textord","\u2019","'"),j("text",$,"textord","\u2019","\\textquoteright"),j("text",$,"textord","\u201c","``"),j("text",$,"textord","\u201c","\\textquotedblleft"),j("text",$,"textord","\u201d","''"),j("text",$,"textord","\u201d","\\textquotedblright"),j("math",$,"textord","\xb0","\\degree",!0),j("text",$,"textord","\xb0","\\degree"),j("text",$,"textord","\xb0","\\textdegree",!0),j("math",$,J,"\xa3","\\pounds"),j("math",$,J,"\xa3","\\mathsterling",!0),j("text",$,J,"\xa3","\\pounds"),j("text",$,J,"\xa3","\\textsterling",!0),j("math",Z,"textord","\u2720","\\maltese"),j("text",Z,"textord","\u2720","\\maltese"),j("text",$,"spacing","\xa0","\\ "),j("text",$,"spacing","\xa0"," "),j("text",$,"spacing","\xa0","~");for(var rt=0;rt<'0123456789/@."'.length;rt++){var at='0123456789/@."'.charAt(rt);j("math",$,"textord",at,at)}for(var nt=0;nt<'0123456789!@*()-=+[]<>|";:?/.,'.length;nt++){var it='0123456789!@*()-=+[]<>|";:?/.,'.charAt(nt);j("text",$,"textord",it,it)}for(var ot="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",st=0;st=5?0:t>=3?1:2]){var r=G[e]={cssEmPerMu:F.quad[e]/18};for(var a in F)F.hasOwnProperty(a)&&(r[a]=F[a][e])}return G[e]}(this.size)),this._fontMetrics},e.getColor=function(){return this.phantom?"transparent":this.color},t}();wt.BASESIZE=6;var kt=wt,St={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:1.00375,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:1.00375},Mt={ex:!0,em:!0,mu:!0},zt=function(t){return"string"!=typeof t&&(t=t.unit),t in St||t in Mt||"ex"===t},Tt=function(t,e){var r;if(t.unit in St)r=St[t.unit]/e.fontMetrics().ptPerEm/e.sizeMultiplier;else if("mu"===t.unit)r=e.fontMetrics().cssEmPerMu;else{var a;if(a=e.style.isTight()?e.havingStyle(e.style.text()):e,"ex"===t.unit)r=a.fontMetrics().xHeight;else{if("em"!==t.unit)throw new o("Invalid unit: '"+t.unit+"'");r=a.fontMetrics().quad}a!==e&&(r*=a.sizeMultiplier/e.sizeMultiplier)}return Math.min(t.number*r,e.maxSize)},At=["\\imath","\u0131","\\jmath","\u0237","\\pounds","\\mathsterling","\\textsterling","\xa3"],Bt=function(t,e,r){return _[r][t]&&_[r][t].replace&&(t=_[r][t].replace),{value:t,metrics:U(t,e,r)}},Ct=function(t,e,r,a,n){var i,o=Bt(t,e,r),s=o.metrics;if(t=o.value,s){var h=s.italic;("text"===r||a&&"mathit"===a.font)&&(h=0),i=new E(t,s.height,s.depth,h,s.skew,s.width,n)}else"undefined"!=typeof console&&console.warn("No character metrics for '"+t+"' in style '"+e+"' and mode '"+r+"'"),i=new E(t,0,0,0,0,0,n);if(a){i.maxFontSize=a.sizeMultiplier,a.style.isTight()&&i.classes.push("mtight");var l=a.getColor();l&&(i.style.color=l)}return i},qt=function(t,e){if(A(t.classes)!==A(e.classes)||t.skew!==e.skew||t.maxFontSize!==e.maxFontSize)return!1;for(var r in t.style)if(t.style.hasOwnProperty(r)&&t.style[r]!==e.style[r])return!1;for(var a in e.style)if(e.style.hasOwnProperty(a)&&t.style[a]!==e.style[a])return!1;return!0},Nt=function(t){for(var e=0,r=0,a=0,n=0;ne&&(e=i.height),i.depth>r&&(r=i.depth),i.maxFontSize>a&&(a=i.maxFontSize)}t.height=e,t.depth=r,t.maxFontSize=a},It=function(t,e,r,a){var n=new N(t,e,r,a);return Nt(n),n},Rt=function(t,e,r,a){return new N(t,e,r,a)},Ot=function(t){var e=new T(t);return Nt(e),e},Et=function(t,e,r){var a="";switch(t){case"amsrm":a="AMS";break;case"textrm":a="Main";break;case"textsf":a="SansSerif";break;case"texttt":a="Typewriter";break;default:a=t}return a+"-"+("textbf"===e&&"textit"===r?"BoldItalic":"textbf"===e?"Bold":"textit"===e?"Italic":"Regular")},Lt={mathbf:{variant:"bold",fontName:"Main-Bold"},mathrm:{variant:"normal",fontName:"Main-Regular"},textit:{variant:"italic",fontName:"Main-Italic"},mathit:{variant:"italic",fontName:"Main-Italic"},mathbb:{variant:"double-struck",fontName:"AMS-Regular"},mathcal:{variant:"script",fontName:"Caligraphic-Regular"},mathfrak:{variant:"fraktur",fontName:"Fraktur-Regular"},mathscr:{variant:"script",fontName:"Script-Regular"},mathsf:{variant:"sans-serif",fontName:"SansSerif-Regular"},mathtt:{variant:"monospace",fontName:"Typewriter-Regular"}},Ht={vec:["vec",.471,.714],oiintSize1:["oiintSize1",.957,.499],oiintSize2:["oiintSize2",1.472,.659],oiiintSize1:["oiiintSize1",1.304,.499],oiiintSize2:["oiiintSize2",1.98,.659]},Pt={fontMap:Lt,makeSymbol:Ct,mathsym:function(t,e,r,a){return void 0===a&&(a=[]),"boldsymbol"===r.font&&Bt(t,"Main-Bold",e).metrics?Ct(t,"Main-Bold",e,r,a.concat(["mathbf"])):"\\"===t||"main"===_[e][t].font?Ct(t,"Main-Regular",e,r,a):Ct(t,"AMS-Regular",e,r,a.concat(["amsrm"]))},makeSpan:It,makeSvgSpan:Rt,makeLineSpan:function(t,e,r){var a=It([t],[],e);return a.height=Math.max(r||e.fontMetrics().defaultRuleThickness,e.minRuleThickness),a.style.borderBottomWidth=a.height+"em",a.maxFontSize=1,a},makeAnchor:function(t,e,r,a){var n=new I(t,e,r,a);return Nt(n),n},makeFragment:Ot,wrapFragment:function(t,e){return t instanceof T?It([],[t],e):t},makeVList:function(t,e){for(var r=function(t){if("individualShift"===t.positionType){for(var e=t.children,r=[e[0]],a=-e[0].shift-e[0].elem.depth,n=a,i=1;i0&&(i.push(ue(o,e)),o=[]),i.push(n[s]));o.length>0&&i.push(ue(o,e)),r&&((a=ue(oe(r,e,!0))).classes=["tag"],i.push(a));var l=ee(["katex-html"],i);if(l.setAttribute("aria-hidden","true"),a){var m=a.children[0];m.style.height=l.height+l.depth+"em",m.style.verticalAlign=-l.depth+"em"}return l}function de(t){return new T(t)}var fe=function(){function t(t,e){this.type=void 0,this.attributes=void 0,this.children=void 0,this.type=t,this.attributes={},this.children=e||[]}var e=t.prototype;return e.setAttribute=function(t,e){this.attributes[t]=e},e.getAttribute=function(t){return this.attributes[t]},e.toNode=function(){var t=document.createElementNS("http://www.w3.org/1998/Math/MathML",this.type);for(var e in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,e)&&t.setAttribute(e,this.attributes[e]);for(var r=0;r"},e.toText=function(){return this.children.map(function(t){return t.toText()}).join("")},t}(),ge=function(){function t(t){this.text=void 0,this.text=t}var e=t.prototype;return e.toNode=function(){return document.createTextNode(this.text)},e.toMarkup=function(){return c.escape(this.toText())},e.toText=function(){return this.text},t}(),xe={MathNode:fe,TextNode:ge,SpaceNode:function(){function t(t){this.width=void 0,this.character=void 0,this.width=t,this.character=t>=.05555&&t<=.05556?"\u200a":t>=.1666&&t<=.1667?"\u2009":t>=.2222&&t<=.2223?"\u2005":t>=.2777&&t<=.2778?"\u2005\u200a":t>=-.05556&&t<=-.05555?"\u200a\u2063":t>=-.1667&&t<=-.1666?"\u2009\u2063":t>=-.2223&&t<=-.2222?"\u205f\u2063":t>=-.2778&&t<=-.2777?"\u2005\u2063":null}var e=t.prototype;return e.toNode=function(){if(this.character)return document.createTextNode(this.character);var t=document.createElementNS("http://www.w3.org/1998/Math/MathML","mspace");return t.setAttribute("width",this.width+"em"),t},e.toMarkup=function(){return this.character?""+this.character+"":''},e.toText=function(){return this.character?this.character:" "},t}(),newDocumentFragment:de},ve=function(t,e,r){return!_[e][t]||!_[e][t].replace||55349===t.charCodeAt(0)||et.hasOwnProperty(t)&&r&&(r.fontFamily&&"tt"===r.fontFamily.substr(4,2)||r.font&&"tt"===r.font.substr(4,2))||(t=_[e][t].replace),new xe.TextNode(t)},be=function(t){return 1===t.length?t[0]:new xe.MathNode("mrow",t)},ye=function(t,e){if("texttt"===e.fontFamily)return"monospace";if("textsf"===e.fontFamily)return"textit"===e.fontShape&&"textbf"===e.fontWeight?"sans-serif-bold-italic":"textit"===e.fontShape?"sans-serif-italic":"textbf"===e.fontWeight?"bold-sans-serif":"sans-serif";if("textit"===e.fontShape&&"textbf"===e.fontWeight)return"bold-italic";if("textit"===e.fontShape)return"italic";if("textbf"===e.fontWeight)return"bold";var r=e.font;if(!r||"mathnormal"===r)return null;var a=t.mode;if("mathit"===r)return"italic";if("boldsymbol"===r)return"bold-italic";if("mathbf"===r)return"bold";if("mathbb"===r)return"double-struck";if("mathfrak"===r)return"fraktur";if("mathscr"===r||"mathcal"===r)return"script";if("mathsf"===r)return"sans-serif";if("mathtt"===r)return"monospace";var n=t.text;return c.contains(["\\imath","\\jmath"],n)?null:(_[a][n]&&_[a][n].replace&&(n=_[a][n].replace),U(n,Pt.fontMap[r].fontName,a)?Pt.fontMap[r].variant:null)},we=function(t,e,r){if(1===t.length){var a=Se(t[0],e);return r&&a instanceof fe&&"mo"===a.type&&(a.setAttribute("lspace","0em"),a.setAttribute("rspace","0em")),[a]}for(var n,i=[],o=0;o0&&(p.text=p.text.slice(0,1)+"\u0338"+p.text.slice(1),i.pop())}}}i.push(s),n=s}return i},ke=function(t,e,r){return be(we(t,e,r))},Se=function(t,e){if(!t)return new xe.MathNode("mrow");if(Kt[t.type])return Kt[t.type](t,e);throw new o("Got group of unknown type: '"+t.type+"'")};function Me(t,e,r,a){var n,i=we(t,r);n=1===i.length&&i[0]instanceof fe&&c.contains(["mrow","mtable"],i[0].type)?i[0]:new xe.MathNode("mrow",i);var o=new xe.MathNode("annotation",[new xe.TextNode(e)]);o.setAttribute("encoding","application/x-tex");var s=new xe.MathNode("semantics",[n,o]),h=new xe.MathNode("math",[s]);h.setAttribute("xmlns","http://www.w3.org/1998/Math/MathML");var l=a?"katex":"katex-mathml";return Pt.makeSpan([l],[h])}var ze=function(t){return new kt({style:t.displayMode?w.DISPLAY:w.TEXT,maxSize:t.maxSize,minRuleThickness:t.minRuleThickness})},Te=function(t,e){if(e.displayMode){var r=["katex-display"];e.leqno&&r.push("leqno"),e.fleqn&&r.push("fleqn"),t=Pt.makeSpan(r,[t])}return t},Ae=function(t,e,r){var a,n=ze(r);if("mathml"===r.output)return Me(t,e,n,!0);if("html"===r.output){var i=pe(t,n);a=Pt.makeSpan(["katex"],[i])}else{var o=Me(t,e,n,!1),s=pe(t,n);a=Pt.makeSpan(["katex"],[o,s])}return Te(a,r)},Be={widehat:"^",widecheck:"\u02c7",widetilde:"~",utilde:"~",overleftarrow:"\u2190",underleftarrow:"\u2190",xleftarrow:"\u2190",overrightarrow:"\u2192",underrightarrow:"\u2192",xrightarrow:"\u2192",underbrace:"\u23df",overbrace:"\u23de",overgroup:"\u23e0",undergroup:"\u23e1",overleftrightarrow:"\u2194",underleftrightarrow:"\u2194",xleftrightarrow:"\u2194",Overrightarrow:"\u21d2",xRightarrow:"\u21d2",overleftharpoon:"\u21bc",xleftharpoonup:"\u21bc",overrightharpoon:"\u21c0",xrightharpoonup:"\u21c0",xLeftarrow:"\u21d0",xLeftrightarrow:"\u21d4",xhookleftarrow:"\u21a9",xhookrightarrow:"\u21aa",xmapsto:"\u21a6",xrightharpoondown:"\u21c1",xleftharpoondown:"\u21bd",xrightleftharpoons:"\u21cc",xleftrightharpoons:"\u21cb",xtwoheadleftarrow:"\u219e",xtwoheadrightarrow:"\u21a0",xlongequal:"=",xtofrom:"\u21c4",xrightleftarrows:"\u21c4",xrightequilibrium:"\u21cc",xleftequilibrium:"\u21cb"},Ce={overrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],overleftarrow:[["leftarrow"],.888,522,"xMinYMin"],underrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],underleftarrow:[["leftarrow"],.888,522,"xMinYMin"],xrightarrow:[["rightarrow"],1.469,522,"xMaxYMin"],xleftarrow:[["leftarrow"],1.469,522,"xMinYMin"],Overrightarrow:[["doublerightarrow"],.888,560,"xMaxYMin"],xRightarrow:[["doublerightarrow"],1.526,560,"xMaxYMin"],xLeftarrow:[["doubleleftarrow"],1.526,560,"xMinYMin"],overleftharpoon:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoonup:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoondown:[["leftharpoondown"],.888,522,"xMinYMin"],overrightharpoon:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoonup:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoondown:[["rightharpoondown"],.888,522,"xMaxYMin"],xlongequal:[["longequal"],.888,334,"xMinYMin"],xtwoheadleftarrow:[["twoheadleftarrow"],.888,334,"xMinYMin"],xtwoheadrightarrow:[["twoheadrightarrow"],.888,334,"xMaxYMin"],overleftrightarrow:[["leftarrow","rightarrow"],.888,522],overbrace:[["leftbrace","midbrace","rightbrace"],1.6,548],underbrace:[["leftbraceunder","midbraceunder","rightbraceunder"],1.6,548],underleftrightarrow:[["leftarrow","rightarrow"],.888,522],xleftrightarrow:[["leftarrow","rightarrow"],1.75,522],xLeftrightarrow:[["doubleleftarrow","doublerightarrow"],1.75,560],xrightleftharpoons:[["leftharpoondownplus","rightharpoonplus"],1.75,716],xleftrightharpoons:[["leftharpoonplus","rightharpoondownplus"],1.75,716],xhookleftarrow:[["leftarrow","righthook"],1.08,522],xhookrightarrow:[["lefthook","rightarrow"],1.08,522],overlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],underlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],overgroup:[["leftgroup","rightgroup"],.888,342],undergroup:[["leftgroupunder","rightgroupunder"],.888,342],xmapsto:[["leftmapsto","rightarrow"],1.5,522],xtofrom:[["leftToFrom","rightToFrom"],1.75,528],xrightleftarrows:[["baraboveleftarrow","rightarrowabovebar"],1.75,901],xrightequilibrium:[["baraboveshortleftharpoon","rightharpoonaboveshortbar"],1.75,716],xleftequilibrium:[["shortbaraboveleftharpoon","shortrightharpoonabovebar"],1.75,716]},qe=function(t){return"ordgroup"===t.type?t.body.length:1},Ne=function(t,e,r,a){var n,i=t.height+t.depth+2*r;if(/fbox|color/.test(e)){if(n=Pt.makeSpan(["stretchy",e],[],a),"fbox"===e){var o=a.color&&a.getColor();o&&(n.style.borderColor=o)}}else{var s=[];/^[bx]cancel$/.test(e)&&s.push(new P({x1:"0",y1:"0",x2:"100%",y2:"100%","stroke-width":"0.046em"})),/^x?cancel$/.test(e)&&s.push(new P({x1:"0",y1:"100%",x2:"100%",y2:"0","stroke-width":"0.046em"}));var h=new L(s,{width:"100%",height:i+"em"});n=Pt.makeSvgSpan([],[h],a)}return n.height=i,n.style.height=i+"em",n},Ie=function(t){var e=new xe.MathNode("mo",[new xe.TextNode(Be[t.substr(1)])]);return e.setAttribute("stretchy","true"),e},Re=function(t,e){var r=function(){var r=4e5,a=t.label.substr(1);if(c.contains(["widehat","widecheck","widetilde","utilde"],a)){var n,i,o,s=qe(t.base);if(s>5)"widehat"===a||"widecheck"===a?(n=420,r=2364,o=.42,i=a+"4"):(n=312,r=2340,o=.34,i="tilde4");else{var h=[1,1,2,2,3,3][s];"widehat"===a||"widecheck"===a?(r=[0,1062,2364,2364,2364][h],n=[0,239,300,360,420][h],o=[0,.24,.3,.3,.36,.42][h],i=a+h):(r=[0,600,1033,2339,2340][h],n=[0,260,286,306,312][h],o=[0,.26,.286,.3,.306,.34][h],i="tilde"+h)}var l=new H(i),m=new L([l],{width:"100%",height:o+"em",viewBox:"0 0 "+r+" "+n,preserveAspectRatio:"none"});return{span:Pt.makeSvgSpan([],[m],e),minWidth:0,height:o}}var u,p,d=[],f=Ce[a],g=f[0],x=f[1],v=f[2],b=v/1e3,y=g.length;if(1===y)u=["hide-tail"],p=[f[3]];else if(2===y)u=["halfarrow-left","halfarrow-right"],p=["xMinYMin","xMaxYMin"];else{if(3!==y)throw new Error("Correct katexImagesData or update code here to support\n "+y+" children.");u=["brace-left","brace-center","brace-right"],p=["xMinYMin","xMidYMin","xMaxYMin"]}for(var w=0;w0&&(a.style.minWidth=n+"em"),a},Oe=function(t,e){var r,a,n,i=Ft(t,"supsub");i?(r=(a=Dt(i.base,"accent")).base,i.base=r,n=function(t){if(t instanceof N)return t;throw new Error("Expected span but got "+String(t)+".")}(ce(i,e)),i.base=a):r=(a=Dt(t,"accent")).base;var o=ce(r,e.havingCrampedStyle()),s=0;if(a.isShifty&&c.isCharacterBox(r)){var h=c.getBaseElem(r);s=function(t){if(t instanceof E)return t;throw new Error("Expected symbolNode but got "+String(t)+".")}(ce(h,e.havingCrampedStyle())).skew}var l,m=Math.min(o.height,e.fontMetrics().xHeight);if(a.isStretchy)l=Re(a,e),l=Pt.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:o},{type:"elem",elem:l,wrapperClasses:["svg-align"],wrapperStyle:s>0?{width:"calc(100% - "+2*s+"em)",marginLeft:2*s+"em"}:void 0}]},e);else{var u,p;"\\vec"===a.label?(u=Pt.staticSvg("vec",e),p=Pt.svgData.vec[1]):((u=Pt.makeSymbol(a.label,"Main-Regular",a.mode,e)).italic=0,p=u.width),l=Pt.makeSpan(["accent-body"],[u]);var d="\\textcircled"===a.label;d&&(l.classes.push("accent-full"),m=o.height);var f=s;d||(f-=p/2),l.style.left=f+"em","\\textcircled"===a.label&&(l.style.top=".2em"),l=Pt.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:o},{type:"kern",size:-m},{type:"elem",elem:l}]},e)}var g=Pt.makeSpan(["mord","accent"],[l],e);return n?(n.children[0]=g,n.height=Math.max(g.height,n.height),n.classes[0]="mord",n):g},Ee=function(t,e){var r=t.isStretchy?Ie(t.label):new xe.MathNode("mo",[ve(t.label,t.mode)]),a=new xe.MathNode("mover",[Se(t.base,e),r]);return a.setAttribute("accent","true"),a},Le=new RegExp(["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring"].map(function(t){return"\\"+t}).join("|"));Jt({type:"accent",names:["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring","\\widecheck","\\widehat","\\widetilde","\\overrightarrow","\\overleftarrow","\\Overrightarrow","\\overleftrightarrow","\\overgroup","\\overlinesegment","\\overleftharpoon","\\overrightharpoon"],props:{numArgs:1},handler:function(t,e){var r=e[0],a=!Le.test(t.funcName),n=!a||"\\widehat"===t.funcName||"\\widetilde"===t.funcName||"\\widecheck"===t.funcName;return{type:"accent",mode:t.parser.mode,label:t.funcName,isStretchy:a,isShifty:n,base:r}},htmlBuilder:Oe,mathmlBuilder:Ee}),Jt({type:"accent",names:["\\'","\\`","\\^","\\~","\\=","\\u","\\.",'\\"',"\\r","\\H","\\v","\\textcircled"],props:{numArgs:1,allowedInText:!0,allowedInMath:!1},handler:function(t,e){var r=e[0];return{type:"accent",mode:t.parser.mode,label:t.funcName,isStretchy:!1,isShifty:!0,base:r}},htmlBuilder:Oe,mathmlBuilder:Ee}),Jt({type:"accentUnder",names:["\\underleftarrow","\\underrightarrow","\\underleftrightarrow","\\undergroup","\\underlinesegment","\\utilde"],props:{numArgs:1},handler:function(t,e){var r=t.parser,a=t.funcName,n=e[0];return{type:"accentUnder",mode:r.mode,label:a,base:n}},htmlBuilder:function(t,e){var r=ce(t.base,e),a=Re(t,e),n="\\utilde"===t.label?.12:0,i=Pt.makeVList({positionType:"bottom",positionData:a.height+n,children:[{type:"elem",elem:a,wrapperClasses:["svg-align"]},{type:"kern",size:n},{type:"elem",elem:r}]},e);return Pt.makeSpan(["mord","accentunder"],[i],e)},mathmlBuilder:function(t,e){var r=Ie(t.label),a=new xe.MathNode("munder",[Se(t.base,e),r]);return a.setAttribute("accentunder","true"),a}});var He=function(t){var e=new xe.MathNode("mpadded",t?[t]:[]);return e.setAttribute("width","+0.6em"),e.setAttribute("lspace","0.3em"),e};Jt({type:"xArrow",names:["\\xleftarrow","\\xrightarrow","\\xLeftarrow","\\xRightarrow","\\xleftrightarrow","\\xLeftrightarrow","\\xhookleftarrow","\\xhookrightarrow","\\xmapsto","\\xrightharpoondown","\\xrightharpoonup","\\xleftharpoondown","\\xleftharpoonup","\\xrightleftharpoons","\\xleftrightharpoons","\\xlongequal","\\xtwoheadrightarrow","\\xtwoheadleftarrow","\\xtofrom","\\xrightleftarrows","\\xrightequilibrium","\\xleftequilibrium"],props:{numArgs:1,numOptionalArgs:1},handler:function(t,e,r){var a=t.parser,n=t.funcName;return{type:"xArrow",mode:a.mode,label:n,body:e[0],below:r[0]}},htmlBuilder:function(t,e){var r,a=e.style,n=e.havingStyle(a.sup()),i=Pt.wrapFragment(ce(t.body,n,e),e);i.classes.push("x-arrow-pad"),t.below&&(n=e.havingStyle(a.sub()),(r=Pt.wrapFragment(ce(t.below,n,e),e)).classes.push("x-arrow-pad"));var o,s=Re(t,e),h=-e.fontMetrics().axisHeight+.5*s.height,l=-e.fontMetrics().axisHeight-.5*s.height-.111;if((i.depth>.25||"\\xleftequilibrium"===t.label)&&(l-=i.depth),r){var m=-e.fontMetrics().axisHeight+r.height+.5*s.height+.111;o=Pt.makeVList({positionType:"individualShift",children:[{type:"elem",elem:i,shift:l},{type:"elem",elem:s,shift:h},{type:"elem",elem:r,shift:m}]},e)}else o=Pt.makeVList({positionType:"individualShift",children:[{type:"elem",elem:i,shift:l},{type:"elem",elem:s,shift:h}]},e);return o.children[0].children[0].children[1].classes.push("svg-align"),Pt.makeSpan(["mrel","x-arrow"],[o],e)},mathmlBuilder:function(t,e){var r,a=Ie(t.label);if(t.body){var n=He(Se(t.body,e));if(t.below){var i=He(Se(t.below,e));r=new xe.MathNode("munderover",[a,i,n])}else r=new xe.MathNode("mover",[a,n])}else if(t.below){var o=He(Se(t.below,e));r=new xe.MathNode("munder",[a,o])}else r=He(),r=new xe.MathNode("mover",[a,r]);return r}}),Jt({type:"textord",names:["\\@char"],props:{numArgs:1,allowedInText:!0},handler:function(t,e){for(var r=t.parser,a=Dt(e[0],"ordgroup").body,n="",i=0;i","\\langle","\\rangle","/","\\backslash","\\lt","\\gt"],Ke=[0,1.2,1.8,2.4,3],Je=[{type:"small",style:w.SCRIPTSCRIPT},{type:"small",style:w.SCRIPT},{type:"small",style:w.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4}],Qe=[{type:"small",style:w.SCRIPTSCRIPT},{type:"small",style:w.SCRIPT},{type:"small",style:w.TEXT},{type:"stack"}],tr=[{type:"small",style:w.SCRIPTSCRIPT},{type:"small",style:w.SCRIPT},{type:"small",style:w.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4},{type:"stack"}],er=function(t){if("small"===t.type)return"Main-Regular";if("large"===t.type)return"Size"+t.size+"-Regular";if("stack"===t.type)return"Size4-Regular";throw new Error("Add support for delim type '"+t.type+"' here.")},rr=function(t,e,r,a){for(var n=Math.min(2,3-a.style.size);ne)return r[n]}return r[r.length-1]},ar=function(t,e,r,a,n,i){var o;"<"===t||"\\lt"===t||"\u27e8"===t?t="\\langle":">"!==t&&"\\gt"!==t&&"\u27e9"!==t||(t="\\rangle"),o=c.contains(Ze,t)?Je:c.contains(je,t)?tr:Qe;var s=rr(t,e,o,a);return"small"===s.type?function(t,e,r,a,n,i){var o=Pt.makeSymbol(t,"Main-Regular",n,a),s=Ve(o,e,a,i);return r&&Ue(s,a,e),s}(t,s.style,r,a,n,i):"large"===s.type?Ge(t,s.size,r,a,n,i):Xe(t,e,r,a,n,i)},nr=function(t,e){var r,a,n=e.havingBaseSizing(),i=rr("\\surd",t*n.sizeMultiplier,tr,n),o=n.sizeMultiplier,s=Math.max(0,e.minRuleThickness-e.fontMetrics().sqrtRuleThickness),h=0,l=0,m=0;return"small"===i.type?(t<1?o=1:t<1.4&&(o=.7),l=(1+s)/o,(r=_e("sqrtMain",h=(1+s+.08)/o,m=1e3+1e3*s+80,s,e)).style.minWidth="0.853em",a=.833/o):"large"===i.type?(m=1080*Ke[i.size],l=(Ke[i.size]+s)/o,h=(Ke[i.size]+s+.08)/o,(r=_e("sqrtSize"+i.size,h,m,s,e)).style.minWidth="1.02em",a=1/o):(h=t+s+.08,l=t+s,m=Math.floor(1e3*t+s)+80,(r=_e("sqrtTall",h,m,s,e)).style.minWidth="0.742em",a=1.056),r.height=l,r.style.height=h+"em",{span:r,advanceWidth:a,ruleWidth:(e.fontMetrics().sqrtRuleThickness+s)*o}},ir=function(t,e,r,a,n){if("<"===t||"\\lt"===t||"\u27e8"===t?t="\\langle":">"!==t&&"\\gt"!==t&&"\u27e9"!==t||(t="\\rangle"),c.contains(je,t)||c.contains(Ze,t))return Ge(t,e,!1,r,a,n);if(c.contains($e,t))return Xe(t,Ke[e],!1,r,a,n);throw new o("Illegal delimiter: '"+t+"'")},or=ar,sr=function(t,e,r,a,n,i){var o=a.fontMetrics().axisHeight*a.sizeMultiplier,s=5/a.fontMetrics().ptPerEm,h=Math.max(e-o,r+o),l=Math.max(h/500*901,2*h-s);return ar(t,l,!0,a,n,i)},hr={"\\bigl":{mclass:"mopen",size:1},"\\Bigl":{mclass:"mopen",size:2},"\\biggl":{mclass:"mopen",size:3},"\\Biggl":{mclass:"mopen",size:4},"\\bigr":{mclass:"mclose",size:1},"\\Bigr":{mclass:"mclose",size:2},"\\biggr":{mclass:"mclose",size:3},"\\Biggr":{mclass:"mclose",size:4},"\\bigm":{mclass:"mrel",size:1},"\\Bigm":{mclass:"mrel",size:2},"\\biggm":{mclass:"mrel",size:3},"\\Biggm":{mclass:"mrel",size:4},"\\big":{mclass:"mord",size:1},"\\Big":{mclass:"mord",size:2},"\\bigg":{mclass:"mord",size:3},"\\Bigg":{mclass:"mord",size:4}},lr=["(","\\lparen",")","\\rparen","[","\\lbrack","]","\\rbrack","\\{","\\lbrace","\\}","\\rbrace","\\lfloor","\\rfloor","\u230a","\u230b","\\lceil","\\rceil","\u2308","\u2309","<",">","\\langle","\u27e8","\\rangle","\u27e9","\\lt","\\gt","\\lvert","\\rvert","\\lVert","\\rVert","\\lgroup","\\rgroup","\u27ee","\u27ef","\\lmoustache","\\rmoustache","\u23b0","\u23b1","/","\\backslash","|","\\vert","\\|","\\Vert","\\uparrow","\\Uparrow","\\downarrow","\\Downarrow","\\updownarrow","\\Updownarrow","."];function mr(t,e){var r=Gt(t);if(r&&c.contains(lr,r.text))return r;throw new o("Invalid delimiter: '"+(r?r.text:JSON.stringify(t))+"' after '"+e.funcName+"'",t)}function cr(t){if(!t.body)throw new Error("Bug: The leftright ParseNode wasn't fully parsed.")}Jt({type:"delimsizing",names:["\\bigl","\\Bigl","\\biggl","\\Biggl","\\bigr","\\Bigr","\\biggr","\\Biggr","\\bigm","\\Bigm","\\biggm","\\Biggm","\\big","\\Big","\\bigg","\\Bigg"],props:{numArgs:1},handler:function(t,e){var r=mr(e[0],t);return{type:"delimsizing",mode:t.parser.mode,size:hr[t.funcName].size,mclass:hr[t.funcName].mclass,delim:r.text}},htmlBuilder:function(t,e){return"."===t.delim?Pt.makeSpan([t.mclass]):ir(t.delim,t.size,e,t.mode,[t.mclass])},mathmlBuilder:function(t){var e=[];"."!==t.delim&&e.push(ve(t.delim,t.mode));var r=new xe.MathNode("mo",e);return"mopen"===t.mclass||"mclose"===t.mclass?r.setAttribute("fence","true"):r.setAttribute("fence","false"),r}}),Jt({type:"leftright-right",names:["\\right"],props:{numArgs:1},handler:function(t,e){var r=t.parser.gullet.macros.get("\\current@color");if(r&&"string"!=typeof r)throw new o("\\current@color set to non-string in \\right");return{type:"leftright-right",mode:t.parser.mode,delim:mr(e[0],t).text,color:r}}}),Jt({type:"leftright",names:["\\left"],props:{numArgs:1},handler:function(t,e){var r=mr(e[0],t),a=t.parser;++a.leftrightDepth;var n=a.parseExpression(!1);--a.leftrightDepth,a.expect("\\right",!1);var i=Dt(a.parseFunction(),"leftright-right");return{type:"leftright",mode:a.mode,body:n,left:r.text,right:i.delim,rightColor:i.color}},htmlBuilder:function(t,e){cr(t);for(var r,a,n=oe(t.body,e,!0,["mopen","mclose"]),i=0,o=0,s=!1,h=0;h-1?"mpadded":"menclose",[Se(t.body,e)]);switch(t.label){case"\\cancel":a.setAttribute("notation","updiagonalstrike");break;case"\\bcancel":a.setAttribute("notation","downdiagonalstrike");break;case"\\sout":a.setAttribute("notation","horizontalstrike");break;case"\\fbox":a.setAttribute("notation","box");break;case"\\fcolorbox":case"\\colorbox":if(r=e.fontMetrics().fboxsep*e.fontMetrics().ptPerEm,a.setAttribute("width","+"+2*r+"pt"),a.setAttribute("height","+"+2*r+"pt"),a.setAttribute("lspace",r+"pt"),a.setAttribute("voffset",r+"pt"),"\\fcolorbox"===t.label){var n=Math.max(e.fontMetrics().fboxrule,e.minRuleThickness);a.setAttribute("style","border: "+n+"em solid "+String(t.borderColor))}break;case"\\xcancel":a.setAttribute("notation","updiagonalstrike downdiagonalstrike")}return t.backgroundColor&&a.setAttribute("mathbackground",t.backgroundColor),a};Jt({type:"enclose",names:["\\colorbox"],props:{numArgs:2,allowedInText:!0,greediness:3,argTypes:["color","text"]},handler:function(t,e,r){var a=t.parser,n=t.funcName,i=Dt(e[0],"color-token").color,o=e[1];return{type:"enclose",mode:a.mode,label:n,backgroundColor:i,body:o}},htmlBuilder:ur,mathmlBuilder:pr}),Jt({type:"enclose",names:["\\fcolorbox"],props:{numArgs:3,allowedInText:!0,greediness:3,argTypes:["color","color","text"]},handler:function(t,e,r){var a=t.parser,n=t.funcName,i=Dt(e[0],"color-token").color,o=Dt(e[1],"color-token").color,s=e[2];return{type:"enclose",mode:a.mode,label:n,backgroundColor:o,borderColor:i,body:s}},htmlBuilder:ur,mathmlBuilder:pr}),Jt({type:"enclose",names:["\\fbox"],props:{numArgs:1,argTypes:["hbox"],allowedInText:!0},handler:function(t,e){return{type:"enclose",mode:t.parser.mode,label:"\\fbox",body:e[0]}}}),Jt({type:"enclose",names:["\\cancel","\\bcancel","\\xcancel","\\sout"],props:{numArgs:1},handler:function(t,e,r){var a=t.parser,n=t.funcName,i=e[0];return{type:"enclose",mode:a.mode,label:n,body:i}},htmlBuilder:ur,mathmlBuilder:pr});var dr={};function fr(t){for(var e=t.type,r=t.names,a=t.props,n=t.handler,i=t.htmlBuilder,o=t.mathmlBuilder,s={type:e,numArgs:a.numArgs||0,greediness:1,allowedInText:!1,numOptionalArgs:0,handler:n},h=0;h0&&(b+=.25),l.push({pos:b,isDashed:t[e]})}for(y(i[0]),r=0;r0&&(M<(B+=v)&&(M=B),B=0),t.addJot&&(M+=f),z.height=S,z.depth=M,b+=S,z.pos=b,b+=M+B,h[r]=z,y(i[r+1])}var C,q,N=b/2+e.fontMetrics().axisHeight,I=t.cols||[],R=[];for(a=0,q=0;a=s)){var P=void 0;(a>0||t.hskipBeforeAndAfter)&&0!==(P=c.deflt(O.pregap,p))&&((C=Pt.makeSpan(["arraycolsep"],[])).style.width=P+"em",R.push(C));var D=[];for(r=0;r0){for(var G=Pt.makeLineSpan("hline",e,m),Y=Pt.makeLineSpan("hdashline",e,m),W=[{type:"elem",elem:h,shift:0}];l.length>0;){var X=l.pop(),_=X.pos-N;X.isDashed?W.push({type:"elem",elem:Y,shift:_}):W.push({type:"elem",elem:G,shift:_})}h=Pt.makeVList({positionType:"individualShift",children:W},e)}return Pt.makeSpan(["mord"],[h],e)},yr={c:"center ",l:"left ",r:"right "},wr=function(t,e){var r=new xe.MathNode("mtable",t.body.map(function(t){return new xe.MathNode("mtr",t.map(function(t){return new xe.MathNode("mtd",[Se(t,e)])}))})),a=.5===t.arraystretch?.1:.16+t.arraystretch-1+(t.addJot?.09:0);r.setAttribute("rowspacing",a+"em");var n="",i="";if(t.cols){var o=t.cols,s="",h=!1,l=0,m=o.length;"separator"===o[0].type&&(n+="top ",l=1),"separator"===o[o.length-1].type&&(n+="bottom ",m-=1);for(var c=l;c0?"left ":"",n+=g[g.length-1].length>0?"right ":"";for(var x=1;x0&&c&&(d=1),a[u]={type:"align",align:p,pregap:d,postgap:0}}return n.colSeparationType=c?"align":"alignat",n};fr({type:"array",names:["array","darray"],props:{numArgs:1},handler:function(t,e){var r={cols:(Gt(e[0])?[e[0]]:Dt(e[0],"ordgroup").body).map(function(t){var e=Ut(t).text;if(-1!=="lcr".indexOf(e))return{type:"align",align:e};if("|"===e)return{type:"separator",separator:"|"};if(":"===e)return{type:"separator",separator:":"};throw new o("Unknown column alignment: "+e,t)}),hskipBeforeAndAfter:!0};return xr(t.parser,r,vr(t.envName))},htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["matrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix"],props:{numArgs:0},handler:function(t){var e={matrix:null,pmatrix:["(",")"],bmatrix:["[","]"],Bmatrix:["\\{","\\}"],vmatrix:["|","|"],Vmatrix:["\\Vert","\\Vert"]}[t.envName],r=xr(t.parser,{hskipBeforeAndAfter:!1},vr(t.envName));return e?{type:"leftright",mode:t.mode,body:[r],left:e[0],right:e[1],rightColor:void 0}:r},htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["smallmatrix"],props:{numArgs:0},handler:function(t){var e=xr(t.parser,{arraystretch:.5},"script");return e.colSeparationType="small",e},htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["subarray"],props:{numArgs:1},handler:function(t,e){var r=(Gt(e[0])?[e[0]]:Dt(e[0],"ordgroup").body).map(function(t){var e=Ut(t).text;if(-1!=="lc".indexOf(e))return{type:"align",align:e};throw new o("Unknown column alignment: "+e,t)});if(r.length>1)throw new o("{subarray} can contain only one column");var a={cols:r,hskipBeforeAndAfter:!1,arraystretch:.5};if((a=xr(t.parser,a,"script")).body[0].length>1)throw new o("{subarray} can contain only one column");return a},htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["cases","dcases"],props:{numArgs:0},handler:function(t){var e=xr(t.parser,{arraystretch:1.2,cols:[{type:"align",align:"l",pregap:0,postgap:1},{type:"align",align:"l",pregap:0,postgap:0}]},vr(t.envName));return{type:"leftright",mode:t.mode,body:[e],left:"\\{",right:".",rightColor:void 0}},htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["aligned"],props:{numArgs:0},handler:kr,htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["gathered"],props:{numArgs:0},handler:function(t){return xr(t.parser,{cols:[{type:"align",align:"c"}],addJot:!0},"display")},htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["alignedat"],props:{numArgs:1},handler:kr,htmlBuilder:br,mathmlBuilder:wr}),Jt({type:"text",names:["\\hline","\\hdashline"],props:{numArgs:0,allowedInText:!0,allowedInMath:!0},handler:function(t,e){throw new o(t.funcName+" valid only within array environment")}});var Sr=dr;Jt({type:"environment",names:["\\begin","\\end"],props:{numArgs:1,argTypes:["text"]},handler:function(t,e){var r=t.parser,a=t.funcName,n=e[0];if("ordgroup"!==n.type)throw new o("Invalid environment name",n);for(var i="",s=0;s=w.SCRIPT.id?r.text():w.DISPLAY:"text"===t&&r.size===w.DISPLAY.size?r=w.TEXT:"script"===t?r=w.SCRIPT:"scriptscript"===t&&(r=w.SCRIPTSCRIPT),r},Ir=function(t,e){var r,a=Nr(t.size,e.style),n=a.fracNum(),i=a.fracDen();r=e.havingStyle(n);var o=ce(t.numer,r,e);if(t.continued){var s=8.5/e.fontMetrics().ptPerEm,h=3.5/e.fontMetrics().ptPerEm;o.height=o.height0?3*c:7*c,d=e.fontMetrics().denom1):(m>0?(u=e.fontMetrics().num2,p=c):(u=e.fontMetrics().num3,p=3*c),d=e.fontMetrics().denom2),l){var y=e.fontMetrics().axisHeight;u-o.depth-(y+.5*m)0&&(e="."===(e=t)?null:e),e};Jt({type:"genfrac",names:["\\genfrac"],props:{numArgs:6,greediness:6,argTypes:["math","math","size","text","math","math"]},handler:function(t,e){var r=t.parser,a=e[4],n=e[5],i=Ft(e[0],"atom");i&&(i=Vt(e[0],"open"));var o=i?Er(i.text):null,s=Ft(e[1],"atom");s&&(s=Vt(e[1],"close"));var h,l=s?Er(s.text):null,m=Dt(e[2],"size"),c=null;h=!!m.isBlank||(c=m.value).number>0;var u="auto",p=Ft(e[3],"ordgroup");if(p){if(p.body.length>0){var d=Dt(p.body[0],"textord");u=Or[Number(d.text)]}}else p=Dt(e[3],"textord"),u=Or[Number(p.text)];return{type:"genfrac",mode:r.mode,numer:a,denom:n,continued:!1,hasBarLine:h,barSize:c,leftDelim:o,rightDelim:l,size:u}},htmlBuilder:Ir,mathmlBuilder:Rr}),Jt({type:"infix",names:["\\above"],props:{numArgs:1,argTypes:["size"],infix:!0},handler:function(t,e){var r=t.parser,a=(t.funcName,t.token);return{type:"infix",mode:r.mode,replaceWith:"\\\\abovefrac",size:Dt(e[0],"size").value,token:a}}}),Jt({type:"genfrac",names:["\\\\abovefrac"],props:{numArgs:3,argTypes:["math","size","math"]},handler:function(t,e){var r=t.parser,a=(t.funcName,e[0]),n=function(t){if(!t)throw new Error("Expected non-null, but got "+String(t));return t}(Dt(e[1],"infix").size),i=e[2],o=n.number>0;return{type:"genfrac",mode:r.mode,numer:a,denom:i,continued:!1,hasBarLine:o,barSize:n,leftDelim:null,rightDelim:null,size:"auto"}},htmlBuilder:Ir,mathmlBuilder:Rr});var Lr=function(t,e){var r,a,n=e.style,i=Ft(t,"supsub");i?(r=i.sup?ce(i.sup,e.havingStyle(n.sup()),e):ce(i.sub,e.havingStyle(n.sub()),e),a=Dt(i.base,"horizBrace")):a=Dt(t,"horizBrace");var o,s=ce(a.base,e.havingBaseStyle(w.DISPLAY)),h=Re(a,e);if(a.isOver?(o=Pt.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:s},{type:"kern",size:.1},{type:"elem",elem:h}]},e)).children[0].children[0].children[1].classes.push("svg-align"):(o=Pt.makeVList({positionType:"bottom",positionData:s.depth+.1+h.height,children:[{type:"elem",elem:h},{type:"kern",size:.1},{type:"elem",elem:s}]},e)).children[0].children[0].children[0].classes.push("svg-align"),r){var l=Pt.makeSpan(["mord",a.isOver?"mover":"munder"],[o],e);o=a.isOver?Pt.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:l},{type:"kern",size:.2},{type:"elem",elem:r}]},e):Pt.makeVList({positionType:"bottom",positionData:l.depth+.2+r.height+r.depth,children:[{type:"elem",elem:r},{type:"kern",size:.2},{type:"elem",elem:l}]},e)}return Pt.makeSpan(["mord",a.isOver?"mover":"munder"],[o],e)};Jt({type:"horizBrace",names:["\\overbrace","\\underbrace"],props:{numArgs:1},handler:function(t,e){var r=t.parser,a=t.funcName;return{type:"horizBrace",mode:r.mode,label:a,isOver:/^\\over/.test(a),base:e[0]}},htmlBuilder:Lr,mathmlBuilder:function(t,e){var r=Ie(t.label);return new xe.MathNode(t.isOver?"mover":"munder",[Se(t.base,e),r])}}),Jt({type:"href",names:["\\href"],props:{numArgs:2,argTypes:["url","original"],allowedInText:!0},handler:function(t,e){var r=t.parser,a=e[1],n=Dt(e[0],"url").url;return r.settings.isTrusted({command:"\\href",url:n})?{type:"href",mode:r.mode,href:n,body:te(a)}:r.formatUnsupportedCmd("\\href")},htmlBuilder:function(t,e){var r=oe(t.body,e,!1);return Pt.makeAnchor(t.href,[],r,e)},mathmlBuilder:function(t,e){var r=ke(t.body,e);return r instanceof fe||(r=new fe("mrow",[r])),r.setAttribute("href",t.href),r}}),Jt({type:"href",names:["\\url"],props:{numArgs:1,argTypes:["url"],allowedInText:!0},handler:function(t,e){var r=t.parser,a=Dt(e[0],"url").url;if(!r.settings.isTrusted({command:"\\url",url:a}))return r.formatUnsupportedCmd("\\url");for(var n=[],i=0;i0&&(a=Tt(t.totalheight,e)-r,a=Number(a.toFixed(2)));var n=0;t.width.number>0&&(n=Tt(t.width,e));var i={height:r+a+"em"};n>0&&(i.width=n+"em"),a>0&&(i.verticalAlign=-a+"em");var o=new R(t.src,t.alt,i);return o.height=r,o.depth=a,o},mathmlBuilder:function(t,e){var r=new xe.MathNode("mglyph",[]);r.setAttribute("alt",t.alt);var a=Tt(t.height,e),n=0;if(t.totalheight.number>0&&(n=(n=Tt(t.totalheight,e)-a).toFixed(2),r.setAttribute("valign","-"+n+"em")),r.setAttribute("height",a+n+"em"),t.width.number>0){var i=Tt(t.width,e);r.setAttribute("width",i+"em")}return r.setAttribute("src",t.src),r}}),Jt({type:"kern",names:["\\kern","\\mkern","\\hskip","\\mskip"],props:{numArgs:1,argTypes:["size"],allowedInText:!0},handler:function(t,e){var r=t.parser,a=t.funcName,n=Dt(e[0],"size");if(r.settings.strict){var i="m"===a[1],o="mu"===n.value.unit;i?(o||r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+a+" supports only mu units, not "+n.value.unit+" units"),"math"!==r.mode&&r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+a+" works only in math mode")):o&&r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+a+" doesn't support mu units")}return{type:"kern",mode:r.mode,dimension:n.value}},htmlBuilder:function(t,e){return Pt.makeGlue(t.dimension,e)},mathmlBuilder:function(t,e){var r=Tt(t.dimension,e);return new xe.SpaceNode(r)}}),Jt({type:"lap",names:["\\mathllap","\\mathrlap","\\mathclap"],props:{numArgs:1,allowedInText:!0},handler:function(t,e){var r=t.parser,a=t.funcName,n=e[0];return{type:"lap",mode:r.mode,alignment:a.slice(5),body:n}},htmlBuilder:function(t,e){var r;"clap"===t.alignment?(r=Pt.makeSpan([],[ce(t.body,e)]),r=Pt.makeSpan(["inner"],[r],e)):r=Pt.makeSpan(["inner"],[ce(t.body,e)]);var a=Pt.makeSpan(["fix"],[]),n=Pt.makeSpan([t.alignment],[r,a],e),i=Pt.makeSpan(["strut"]);return i.style.height=n.height+n.depth+"em",i.style.verticalAlign=-n.depth+"em",n.children.unshift(i),n=Pt.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:n}]},e),Pt.makeSpan(["mord"],[n],e)},mathmlBuilder:function(t,e){var r=new xe.MathNode("mpadded",[Se(t.body,e)]);if("rlap"!==t.alignment){var a="llap"===t.alignment?"-1":"-0.5";r.setAttribute("lspace",a+"width")}return r.setAttribute("width","0px"),r}}),Jt({type:"styling",names:["\\(","$"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1,consumeMode:"math"},handler:function(t,e){var r=t.funcName,a=t.parser,n=a.mode;a.switchMode("math");var i="\\("===r?"\\)":"$",o=a.parseExpression(!1,i);return a.expect(i,!1),a.switchMode(n),a.consume(),{type:"styling",mode:a.mode,style:"text",body:o}}}),Jt({type:"text",names:["\\)","\\]"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler:function(t,e){throw new o("Mismatched "+t.funcName)}});var Pr=function(t,e){switch(e.style.size){case w.DISPLAY.size:return t.display;case w.TEXT.size:return t.text;case w.SCRIPT.size:return t.script;case w.SCRIPTSCRIPT.size:return t.scriptscript;default:return t.text}};Jt({type:"mathchoice",names:["\\mathchoice"],props:{numArgs:4},handler:function(t,e){return{type:"mathchoice",mode:t.parser.mode,display:te(e[0]),text:te(e[1]),script:te(e[2]),scriptscript:te(e[3])}},htmlBuilder:function(t,e){var r=Pr(t,e),a=oe(r,e,!1);return Pt.makeFragment(a)},mathmlBuilder:function(t,e){var r=Pr(t,e);return ke(r,e)}});var Dr=function(t,e,r,a,n,i,o){var s,h,l;if(t=Pt.makeSpan([],[t]),e){var m=ce(e,a.havingStyle(n.sup()),a);h={elem:m,kern:Math.max(a.fontMetrics().bigOpSpacing1,a.fontMetrics().bigOpSpacing3-m.depth)}}if(r){var c=ce(r,a.havingStyle(n.sub()),a);s={elem:c,kern:Math.max(a.fontMetrics().bigOpSpacing2,a.fontMetrics().bigOpSpacing4-c.height)}}if(h&&s){var u=a.fontMetrics().bigOpSpacing5+s.elem.height+s.elem.depth+s.kern+t.depth+o;l=Pt.makeVList({positionType:"bottom",positionData:u,children:[{type:"kern",size:a.fontMetrics().bigOpSpacing5},{type:"elem",elem:s.elem,marginLeft:-i+"em"},{type:"kern",size:s.kern},{type:"elem",elem:t},{type:"kern",size:h.kern},{type:"elem",elem:h.elem,marginLeft:i+"em"},{type:"kern",size:a.fontMetrics().bigOpSpacing5}]},a)}else if(s){var p=t.height-o;l=Pt.makeVList({positionType:"top",positionData:p,children:[{type:"kern",size:a.fontMetrics().bigOpSpacing5},{type:"elem",elem:s.elem,marginLeft:-i+"em"},{type:"kern",size:s.kern},{type:"elem",elem:t}]},a)}else{if(!h)return t;var d=t.depth+o;l=Pt.makeVList({positionType:"bottom",positionData:d,children:[{type:"elem",elem:t},{type:"kern",size:h.kern},{type:"elem",elem:h.elem,marginLeft:i+"em"},{type:"kern",size:a.fontMetrics().bigOpSpacing5}]},a)}return Pt.makeSpan(["mop","op-limits"],[l],a)},Fr=["\\smallint"],Vr=function(t,e){var r,a,n,i=!1,o=Ft(t,"supsub");o?(r=o.sup,a=o.sub,n=Dt(o.base,"op"),i=!0):n=Dt(t,"op");var s,h=e.style,l=!1;if(h.size===w.DISPLAY.size&&n.symbol&&!c.contains(Fr,n.name)&&(l=!0),n.symbol){var m=l?"Size2-Regular":"Size1-Regular",u="";if("\\oiint"!==n.name&&"\\oiiint"!==n.name||(u=n.name.substr(1),n.name="oiint"===u?"\\iint":"\\iiint"),s=Pt.makeSymbol(n.name,m,"math",e,["mop","op-symbol",l?"large-op":"small-op"]),u.length>0){var p=s.italic,d=Pt.staticSvg(u+"Size"+(l?"2":"1"),e);s=Pt.makeVList({positionType:"individualShift",children:[{type:"elem",elem:s,shift:0},{type:"elem",elem:d,shift:l?.08:0}]},e),n.name="\\"+u,s.classes.unshift("mop"),s.italic=p}}else if(n.body){var f=oe(n.body,e,!0);1===f.length&&f[0]instanceof E?(s=f[0]).classes[0]="mop":s=Pt.makeSpan(["mop"],Pt.tryCombineChars(f),e)}else{for(var g=[],x=1;x0){for(var h=n.body.map(function(t){var e=t.text;return"string"==typeof e?{type:"textord",mode:t.mode,text:e}:t}),l=oe(h,e.withFont("mathrm"),!0),m=0;m=0?s.setAttribute("height","+"+n+"em"):(s.setAttribute("height",n+"em"),s.setAttribute("depth","+"+-n+"em")),s.setAttribute("voffset",n+"em"),s}});var _r=["\\tiny","\\sixptsize","\\scriptsize","\\footnotesize","\\small","\\normalsize","\\large","\\Large","\\LARGE","\\huge","\\Huge"];Jt({type:"sizing",names:_r,props:{numArgs:0,allowedInText:!0},handler:function(t,e){var r=t.breakOnTokenText,a=t.funcName,n=t.parser,i=n.parseExpression(!1,r);return{type:"sizing",mode:n.mode,size:_r.indexOf(a)+1,body:i}},htmlBuilder:function(t,e){var r=e.havingSize(t.size);return Xr(t.body,r,e)},mathmlBuilder:function(t,e){var r=e.havingSize(t.size),a=we(t.body,r),n=new xe.MathNode("mstyle",a);return n.setAttribute("mathsize",r.sizeMultiplier+"em"),n}}),Jt({type:"smash",names:["\\smash"],props:{numArgs:1,numOptionalArgs:1,allowedInText:!0},handler:function(t,e,r){var a=t.parser,n=!1,i=!1,o=r[0]&&Dt(r[0],"ordgroup");if(o)for(var s="",h=0;hr.height+r.depth+i&&(i=(i+c-r.height-r.depth)/2);var u=h.height-r.height-i-l;r.style.paddingLeft=m+"em";var p=Pt.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:r,wrapperClasses:["svg-align"]},{type:"kern",size:-(r.height+u)},{type:"elem",elem:h},{type:"kern",size:l}]},e);if(t.index){var d=e.havingStyle(w.SCRIPTSCRIPT),f=ce(t.index,d,e),g=.6*(p.height-p.depth),x=Pt.makeVList({positionType:"shift",positionData:-g,children:[{type:"elem",elem:f}]},e),v=Pt.makeSpan(["root"],[x]);return Pt.makeSpan(["mord","sqrt"],[v,p],e)}return Pt.makeSpan(["mord","sqrt"],[p],e)},mathmlBuilder:function(t,e){var r=t.body,a=t.index;return a?new xe.MathNode("mroot",[Se(r,e),Se(a,e)]):new xe.MathNode("msqrt",[Se(r,e)])}});var jr={display:w.DISPLAY,text:w.TEXT,script:w.SCRIPT,scriptscript:w.SCRIPTSCRIPT};Jt({type:"styling",names:["\\displaystyle","\\textstyle","\\scriptstyle","\\scriptscriptstyle"],props:{numArgs:0,allowedInText:!0},handler:function(t,e){var r=t.breakOnTokenText,a=t.funcName,n=t.parser,i=n.parseExpression(!0,r),o=a.slice(1,a.length-5);return{type:"styling",mode:n.mode,style:o,body:i}},htmlBuilder:function(t,e){var r=jr[t.style],a=e.havingStyle(r).withFont("");return Xr(t.body,a,e)},mathmlBuilder:function(t,e){var r=jr[t.style],a=e.havingStyle(r),n=we(t.body,a),i=new xe.MathNode("mstyle",n),o={display:["0","true"],text:["0","false"],script:["1","false"],scriptscript:["2","false"]}[t.style];return i.setAttribute("scriptlevel",o[0]),i.setAttribute("displaystyle",o[1]),i}});Qt({type:"supsub",htmlBuilder:function(t,e){var r=function(t,e){var r=t.base;return r?"op"===r.type?r.limits&&(e.style.size===w.DISPLAY.size||r.alwaysHandleSupSub)?Vr:null:"operatorname"===r.type?r.alwaysHandleSupSub&&(e.style.size===w.DISPLAY.size||r.limits)?Wr:null:"accent"===r.type?c.isCharacterBox(r.base)?Oe:null:"horizBrace"===r.type&&!t.sub===r.isOver?Lr:null:null}(t,e);if(r)return r(t,e);var a,n,i,o=t.base,s=t.sup,h=t.sub,l=ce(o,e),m=e.fontMetrics(),u=0,p=0,d=o&&c.isCharacterBox(o);if(s){var f=e.havingStyle(e.style.sup());a=ce(s,f,e),d||(u=l.height-f.fontMetrics().supDrop*f.sizeMultiplier/e.sizeMultiplier)}if(h){var g=e.havingStyle(e.style.sub());n=ce(h,g,e),d||(p=l.depth+g.fontMetrics().subDrop*g.sizeMultiplier/e.sizeMultiplier)}i=e.style===w.DISPLAY?m.sup1:e.style.cramped?m.sup3:m.sup2;var x,v=e.sizeMultiplier,b=.5/m.ptPerEm/v+"em",y=null;if(n){var k=t.base&&"op"===t.base.type&&t.base.name&&("\\oiint"===t.base.name||"\\oiiint"===t.base.name);(l instanceof E||k)&&(y=-l.italic+"em")}if(a&&n){u=Math.max(u,i,a.depth+.25*m.xHeight),p=Math.max(p,m.sub2);var S=4*m.defaultRuleThickness;if(u-a.depth-(n.height-p)0&&(u+=M,p-=M)}var z=[{type:"elem",elem:n,shift:p,marginRight:b,marginLeft:y},{type:"elem",elem:a,shift:-u,marginRight:b}];x=Pt.makeVList({positionType:"individualShift",children:z},e)}else if(n){p=Math.max(p,m.sub1,n.height-.8*m.xHeight);var T=[{type:"elem",elem:n,marginLeft:y,marginRight:b}];x=Pt.makeVList({positionType:"shift",positionData:p,children:T},e)}else{if(!a)throw new Error("supsub must have either sup or sub.");u=Math.max(u,i,a.depth+.25*m.xHeight),x=Pt.makeVList({positionType:"shift",positionData:-u,children:[{type:"elem",elem:a,marginRight:b}]},e)}var A=le(l,"right")||"mord";return Pt.makeSpan([A],[l,Pt.makeSpan(["msupsub"],[x])],e)},mathmlBuilder:function(t,e){var r,a=!1,n=Ft(t.base,"horizBrace");n&&!!t.sup===n.isOver&&(a=!0,r=n.isOver),!t.base||"op"!==t.base.type&&"operatorname"!==t.base.type||(t.base.parentIsSupSub=!0);var i,o=[Se(t.base,e)];if(t.sub&&o.push(Se(t.sub,e)),t.sup&&o.push(Se(t.sup,e)),a)i=r?"mover":"munder";else if(t.sub)if(t.sup){var s=t.base;i=s&&"op"===s.type&&s.limits&&e.style===w.DISPLAY?"munderover":s&&"operatorname"===s.type&&s.alwaysHandleSupSub&&(e.style===w.DISPLAY||s.limits)?"munderover":"msubsup"}else{var h=t.base;i=h&&"op"===h.type&&h.limits&&(e.style===w.DISPLAY||h.alwaysHandleSupSub)?"munder":h&&"operatorname"===h.type&&h.alwaysHandleSupSub&&(h.limits||e.style===w.DISPLAY)?"munder":"msub"}else{var l=t.base;i=l&&"op"===l.type&&l.limits&&(e.style===w.DISPLAY||l.alwaysHandleSupSub)?"mover":l&&"operatorname"===l.type&&l.alwaysHandleSupSub&&(l.limits||e.style===w.DISPLAY)?"mover":"msup"}return new xe.MathNode(i,o)}}),Qt({type:"atom",htmlBuilder:function(t,e){return Pt.mathsym(t.text,t.mode,e,["m"+t.family])},mathmlBuilder:function(t,e){var r=new xe.MathNode("mo",[ve(t.text,t.mode)]);if("bin"===t.family){var a=ye(t,e);"bold-italic"===a&&r.setAttribute("mathvariant",a)}else"punct"===t.family?r.setAttribute("separator","true"):"open"!==t.family&&"close"!==t.family||r.setAttribute("stretchy","false");return r}});var $r={mi:"italic",mn:"normal",mtext:"normal"};Qt({type:"mathord",htmlBuilder:function(t,e){return Pt.makeOrd(t,e,"mathord")},mathmlBuilder:function(t,e){var r=new xe.MathNode("mi",[ve(t.text,t.mode,e)]),a=ye(t,e)||"italic";return a!==$r[r.type]&&r.setAttribute("mathvariant",a),r}}),Qt({type:"textord",htmlBuilder:function(t,e){return Pt.makeOrd(t,e,"textord")},mathmlBuilder:function(t,e){var r,a=ve(t.text,t.mode,e),n=ye(t,e)||"normal";return r="text"===t.mode?new xe.MathNode("mtext",[a]):/[0-9]/.test(t.text)?new xe.MathNode("mn",[a]):"\\prime"===t.text?new xe.MathNode("mo",[a]):new xe.MathNode("mi",[a]),n!==$r[r.type]&&r.setAttribute("mathvariant",n),r}});var Zr={"\\nobreak":"nobreak","\\allowbreak":"allowbreak"},Kr={" ":{},"\\ ":{},"~":{className:"nobreak"},"\\space":{},"\\nobreakspace":{className:"nobreak"}};Qt({type:"spacing",htmlBuilder:function(t,e){if(Kr.hasOwnProperty(t.text)){var r=Kr[t.text].className||"";if("text"===t.mode){var a=Pt.makeOrd(t,e,"textord");return a.classes.push(r),a}return Pt.makeSpan(["mspace",r],[Pt.mathsym(t.text,t.mode,e)],e)}if(Zr.hasOwnProperty(t.text))return Pt.makeSpan(["mspace",Zr[t.text]],[],e);throw new o('Unknown type of space "'+t.text+'"')},mathmlBuilder:function(t,e){if(!Kr.hasOwnProperty(t.text)){if(Zr.hasOwnProperty(t.text))return new xe.MathNode("mspace");throw new o('Unknown type of space "'+t.text+'"')}return new xe.MathNode("mtext",[new xe.TextNode("\xa0")])}});var Jr=function(){var t=new xe.MathNode("mtd",[]);return t.setAttribute("width","50%"),t};Qt({type:"tag",mathmlBuilder:function(t,e){var r=new xe.MathNode("mtable",[new xe.MathNode("mtr",[Jr(),new xe.MathNode("mtd",[ke(t.body,e)]),Jr(),new xe.MathNode("mtd",[ke(t.tag,e)])])]);return r.setAttribute("width","100%"),r}});var Qr={"\\text":void 0,"\\textrm":"textrm","\\textsf":"textsf","\\texttt":"texttt","\\textnormal":"textrm"},ta={"\\textbf":"textbf","\\textmd":"textmd"},ea={"\\textit":"textit","\\textup":"textup"},ra=function(t,e){var r=t.font;return r?Qr[r]?e.withTextFontFamily(Qr[r]):ta[r]?e.withTextFontWeight(ta[r]):e.withTextFontShape(ea[r]):e};Jt({type:"text",names:["\\text","\\textrm","\\textsf","\\texttt","\\textnormal","\\textbf","\\textmd","\\textit","\\textup"],props:{numArgs:1,argTypes:["text"],greediness:2,allowedInText:!0,consumeMode:"text"},handler:function(t,e){var r=t.parser,a=t.funcName,n=e[0];return{type:"text",mode:r.mode,body:te(n),font:a}},htmlBuilder:function(t,e){var r=ra(t,e),a=oe(t.body,r,!0);return Pt.makeSpan(["mord","text"],Pt.tryCombineChars(a),r)},mathmlBuilder:function(t,e){var r=ra(t,e);return ke(t.body,r)}}),Jt({type:"underline",names:["\\underline"],props:{numArgs:1,allowedInText:!0},handler:function(t,e){return{type:"underline",mode:t.parser.mode,body:e[0]}},htmlBuilder:function(t,e){var r=ce(t.body,e),a=Pt.makeLineSpan("underline-line",e),n=e.fontMetrics().defaultRuleThickness,i=Pt.makeVList({positionType:"top",positionData:r.height,children:[{type:"kern",size:n},{type:"elem",elem:a},{type:"kern",size:3*n},{type:"elem",elem:r}]},e);return Pt.makeSpan(["mord","underline"],[i],e)},mathmlBuilder:function(t,e){var r=new xe.MathNode("mo",[new xe.TextNode("\u203e")]);r.setAttribute("stretchy","true");var a=new xe.MathNode("munder",[Se(t.body,e),r]);return a.setAttribute("accentunder","true"),a}}),Jt({type:"verb",names:["\\verb"],props:{numArgs:0,allowedInText:!0},handler:function(t,e,r){throw new o("\\verb ended by end of line instead of matching delimiter")},htmlBuilder:function(t,e){for(var r=aa(t),a=[],n=e.havingStyle(e.style.text()),i=0;i0&&(this.undefStack[this.undefStack.length-1][t]=e)}else{var n=this.undefStack[this.undefStack.length-1];n&&!n.hasOwnProperty(t)&&(n[t]=this.current[t])}this.current[t]=e},t}(),ma={},ca=ma;function ua(t,e){ma[t]=e}ua("\\@firstoftwo",function(t){return{tokens:t.consumeArgs(2)[0],numArgs:0}}),ua("\\@secondoftwo",function(t){return{tokens:t.consumeArgs(2)[1],numArgs:0}}),ua("\\@ifnextchar",function(t){var e=t.consumeArgs(3),r=t.future();return 1===e[0].length&&e[0][0].text===r.text?{tokens:e[1],numArgs:0}:{tokens:e[2],numArgs:0}}),ua("\\@ifstar","\\@ifnextchar *{\\@firstoftwo{#1}}"),ua("\\TextOrMath",function(t){var e=t.consumeArgs(2);return"text"===t.mode?{tokens:e[0],numArgs:0}:{tokens:e[1],numArgs:0}});var pa={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};ua("\\char",function(t){var e,r=t.popToken(),a="";if("'"===r.text)e=8,r=t.popToken();else if('"'===r.text)e=16,r=t.popToken();else if("`"===r.text)if("\\"===(r=t.popToken()).text[0])a=r.text.charCodeAt(1);else{if("EOF"===r.text)throw new o("\\char` missing argument");a=r.text.charCodeAt(0)}else e=10;if(e){if(null==(a=pa[r.text])||a>=e)throw new o("Invalid base-"+e+" digit "+r.text);for(var n;null!=(n=pa[t.future().text])&&n":"\\dotsb","-":"\\dotsb","*":"\\dotsb",":":"\\dotsb","\\DOTSB":"\\dotsb","\\coprod":"\\dotsb","\\bigvee":"\\dotsb","\\bigwedge":"\\dotsb","\\biguplus":"\\dotsb","\\bigcap":"\\dotsb","\\bigcup":"\\dotsb","\\prod":"\\dotsb","\\sum":"\\dotsb","\\bigotimes":"\\dotsb","\\bigoplus":"\\dotsb","\\bigodot":"\\dotsb","\\bigsqcup":"\\dotsb","\\And":"\\dotsb","\\longrightarrow":"\\dotsb","\\Longrightarrow":"\\dotsb","\\longleftarrow":"\\dotsb","\\Longleftarrow":"\\dotsb","\\longleftrightarrow":"\\dotsb","\\Longleftrightarrow":"\\dotsb","\\mapsto":"\\dotsb","\\longmapsto":"\\dotsb","\\hookrightarrow":"\\dotsb","\\doteq":"\\dotsb","\\mathbin":"\\dotsb","\\mathrel":"\\dotsb","\\relbar":"\\dotsb","\\Relbar":"\\dotsb","\\xrightarrow":"\\dotsb","\\xleftarrow":"\\dotsb","\\DOTSI":"\\dotsi","\\int":"\\dotsi","\\oint":"\\dotsi","\\iint":"\\dotsi","\\iiint":"\\dotsi","\\iiiint":"\\dotsi","\\idotsint":"\\dotsi","\\DOTSX":"\\dotsx"};ua("\\dots",function(t){var e="\\dotso",r=t.expandAfterFuture().text;return r in ga?e=ga[r]:"\\not"===r.substr(0,4)?e="\\dotsb":r in _.math&&c.contains(["bin","rel"],_.math[r].group)&&(e="\\dotsb"),e});var xa={")":!0,"]":!0,"\\rbrack":!0,"\\}":!0,"\\rbrace":!0,"\\rangle":!0,"\\rceil":!0,"\\rfloor":!0,"\\rgroup":!0,"\\rmoustache":!0,"\\right":!0,"\\bigr":!0,"\\biggr":!0,"\\Bigr":!0,"\\Biggr":!0,$:!0,";":!0,".":!0,",":!0};ua("\\dotso",function(t){return t.future().text in xa?"\\ldots\\,":"\\ldots"}),ua("\\dotsc",function(t){var e=t.future().text;return e in xa&&","!==e?"\\ldots\\,":"\\ldots"}),ua("\\cdots",function(t){return t.future().text in xa?"\\@cdots\\,":"\\@cdots"}),ua("\\dotsb","\\cdots"),ua("\\dotsm","\\cdots"),ua("\\dotsi","\\!\\cdots"),ua("\\dotsx","\\ldots\\,"),ua("\\DOTSI","\\relax"),ua("\\DOTSB","\\relax"),ua("\\DOTSX","\\relax"),ua("\\tmspace","\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax"),ua("\\,","\\tmspace+{3mu}{.1667em}"),ua("\\thinspace","\\,"),ua("\\>","\\mskip{4mu}"),ua("\\:","\\tmspace+{4mu}{.2222em}"),ua("\\medspace","\\:"),ua("\\;","\\tmspace+{5mu}{.2777em}"),ua("\\thickspace","\\;"),ua("\\!","\\tmspace-{3mu}{.1667em}"),ua("\\negthinspace","\\!"),ua("\\negmedspace","\\tmspace-{4mu}{.2222em}"),ua("\\negthickspace","\\tmspace-{5mu}{.277em}"),ua("\\enspace","\\kern.5em "),ua("\\enskip","\\hskip.5em\\relax"),ua("\\quad","\\hskip1em\\relax"),ua("\\qquad","\\hskip2em\\relax"),ua("\\tag","\\@ifstar\\tag@literal\\tag@paren"),ua("\\tag@paren","\\tag@literal{({#1})}"),ua("\\tag@literal",function(t){if(t.macros.get("\\df@tag"))throw new o("Multiple \\tag");return"\\gdef\\df@tag{\\text{#1}}"}),ua("\\bmod","\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}"),ua("\\pod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)"),ua("\\pmod","\\pod{{\\rm mod}\\mkern6mu#1}"),ua("\\mod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1"),ua("\\pmb","\\html@mathml{\\@binrel{#1}{\\mathrlap{#1}\\kern0.5px#1}}{\\mathbf{#1}}"),ua("\\\\","\\newline"),ua("\\TeX","\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}");var va=D["Main-Regular"]["T".charCodeAt(0)][1]-.7*D["Main-Regular"]["A".charCodeAt(0)][1]+"em";ua("\\LaTeX","\\textrm{\\html@mathml{L\\kern-.36em\\raisebox{"+va+"}{\\scriptstyle A}\\kern-.15em\\TeX}{LaTeX}}"),ua("\\KaTeX","\\textrm{\\html@mathml{K\\kern-.17em\\raisebox{"+va+"}{\\scriptstyle A}\\kern-.15em\\TeX}{KaTeX}}"),ua("\\hspace","\\@ifstar\\@hspacer\\@hspace"),ua("\\@hspace","\\hskip #1\\relax"),ua("\\@hspacer","\\rule{0pt}{0pt}\\hskip #1\\relax"),ua("\\ordinarycolon",":"),ua("\\vcentcolon","\\mathrel{\\mathop\\ordinarycolon}"),ua("\\dblcolon",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char"2237}}'),ua("\\coloneqq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2254}}'),ua("\\Coloneqq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2237\\char"3d}}'),ua("\\coloneq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"3a\\char"2212}}'),ua("\\Coloneq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"2237\\char"2212}}'),ua("\\eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2255}}'),ua("\\Eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"3d\\char"2237}}'),ua("\\eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2239}}'),ua("\\Eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"2212\\char"2237}}'),ua("\\colonapprox",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"3a\\char"2248}}'),ua("\\Colonapprox",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"2237\\char"2248}}'),ua("\\colonsim",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"3a\\char"223c}}'),ua("\\Colonsim",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"2237\\char"223c}}'),ua("\u2237","\\dblcolon"),ua("\u2239","\\eqcolon"),ua("\u2254","\\coloneqq"),ua("\u2255","\\eqqcolon"),ua("\u2a74","\\Coloneqq"),ua("\\ratio","\\vcentcolon"),ua("\\coloncolon","\\dblcolon"),ua("\\colonequals","\\coloneqq"),ua("\\coloncolonequals","\\Coloneqq"),ua("\\equalscolon","\\eqqcolon"),ua("\\equalscoloncolon","\\Eqqcolon"),ua("\\colonminus","\\coloneq"),ua("\\coloncolonminus","\\Coloneq"),ua("\\minuscolon","\\eqcolon"),ua("\\minuscoloncolon","\\Eqcolon"),ua("\\coloncolonapprox","\\Colonapprox"),ua("\\coloncolonsim","\\Colonsim"),ua("\\simcolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}"),ua("\\simcoloncolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}"),ua("\\approxcolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}"),ua("\\approxcoloncolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}"),ua("\\notni","\\html@mathml{\\not\\ni}{\\mathrel{\\char`\u220c}}"),ua("\\limsup","\\DOTSB\\operatorname*{lim\\,sup}"),ua("\\liminf","\\DOTSB\\operatorname*{lim\\,inf}"),ua("\\gvertneqq","\\html@mathml{\\@gvertneqq}{\u2269}"),ua("\\lvertneqq","\\html@mathml{\\@lvertneqq}{\u2268}"),ua("\\ngeqq","\\html@mathml{\\@ngeqq}{\u2271}"),ua("\\ngeqslant","\\html@mathml{\\@ngeqslant}{\u2271}"),ua("\\nleqq","\\html@mathml{\\@nleqq}{\u2270}"),ua("\\nleqslant","\\html@mathml{\\@nleqslant}{\u2270}"),ua("\\nshortmid","\\html@mathml{\\@nshortmid}{\u2224}"),ua("\\nshortparallel","\\html@mathml{\\@nshortparallel}{\u2226}"),ua("\\nsubseteqq","\\html@mathml{\\@nsubseteqq}{\u2288}"),ua("\\nsupseteqq","\\html@mathml{\\@nsupseteqq}{\u2289}"),ua("\\varsubsetneq","\\html@mathml{\\@varsubsetneq}{\u228a}"),ua("\\varsubsetneqq","\\html@mathml{\\@varsubsetneqq}{\u2acb}"),ua("\\varsupsetneq","\\html@mathml{\\@varsupsetneq}{\u228b}"),ua("\\varsupsetneqq","\\html@mathml{\\@varsupsetneqq}{\u2acc}"),ua("\\llbracket","\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`\u27e6}}"),ua("\\rrbracket","\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`\u27e7}}"),ua("\u27e6","\\llbracket"),ua("\u27e7","\\rrbracket"),ua("\\lBrace","\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`\u2983}}"),ua("\\rBrace","\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`\u2984}}"),ua("\u2983","\\lBrace"),ua("\u2984","\\rBrace"),ua("\\darr","\\downarrow"),ua("\\dArr","\\Downarrow"),ua("\\Darr","\\Downarrow"),ua("\\lang","\\langle"),ua("\\rang","\\rangle"),ua("\\uarr","\\uparrow"),ua("\\uArr","\\Uparrow"),ua("\\Uarr","\\Uparrow"),ua("\\N","\\mathbb{N}"),ua("\\R","\\mathbb{R}"),ua("\\Z","\\mathbb{Z}"),ua("\\alef","\\aleph"),ua("\\alefsym","\\aleph"),ua("\\Alpha","\\mathrm{A}"),ua("\\Beta","\\mathrm{B}"),ua("\\bull","\\bullet"),ua("\\Chi","\\mathrm{X}"),ua("\\clubs","\\clubsuit"),ua("\\cnums","\\mathbb{C}"),ua("\\Complex","\\mathbb{C}"),ua("\\Dagger","\\ddagger"),ua("\\diamonds","\\diamondsuit"),ua("\\empty","\\emptyset"),ua("\\Epsilon","\\mathrm{E}"),ua("\\Eta","\\mathrm{H}"),ua("\\exist","\\exists"),ua("\\harr","\\leftrightarrow"),ua("\\hArr","\\Leftrightarrow"),ua("\\Harr","\\Leftrightarrow"),ua("\\hearts","\\heartsuit"),ua("\\image","\\Im"),ua("\\infin","\\infty"),ua("\\Iota","\\mathrm{I}"),ua("\\isin","\\in"),ua("\\Kappa","\\mathrm{K}"),ua("\\larr","\\leftarrow"),ua("\\lArr","\\Leftarrow"),ua("\\Larr","\\Leftarrow"),ua("\\lrarr","\\leftrightarrow"),ua("\\lrArr","\\Leftrightarrow"),ua("\\Lrarr","\\Leftrightarrow"),ua("\\Mu","\\mathrm{M}"),ua("\\natnums","\\mathbb{N}"),ua("\\Nu","\\mathrm{N}"),ua("\\Omicron","\\mathrm{O}"),ua("\\plusmn","\\pm"),ua("\\rarr","\\rightarrow"),ua("\\rArr","\\Rightarrow"),ua("\\Rarr","\\Rightarrow"),ua("\\real","\\Re"),ua("\\reals","\\mathbb{R}"),ua("\\Reals","\\mathbb{R}"),ua("\\Rho","\\mathrm{P}"),ua("\\sdot","\\cdot"),ua("\\sect","\\S"),ua("\\spades","\\spadesuit"),ua("\\sub","\\subset"),ua("\\sube","\\subseteq"),ua("\\supe","\\supseteq"),ua("\\Tau","\\mathrm{T}"),ua("\\thetasym","\\vartheta"),ua("\\weierp","\\wp"),ua("\\Zeta","\\mathrm{Z}"),ua("\\argmin","\\DOTSB\\operatorname*{arg\\,min}"),ua("\\argmax","\\DOTSB\\operatorname*{arg\\,max}"),ua("\\plim","\\DOTSB\\mathop{\\operatorname{plim}}\\limits"),ua("\\blue","\\textcolor{##6495ed}{#1}"),ua("\\orange","\\textcolor{##ffa500}{#1}"),ua("\\pink","\\textcolor{##ff00af}{#1}"),ua("\\red","\\textcolor{##df0030}{#1}"),ua("\\green","\\textcolor{##28ae7b}{#1}"),ua("\\gray","\\textcolor{gray}{##1}"),ua("\\purple","\\textcolor{##9d38bd}{#1}"),ua("\\blueA","\\textcolor{##ccfaff}{#1}"),ua("\\blueB","\\textcolor{##80f6ff}{#1}"),ua("\\blueC","\\textcolor{##63d9ea}{#1}"),ua("\\blueD","\\textcolor{##11accd}{#1}"),ua("\\blueE","\\textcolor{##0c7f99}{#1}"),ua("\\tealA","\\textcolor{##94fff5}{#1}"),ua("\\tealB","\\textcolor{##26edd5}{#1}"),ua("\\tealC","\\textcolor{##01d1c1}{#1}"),ua("\\tealD","\\textcolor{##01a995}{#1}"),ua("\\tealE","\\textcolor{##208170}{#1}"),ua("\\greenA","\\textcolor{##b6ffb0}{#1}"),ua("\\greenB","\\textcolor{##8af281}{#1}"),ua("\\greenC","\\textcolor{##74cf70}{#1}"),ua("\\greenD","\\textcolor{##1fab54}{#1}"),ua("\\greenE","\\textcolor{##0d923f}{#1}"),ua("\\goldA","\\textcolor{##ffd0a9}{#1}"),ua("\\goldB","\\textcolor{##ffbb71}{#1}"),ua("\\goldC","\\textcolor{##ff9c39}{#1}"),ua("\\goldD","\\textcolor{##e07d10}{#1}"),ua("\\goldE","\\textcolor{##a75a05}{#1}"),ua("\\redA","\\textcolor{##fca9a9}{#1}"),ua("\\redB","\\textcolor{##ff8482}{#1}"),ua("\\redC","\\textcolor{##f9685d}{#1}"),ua("\\redD","\\textcolor{##e84d39}{#1}"),ua("\\redE","\\textcolor{##bc2612}{#1}"),ua("\\maroonA","\\textcolor{##ffbde0}{#1}"),ua("\\maroonB","\\textcolor{##ff92c6}{#1}"),ua("\\maroonC","\\textcolor{##ed5fa6}{#1}"),ua("\\maroonD","\\textcolor{##ca337c}{#1}"),ua("\\maroonE","\\textcolor{##9e034e}{#1}"),ua("\\purpleA","\\textcolor{##ddd7ff}{#1}"),ua("\\purpleB","\\textcolor{##c6b9fc}{#1}"),ua("\\purpleC","\\textcolor{##aa87ff}{#1}"),ua("\\purpleD","\\textcolor{##7854ab}{#1}"),ua("\\purpleE","\\textcolor{##543b78}{#1}"),ua("\\mintA","\\textcolor{##f5f9e8}{#1}"),ua("\\mintB","\\textcolor{##edf2df}{#1}"),ua("\\mintC","\\textcolor{##e0e5cc}{#1}"),ua("\\grayA","\\textcolor{##f6f7f7}{#1}"),ua("\\grayB","\\textcolor{##f0f1f2}{#1}"),ua("\\grayC","\\textcolor{##e3e5e6}{#1}"),ua("\\grayD","\\textcolor{##d6d8da}{#1}"),ua("\\grayE","\\textcolor{##babec2}{#1}"),ua("\\grayF","\\textcolor{##888d93}{#1}"),ua("\\grayG","\\textcolor{##626569}{#1}"),ua("\\grayH","\\textcolor{##3b3e40}{#1}"),ua("\\grayI","\\textcolor{##21242c}{#1}"),ua("\\kaBlue","\\textcolor{##314453}{#1}"),ua("\\kaGreen","\\textcolor{##71B307}{#1}");var ba={"\\relax":!0,"^":!0,_:!0,"\\limits":!0,"\\nolimits":!0},ya=function(){function t(t,e,r){this.settings=void 0,this.expansionCount=void 0,this.lexer=void 0,this.macros=void 0,this.stack=void 0,this.mode=void 0,this.settings=e,this.expansionCount=0,this.feed(t),this.macros=new la(ca,e.macros),this.mode=r,this.stack=[]}var e=t.prototype;return e.feed=function(t){this.lexer=new ha(t,this.settings)},e.switchMode=function(t){this.mode=t},e.beginGroup=function(){this.macros.beginGroup()},e.endGroup=function(){this.macros.endGroup()},e.future=function(){return 0===this.stack.length&&this.pushToken(this.lexer.lex()),this.stack[this.stack.length-1]},e.popToken=function(){return this.future(),this.stack.pop()},e.pushToken=function(t){this.stack.push(t)},e.pushTokens=function(t){var e;(e=this.stack).push.apply(e,t)},e.consumeSpaces=function(){for(;;){if(" "!==this.future().text)break;this.stack.pop()}},e.consumeArgs=function(t){for(var e=[],r=0;rthis.settings.maxExpand)throw new o("Too many expansions: infinite loop or need to increase maxExpand setting");var a=r.tokens;if(r.numArgs)for(var n=this.consumeArgs(r.numArgs),i=(a=a.slice()).length-1;i>=0;--i){var s=a[i];if("#"===s.text){if(0===i)throw new o("Incomplete placeholder at end of macro body",s);if("#"===(s=a[--i]).text)a.splice(i+1,1);else{if(!/^[1-9]$/.test(s.text))throw new o("Not a valid argument number",s);var h;(h=a).splice.apply(h,[i,2].concat(n[+s.text-1]))}}}return this.pushTokens(a),a},e.expandAfterFuture=function(){return this.expandOnce(),this.future()},e.expandNextToken=function(){for(;;){var t=this.expandOnce();if(t instanceof n){if("\\relax"!==t.text)return this.stack.pop();this.stack.pop()}}throw new Error},e.expandMacro=function(t){if(this.macros.get(t)){var e=[],r=this.stack.length;for(this.pushToken(new n(t));this.stack.length>r;){this.expandOnce()instanceof n&&e.push(this.stack.pop())}return e}},e.expandMacroAsText=function(t){var e=this.expandMacro(t);return e?e.map(function(t){return t.text}).join(""):e},e._getExpansion=function(t){var e=this.macros.get(t);if(null==e)return e;var r="function"==typeof e?e(this):e;if("string"==typeof r){var a=0;if(-1!==r.indexOf("#"))for(var n=r.replace(/##/g,"");-1!==n.indexOf("#"+(a+1));)++a;for(var i=new ha(r,this.settings),o=[],s=i.lex();"EOF"!==s.text;)o.push(s),s=i.lex();return o.reverse(),{tokens:o,numArgs:a}}return r},e.isDefined=function(t){return this.macros.has(t)||na.hasOwnProperty(t)||_.math.hasOwnProperty(t)||_.text.hasOwnProperty(t)||ba.hasOwnProperty(t)},t}(),wa={"\u0301":{text:"\\'",math:"\\acute"},"\u0300":{text:"\\`",math:"\\grave"},"\u0308":{text:'\\"',math:"\\ddot"},"\u0303":{text:"\\~",math:"\\tilde"},"\u0304":{text:"\\=",math:"\\bar"},"\u0306":{text:"\\u",math:"\\breve"},"\u030c":{text:"\\v",math:"\\check"},"\u0302":{text:"\\^",math:"\\hat"},"\u0307":{text:"\\.",math:"\\dot"},"\u030a":{text:"\\r",math:"\\mathring"},"\u030b":{text:"\\H"}},ka={"\xe1":"a\u0301","\xe0":"a\u0300","\xe4":"a\u0308","\u01df":"a\u0308\u0304","\xe3":"a\u0303","\u0101":"a\u0304","\u0103":"a\u0306","\u1eaf":"a\u0306\u0301","\u1eb1":"a\u0306\u0300","\u1eb5":"a\u0306\u0303","\u01ce":"a\u030c","\xe2":"a\u0302","\u1ea5":"a\u0302\u0301","\u1ea7":"a\u0302\u0300","\u1eab":"a\u0302\u0303","\u0227":"a\u0307","\u01e1":"a\u0307\u0304","\xe5":"a\u030a","\u01fb":"a\u030a\u0301","\u1e03":"b\u0307","\u0107":"c\u0301","\u010d":"c\u030c","\u0109":"c\u0302","\u010b":"c\u0307","\u010f":"d\u030c","\u1e0b":"d\u0307","\xe9":"e\u0301","\xe8":"e\u0300","\xeb":"e\u0308","\u1ebd":"e\u0303","\u0113":"e\u0304","\u1e17":"e\u0304\u0301","\u1e15":"e\u0304\u0300","\u0115":"e\u0306","\u011b":"e\u030c","\xea":"e\u0302","\u1ebf":"e\u0302\u0301","\u1ec1":"e\u0302\u0300","\u1ec5":"e\u0302\u0303","\u0117":"e\u0307","\u1e1f":"f\u0307","\u01f5":"g\u0301","\u1e21":"g\u0304","\u011f":"g\u0306","\u01e7":"g\u030c","\u011d":"g\u0302","\u0121":"g\u0307","\u1e27":"h\u0308","\u021f":"h\u030c","\u0125":"h\u0302","\u1e23":"h\u0307","\xed":"i\u0301","\xec":"i\u0300","\xef":"i\u0308","\u1e2f":"i\u0308\u0301","\u0129":"i\u0303","\u012b":"i\u0304","\u012d":"i\u0306","\u01d0":"i\u030c","\xee":"i\u0302","\u01f0":"j\u030c","\u0135":"j\u0302","\u1e31":"k\u0301","\u01e9":"k\u030c","\u013a":"l\u0301","\u013e":"l\u030c","\u1e3f":"m\u0301","\u1e41":"m\u0307","\u0144":"n\u0301","\u01f9":"n\u0300","\xf1":"n\u0303","\u0148":"n\u030c","\u1e45":"n\u0307","\xf3":"o\u0301","\xf2":"o\u0300","\xf6":"o\u0308","\u022b":"o\u0308\u0304","\xf5":"o\u0303","\u1e4d":"o\u0303\u0301","\u1e4f":"o\u0303\u0308","\u022d":"o\u0303\u0304","\u014d":"o\u0304","\u1e53":"o\u0304\u0301","\u1e51":"o\u0304\u0300","\u014f":"o\u0306","\u01d2":"o\u030c","\xf4":"o\u0302","\u1ed1":"o\u0302\u0301","\u1ed3":"o\u0302\u0300","\u1ed7":"o\u0302\u0303","\u022f":"o\u0307","\u0231":"o\u0307\u0304","\u0151":"o\u030b","\u1e55":"p\u0301","\u1e57":"p\u0307","\u0155":"r\u0301","\u0159":"r\u030c","\u1e59":"r\u0307","\u015b":"s\u0301","\u1e65":"s\u0301\u0307","\u0161":"s\u030c","\u1e67":"s\u030c\u0307","\u015d":"s\u0302","\u1e61":"s\u0307","\u1e97":"t\u0308","\u0165":"t\u030c","\u1e6b":"t\u0307","\xfa":"u\u0301","\xf9":"u\u0300","\xfc":"u\u0308","\u01d8":"u\u0308\u0301","\u01dc":"u\u0308\u0300","\u01d6":"u\u0308\u0304","\u01da":"u\u0308\u030c","\u0169":"u\u0303","\u1e79":"u\u0303\u0301","\u016b":"u\u0304","\u1e7b":"u\u0304\u0308","\u016d":"u\u0306","\u01d4":"u\u030c","\xfb":"u\u0302","\u016f":"u\u030a","\u0171":"u\u030b","\u1e7d":"v\u0303","\u1e83":"w\u0301","\u1e81":"w\u0300","\u1e85":"w\u0308","\u0175":"w\u0302","\u1e87":"w\u0307","\u1e98":"w\u030a","\u1e8d":"x\u0308","\u1e8b":"x\u0307","\xfd":"y\u0301","\u1ef3":"y\u0300","\xff":"y\u0308","\u1ef9":"y\u0303","\u0233":"y\u0304","\u0177":"y\u0302","\u1e8f":"y\u0307","\u1e99":"y\u030a","\u017a":"z\u0301","\u017e":"z\u030c","\u1e91":"z\u0302","\u017c":"z\u0307","\xc1":"A\u0301","\xc0":"A\u0300","\xc4":"A\u0308","\u01de":"A\u0308\u0304","\xc3":"A\u0303","\u0100":"A\u0304","\u0102":"A\u0306","\u1eae":"A\u0306\u0301","\u1eb0":"A\u0306\u0300","\u1eb4":"A\u0306\u0303","\u01cd":"A\u030c","\xc2":"A\u0302","\u1ea4":"A\u0302\u0301","\u1ea6":"A\u0302\u0300","\u1eaa":"A\u0302\u0303","\u0226":"A\u0307","\u01e0":"A\u0307\u0304","\xc5":"A\u030a","\u01fa":"A\u030a\u0301","\u1e02":"B\u0307","\u0106":"C\u0301","\u010c":"C\u030c","\u0108":"C\u0302","\u010a":"C\u0307","\u010e":"D\u030c","\u1e0a":"D\u0307","\xc9":"E\u0301","\xc8":"E\u0300","\xcb":"E\u0308","\u1ebc":"E\u0303","\u0112":"E\u0304","\u1e16":"E\u0304\u0301","\u1e14":"E\u0304\u0300","\u0114":"E\u0306","\u011a":"E\u030c","\xca":"E\u0302","\u1ebe":"E\u0302\u0301","\u1ec0":"E\u0302\u0300","\u1ec4":"E\u0302\u0303","\u0116":"E\u0307","\u1e1e":"F\u0307","\u01f4":"G\u0301","\u1e20":"G\u0304","\u011e":"G\u0306","\u01e6":"G\u030c","\u011c":"G\u0302","\u0120":"G\u0307","\u1e26":"H\u0308","\u021e":"H\u030c","\u0124":"H\u0302","\u1e22":"H\u0307","\xcd":"I\u0301","\xcc":"I\u0300","\xcf":"I\u0308","\u1e2e":"I\u0308\u0301","\u0128":"I\u0303","\u012a":"I\u0304","\u012c":"I\u0306","\u01cf":"I\u030c","\xce":"I\u0302","\u0130":"I\u0307","\u0134":"J\u0302","\u1e30":"K\u0301","\u01e8":"K\u030c","\u0139":"L\u0301","\u013d":"L\u030c","\u1e3e":"M\u0301","\u1e40":"M\u0307","\u0143":"N\u0301","\u01f8":"N\u0300","\xd1":"N\u0303","\u0147":"N\u030c","\u1e44":"N\u0307","\xd3":"O\u0301","\xd2":"O\u0300","\xd6":"O\u0308","\u022a":"O\u0308\u0304","\xd5":"O\u0303","\u1e4c":"O\u0303\u0301","\u1e4e":"O\u0303\u0308","\u022c":"O\u0303\u0304","\u014c":"O\u0304","\u1e52":"O\u0304\u0301","\u1e50":"O\u0304\u0300","\u014e":"O\u0306","\u01d1":"O\u030c","\xd4":"O\u0302","\u1ed0":"O\u0302\u0301","\u1ed2":"O\u0302\u0300","\u1ed6":"O\u0302\u0303","\u022e":"O\u0307","\u0230":"O\u0307\u0304","\u0150":"O\u030b","\u1e54":"P\u0301","\u1e56":"P\u0307","\u0154":"R\u0301","\u0158":"R\u030c","\u1e58":"R\u0307","\u015a":"S\u0301","\u1e64":"S\u0301\u0307","\u0160":"S\u030c","\u1e66":"S\u030c\u0307","\u015c":"S\u0302","\u1e60":"S\u0307","\u0164":"T\u030c","\u1e6a":"T\u0307","\xda":"U\u0301","\xd9":"U\u0300","\xdc":"U\u0308","\u01d7":"U\u0308\u0301","\u01db":"U\u0308\u0300","\u01d5":"U\u0308\u0304","\u01d9":"U\u0308\u030c","\u0168":"U\u0303","\u1e78":"U\u0303\u0301","\u016a":"U\u0304","\u1e7a":"U\u0304\u0308","\u016c":"U\u0306","\u01d3":"U\u030c","\xdb":"U\u0302","\u016e":"U\u030a","\u0170":"U\u030b","\u1e7c":"V\u0303","\u1e82":"W\u0301","\u1e80":"W\u0300","\u1e84":"W\u0308","\u0174":"W\u0302","\u1e86":"W\u0307","\u1e8c":"X\u0308","\u1e8a":"X\u0307","\xdd":"Y\u0301","\u1ef2":"Y\u0300","\u0178":"Y\u0308","\u1ef8":"Y\u0303","\u0232":"Y\u0304","\u0176":"Y\u0302","\u1e8e":"Y\u0307","\u0179":"Z\u0301","\u017d":"Z\u030c","\u1e90":"Z\u0302","\u017b":"Z\u0307","\u03ac":"\u03b1\u0301","\u1f70":"\u03b1\u0300","\u1fb1":"\u03b1\u0304","\u1fb0":"\u03b1\u0306","\u03ad":"\u03b5\u0301","\u1f72":"\u03b5\u0300","\u03ae":"\u03b7\u0301","\u1f74":"\u03b7\u0300","\u03af":"\u03b9\u0301","\u1f76":"\u03b9\u0300","\u03ca":"\u03b9\u0308","\u0390":"\u03b9\u0308\u0301","\u1fd2":"\u03b9\u0308\u0300","\u1fd1":"\u03b9\u0304","\u1fd0":"\u03b9\u0306","\u03cc":"\u03bf\u0301","\u1f78":"\u03bf\u0300","\u03cd":"\u03c5\u0301","\u1f7a":"\u03c5\u0300","\u03cb":"\u03c5\u0308","\u03b0":"\u03c5\u0308\u0301","\u1fe2":"\u03c5\u0308\u0300","\u1fe1":"\u03c5\u0304","\u1fe0":"\u03c5\u0306","\u03ce":"\u03c9\u0301","\u1f7c":"\u03c9\u0300","\u038e":"\u03a5\u0301","\u1fea":"\u03a5\u0300","\u03ab":"\u03a5\u0308","\u1fe9":"\u03a5\u0304","\u1fe8":"\u03a5\u0306","\u038f":"\u03a9\u0301","\u1ffa":"\u03a9\u0300"},Sa=function(){function t(t,e){this.mode=void 0,this.gullet=void 0,this.settings=void 0,this.leftrightDepth=void 0,this.nextToken=void 0,this.mode="math",this.gullet=new ya(t,e,this.mode),this.settings=e,this.leftrightDepth=0}var e=t.prototype;return e.expect=function(t,e){if(void 0===e&&(e=!0),this.nextToken.text!==t)throw new o("Expected '"+t+"', got '"+this.nextToken.text+"'",this.nextToken);e&&this.consume()},e.consume=function(){this.nextToken=this.gullet.expandNextToken()},e.switchMode=function(t){this.mode=t,this.gullet.switchMode(t)},e.parse=function(){this.gullet.beginGroup(),this.settings.colorIsTextColor&&this.gullet.macros.set("\\color","\\textcolor"),this.consume();var t=this.parseExpression(!1);return this.expect("EOF",!1),this.gullet.endGroup(),t},e.parseExpression=function(e,r){for(var a=[];;){"math"===this.mode&&this.consumeSpaces();var n=this.nextToken;if(-1!==t.endOfExpression.indexOf(n.text))break;if(r&&n.text===r)break;if(e&&na[n.text]&&na[n.text].infix)break;var i=this.parseAtom(r);if(!i)break;a.push(i)}return"text"===this.mode&&this.formLigatures(a),this.handleInfixNodes(a)},e.handleInfixNodes=function(t){for(var e,r=-1,a=0;a0&&!l&&this.consumeSpaces(),0!==s||l||"math"!==this.mode||this.consumeSpaces();var m=this.nextToken,c=this.parseGroupOfType("argument to '"+t+"'",h,l,a);if(!c){if(l){i.push(null);continue}throw new o("Expected group after '"+t+"'",m)}(l?i:n).push(c)}return{args:n,optArgs:i}},e.parseGroupOfType=function(t,e,r,a){switch(e){case"color":return this.parseColorGroup(r);case"size":return this.parseSizeGroup(r);case"url":return this.parseUrlGroup(r);case"math":case"text":return this.parseGroup(t,r,a,void 0,e);case"hbox":var n=this.parseGroup(t,r,a,void 0,"text");return n?{type:"styling",mode:n.mode,body:[n],style:"text"}:n;case"raw":if(r&&"{"===this.nextToken.text)return null;var i=this.parseStringGroup("raw",r,!0);if(i)return{type:"raw",mode:"text",string:i.text};throw new o("Expected raw group",this.nextToken);case"original":case null:case void 0:return this.parseGroup(t,r,a);default:throw new o("Unknown group type as "+t,this.nextToken)}},e.consumeSpaces=function(){for(;" "===this.nextToken.text;)this.consume()},e.parseStringGroup=function(t,e,r){var a=e?"[":"{",n=e?"]":"}",i=this.nextToken;if(i.text!==a){if(e)return null;if(r&&"EOF"!==i.text&&/[^{}[\]]/.test(i.text))return this.gullet.lexer.setCatcode("%",14),this.consume(),i}var s=this.mode;this.mode="text",this.expect(a);for(var h="",l=this.nextToken,m=0,c=l;r&&m>0||this.nextToken.text!==n;){switch(this.nextToken.text){case"EOF":throw new o("Unexpected end of input in "+t,l.range(c,h));case a:m++;break;case n:m--}h+=(c=this.nextToken).text,this.consume()}return this.mode=s,this.gullet.lexer.setCatcode("%",14),this.expect(n),l.range(c,h)},e.parseRegexGroup=function(t,e){var r=this.mode;this.mode="text";for(var a=this.nextToken,n=a,i="";"EOF"!==this.nextToken.text&&t.test(i+this.nextToken.text);)i+=(n=this.nextToken).text,this.consume();if(""===i)throw new o("Invalid "+e+": '"+a.text+"'",a);return this.mode=r,a.range(n,i)},e.parseColorGroup=function(t){var e=this.parseStringGroup("color",t);if(!e)return null;var r=/^(#[a-f0-9]{3}|#?[a-f0-9]{6}|[a-z]+)$/i.exec(e.text);if(!r)throw new o("Invalid color: '"+e.text+"'",e);var a=r[0];return/^[0-9a-f]{6}$/i.test(a)&&(a="#"+a),{type:"color-token",mode:this.mode,color:a}},e.parseSizeGroup=function(t){var e,r=!1;if(!(e=t||"{"===this.nextToken.text?this.parseStringGroup("size",t):this.parseRegexGroup(/^[-+]? *(?:$|\d+|\d+\.\d*|\.\d*) *[a-z]{0,2} *$/,"size")))return null;t||0!==e.text.length||(e.text="0pt",r=!0);var a=/([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(e.text);if(!a)throw new o("Invalid size: '"+e.text+"'",e);var n={number:+(a[1]+a[2]),unit:a[3]};if(!zt(n))throw new o("Invalid unit: '"+n.unit+"'",e);return{type:"size",mode:this.mode,value:n,isBlank:r}},e.parseUrlGroup=function(t){var e=this.parseStringGroup("url",t,!0);if(!e)return null;var r=e.text.replace(/\\([#$%&~_^{}])/g,"$1");return{type:"url",mode:this.mode,url:r}},e.parseGroup=function(e,r,n,i,s){var h,l,m=this.mode,c=this.nextToken,u=c.text;if(s&&this.switchMode(s),r?"["===u:"{"===u||"\\begingroup"===u){h=t.endOfGroup[u],this.gullet.beginGroup(),this.consume();var p=this.parseExpression(!1,h),d=this.nextToken;this.gullet.endGroup(),l={type:"ordgroup",mode:this.mode,loc:a.range(c,d),body:p,semisimple:"\\begingroup"===u||void 0}}else if(r)l=null;else if(null==(l=this.parseFunction(i,e,n)||this.parseSymbol())&&"\\"===u[0]&&!ba.hasOwnProperty(u)){if(this.settings.throwOnError)throw new o("Undefined control sequence: "+u,c);l=this.formatUnsupportedCmd(u),this.consume()}return s&&this.switchMode(m),h&&this.expect(h),l},e.formLigatures=function(t){for(var e=t.length-1,r=0;r=0&&this.settings.reportNonstrict("unicodeTextInMathMode",'Latin-1/Unicode text character "'+e[0]+'" used in math mode',t);var h,l=_[this.mode][e].group,m=a.range(t);if(Y.hasOwnProperty(l)){var c=l;h={type:"atom",mode:this.mode,family:c,loc:m,text:e}}else h={type:l,mode:this.mode,loc:m,text:e};i=h}else{if(!(e.charCodeAt(0)>=128))return null;this.settings.strict&&(M(e.charCodeAt(0))?"math"===this.mode&&this.settings.reportNonstrict("unicodeTextInMathMode",'Unicode text character "'+e[0]+'" used in math mode',t):this.settings.reportNonstrict("unknownSymbol",'Unrecognized Unicode character "'+e[0]+'" ('+e.charCodeAt(0)+")",t)),i={type:"textord",mode:"text",loc:a.range(t),text:e}}if(this.consume(),s)for(var u=0;un?1:t>=n?0:NaN}function e(t){var e;return 1===t.length&&(e=t,t=function(t,r){return n(e(t),r)}),{left:function(n,e,r,i){for(null==r&&(r=0),null==i&&(i=n.length);r>>1;t(n[o],e)<0?r=o+1:i=o}return r},right:function(n,e,r,i){for(null==r&&(r=0),null==i&&(i=n.length);r>>1;t(n[o],e)>0?i=o:r=o+1}return r}}}var r=e(n),i=r.right,o=r.left;function a(t,n){return[t,n]}function u(t){return null===t?NaN:+t}function c(t,n){var e,r,i=t.length,o=0,a=-1,c=0,f=0;if(null==n)for(;++a1)return f/(o-1)}function f(t,n){var e=c(t,n);return e?Math.sqrt(e):e}function s(t,n){var e,r,i,o=t.length,a=-1;if(null==n){for(;++a=e)for(r=i=e;++ae&&(r=e),i=e)for(r=i=e;++ae&&(r=e),i0)return[t];if((r=n0)for(t=Math.ceil(t/a),n=Math.floor(n/a),o=new Array(i=Math.ceil(n-t+1));++u=0?(o>=y?10:o>=_?5:o>=b?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(o>=y?10:o>=_?5:o>=b?2:1)}function w(t,n,e){var r=Math.abs(n-t)/Math.max(0,e),i=Math.pow(10,Math.floor(Math.log(r)/Math.LN10)),o=r/i;return o>=y?i*=10:o>=_?i*=5:o>=b&&(i*=2),n=1)return+e(t[r-1],r-1,t);var r,i=(r-1)*n,o=Math.floor(i),a=+e(t[o],o,t);return a+(+e(t[o+1],o+1,t)-a)*(i-o)}}function T(t,n){var e,r,i=t.length,o=-1;if(null==n){for(;++o=e)for(r=e;++or&&(r=e)}else for(;++o=e)for(r=e;++or&&(r=e);return r}function A(t){for(var n,e,r,i=t.length,o=-1,a=0;++o=0;)for(n=(r=t[i]).length;--n>=0;)e[--a]=r[n];return e}function S(t,n){var e,r,i=t.length,o=-1;if(null==n){for(;++o=e)for(r=e;++oe&&(r=e)}else for(;++o=e)for(r=e;++oe&&(r=e);return r}function k(t){if(!(i=t.length))return[];for(var n=-1,e=S(t,E),r=new Array(e);++n=0&&(e=t.slice(r+1),t=t.slice(0,r)),t&&!n.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:e}})}function X(t,n){for(var e,r=0,i=t.length;r0)for(var e,r,i=new Array(e),o=0;o=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),$.hasOwnProperty(n)?{space:$[n],local:t}:t}function Z(t){var n=W(t);return(n.local?function(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}:function(t){return function(){var n=this.ownerDocument,e=this.namespaceURI;return e===V&&n.documentElement.namespaceURI===V?n.createElement(t):n.createElementNS(e,t)}})(n)}function Q(){}function K(t){return null==t?Q:function(){return this.querySelector(t)}}function J(){return[]}function tt(t){return null==t?J:function(){return this.querySelectorAll(t)}}function nt(t){return function(){return this.matches(t)}}function et(t){return new Array(t.length)}function rt(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}rt.prototype={constructor:rt,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,n){return this._parent.insertBefore(t,n)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};var it="$";function ot(t,n,e,r,i,o){for(var a,u=0,c=n.length,f=o.length;un?1:t>=n?0:NaN}function ct(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function ft(t,n){return t.style.getPropertyValue(n)||ct(t).getComputedStyle(t,null).getPropertyValue(n)}function st(t){return t.trim().split(/^|\s+/)}function lt(t){return t.classList||new ht(t)}function ht(t){this._node=t,this._names=st(t.getAttribute("class")||"")}function dt(t,n){for(var e=lt(t),r=-1,i=n.length;++r=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var Mt={};(t.event=null,"undefined"!=typeof document)&&("onmouseenter"in document.documentElement||(Mt={mouseenter:"mouseover",mouseleave:"mouseout"}));function Nt(t,n,e){return t=Tt(t,n,e),function(n){var e=n.relatedTarget;e&&(e===this||8&e.compareDocumentPosition(this))||t.call(this,n)}}function Tt(n,e,r){return function(i){var o=t.event;t.event=i;try{n.call(this,this.__data__,e,r)}finally{t.event=o}}}function At(t){return function(){var n=this.__on;if(n){for(var e,r=0,i=-1,o=n.length;r=m&&(m=b+1);!(_=g[m])&&++m=0;)(r=i[o])&&(a&&4^r.compareDocumentPosition(a)&&a.parentNode.insertBefore(r,a),a=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=ut);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o1?this.each((null==n?function(t){return function(){this.style.removeProperty(t)}}:"function"==typeof n?function(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}:function(t,n,e){return function(){this.style.setProperty(t,n,e)}})(t,n,null==e?"":e)):ft(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?function(t){return function(){delete this[t]}}:"function"==typeof n?function(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}:function(t,n){return function(){this[t]=n}})(t,n)):this.node()[t]},classed:function(t,n){var e=st(t+"");if(arguments.length<2){for(var r=lt(this.node()),i=-1,o=e.length;++i=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}})}(t+""),a=o.length;if(!(arguments.length<2)){for(u=n?St:At,null==e&&(e=!1),r=0;r>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):(n=on.exec(t))?gn(parseInt(n[1],16)):(n=an.exec(t))?new mn(n[1],n[2],n[3],1):(n=un.exec(t))?new mn(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=cn.exec(t))?yn(n[1],n[2],n[3],n[4]):(n=fn.exec(t))?yn(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=sn.exec(t))?Nn(n[1],n[2]/100,n[3]/100,1):(n=ln.exec(t))?Nn(n[1],n[2]/100,n[3]/100,n[4]):hn.hasOwnProperty(t)?gn(hn[t]):"transparent"===t?new mn(NaN,NaN,NaN,0):null}function gn(t){return new mn(t>>16&255,t>>8&255,255&t,1)}function yn(t,n,e,r){return r<=0&&(t=n=e=NaN),new mn(t,n,e,r)}function _n(t){return t instanceof Jt||(t=vn(t)),t?new mn((t=t.rgb()).r,t.g,t.b,t.opacity):new mn}function bn(t,n,e,r){return 1===arguments.length?_n(t):new mn(t,n,e,null==r?1:r)}function mn(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function xn(){return"#"+Mn(this.r)+Mn(this.g)+Mn(this.b)}function wn(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}function Mn(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function Nn(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new Sn(t,n,e,r)}function Tn(t){if(t instanceof Sn)return new Sn(t.h,t.s,t.l,t.opacity);if(t instanceof Jt||(t=vn(t)),!t)return new Sn;if(t instanceof Sn)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),a=NaN,u=o-i,c=(o+i)/2;return u?(a=n===o?(e-r)/u+6*(e0&&c<1?0:a,new Sn(a,u,c,t.opacity)}function An(t,n,e,r){return 1===arguments.length?Tn(t):new Sn(t,n,e,null==r?1:r)}function Sn(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function kn(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}Qt(Jt,vn,{copy:function(t){return Object.assign(new this.constructor,this,t)},displayable:function(){return this.rgb().displayable()},hex:dn,formatHex:dn,formatHsl:function(){return Tn(this).formatHsl()},formatRgb:pn,toString:pn}),Qt(mn,bn,Kt(Jt,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new mn(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new mn(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:xn,formatHex:xn,formatRgb:wn,toString:wn})),Qt(Sn,An,Kt(Jt,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new Sn(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new Sn(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new mn(kn(t>=240?t-240:t+120,i,r),kn(t,i,r),kn(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===t?")":", "+t+")")}}));var En=Math.PI/180,Cn=180/Math.PI,Pn=.96422,zn=1,Rn=.82521,Dn=4/29,qn=6/29,Ln=3*qn*qn,Un=qn*qn*qn;function On(t){if(t instanceof Yn)return new Yn(t.l,t.a,t.b,t.opacity);if(t instanceof Vn)return $n(t);t instanceof mn||(t=_n(t));var n,e,r=jn(t.r),i=jn(t.g),o=jn(t.b),a=Fn((.2225045*r+.7168786*i+.0606169*o)/zn);return r===i&&i===o?n=e=a:(n=Fn((.4360747*r+.3850649*i+.1430804*o)/Pn),e=Fn((.0139322*r+.0971045*i+.7141733*o)/Rn)),new Yn(116*a-16,500*(n-a),200*(a-e),t.opacity)}function Bn(t,n,e,r){return 1===arguments.length?On(t):new Yn(t,n,e,null==r?1:r)}function Yn(t,n,e,r){this.l=+t,this.a=+n,this.b=+e,this.opacity=+r}function Fn(t){return t>Un?Math.pow(t,1/3):t/Ln+Dn}function In(t){return t>qn?t*t*t:Ln*(t-Dn)}function Hn(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function jn(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Xn(t){if(t instanceof Vn)return new Vn(t.h,t.c,t.l,t.opacity);if(t instanceof Yn||(t=On(t)),0===t.a&&0===t.b)return new Vn(NaN,0=1?(e=1,n-1):Math.floor(e*n),i=t[r],o=t[r+1],a=r>0?t[r-1]:2*i-o,u=r180||e<-180?e-360*Math.round(e/360):e):ce(isNaN(t)?n:t)}function le(t){return 1==(t=+t)?he:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):ce(isNaN(n)?e:n)}}function he(t,n){var e=n-t;return e?fe(t,e):ce(isNaN(t)?n:t)}Qt(ie,re,Kt(Jt,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new ie(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new ie(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=isNaN(this.h)?0:(this.h+120)*En,n=+this.l,e=isNaN(this.s)?0:this.s*n*(1-n),r=Math.cos(t),i=Math.sin(t);return new mn(255*(n+e*(Wn*r+Zn*i)),255*(n+e*(Qn*r+Kn*i)),255*(n+e*(Jn*r)),this.opacity)}}));var de=function t(n){var e=le(n);function r(t,n){var r=e((t=bn(t)).r,(n=bn(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),a=he(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=a(n),t+""}}return r.gamma=t,r}(1);function pe(t){return function(n){var e,r,i=n.length,o=new Array(i),a=new Array(i),u=new Array(i);for(e=0;eo&&(i=n.slice(o,i),u[a]?u[a]+=i:u[++a]=i),(e=e[0])===(r=r[0])?u[a]?u[a]+=r:u[++a]=r:(u[++a]=null,c.push({i:a,x:be(e,r)})),o=we.lastIndex;return o180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:be(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,a.rotate,u,c),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:be(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,a.skewX,u,c),function(t,n,e,r,o,a){if(t!==e||n!==r){var u=o.push(i(o)+"scale(",null,",",null,")");a.push({i:u-4,x:be(t,e)},{i:u-2,x:be(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,a.scaleX,a.scaleY,u,c),o=a=null,function(t){for(var n,e=-1,r=c.length;++e=0&&n._call.call(null,t),n=n._next;--Je}function dr(){ir=(rr=ar.now())+or,Je=tr=0;try{hr()}finally{Je=0,function(){var t,n,e=Qe,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:Qe=n);Ke=t,vr(r)}(),ir=0}}function pr(){var t=ar.now(),n=t-rr;n>er&&(or-=n,rr=t)}function vr(t){Je||(tr&&(tr=clearTimeout(tr)),t-ir>24?(t<1/0&&(tr=setTimeout(dr,t-ar.now()-or)),nr&&(nr=clearInterval(nr))):(nr||(rr=ar.now(),nr=setInterval(pr,er)),Je=1,ur(dr)))}function gr(t,n,e){var r=new sr;return n=null==n?0:+n,r.restart(function(e){r.stop(),t(e+n)},n,e),r}sr.prototype=lr.prototype={constructor:sr,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?cr():+e)+(null==n?0:+n),this._next||Ke===this||(Ke?Ke._next=this:Qe=this,Ke=this),this._call=t,this._time=e,vr()},stop:function(){this._call&&(this._call=null,this._time=1/0,vr())}};var yr=I("start","end","cancel","interrupt"),_r=[],br=0,mr=1,xr=2,wr=3,Mr=4,Nr=5,Tr=6;function Ar(t,n,e,r,i,o){var a=t.__transition;if(a){if(e in a)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(c){var f,s,l,h;if(e.state!==mr)return u();for(f in i)if((h=i[f]).name===e.name){if(h.state===wr)return gr(o);h.state===Mr?(h.state=Tr,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[f]):+fbr)throw new Error("too late; already scheduled");return e}function kr(t,n){var e=Er(t,n);if(e.state>wr)throw new Error("too late; already running");return e}function Er(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}function Cr(t,n){var e,r,i,o=t.__transition,a=!0;if(o){for(i in n=null==n?null:n+"",o)(e=o[i]).name===n?(r=e.state>xr&&e.state=0&&(t=t.slice(0,n)),!t||"start"===t})}(n)?Sr:kr;return function(){var a=o(this,t),u=a.on;u!==r&&(i=(r=u).copy()).on(n,e),a.on=i}}(e,t,n))},attr:function(t,n){var e=W(t),r="transform"===e?qe:zr;return this.attrTween(t,"function"==typeof n?(e.local?function(t,n,e){var r,i,o;return function(){var a,u,c=e(this);if(null!=c)return(a=this.getAttributeNS(t.space,t.local))===(u=c+"")?null:a===r&&u===i?o:(i=u,o=n(r=a,c));this.removeAttributeNS(t.space,t.local)}}:function(t,n,e){var r,i,o;return function(){var a,u,c=e(this);if(null!=c)return(a=this.getAttribute(t))===(u=c+"")?null:a===r&&u===i?o:(i=u,o=n(r=a,c));this.removeAttribute(t)}})(e,r,Pr(this,"attr."+t,n)):null==n?(e.local?function(t){return function(){this.removeAttributeNS(t.space,t.local)}}:function(t){return function(){this.removeAttribute(t)}})(e):(e.local?function(t,n,e){var r,i,o=e+"";return function(){var a=this.getAttributeNS(t.space,t.local);return a===o?null:a===r?i:i=n(r=a,e)}}:function(t,n,e){var r,i,o=e+"";return function(){var a=this.getAttribute(t);return a===o?null:a===r?i:i=n(r=a,e)}})(e,r,n))},attrTween:function(t,n){var e="attr."+t;if(arguments.length<2)return(e=this.tween(e))&&e._value;if(null==n)return this.tween(e,null);if("function"!=typeof n)throw new Error;var r=W(t);return this.tween(e,(r.local?function(t,n){var e,r;function i(){var i=n.apply(this,arguments);return i!==r&&(e=(r=i)&&function(t,n){return function(e){this.setAttributeNS(t.space,t.local,n(e))}}(t,i)),e}return i._value=n,i}:function(t,n){var e,r;function i(){var i=n.apply(this,arguments);return i!==r&&(e=(r=i)&&function(t,n){return function(e){this.setAttribute(t,n(e))}}(t,i)),e}return i._value=n,i})(r,n))},style:function(t,n,e){var r="transform"==(t+="")?De:zr;return null==n?this.styleTween(t,function(t,n){var e,r,i;return function(){var o=ft(this,t),a=(this.style.removeProperty(t),ft(this,t));return o===a?null:o===e&&a===r?i:i=n(e=o,r=a)}}(t,r)).on("end.style."+t,Dr(t)):"function"==typeof n?this.styleTween(t,function(t,n,e){var r,i,o;return function(){var a=ft(this,t),u=e(this),c=u+"";return null==u&&(this.style.removeProperty(t),c=u=ft(this,t)),a===c?null:a===r&&c===i?o:(i=c,o=n(r=a,u))}}(t,r,Pr(this,"style."+t,n))).each(function(t,n){var e,r,i,o,a="style."+n,u="end."+a;return function(){var c=kr(this,t),f=c.on,s=null==c.value[a]?o||(o=Dr(n)):void 0;f===e&&i===s||(r=(e=f).copy()).on(u,i=s),c.on=r}}(this._id,t)):this.styleTween(t,function(t,n,e){var r,i,o=e+"";return function(){var a=ft(this,t);return a===o?null:a===r?i:i=n(r=a,e)}}(t,r,n),e).on("end.style."+t,null)},styleTween:function(t,n,e){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==n)return this.tween(r,null);if("function"!=typeof n)throw new Error;return this.tween(r,function(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&function(t,n,e){return function(r){this.style.setProperty(t,n(r),e)}}(t,o,e)),r}return o._value=n,o}(t,n,null==e?"":e))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var n=t(this);this.textContent=null==n?"":n}}(Pr(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},remove:function(){return this.on("end.remove",function(t){return function(){var n=this.parentNode;for(var e in this.__transition)if(+e!==t)return;n&&n.removeChild(this)}}(this._id))},tween:function(t,n){var e=this._id;if(t+="",arguments.length<2){for(var r,i=Er(this.node(),e).tween,o=0,a=i.length;o0&&(r=o-P),M<0?d=p-z:M>0&&(u=c-z),x=wi,B.attr("cursor",Ci.selection),I());break;default:return}mi()},!0).on("keyup.brush",function(){switch(t.event.keyCode){case 16:R&&(g=y=R=!1,I());break;case 18:x===Ni&&(w<0?f=h:w>0&&(r=o),M<0?d=p:M>0&&(u=c),x=Mi,I());break;case 32:x===wi&&(t.event.altKey?(w&&(f=h-P*w,r=o+P*w),M&&(d=p-z*M,u=c+z*M),x=Ni):(w<0?f=h:w>0&&(r=o),M<0?d=p:M>0&&(u=c),x=Mi),B.attr("cursor",Ci[m]),I());break;default:return}mi()},!0),Ht(t.event.view)}bi(),Cr(b),s.call(b),U.start()}function F(){var t=D(b);!R||g||y||(Math.abs(t[0]-L[0])>Math.abs(t[1]-L[1])?y=!0:g=!0),L=t,v=!0,mi(),I()}function I(){var t;switch(P=L[0]-q[0],z=L[1]-q[1],x){case wi:case xi:w&&(P=Math.max(S-r,Math.min(E-f,P)),o=r+P,h=f+P),M&&(z=Math.max(k-u,Math.min(C-d,z)),c=u+z,p=d+z);break;case Mi:w<0?(P=Math.max(S-r,Math.min(E-r,P)),o=r+P,h=f):w>0&&(P=Math.max(S-f,Math.min(E-f,P)),o=r,h=f+P),M<0?(z=Math.max(k-u,Math.min(C-u,z)),c=u+z,p=d):M>0&&(z=Math.max(k-d,Math.min(C-d,z)),c=u,p=d+z);break;case Ni:w&&(o=Math.max(S,Math.min(E,r-P*w)),h=Math.max(S,Math.min(E,f+P*w))),M&&(c=Math.max(k,Math.min(C,u-z*M)),p=Math.max(k,Math.min(C,d+z*M)))}h1e-6)if(Math.abs(s*u-c*f)>1e-6&&i){var h=e-o,d=r-a,p=u*u+c*c,v=h*h+d*d,g=Math.sqrt(p),y=Math.sqrt(l),_=i*Math.tan((Zi-Math.acos((p+l-v)/(2*g*y)))/2),b=_/y,m=_/g;Math.abs(b-1)>1e-6&&(this._+="L"+(t+b*f)+","+(n+b*s)),this._+="A"+i+","+i+",0,0,"+ +(s*h>f*d)+","+(this._x1=t+m*u)+","+(this._y1=n+m*c)}else this._+="L"+(this._x1=t)+","+(this._y1=n);else;},arc:function(t,n,e,r,i,o){t=+t,n=+n,o=!!o;var a=(e=+e)*Math.cos(r),u=e*Math.sin(r),c=t+a,f=n+u,s=1^o,l=o?r-i:i-r;if(e<0)throw new Error("negative radius: "+e);null===this._x1?this._+="M"+c+","+f:(Math.abs(this._x1-c)>1e-6||Math.abs(this._y1-f)>1e-6)&&(this._+="L"+c+","+f),e&&(l<0&&(l=l%Qi+Qi),l>Ki?this._+="A"+e+","+e+",0,1,"+s+","+(t-a)+","+(n-u)+"A"+e+","+e+",0,1,"+s+","+(this._x1=c)+","+(this._y1=f):l>1e-6&&(this._+="A"+e+","+e+",0,"+ +(l>=Zi)+","+s+","+(this._x1=t+e*Math.cos(i))+","+(this._y1=n+e*Math.sin(i))))},rect:function(t,n,e,r){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+n)+"h"+ +e+"v"+ +r+"h"+-e+"Z"},toString:function(){return this._}};function ao(){}function uo(t,n){var e=new ao;if(t instanceof ao)t.each(function(t,n){e.set(n,t)});else if(Array.isArray(t)){var r,i=-1,o=t.length;if(null==n)for(;++ir!=d>r&&e<(h-f)*(r-s)/(d-s)+f&&(i=-i)}return i}function xo(t,n,e){var r,i,o,a;return function(t,n,e){return(n[0]-t[0])*(e[1]-t[1])==(e[0]-t[0])*(n[1]-t[1])}(t,n,e)&&(i=t[r=+(t[0]===n[0])],o=e[r],a=n[r],i<=o&&o<=a||a<=o&&o<=i)}function wo(){}var Mo=[[],[[[1,1.5],[.5,1]]],[[[1.5,1],[1,1.5]]],[[[1.5,1],[.5,1]]],[[[1,.5],[1.5,1]]],[[[1,1.5],[.5,1]],[[1,.5],[1.5,1]]],[[[1,.5],[1,1.5]]],[[[1,.5],[.5,1]]],[[[.5,1],[1,.5]]],[[[1,1.5],[1,.5]]],[[[.5,1],[1,.5]],[[1.5,1],[1,1.5]]],[[[1.5,1],[1,.5]]],[[[.5,1],[1.5,1]]],[[[1,1.5],[1.5,1]]],[[[.5,1],[1,1.5]]],[]];function No(){var t=1,n=1,e=M,r=u;function i(t){var n=e(t);if(Array.isArray(n))n=n.slice().sort(yo);else{var r=s(t),i=r[0],a=r[1];n=w(i,a,n),n=g(Math.floor(i/n)*n,Math.floor(a/n)*n,n)}return n.map(function(n){return o(t,n)})}function o(e,i){var o=[],u=[];return function(e,r,i){var o,u,c,f,s,l,h=new Array,d=new Array;o=u=-1,f=e[0]>=r,Mo[f<<1].forEach(p);for(;++o=r,Mo[c|f<<1].forEach(p);Mo[f<<0].forEach(p);for(;++u=r,s=e[u*t]>=r,Mo[f<<1|s<<2].forEach(p);++o=r,l=s,s=e[u*t+o+1]>=r,Mo[c|f<<1|s<<2|l<<3].forEach(p);Mo[f|s<<3].forEach(p)}o=-1,s=e[u*t]>=r,Mo[s<<2].forEach(p);for(;++o=r,Mo[s<<2|l<<3].forEach(p);function p(t){var n,e,r=[t[0][0]+o,t[0][1]+u],c=[t[1][0]+o,t[1][1]+u],f=a(r),s=a(c);(n=d[f])?(e=h[s])?(delete d[n.end],delete h[e.start],n===e?(n.ring.push(c),i(n.ring)):h[n.start]=d[e.end]={start:n.start,end:e.end,ring:n.ring.concat(e.ring)}):(delete d[n.end],n.ring.push(c),d[n.end=s]=n):(n=h[s])?(e=d[f])?(delete h[n.start],delete d[e.end],n===e?(n.ring.push(c),i(n.ring)):h[e.start]=d[n.end]={start:e.start,end:n.end,ring:e.ring.concat(n.ring)}):(delete h[n.start],n.ring.unshift(r),h[n.start=f]=n):h[f]=d[s]={start:f,end:s,ring:[r,c]}}Mo[s<<3].forEach(p)}(e,i,function(t){r(t,e,i),function(t){for(var n=0,e=t.length,r=t[e-1][1]*t[0][0]-t[e-1][0]*t[0][1];++n0?o.push([t]):u.push(t)}),u.forEach(function(t){for(var n,e=0,r=o.length;e0&&a0&&u0&&o>0))throw new Error("invalid size");return t=r,n=o,i},i.thresholds=function(t){return arguments.length?(e="function"==typeof t?t:Array.isArray(t)?_o(go.call(t)):_o(t),i):e},i.smooth=function(t){return arguments.length?(r=t?u:wo,i):r===u},i}function To(t,n,e){for(var r=t.width,i=t.height,o=1+(e<<1),a=0;a=e&&(u>=o&&(c-=t.data[u-o+a*r]),n.data[u-e+a*r]=c/Math.min(u+1,r-1+o-u,o))}function Ao(t,n,e){for(var r=t.width,i=t.height,o=1+(e<<1),a=0;a=e&&(u>=o&&(c-=t.data[a+(u-o)*r]),n.data[a+(u-e)*r]=c/Math.min(u+1,i-1+o-u,o))}function So(t){return t[0]}function ko(t){return t[1]}function Eo(){return 1}var Co={},Po={},zo=34,Ro=10,Do=13;function qo(t){return new Function("d","return {"+t.map(function(t,n){return JSON.stringify(t)+": d["+n+"]"}).join(",")+"}")}function Lo(t){var n=Object.create(null),e=[];return t.forEach(function(t){for(var r in t)r in n||e.push(n[r]=r)}),e}function Uo(t,n){var e=t+"",r=e.length;return r9999?"+"+Uo(t,6):Uo(t,4)}(t.getUTCFullYear())+"-"+Uo(t.getUTCMonth()+1,2)+"-"+Uo(t.getUTCDate(),2)+(i?"T"+Uo(n,2)+":"+Uo(e,2)+":"+Uo(r,2)+"."+Uo(i,3)+"Z":r?"T"+Uo(n,2)+":"+Uo(e,2)+":"+Uo(r,2)+"Z":e||n?"T"+Uo(n,2)+":"+Uo(e,2)+"Z":"")}function Bo(t){var n=new RegExp('["'+t+"\n\r]"),e=t.charCodeAt(0);function r(t,n){var r,i=[],o=t.length,a=0,u=0,c=o<=0,f=!1;function s(){if(c)return Po;if(f)return f=!1,Co;var n,r,i=a;if(t.charCodeAt(i)===zo){for(;a++=o?c=!0:(r=t.charCodeAt(a++))===Ro?f=!0:r===Do&&(f=!0,t.charCodeAt(a)===Ro&&++a),t.slice(i+1,n-1).replace(/""/g,'"')}for(;a=(o=(v+y)/2))?v=o:y=o,(s=e>=(a=(g+_)/2))?g=a:_=a,i=d,!(d=d[l=s<<1|f]))return i[l]=p,t;if(u=+t._x.call(null,d.data),c=+t._y.call(null,d.data),n===u&&e===c)return p.next=d,i?i[l]=p:t._root=p,t;do{i=i?i[l]=new Array(4):t._root=new Array(4),(f=n>=(o=(v+y)/2))?v=o:y=o,(s=e>=(a=(g+_)/2))?g=a:_=a}while((l=s<<1|f)==(h=(c>=a)<<1|u>=o));return i[h]=d,i[l]=p,t}function da(t,n,e,r,i){this.node=t,this.x0=n,this.y0=e,this.x1=r,this.y1=i}function pa(t){return t[0]}function va(t){return t[1]}function ga(t,n,e){var r=new ya(null==n?pa:n,null==e?va:e,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function ya(t,n,e,r,i,o){this._x=t,this._y=n,this._x0=e,this._y0=r,this._x1=i,this._y1=o,this._root=void 0}function _a(t){for(var n={data:t.data},e=n;t=t.next;)e=e.next={data:t.data};return n}var ba=ga.prototype=ya.prototype;function ma(t){return t.x+t.vx}function xa(t){return t.y+t.vy}function wa(t){return t.index}function Ma(t,n){var e=t.get(n);if(!e)throw new Error("missing: "+n);return e}function Na(t){return t.x}function Ta(t){return t.y}ba.copy=function(){var t,n,e=new ya(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return e;if(!r.length)return e._root=_a(r),e;for(t=[{source:r,target:e._root=new Array(4)}];r=t.pop();)for(var i=0;i<4;++i)(n=r.source[i])&&(n.length?t.push({source:n,target:r.target[i]=new Array(4)}):r.target[i]=_a(n));return e},ba.add=function(t){var n=+this._x.call(null,t),e=+this._y.call(null,t);return ha(this.cover(n,e),n,e,t)},ba.addAll=function(t){var n,e,r,i,o=t.length,a=new Array(o),u=new Array(o),c=1/0,f=1/0,s=-1/0,l=-1/0;for(e=0;es&&(s=r),il&&(l=i));if(c>s||f>l)return this;for(this.cover(c,f).cover(s,l),e=0;et||t>=i||r>n||n>=o;)switch(u=(nh||(o=c.y0)>d||(a=c.x1)=y)<<1|t>=g)&&(c=p[p.length-1],p[p.length-1]=p[p.length-1-f],p[p.length-1-f]=c)}else{var _=t-+this._x.call(null,v.data),b=n-+this._y.call(null,v.data),m=_*_+b*b;if(m=(u=(p+g)/2))?p=u:g=u,(s=a>=(c=(v+y)/2))?v=c:y=c,n=d,!(d=d[l=s<<1|f]))return this;if(!d.length)break;(n[l+1&3]||n[l+2&3]||n[l+3&3])&&(e=n,h=l)}for(;d.data!==t;)if(r=d,!(d=d.next))return this;return(i=d.next)&&delete d.next,r?(i?r.next=i:delete r.next,this):n?(i?n[l]=i:delete n[l],(d=n[0]||n[1]||n[2]||n[3])&&d===(n[3]||n[2]||n[1]||n[0])&&!d.length&&(e?e[h]=d:this._root=d),this):(this._root=i,this)},ba.removeAll=function(t){for(var n=0,e=t.length;n1?r[0]+r.slice(2):r,+t.slice(e+1)]}function Ea(t){return(t=ka(Math.abs(t)))?t[1]:NaN}var Ca,Pa=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function za(t){return new Ra(t)}function Ra(t){if(!(n=Pa.exec(t)))throw new Error("invalid format: "+t);var n;this.fill=n[1]||" ",this.align=n[2]||">",this.sign=n[3]||"-",this.symbol=n[4]||"",this.zero=!!n[5],this.width=n[6]&&+n[6],this.comma=!!n[7],this.precision=n[8]&&+n[8].slice(1),this.trim=!!n[9],this.type=n[10]||""}function Da(t,n){var e=ka(t,n);if(!e)return t+"";var r=e[0],i=e[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}za.prototype=Ra.prototype,Ra.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(null==this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(null==this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};var qa={"%":function(t,n){return(100*t).toFixed(n)},b:function(t){return Math.round(t).toString(2)},c:function(t){return t+""},d:function(t){return Math.round(t).toString(10)},e:function(t,n){return t.toExponential(n)},f:function(t,n){return t.toFixed(n)},g:function(t,n){return t.toPrecision(n)},o:function(t){return Math.round(t).toString(8)},p:function(t,n){return Da(100*t,n)},r:Da,s:function(t,n){var e=ka(t,n);if(!e)return t+"";var r=e[0],i=e[1],o=i-(Ca=3*Math.max(-8,Math.min(8,Math.floor(i/3))))+1,a=r.length;return o===a?r:o>a?r+new Array(o-a+1).join("0"):o>0?r.slice(0,o)+"."+r.slice(o):"0."+new Array(1-o).join("0")+ka(t,Math.max(0,n+o-1))[0]},X:function(t){return Math.round(t).toString(16).toUpperCase()},x:function(t){return Math.round(t).toString(16)}};function La(t){return t}var Ua,Oa=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Ba(t){var n,e,r=t.grouping&&t.thousands?(n=t.grouping,e=t.thousands,function(t,r){for(var i=t.length,o=[],a=0,u=n[0],c=0;i>0&&u>0&&(c+u+1>r&&(u=Math.max(1,r-c)),o.push(t.substring(i-=u,i+u)),!((c+=u+1)>r));)u=n[a=(a+1)%n.length];return o.reverse().join(e)}):La,i=t.currency,o=t.decimal,a=t.numerals?function(t){return function(n){return n.replace(/[0-9]/g,function(n){return t[+n]})}}(t.numerals):La,u=t.percent||"%";function c(t){var n=(t=za(t)).fill,e=t.align,c=t.sign,f=t.symbol,s=t.zero,l=t.width,h=t.comma,d=t.precision,p=t.trim,v=t.type;"n"===v?(h=!0,v="g"):qa[v]||(null==d&&(d=12),p=!0,v="g"),(s||"0"===n&&"="===e)&&(s=!0,n="0",e="=");var g="$"===f?i[0]:"#"===f&&/[boxX]/.test(v)?"0"+v.toLowerCase():"",y="$"===f?i[1]:/[%p]/.test(v)?u:"",_=qa[v],b=/[defgprs%]/.test(v);function m(t){var i,u,f,m=g,x=y;if("c"===v)x=_(t)+x,t="";else{var w=(t=+t)<0;if(t=_(Math.abs(t),d),p&&(t=function(t){t:for(var n,e=t.length,r=1,i=-1;r0){if(!+t[r])break t;i=0}}return i>0?t.slice(0,i)+t.slice(n+1):t}(t)),w&&0==+t&&(w=!1),m=(w?"("===c?c:"-":"-"===c||"("===c?"":c)+m,x=("s"===v?Oa[8+Ca/3]:"")+x+(w&&"("===c?")":""),b)for(i=-1,u=t.length;++i(f=t.charCodeAt(i))||f>57){x=(46===f?o+t.slice(i+1):t.slice(i))+x,t=t.slice(0,i);break}}h&&!s&&(t=r(t,1/0));var M=m.length+t.length+x.length,N=M>1)+m+t+x+N.slice(M);break;default:t=N+m+t+x}return a(t)}return d=null==d?6:/[gprs]/.test(v)?Math.max(1,Math.min(21,d)):Math.max(0,Math.min(20,d)),m.toString=function(){return t+""},m}return{format:c,formatPrefix:function(t,n){var e=c(((t=za(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor(Ea(n)/3))),i=Math.pow(10,-r),o=Oa[8+r/3];return function(t){return e(i*t)+o}}}}function Ya(n){return Ua=Ba(n),t.format=Ua.format,t.formatPrefix=Ua.formatPrefix,Ua}function Fa(t){return Math.max(0,-Ea(Math.abs(t)))}function Ia(t,n){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor(Ea(n)/3)))-Ea(Math.abs(t)))}function Ha(t,n){return t=Math.abs(t),n=Math.abs(n)-t,Math.max(0,Ea(n)-Ea(t))+1}function ja(){return new Xa}function Xa(){this.reset()}Ya({decimal:".",thousands:",",grouping:[3],currency:["$",""]}),Xa.prototype={constructor:Xa,reset:function(){this.s=this.t=0},add:function(t){Va(Ga,t,this.t),Va(this,Ga.s,this.s),this.s?this.t+=Ga.t:this.s=Ga.t},valueOf:function(){return this.s}};var Ga=new Xa;function Va(t,n,e){var r=t.s=n+e,i=r-n,o=r-i;t.t=n-o+(e-i)}var $a=1e-6,Wa=1e-12,Za=Math.PI,Qa=Za/2,Ka=Za/4,Ja=2*Za,tu=180/Za,nu=Za/180,eu=Math.abs,ru=Math.atan,iu=Math.atan2,ou=Math.cos,au=Math.ceil,uu=Math.exp,cu=Math.log,fu=Math.pow,su=Math.sin,lu=Math.sign||function(t){return t>0?1:t<0?-1:0},hu=Math.sqrt,du=Math.tan;function pu(t){return t>1?0:t<-1?Za:Math.acos(t)}function vu(t){return t>1?Qa:t<-1?-Qa:Math.asin(t)}function gu(t){return(t=su(t/2))*t}function yu(){}function _u(t,n){t&&mu.hasOwnProperty(t.type)&&mu[t.type](t,n)}var bu={Feature:function(t,n){_u(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r=0?1:-1,i=r*e,o=ou(n=(n*=nu)/2+Ka),a=su(n),u=ku*a,c=Su*o+u*ou(i),f=u*r*su(i);Eu.add(iu(f,c)),Au=t,Su=o,ku=a}function Lu(t){return[iu(t[1],t[0]),vu(t[2])]}function Uu(t){var n=t[0],e=t[1],r=ou(e);return[r*ou(n),r*su(n),su(e)]}function Ou(t,n){return t[0]*n[0]+t[1]*n[1]+t[2]*n[2]}function Bu(t,n){return[t[1]*n[2]-t[2]*n[1],t[2]*n[0]-t[0]*n[2],t[0]*n[1]-t[1]*n[0]]}function Yu(t,n){t[0]+=n[0],t[1]+=n[1],t[2]+=n[2]}function Fu(t,n){return[t[0]*n,t[1]*n,t[2]*n]}function Iu(t){var n=hu(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=n,t[1]/=n,t[2]/=n}var Hu,ju,Xu,Gu,Vu,$u,Wu,Zu,Qu,Ku,Ju,tc,nc,ec,rc,ic,oc,ac,uc,cc,fc,sc,lc,hc,dc,pc,vc=ja(),gc={point:yc,lineStart:bc,lineEnd:mc,polygonStart:function(){gc.point=xc,gc.lineStart=wc,gc.lineEnd=Mc,vc.reset(),Pu.polygonStart()},polygonEnd:function(){Pu.polygonEnd(),gc.point=yc,gc.lineStart=bc,gc.lineEnd=mc,Eu<0?(Hu=-(Xu=180),ju=-(Gu=90)):vc>$a?Gu=90:vc<-$a&&(ju=-90),Ku[0]=Hu,Ku[1]=Xu},sphere:function(){Hu=-(Xu=180),ju=-(Gu=90)}};function yc(t,n){Qu.push(Ku=[Hu=t,Xu=t]),nGu&&(Gu=n)}function _c(t,n){var e=Uu([t*nu,n*nu]);if(Zu){var r=Bu(Zu,e),i=Bu([r[1],-r[0],0],r);Iu(i),i=Lu(i);var o,a=t-Vu,u=a>0?1:-1,c=i[0]*tu*u,f=eu(a)>180;f^(u*VuGu&&(Gu=o):f^(u*Vu<(c=(c+360)%360-180)&&cGu&&(Gu=n)),f?tNc(Hu,Xu)&&(Xu=t):Nc(t,Xu)>Nc(Hu,Xu)&&(Hu=t):Xu>=Hu?(tXu&&(Xu=t)):t>Vu?Nc(Hu,t)>Nc(Hu,Xu)&&(Xu=t):Nc(t,Xu)>Nc(Hu,Xu)&&(Hu=t)}else Qu.push(Ku=[Hu=t,Xu=t]);nGu&&(Gu=n),Zu=e,Vu=t}function bc(){gc.point=_c}function mc(){Ku[0]=Hu,Ku[1]=Xu,gc.point=yc,Zu=null}function xc(t,n){if(Zu){var e=t-Vu;vc.add(eu(e)>180?e+(e>0?360:-360):e)}else $u=t,Wu=n;Pu.point(t,n),_c(t,n)}function wc(){Pu.lineStart()}function Mc(){xc($u,Wu),Pu.lineEnd(),eu(vc)>$a&&(Hu=-(Xu=180)),Ku[0]=Hu,Ku[1]=Xu,Zu=null}function Nc(t,n){return(n-=t)<0?n+360:n}function Tc(t,n){return t[0]-n[0]}function Ac(t,n){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:nZa?t+Math.round(-t/Ja)*Ja:t,n]}function Fc(t,n,e){return(t%=Ja)?n||e?Bc(Hc(t),jc(n,e)):Hc(t):n||e?jc(n,e):Yc}function Ic(t){return function(n,e){return[(n+=t)>Za?n-Ja:n<-Za?n+Ja:n,e]}}function Hc(t){var n=Ic(t);return n.invert=Ic(-t),n}function jc(t,n){var e=ou(t),r=su(t),i=ou(n),o=su(n);function a(t,n){var a=ou(n),u=ou(t)*a,c=su(t)*a,f=su(n),s=f*e+u*r;return[iu(c*i-s*o,u*e-f*r),vu(s*i+c*o)]}return a.invert=function(t,n){var a=ou(n),u=ou(t)*a,c=su(t)*a,f=su(n),s=f*i-c*o;return[iu(c*i+f*o,u*e+s*r),vu(s*e-u*r)]},a}function Xc(t){function n(n){return(n=t(n[0]*nu,n[1]*nu))[0]*=tu,n[1]*=tu,n}return t=Fc(t[0]*nu,t[1]*nu,t.length>2?t[2]*nu:0),n.invert=function(n){return(n=t.invert(n[0]*nu,n[1]*nu))[0]*=tu,n[1]*=tu,n},n}function Gc(t,n,e,r,i,o){if(e){var a=ou(n),u=su(n),c=r*e;null==i?(i=n+r*Ja,o=n-c/2):(i=Vc(a,i),o=Vc(a,o),(r>0?io)&&(i+=r*Ja));for(var f,s=i;r>0?s>o:s1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}}function Wc(t,n){return eu(t[0]-n[0])<$a&&eu(t[1]-n[1])<$a}function Zc(t,n,e,r){this.x=t,this.z=n,this.o=e,this.e=r,this.v=!1,this.n=this.p=null}function Qc(t,n,e,r,i){var o,a,u=[],c=[];if(t.forEach(function(t){if(!((n=t.length-1)<=0)){var n,e,r=t[0],a=t[n];if(Wc(r,a)){for(i.lineStart(),o=0;o=0;--o)i.point((s=f[o])[0],s[1]);else r(h.x,h.p.x,-1,i);h=h.p}f=(h=h.o).z,d=!d}while(!h.v);i.lineEnd()}}}function Kc(t){if(n=t.length){for(var n,e,r=0,i=t[0];++r=0?1:-1,T=N*M,A=T>Za,S=v*x;if(Jc.add(iu(S*N*su(T),g*w+S*ou(T))),a+=A?M+N*Ja:M,A^d>=e^b>=e){var k=Bu(Uu(h),Uu(_));Iu(k);var E=Bu(o,k);Iu(E);var C=(A^M>=0?-1:1)*vu(E[2]);(r>C||r===C&&(k[0]||k[1]))&&(u+=A^M>=0?1:-1)}}return(a<-$a||a<$a&&Jc<-$a)^1&u}function ef(t,n,e,r){return function(i){var o,a,u,c=n(i),f=$c(),s=n(f),l=!1,h={point:d,lineStart:v,lineEnd:g,polygonStart:function(){h.point=y,h.lineStart=_,h.lineEnd=b,a=[],o=[]},polygonEnd:function(){h.point=d,h.lineStart=v,h.lineEnd=g,a=A(a);var t=nf(o,r);a.length?(l||(i.polygonStart(),l=!0),Qc(a,of,t,e,i)):t&&(l||(i.polygonStart(),l=!0),i.lineStart(),e(null,null,1,i),i.lineEnd()),l&&(i.polygonEnd(),l=!1),a=o=null},sphere:function(){i.polygonStart(),i.lineStart(),e(null,null,1,i),i.lineEnd(),i.polygonEnd()}};function d(n,e){t(n,e)&&i.point(n,e)}function p(t,n){c.point(t,n)}function v(){h.point=p,c.lineStart()}function g(){h.point=d,c.lineEnd()}function y(t,n){u.push([t,n]),s.point(t,n)}function _(){s.lineStart(),u=[]}function b(){y(u[0][0],u[0][1]),s.lineEnd();var t,n,e,r,c=s.clean(),h=f.result(),d=h.length;if(u.pop(),o.push(u),u=null,d)if(1&c){if((n=(e=h[0]).length-1)>0){for(l||(i.polygonStart(),l=!0),i.lineStart(),t=0;t1&&2&c&&h.push(h.pop().concat(h.shift())),a.push(h.filter(rf))}return h}}function rf(t){return t.length>1}function of(t,n){return((t=t.x)[0]<0?t[1]-Qa-$a:Qa-t[1])-((n=n.x)[0]<0?n[1]-Qa-$a:Qa-n[1])}var af=ef(function(){return!0},function(t){var n,e=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),n=1},point:function(o,a){var u=o>0?Za:-Za,c=eu(o-e);eu(c-Za)<$a?(t.point(e,r=(r+a)/2>0?Qa:-Qa),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),t.point(o,r),n=0):i!==u&&c>=Za&&(eu(e-i)<$a&&(e-=i*$a),eu(o-u)<$a&&(o-=u*$a),r=function(t,n,e,r){var i,o,a=su(t-e);return eu(a)>$a?ru((su(n)*(o=ou(r))*su(e)-su(r)*(i=ou(n))*su(t))/(i*o*a)):(n+r)/2}(e,r,o,a),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),n=0),t.point(e=o,r=a),i=u},lineEnd:function(){t.lineEnd(),e=r=NaN},clean:function(){return 2-n}}},function(t,n,e,r){var i;if(null==t)i=e*Qa,r.point(-Za,i),r.point(0,i),r.point(Za,i),r.point(Za,0),r.point(Za,-i),r.point(0,-i),r.point(-Za,-i),r.point(-Za,0),r.point(-Za,i);else if(eu(t[0]-n[0])>$a){var o=t[0]0,i=eu(n)>$a;function o(t,e){return ou(t)*ou(e)>n}function a(t,e,r){var i=[1,0,0],o=Bu(Uu(t),Uu(e)),a=Ou(o,o),u=o[0],c=a-u*u;if(!c)return!r&&t;var f=n*a/c,s=-n*u/c,l=Bu(i,o),h=Fu(i,f);Yu(h,Fu(o,s));var d=l,p=Ou(h,d),v=Ou(d,d),g=p*p-v*(Ou(h,h)-1);if(!(g<0)){var y=hu(g),_=Fu(d,(-p-y)/v);if(Yu(_,h),_=Lu(_),!r)return _;var b,m=t[0],x=e[0],w=t[1],M=e[1];x0^_[1]<(eu(_[0]-m)<$a?w:M):w<=_[1]&&_[1]<=M:N>Za^(m<=_[0]&&_[0]<=x)){var A=Fu(d,(-p+y)/v);return Yu(A,h),[_,Lu(A)]}}}function u(n,e){var i=r?t:Za-t,o=0;return n<-i?o|=1:n>i&&(o|=2),e<-i?o|=4:e>i&&(o|=8),o}return ef(o,function(t){var n,e,c,f,s;return{lineStart:function(){f=c=!1,s=1},point:function(l,h){var d,p=[l,h],v=o(l,h),g=r?v?0:u(l,h):v?u(l+(l<0?Za:-Za),h):0;if(!n&&(f=c=v)&&t.lineStart(),v!==c&&(!(d=a(n,p))||Wc(n,d)||Wc(p,d))&&(p[0]+=$a,p[1]+=$a,v=o(p[0],p[1])),v!==c)s=0,v?(t.lineStart(),d=a(p,n),t.point(d[0],d[1])):(d=a(n,p),t.point(d[0],d[1]),t.lineEnd()),n=d;else if(i&&n&&r^v){var y;g&e||!(y=a(p,n,!0))||(s=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1])))}!v||n&&Wc(n,p)||t.point(p[0],p[1]),n=p,c=v,e=g},lineEnd:function(){c&&t.lineEnd(),n=null},clean:function(){return s|(f&&c)<<1}}},function(n,r,i,o){Gc(o,t,e,i,n,r)},r?[0,-t]:[-Za,t-Za])}var cf=1e9,ff=-cf;function sf(t,n,e,r){function i(i,o){return t<=i&&i<=e&&n<=o&&o<=r}function o(i,o,u,f){var s=0,l=0;if(null==i||(s=a(i,u))!==(l=a(o,u))||c(i,o)<0^u>0)do{f.point(0===s||3===s?t:e,s>1?r:n)}while((s=(s+u+4)%4)!==l);else f.point(o[0],o[1])}function a(r,i){return eu(r[0]-t)<$a?i>0?0:3:eu(r[0]-e)<$a?i>0?2:1:eu(r[1]-n)<$a?i>0?1:0:i>0?3:2}function u(t,n){return c(t.x,n.x)}function c(t,n){var e=a(t,1),r=a(n,1);return e!==r?e-r:0===e?n[1]-t[1]:1===e?t[0]-n[0]:2===e?t[1]-n[1]:n[0]-t[0]}return function(a){var c,f,s,l,h,d,p,v,g,y,_,b=a,m=$c(),x={point:w,lineStart:function(){x.point=M,f&&f.push(s=[]);y=!0,g=!1,p=v=NaN},lineEnd:function(){c&&(M(l,h),d&&g&&m.rejoin(),c.push(m.result()));x.point=w,g&&b.lineEnd()},polygonStart:function(){b=m,c=[],f=[],_=!0},polygonEnd:function(){var n=function(){for(var n=0,e=0,i=f.length;er&&(h-o)*(r-a)>(d-a)*(t-o)&&++n:d<=r&&(h-o)*(r-a)<(d-a)*(t-o)&&--n;return n}(),e=_&&n,i=(c=A(c)).length;(e||i)&&(a.polygonStart(),e&&(a.lineStart(),o(null,null,1,a),a.lineEnd()),i&&Qc(c,u,n,o,a),a.polygonEnd());b=a,c=f=s=null}};function w(t,n){i(t,n)&&b.point(t,n)}function M(o,a){var u=i(o,a);if(f&&s.push([o,a]),y)l=o,h=a,d=u,y=!1,u&&(b.lineStart(),b.point(o,a));else if(u&&g)b.point(o,a);else{var c=[p=Math.max(ff,Math.min(cf,p)),v=Math.max(ff,Math.min(cf,v))],m=[o=Math.max(ff,Math.min(cf,o)),a=Math.max(ff,Math.min(cf,a))];!function(t,n,e,r,i,o){var a,u=t[0],c=t[1],f=0,s=1,l=n[0]-u,h=n[1]-c;if(a=e-u,l||!(a>0)){if(a/=l,l<0){if(a0){if(a>s)return;a>f&&(f=a)}if(a=i-u,l||!(a<0)){if(a/=l,l<0){if(a>s)return;a>f&&(f=a)}else if(l>0){if(a0)){if(a/=h,h<0){if(a0){if(a>s)return;a>f&&(f=a)}if(a=o-c,h||!(a<0)){if(a/=h,h<0){if(a>s)return;a>f&&(f=a)}else if(h>0){if(a0&&(t[0]=u+f*l,t[1]=c+f*h),s<1&&(n[0]=u+s*l,n[1]=c+s*h),!0}}}}}(c,m,t,n,e,r)?u&&(b.lineStart(),b.point(o,a),_=!1):(g||(b.lineStart(),b.point(c[0],c[1])),b.point(m[0],m[1]),u||b.lineEnd(),_=!1)}p=o,v=a,g=u}return x}}var lf,hf,df,pf=ja(),vf={sphere:yu,point:yu,lineStart:function(){vf.point=yf,vf.lineEnd=gf},lineEnd:yu,polygonStart:yu,polygonEnd:yu};function gf(){vf.point=vf.lineEnd=yu}function yf(t,n){lf=t*=nu,hf=su(n*=nu),df=ou(n),vf.point=_f}function _f(t,n){t*=nu;var e=su(n*=nu),r=ou(n),i=eu(t-lf),o=ou(i),a=r*su(i),u=df*e-hf*r*o,c=hf*e+df*r*o;pf.add(iu(hu(a*a+u*u),c)),lf=t,hf=e,df=r}function bf(t){return pf.reset(),Mu(t,vf),+pf}var mf=[null,null],xf={type:"LineString",coordinates:mf};function wf(t,n){return mf[0]=t,mf[1]=n,bf(xf)}var Mf={Feature:function(t,n){return Tf(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r0&&(i=wf(t[o],t[o-1]))>0&&e<=i&&r<=i&&(e+r-i)*(1-Math.pow((e-r)/i,2))$a}).map(c)).concat(g(au(o/d)*d,i,d).filter(function(t){return eu(t%v)>$a}).map(f))}return _.lines=function(){return b().map(function(t){return{type:"LineString",coordinates:t}})},_.outline=function(){return{type:"Polygon",coordinates:[s(r).concat(l(a).slice(1),s(e).reverse().slice(1),l(u).reverse().slice(1))]}},_.extent=function(t){return arguments.length?_.extentMajor(t).extentMinor(t):_.extentMinor()},_.extentMajor=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],u=+t[0][1],a=+t[1][1],r>e&&(t=r,r=e,e=t),u>a&&(t=u,u=a,a=t),_.precision(y)):[[r,u],[e,a]]},_.extentMinor=function(e){return arguments.length?(n=+e[0][0],t=+e[1][0],o=+e[0][1],i=+e[1][1],n>t&&(e=n,n=t,t=e),o>i&&(e=o,o=i,i=e),_.precision(y)):[[n,o],[t,i]]},_.step=function(t){return arguments.length?_.stepMajor(t).stepMinor(t):_.stepMinor()},_.stepMajor=function(t){return arguments.length?(p=+t[0],v=+t[1],_):[p,v]},_.stepMinor=function(t){return arguments.length?(h=+t[0],d=+t[1],_):[h,d]},_.precision=function(h){return arguments.length?(y=+h,c=Pf(o,i,90),f=zf(n,t,y),s=Pf(u,a,90),l=zf(r,e,y),_):y},_.extentMajor([[-180,-90+$a],[180,90-$a]]).extentMinor([[-180,-80-$a],[180,80+$a]])}function Df(t){return t}var qf,Lf,Uf,Of,Bf=ja(),Yf=ja(),Ff={point:yu,lineStart:yu,lineEnd:yu,polygonStart:function(){Ff.lineStart=If,Ff.lineEnd=Xf},polygonEnd:function(){Ff.lineStart=Ff.lineEnd=Ff.point=yu,Bf.add(eu(Yf)),Yf.reset()},result:function(){var t=Bf/2;return Bf.reset(),t}};function If(){Ff.point=Hf}function Hf(t,n){Ff.point=jf,qf=Uf=t,Lf=Of=n}function jf(t,n){Yf.add(Of*t-Uf*n),Uf=t,Of=n}function Xf(){jf(qf,Lf)}var Gf=1/0,Vf=Gf,$f=-Gf,Wf=$f,Zf={point:function(t,n){t$f&&($f=t);nWf&&(Wf=n)},lineStart:yu,lineEnd:yu,polygonStart:yu,polygonEnd:yu,result:function(){var t=[[Gf,Vf],[$f,Wf]];return $f=Wf=-(Vf=Gf=1/0),t}};var Qf,Kf,Jf,ts,ns=0,es=0,rs=0,is=0,os=0,as=0,us=0,cs=0,fs=0,ss={point:ls,lineStart:hs,lineEnd:vs,polygonStart:function(){ss.lineStart=gs,ss.lineEnd=ys},polygonEnd:function(){ss.point=ls,ss.lineStart=hs,ss.lineEnd=vs},result:function(){var t=fs?[us/fs,cs/fs]:as?[is/as,os/as]:rs?[ns/rs,es/rs]:[NaN,NaN];return ns=es=rs=is=os=as=us=cs=fs=0,t}};function ls(t,n){ns+=t,es+=n,++rs}function hs(){ss.point=ds}function ds(t,n){ss.point=ps,ls(Jf=t,ts=n)}function ps(t,n){var e=t-Jf,r=n-ts,i=hu(e*e+r*r);is+=i*(Jf+t)/2,os+=i*(ts+n)/2,as+=i,ls(Jf=t,ts=n)}function vs(){ss.point=ls}function gs(){ss.point=_s}function ys(){bs(Qf,Kf)}function _s(t,n){ss.point=bs,ls(Qf=Jf=t,Kf=ts=n)}function bs(t,n){var e=t-Jf,r=n-ts,i=hu(e*e+r*r);is+=i*(Jf+t)/2,os+=i*(ts+n)/2,as+=i,us+=(i=ts*t-Jf*n)*(Jf+t),cs+=i*(ts+n),fs+=3*i,ls(Jf=t,ts=n)}function ms(t){this._context=t}ms.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._context.moveTo(t,n),this._point=1;break;case 1:this._context.lineTo(t,n);break;default:this._context.moveTo(t+this._radius,n),this._context.arc(t,n,this._radius,0,Ja)}},result:yu};var xs,ws,Ms,Ns,Ts,As=ja(),Ss={point:yu,lineStart:function(){Ss.point=ks},lineEnd:function(){xs&&Es(ws,Ms),Ss.point=yu},polygonStart:function(){xs=!0},polygonEnd:function(){xs=null},result:function(){var t=+As;return As.reset(),t}};function ks(t,n){Ss.point=Es,ws=Ns=t,Ms=Ts=n}function Es(t,n){Ns-=t,Ts-=n,As.add(hu(Ns*Ns+Ts*Ts)),Ns=t,Ts=n}function Cs(){this._string=[]}function Ps(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function zs(t){return function(n){var e=new Rs;for(var r in t)e[r]=t[r];return e.stream=n,e}}function Rs(){}function Ds(t,n,e){var r=t.clipExtent&&t.clipExtent();return t.scale(150).translate([0,0]),null!=r&&t.clipExtent(null),Mu(e,t.stream(Zf)),n(Zf.result()),null!=r&&t.clipExtent(r),t}function qs(t,n,e){return Ds(t,function(e){var r=n[1][0]-n[0][0],i=n[1][1]-n[0][1],o=Math.min(r/(e[1][0]-e[0][0]),i/(e[1][1]-e[0][1])),a=+n[0][0]+(r-o*(e[1][0]+e[0][0]))/2,u=+n[0][1]+(i-o*(e[1][1]+e[0][1]))/2;t.scale(150*o).translate([a,u])},e)}function Ls(t,n,e){return qs(t,[[0,0],n],e)}function Us(t,n,e){return Ds(t,function(e){var r=+n,i=r/(e[1][0]-e[0][0]),o=(r-i*(e[1][0]+e[0][0]))/2,a=-i*e[0][1];t.scale(150*i).translate([o,a])},e)}function Os(t,n,e){return Ds(t,function(e){var r=+n,i=r/(e[1][1]-e[0][1]),o=-i*e[0][0],a=(r-i*(e[1][1]+e[0][1]))/2;t.scale(150*i).translate([o,a])},e)}Cs.prototype={_radius:4.5,_circle:Ps(4.5),pointRadius:function(t){return(t=+t)!==this._radius&&(this._radius=t,this._circle=null),this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._string.push("Z"),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._string.push("M",t,",",n),this._point=1;break;case 1:this._string.push("L",t,",",n);break;default:null==this._circle&&(this._circle=Ps(this._radius)),this._string.push("M",t,",",n,this._circle)}},result:function(){if(this._string.length){var t=this._string.join("");return this._string=[],t}return null}},Rs.prototype={constructor:Rs,point:function(t,n){this.stream.point(t,n)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};var Bs=16,Ys=ou(30*nu);function Fs(t,n){return+n?function(t,n){function e(r,i,o,a,u,c,f,s,l,h,d,p,v,g){var y=f-r,_=s-i,b=y*y+_*_;if(b>4*n&&v--){var m=a+h,x=u+d,w=c+p,M=hu(m*m+x*x+w*w),N=vu(w/=M),T=eu(eu(w)-1)<$a||eu(o-l)<$a?(o+l)/2:iu(x,m),A=t(T,N),S=A[0],k=A[1],E=S-r,C=k-i,P=_*E-y*C;(P*P/b>n||eu((y*E+_*C)/b-.5)>.3||a*h+u*d+c*p2?t[2]%360*nu:0,S()):[g*tu,y*tu,_*tu]},T.angle=function(t){return arguments.length?(b=t%360*nu,S()):b*tu},T.precision=function(t){return arguments.length?(a=Fs(u,N=t*t),k()):hu(N)},T.fitExtent=function(t,n){return qs(T,t,n)},T.fitSize=function(t,n){return Ls(T,t,n)},T.fitWidth=function(t,n){return Us(T,t,n)},T.fitHeight=function(t,n){return Os(T,t,n)},function(){return n=t.apply(this,arguments),T.invert=n.invert&&A,S()}}function Gs(t){var n=0,e=Za/3,r=Xs(t),i=r(n,e);return i.parallels=function(t){return arguments.length?r(n=t[0]*nu,e=t[1]*nu):[n*tu,e*tu]},i}function Vs(t,n){var e=su(t),r=(e+su(n))/2;if(eu(r)<$a)return function(t){var n=ou(t);function e(t,e){return[t*n,su(e)/n]}return e.invert=function(t,e){return[t/n,vu(e*n)]},e}(t);var i=1+e*(2*r-e),o=hu(i)/r;function a(t,n){var e=hu(i-2*r*su(n))/r;return[e*su(t*=r),o-e*ou(t)]}return a.invert=function(t,n){var e=o-n;return[iu(t,eu(e))/r*lu(e),vu((i-(t*t+e*e)*r*r)/(2*r))]},a}function $s(){return Gs(Vs).scale(155.424).center([0,33.6442])}function Ws(){return $s().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}function Zs(t){return function(n,e){var r=ou(n),i=ou(e),o=t(r*i);return[o*i*su(n),o*su(e)]}}function Qs(t){return function(n,e){var r=hu(n*n+e*e),i=t(r),o=su(i),a=ou(i);return[iu(n*o,r*a),vu(r&&e*o/r)]}}var Ks=Zs(function(t){return hu(2/(1+t))});Ks.invert=Qs(function(t){return 2*vu(t/2)});var Js=Zs(function(t){return(t=pu(t))&&t/su(t)});function tl(t,n){return[t,cu(du((Qa+n)/2))]}function nl(t){var n,e,r,i=js(t),o=i.center,a=i.scale,u=i.translate,c=i.clipExtent,f=null;function s(){var o=Za*a(),u=i(Xc(i.rotate()).invert([0,0]));return c(null==f?[[u[0]-o,u[1]-o],[u[0]+o,u[1]+o]]:t===tl?[[Math.max(u[0]-o,f),n],[Math.min(u[0]+o,e),r]]:[[f,Math.max(u[1]-o,n)],[e,Math.min(u[1]+o,r)]])}return i.scale=function(t){return arguments.length?(a(t),s()):a()},i.translate=function(t){return arguments.length?(u(t),s()):u()},i.center=function(t){return arguments.length?(o(t),s()):o()},i.clipExtent=function(t){return arguments.length?(null==t?f=n=e=r=null:(f=+t[0][0],n=+t[0][1],e=+t[1][0],r=+t[1][1]),s()):null==f?null:[[f,n],[e,r]]},s()}function el(t){return du((Qa+t)/2)}function rl(t,n){var e=ou(t),r=t===n?su(t):cu(e/ou(n))/cu(el(n)/el(t)),i=e*fu(el(t),r)/r;if(!r)return tl;function o(t,n){i>0?n<-Qa+$a&&(n=-Qa+$a):n>Qa-$a&&(n=Qa-$a);var e=i/fu(el(n),r);return[e*su(r*t),i-e*ou(r*t)]}return o.invert=function(t,n){var e=i-n,o=lu(r)*hu(t*t+e*e);return[iu(t,eu(e))/r*lu(e),2*ru(fu(i/o,1/r))-Qa]},o}function il(t,n){return[t,n]}function ol(t,n){var e=ou(t),r=t===n?su(t):(e-ou(n))/(n-t),i=e/r+t;if(eu(r)<$a)return il;function o(t,n){var e=i-n,o=r*t;return[e*su(o),i-e*ou(o)]}return o.invert=function(t,n){var e=i-n;return[iu(t,eu(e))/r*lu(e),i-lu(r)*hu(t*t+e*e)]},o}Js.invert=Qs(function(t){return t}),tl.invert=function(t,n){return[t,2*ru(uu(n))-Qa]},il.invert=il;var al=1.340264,ul=-.081106,cl=893e-6,fl=.003796,sl=hu(3)/2;function ll(t,n){var e=vu(sl*su(n)),r=e*e,i=r*r*r;return[t*ou(e)/(sl*(al+3*ul*r+i*(7*cl+9*fl*r))),e*(al+ul*r+i*(cl+fl*r))]}function hl(t,n){var e=ou(n),r=ou(t)*e;return[e*su(t)/r,su(n)/r]}function dl(t,n,e,r){return 1===t&&1===n&&0===e&&0===r?Df:zs({point:function(i,o){this.stream.point(i*t+e,o*n+r)}})}function pl(t,n){var e=n*n,r=e*e;return[t*(.8707-.131979*e+r*(r*(.003971*e-.001529*r)-.013791)),n*(1.007226+e*(.015085+r*(.028874*e-.044475-.005916*r)))]}function vl(t,n){return[ou(n)*su(t),su(n)]}function gl(t,n){var e=ou(n),r=1+ou(t)*e;return[e*su(t)/r,su(n)/r]}function yl(t,n){return[cu(du((Qa+n)/2)),-t]}function _l(t,n){return t.parent===n.parent?1:2}function bl(t,n){return t+n.x}function ml(t,n){return Math.max(t,n.y)}function xl(t){var n=0,e=t.children,r=e&&e.length;if(r)for(;--r>=0;)n+=e[r].value;else n=1;t.value=n}function wl(t,n){var e,r,i,o,a,u=new Al(t),c=+t.value&&(u.value=t.value),f=[u];for(null==n&&(n=Ml);e=f.pop();)if(c&&(e.value=+e.data.value),(i=n(e.data))&&(a=i.length))for(e.children=new Array(a),o=a-1;o>=0;--o)f.push(r=e.children[o]=new Al(i[o])),r.parent=e,r.depth=e.depth+1;return u.eachBefore(Tl)}function Ml(t){return t.children}function Nl(t){t.data=t.data.data}function Tl(t){var n=0;do{t.height=n}while((t=t.parent)&&t.height<++n)}function Al(t){this.data=t,this.depth=this.height=0,this.parent=null}ll.invert=function(t,n){for(var e,r=n,i=r*r,o=i*i*i,a=0;a<12&&(o=(i=(r-=e=(r*(al+ul*i+o*(cl+fl*i))-n)/(al+3*ul*i+o*(7*cl+9*fl*i)))*r)*i*i,!(eu(e)$a&&--i>0);return[t/(.8707+(o=r*r)*(o*(o*o*o*(.003971-.001529*o)-.013791)-.131979)),r]},vl.invert=Qs(vu),gl.invert=Qs(function(t){return 2*ru(t)}),yl.invert=function(t,n){return[-n,2*ru(uu(t))-Qa]},Al.prototype=wl.prototype={constructor:Al,count:function(){return this.eachAfter(xl)},each:function(t){var n,e,r,i,o=this,a=[o];do{for(n=a.reverse(),a=[];o=n.pop();)if(t(o),e=o.children)for(r=0,i=e.length;r=0;--e)i.push(n[e]);return this},sum:function(t){return this.eachAfter(function(n){for(var e=+t(n.data)||0,r=n.children,i=r&&r.length;--i>=0;)e+=r[i].value;n.value=e})},sort:function(t){return this.eachBefore(function(n){n.children&&n.children.sort(t)})},path:function(t){for(var n=this,e=function(t,n){if(t===n)return t;var e=t.ancestors(),r=n.ancestors(),i=null;for(t=e.pop(),n=r.pop();t===n;)i=t,t=e.pop(),n=r.pop();return i}(n,t),r=[n];n!==e;)n=n.parent,r.push(n);for(var i=r.length;t!==e;)r.splice(i,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,n=[t];t=t.parent;)n.push(t);return n},descendants:function(){var t=[];return this.each(function(n){t.push(n)}),t},leaves:function(){var t=[];return this.eachBefore(function(n){n.children||t.push(n)}),t},links:function(){var t=this,n=[];return t.each(function(e){e!==t&&n.push({source:e.parent,target:e})}),n},copy:function(){return wl(this).eachBefore(Nl)}};var Sl=Array.prototype.slice;function kl(t){for(var n,e,r=0,i=(t=function(t){for(var n,e,r=t.length;r;)e=Math.random()*r--|0,n=t[r],t[r]=t[e],t[e]=n;return t}(Sl.call(t))).length,o=[];r0&&e*e>r*r+i*i}function zl(t,n){for(var e=0;e(a*=a)?(r=(f+a-i)/(2*f),o=Math.sqrt(Math.max(0,a/f-r*r)),e.x=t.x-r*u-o*c,e.y=t.y-r*c+o*u):(r=(f+i-a)/(2*f),o=Math.sqrt(Math.max(0,i/f-r*r)),e.x=n.x+r*u-o*c,e.y=n.y+r*c+o*u)):(e.x=n.x+e.r,e.y=n.y)}function Ul(t,n){var e=t.r+n.r-1e-6,r=n.x-t.x,i=n.y-t.y;return e>0&&e*e>r*r+i*i}function Ol(t){var n=t._,e=t.next._,r=n.r+e.r,i=(n.x*e.r+e.x*n.r)/r,o=(n.y*e.r+e.y*n.r)/r;return i*i+o*o}function Bl(t){this._=t,this.next=null,this.previous=null}function Yl(t){if(!(i=t.length))return 0;var n,e,r,i,o,a,u,c,f,s,l;if((n=t[0]).x=0,n.y=0,!(i>1))return n.r;if(e=t[1],n.x=-e.r,e.x=n.r,e.y=0,!(i>2))return n.r+e.r;Ll(e,n,r=t[2]),n=new Bl(n),e=new Bl(e),r=new Bl(r),n.next=r.previous=e,e.next=n.previous=r,r.next=e.previous=n;t:for(u=3;uh&&(h=u),g=s*s*v,(d=Math.max(h/g,g/l))>p){s-=u;break}p=d}y.push(a={value:s,dice:c1?n:1)},e}(fh);var hh=function t(n){function e(t,e,r,i,o){if((a=t._squarify)&&a.ratio===n)for(var a,u,c,f,s,l=-1,h=a.length,d=t.value;++l1?n:1)},e}(fh);function dh(t,n,e){return(n[0]-t[0])*(e[1]-t[1])-(n[1]-t[1])*(e[0]-t[0])}function ph(t,n){return t[0]-n[0]||t[1]-n[1]}function vh(t){for(var n=t.length,e=[0,1],r=2,i=2;i1&&dh(t[e[r-2]],t[e[r-1]],t[i])<=0;)--r;e[r++]=i}return e.slice(0,r)}function gh(){return Math.random()}var yh=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,1===arguments.length?(e=t,t=0):e-=t,function(){return n()*e+t}}return e.source=t,e}(gh),_h=function t(n){function e(t,e){var r,i;return t=null==t?0:+t,e=null==e?1:+e,function(){var o;if(null!=r)o=r,r=null;else do{r=2*n()-1,o=2*n()-1,i=r*r+o*o}while(!i||i>1);return t+e*o*Math.sqrt(-2*Math.log(i)/i)}}return e.source=t,e}(gh),bh=function t(n){function e(){var t=_h.source(n).apply(this,arguments);return function(){return Math.exp(t())}}return e.source=t,e}(gh),mh=function t(n){function e(t){return function(){for(var e=0,r=0;rr&&(n=e,e=r,r=n),function(t){return Math.max(e,Math.min(r,t))}}function Lh(t,n,e){var r=t[0],i=t[1],o=n[0],a=n[1];return i2?Uh:Lh,i=o=null,l}function l(n){return isNaN(n=+n)?e:(i||(i=r(a.map(t),u,c)))(t(f(n)))}return l.invert=function(e){return f(n((o||(o=r(u,a.map(t),be)))(e)))},l.domain=function(t){return arguments.length?(a=Ah.call(t,Ph),f===Rh||(f=qh(a)),s()):a.slice()},l.range=function(t){return arguments.length?(u=Sh.call(t),s()):u.slice()},l.rangeRound=function(t){return u=Sh.call(t),c=Te,s()},l.clamp=function(t){return arguments.length?(f=t?qh(a):Rh,l):f!==Rh},l.interpolate=function(t){return arguments.length?(c=t,s()):c},l.unknown=function(t){return arguments.length?(e=t,l):e},function(e,r){return t=e,n=r,s()}}function Yh(t,n){return Bh()(t,n)}function Fh(n,e,r,i){var o,a=w(n,e,r);switch((i=za(null==i?",f":i)).type){case"s":var u=Math.max(Math.abs(n),Math.abs(e));return null!=i.precision||isNaN(o=Ia(a,u))||(i.precision=o),t.formatPrefix(i,u);case"":case"e":case"g":case"p":case"r":null!=i.precision||isNaN(o=Ha(a,Math.max(Math.abs(n),Math.abs(e))))||(i.precision=o-("e"===i.type));break;case"f":case"%":null!=i.precision||isNaN(o=Fa(a))||(i.precision=o-2*("%"===i.type))}return t.format(i)}function Ih(t){var n=t.domain;return t.ticks=function(t){var e=n();return m(e[0],e[e.length-1],null==t?10:t)},t.tickFormat=function(t,e){var r=n();return Fh(r[0],r[r.length-1],null==t?10:t,e)},t.nice=function(e){null==e&&(e=10);var r,i=n(),o=0,a=i.length-1,u=i[o],c=i[a];return c0?r=x(u=Math.floor(u/r)*r,c=Math.ceil(c/r)*r,e):r<0&&(r=x(u=Math.ceil(u*r)/r,c=Math.floor(c*r)/r,e)),r>0?(i[o]=Math.floor(u/r)*r,i[a]=Math.ceil(c/r)*r,n(i)):r<0&&(i[o]=Math.ceil(u*r)/r,i[a]=Math.floor(c*r)/r,n(i)),t},t}function Hh(t,n){var e,r=0,i=(t=t.slice()).length-1,o=t[r],a=t[i];return a0){for(;hc)break;v.push(l)}}else for(;h=1;--s)if(!((l=f*s)c)break;v.push(l)}}else v=m(h,d,Math.min(d-h,p)).map(r);return n?v.reverse():v},i.tickFormat=function(n,o){if(null==o&&(o=10===a?".0e":","),"function"!=typeof o&&(o=t.format(o)),n===1/0)return o;null==n&&(n=10);var u=Math.max(1,a*n/i.ticks().length);return function(t){var n=t/r(Math.round(e(t)));return n*a0))return u;do{u.push(a=new Date(+e)),n(e,o),t(e)}while(a=n)for(;t(n),!e(n);)n.setTime(n-1)},function(t,r){if(t>=t)if(r<0)for(;++r<=0;)for(;n(t,-1),!e(t););else for(;--r>=0;)for(;n(t,1),!e(t););})},e&&(i.count=function(n,r){return od.setTime(+n),ad.setTime(+r),t(od),t(ad),Math.floor(e(od,ad))},i.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?i.filter(r?function(n){return r(n)%t==0}:function(n){return i.count(0,n)%t==0}):i:null}),i}var cd=ud(function(){},function(t,n){t.setTime(+t+n)},function(t,n){return n-t});cd.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?ud(function(n){n.setTime(Math.floor(n/t)*t)},function(n,e){n.setTime(+n+e*t)},function(n,e){return(e-n)/t}):cd:null};var fd=cd.range,sd=6e4,ld=6048e5,hd=ud(function(t){t.setTime(t-t.getMilliseconds())},function(t,n){t.setTime(+t+1e3*n)},function(t,n){return(n-t)/1e3},function(t){return t.getUTCSeconds()}),dd=hd.range,pd=ud(function(t){t.setTime(t-t.getMilliseconds()-1e3*t.getSeconds())},function(t,n){t.setTime(+t+n*sd)},function(t,n){return(n-t)/sd},function(t){return t.getMinutes()}),vd=pd.range,gd=ud(function(t){t.setTime(t-t.getMilliseconds()-1e3*t.getSeconds()-t.getMinutes()*sd)},function(t,n){t.setTime(+t+36e5*n)},function(t,n){return(n-t)/36e5},function(t){return t.getHours()}),yd=gd.range,_d=ud(function(t){t.setHours(0,0,0,0)},function(t,n){t.setDate(t.getDate()+n)},function(t,n){return(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*sd)/864e5},function(t){return t.getDate()-1}),bd=_d.range;function md(t){return ud(function(n){n.setDate(n.getDate()-(n.getDay()+7-t)%7),n.setHours(0,0,0,0)},function(t,n){t.setDate(t.getDate()+7*n)},function(t,n){return(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*sd)/ld})}var xd=md(0),wd=md(1),Md=md(2),Nd=md(3),Td=md(4),Ad=md(5),Sd=md(6),kd=xd.range,Ed=wd.range,Cd=Md.range,Pd=Nd.range,zd=Td.range,Rd=Ad.range,Dd=Sd.range,qd=ud(function(t){t.setDate(1),t.setHours(0,0,0,0)},function(t,n){t.setMonth(t.getMonth()+n)},function(t,n){return n.getMonth()-t.getMonth()+12*(n.getFullYear()-t.getFullYear())},function(t){return t.getMonth()}),Ld=qd.range,Ud=ud(function(t){t.setMonth(0,1),t.setHours(0,0,0,0)},function(t,n){t.setFullYear(t.getFullYear()+n)},function(t,n){return n.getFullYear()-t.getFullYear()},function(t){return t.getFullYear()});Ud.every=function(t){return isFinite(t=Math.floor(t))&&t>0?ud(function(n){n.setFullYear(Math.floor(n.getFullYear()/t)*t),n.setMonth(0,1),n.setHours(0,0,0,0)},function(n,e){n.setFullYear(n.getFullYear()+e*t)}):null};var Od=Ud.range,Bd=ud(function(t){t.setUTCSeconds(0,0)},function(t,n){t.setTime(+t+n*sd)},function(t,n){return(n-t)/sd},function(t){return t.getUTCMinutes()}),Yd=Bd.range,Fd=ud(function(t){t.setUTCMinutes(0,0,0)},function(t,n){t.setTime(+t+36e5*n)},function(t,n){return(n-t)/36e5},function(t){return t.getUTCHours()}),Id=Fd.range,Hd=ud(function(t){t.setUTCHours(0,0,0,0)},function(t,n){t.setUTCDate(t.getUTCDate()+n)},function(t,n){return(n-t)/864e5},function(t){return t.getUTCDate()-1}),jd=Hd.range;function Xd(t){return ud(function(n){n.setUTCDate(n.getUTCDate()-(n.getUTCDay()+7-t)%7),n.setUTCHours(0,0,0,0)},function(t,n){t.setUTCDate(t.getUTCDate()+7*n)},function(t,n){return(n-t)/ld})}var Gd=Xd(0),Vd=Xd(1),$d=Xd(2),Wd=Xd(3),Zd=Xd(4),Qd=Xd(5),Kd=Xd(6),Jd=Gd.range,tp=Vd.range,np=$d.range,ep=Wd.range,rp=Zd.range,ip=Qd.range,op=Kd.range,ap=ud(function(t){t.setUTCDate(1),t.setUTCHours(0,0,0,0)},function(t,n){t.setUTCMonth(t.getUTCMonth()+n)},function(t,n){return n.getUTCMonth()-t.getUTCMonth()+12*(n.getUTCFullYear()-t.getUTCFullYear())},function(t){return t.getUTCMonth()}),up=ap.range,cp=ud(function(t){t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},function(t,n){t.setUTCFullYear(t.getUTCFullYear()+n)},function(t,n){return n.getUTCFullYear()-t.getUTCFullYear()},function(t){return t.getUTCFullYear()});cp.every=function(t){return isFinite(t=Math.floor(t))&&t>0?ud(function(n){n.setUTCFullYear(Math.floor(n.getUTCFullYear()/t)*t),n.setUTCMonth(0,1),n.setUTCHours(0,0,0,0)},function(n,e){n.setUTCFullYear(n.getUTCFullYear()+e*t)}):null};var fp=cp.range;function sp(t){if(0<=t.y&&t.y<100){var n=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return n.setFullYear(t.y),n}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function lp(t){if(0<=t.y&&t.y<100){var n=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return n.setUTCFullYear(t.y),n}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function hp(t){return{y:t,m:0,d:1,H:0,M:0,S:0,L:0}}function dp(t){var n=t.dateTime,e=t.date,r=t.time,i=t.periods,o=t.days,a=t.shortDays,u=t.months,c=t.shortMonths,f=xp(i),s=wp(i),l=xp(o),h=wp(o),d=xp(a),p=wp(a),v=xp(u),g=wp(u),y=xp(c),_=wp(c),b={a:function(t){return a[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return c[t.getMonth()]},B:function(t){return u[t.getMonth()]},c:null,d:Ip,e:Ip,f:Vp,H:Hp,I:jp,j:Xp,L:Gp,m:$p,M:Wp,p:function(t){return i[+(t.getHours()>=12)]},Q:Mv,s:Nv,S:Zp,u:Qp,U:Kp,V:Jp,w:tv,W:nv,x:null,X:null,y:ev,Y:rv,Z:iv,"%":wv},m={a:function(t){return a[t.getUTCDay()]},A:function(t){return o[t.getUTCDay()]},b:function(t){return c[t.getUTCMonth()]},B:function(t){return u[t.getUTCMonth()]},c:null,d:ov,e:ov,f:sv,H:av,I:uv,j:cv,L:fv,m:lv,M:hv,p:function(t){return i[+(t.getUTCHours()>=12)]},Q:Mv,s:Nv,S:dv,u:pv,U:vv,V:gv,w:yv,W:_v,x:null,X:null,y:bv,Y:mv,Z:xv,"%":wv},x={a:function(t,n,e){var r=d.exec(n.slice(e));return r?(t.w=p[r[0].toLowerCase()],e+r[0].length):-1},A:function(t,n,e){var r=l.exec(n.slice(e));return r?(t.w=h[r[0].toLowerCase()],e+r[0].length):-1},b:function(t,n,e){var r=y.exec(n.slice(e));return r?(t.m=_[r[0].toLowerCase()],e+r[0].length):-1},B:function(t,n,e){var r=v.exec(n.slice(e));return r?(t.m=g[r[0].toLowerCase()],e+r[0].length):-1},c:function(t,e,r){return N(t,n,e,r)},d:zp,e:zp,f:Op,H:Dp,I:Dp,j:Rp,L:Up,m:Pp,M:qp,p:function(t,n,e){var r=f.exec(n.slice(e));return r?(t.p=s[r[0].toLowerCase()],e+r[0].length):-1},Q:Yp,s:Fp,S:Lp,u:Np,U:Tp,V:Ap,w:Mp,W:Sp,x:function(t,n,r){return N(t,e,n,r)},X:function(t,n,e){return N(t,r,n,e)},y:Ep,Y:kp,Z:Cp,"%":Bp};function w(t,n){return function(e){var r,i,o,a=[],u=-1,c=0,f=t.length;for(e instanceof Date||(e=new Date(+e));++u53)return null;"w"in o||(o.w=1),"Z"in o?(i=(r=lp(hp(o.y))).getUTCDay(),r=i>4||0===i?Vd.ceil(r):Vd(r),r=Hd.offset(r,7*(o.V-1)),o.y=r.getUTCFullYear(),o.m=r.getUTCMonth(),o.d=r.getUTCDate()+(o.w+6)%7):(i=(r=n(hp(o.y))).getDay(),r=i>4||0===i?wd.ceil(r):wd(r),r=_d.offset(r,7*(o.V-1)),o.y=r.getFullYear(),o.m=r.getMonth(),o.d=r.getDate()+(o.w+6)%7)}else("W"in o||"U"in o)&&("w"in o||(o.w="u"in o?o.u%7:"W"in o?1:0),i="Z"in o?lp(hp(o.y)).getUTCDay():n(hp(o.y)).getDay(),o.m=0,o.d="W"in o?(o.w+6)%7+7*o.W-(i+5)%7:o.w+7*o.U-(i+6)%7);return"Z"in o?(o.H+=o.Z/100|0,o.M+=o.Z%100,lp(o)):n(o)}}function N(t,n,e,r){for(var i,o,a=0,u=n.length,c=e.length;a=c)return-1;if(37===(i=n.charCodeAt(a++))){if(i=n.charAt(a++),!(o=x[i in vp?n.charAt(a++):i])||(r=o(t,e,r))<0)return-1}else if(i!=e.charCodeAt(r++))return-1}return r}return b.x=w(e,b),b.X=w(r,b),b.c=w(n,b),m.x=w(e,m),m.X=w(r,m),m.c=w(n,m),{format:function(t){var n=w(t+="",b);return n.toString=function(){return t},n},parse:function(t){var n=M(t+="",sp);return n.toString=function(){return t},n},utcFormat:function(t){var n=w(t+="",m);return n.toString=function(){return t},n},utcParse:function(t){var n=M(t,lp);return n.toString=function(){return t},n}}}var pp,vp={"-":"",_:" ",0:"0"},gp=/^\s*\d+/,yp=/^%/,_p=/[\\^$*+?|[\]().{}]/g;function bp(t,n,e){var r=t<0?"-":"",i=(r?-t:t)+"",o=i.length;return r+(o68?1900:2e3),e+r[0].length):-1}function Cp(t,n,e){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(n.slice(e,e+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),e+r[0].length):-1}function Pp(t,n,e){var r=gp.exec(n.slice(e,e+2));return r?(t.m=r[0]-1,e+r[0].length):-1}function zp(t,n,e){var r=gp.exec(n.slice(e,e+2));return r?(t.d=+r[0],e+r[0].length):-1}function Rp(t,n,e){var r=gp.exec(n.slice(e,e+3));return r?(t.m=0,t.d=+r[0],e+r[0].length):-1}function Dp(t,n,e){var r=gp.exec(n.slice(e,e+2));return r?(t.H=+r[0],e+r[0].length):-1}function qp(t,n,e){var r=gp.exec(n.slice(e,e+2));return r?(t.M=+r[0],e+r[0].length):-1}function Lp(t,n,e){var r=gp.exec(n.slice(e,e+2));return r?(t.S=+r[0],e+r[0].length):-1}function Up(t,n,e){var r=gp.exec(n.slice(e,e+3));return r?(t.L=+r[0],e+r[0].length):-1}function Op(t,n,e){var r=gp.exec(n.slice(e,e+6));return r?(t.L=Math.floor(r[0]/1e3),e+r[0].length):-1}function Bp(t,n,e){var r=yp.exec(n.slice(e,e+1));return r?e+r[0].length:-1}function Yp(t,n,e){var r=gp.exec(n.slice(e));return r?(t.Q=+r[0],e+r[0].length):-1}function Fp(t,n,e){var r=gp.exec(n.slice(e));return r?(t.Q=1e3*+r[0],e+r[0].length):-1}function Ip(t,n){return bp(t.getDate(),n,2)}function Hp(t,n){return bp(t.getHours(),n,2)}function jp(t,n){return bp(t.getHours()%12||12,n,2)}function Xp(t,n){return bp(1+_d.count(Ud(t),t),n,3)}function Gp(t,n){return bp(t.getMilliseconds(),n,3)}function Vp(t,n){return Gp(t,n)+"000"}function $p(t,n){return bp(t.getMonth()+1,n,2)}function Wp(t,n){return bp(t.getMinutes(),n,2)}function Zp(t,n){return bp(t.getSeconds(),n,2)}function Qp(t){var n=t.getDay();return 0===n?7:n}function Kp(t,n){return bp(xd.count(Ud(t),t),n,2)}function Jp(t,n){var e=t.getDay();return t=e>=4||0===e?Td(t):Td.ceil(t),bp(Td.count(Ud(t),t)+(4===Ud(t).getDay()),n,2)}function tv(t){return t.getDay()}function nv(t,n){return bp(wd.count(Ud(t),t),n,2)}function ev(t,n){return bp(t.getFullYear()%100,n,2)}function rv(t,n){return bp(t.getFullYear()%1e4,n,4)}function iv(t){var n=t.getTimezoneOffset();return(n>0?"-":(n*=-1,"+"))+bp(n/60|0,"0",2)+bp(n%60,"0",2)}function ov(t,n){return bp(t.getUTCDate(),n,2)}function av(t,n){return bp(t.getUTCHours(),n,2)}function uv(t,n){return bp(t.getUTCHours()%12||12,n,2)}function cv(t,n){return bp(1+Hd.count(cp(t),t),n,3)}function fv(t,n){return bp(t.getUTCMilliseconds(),n,3)}function sv(t,n){return fv(t,n)+"000"}function lv(t,n){return bp(t.getUTCMonth()+1,n,2)}function hv(t,n){return bp(t.getUTCMinutes(),n,2)}function dv(t,n){return bp(t.getUTCSeconds(),n,2)}function pv(t){var n=t.getUTCDay();return 0===n?7:n}function vv(t,n){return bp(Gd.count(cp(t),t),n,2)}function gv(t,n){var e=t.getUTCDay();return t=e>=4||0===e?Zd(t):Zd.ceil(t),bp(Zd.count(cp(t),t)+(4===cp(t).getUTCDay()),n,2)}function yv(t){return t.getUTCDay()}function _v(t,n){return bp(Vd.count(cp(t),t),n,2)}function bv(t,n){return bp(t.getUTCFullYear()%100,n,2)}function mv(t,n){return bp(t.getUTCFullYear()%1e4,n,4)}function xv(){return"+0000"}function wv(){return"%"}function Mv(t){return+t}function Nv(t){return Math.floor(+t/1e3)}function Tv(n){return pp=dp(n),t.timeFormat=pp.format,t.timeParse=pp.parse,t.utcFormat=pp.utcFormat,t.utcParse=pp.utcParse,pp}Tv({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});var Av=Date.prototype.toISOString?function(t){return t.toISOString()}:t.utcFormat("%Y-%m-%dT%H:%M:%S.%LZ");var Sv=+new Date("2000-01-01T00:00:00.000Z")?function(t){var n=new Date(t);return isNaN(n)?null:n}:t.utcParse("%Y-%m-%dT%H:%M:%S.%LZ"),kv=1e3,Ev=60*kv,Cv=60*Ev,Pv=24*Cv,zv=7*Pv,Rv=30*Pv,Dv=365*Pv;function qv(t){return new Date(t)}function Lv(t){return t instanceof Date?+t:+new Date(+t)}function Uv(t,n,r,i,o,a,u,c,f){var s=Yh(Rh,Rh),l=s.invert,h=s.domain,d=f(".%L"),p=f(":%S"),v=f("%I:%M"),g=f("%I %p"),y=f("%a %d"),_=f("%b %d"),b=f("%B"),m=f("%Y"),x=[[u,1,kv],[u,5,5*kv],[u,15,15*kv],[u,30,30*kv],[a,1,Ev],[a,5,5*Ev],[a,15,15*Ev],[a,30,30*Ev],[o,1,Cv],[o,3,3*Cv],[o,6,6*Cv],[o,12,12*Cv],[i,1,Pv],[i,2,2*Pv],[r,1,zv],[n,1,Rv],[n,3,3*Rv],[t,1,Dv]];function M(e){return(u(e)=1?My:t<=-1?-My:Math.asin(t)}function Ay(t){return t.innerRadius}function Sy(t){return t.outerRadius}function ky(t){return t.startAngle}function Ey(t){return t.endAngle}function Cy(t){return t&&t.padAngle}function Py(t,n,e,r,i,o,a){var u=t-e,c=n-r,f=(a?o:-o)/my(u*u+c*c),s=f*c,l=-f*u,h=t+s,d=n+l,p=e+s,v=r+l,g=(h+p)/2,y=(d+v)/2,_=p-h,b=v-d,m=_*_+b*b,x=i-o,w=h*v-p*d,M=(b<0?-1:1)*my(yy(0,x*x*m-w*w)),N=(w*b-_*M)/m,T=(-w*_-b*M)/m,A=(w*b+_*M)/m,S=(-w*_+b*M)/m,k=N-g,E=T-y,C=A-g,P=S-y;return k*k+E*E>C*C+P*P&&(N=A,T=S),{cx:N,cy:T,x01:-s,y01:-l,x11:N*(i/x-1),y11:T*(i/x-1)}}function zy(t){this._context=t}function Ry(t){return new zy(t)}function Dy(t){return t[0]}function qy(t){return t[1]}function Ly(){var t=Dy,n=qy,e=dy(!0),r=null,i=Ry,o=null;function a(a){var u,c,f,s=a.length,l=!1;for(null==r&&(o=i(f=to())),u=0;u<=s;++u)!(u=s;--l)u.point(g[l],y[l]);u.lineEnd(),u.areaEnd()}v&&(g[f]=+t(h,f,c),y[f]=+e(h,f,c),u.point(n?+n(h,f,c):g[f],r?+r(h,f,c):y[f]))}if(d)return u=null,d+""||null}function f(){return Ly().defined(i).curve(a).context(o)}return c.x=function(e){return arguments.length?(t="function"==typeof e?e:dy(+e),n=null,c):t},c.x0=function(n){return arguments.length?(t="function"==typeof n?n:dy(+n),c):t},c.x1=function(t){return arguments.length?(n=null==t?null:"function"==typeof t?t:dy(+t),c):n},c.y=function(t){return arguments.length?(e="function"==typeof t?t:dy(+t),r=null,c):e},c.y0=function(t){return arguments.length?(e="function"==typeof t?t:dy(+t),c):e},c.y1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:dy(+t),c):r},c.lineX0=c.lineY0=function(){return f().x(t).y(e)},c.lineY1=function(){return f().x(t).y(r)},c.lineX1=function(){return f().x(n).y(e)},c.defined=function(t){return arguments.length?(i="function"==typeof t?t:dy(!!t),c):i},c.curve=function(t){return arguments.length?(a=t,null!=o&&(u=a(o)),c):a},c.context=function(t){return arguments.length?(null==t?o=u=null:u=a(o=t),c):o},c}function Oy(t,n){return nt?1:n>=t?0:NaN}function By(t){return t}zy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:this._context.lineTo(t,n)}}};var Yy=Iy(Ry);function Fy(t){this._curve=t}function Iy(t){function n(n){return new Fy(t(n))}return n._curve=t,n}function Hy(t){var n=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?n(Iy(t)):n()._curve},t}function jy(){return Hy(Ly().curve(Yy))}function Xy(){var t=Uy().curve(Yy),n=t.curve,e=t.lineX0,r=t.lineX1,i=t.lineY0,o=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return Hy(e())},delete t.lineX0,t.lineEndAngle=function(){return Hy(r())},delete t.lineX1,t.lineInnerRadius=function(){return Hy(i())},delete t.lineY0,t.lineOuterRadius=function(){return Hy(o())},delete t.lineY1,t.curve=function(t){return arguments.length?n(Iy(t)):n()._curve},t}function Gy(t,n){return[(n=+n)*Math.cos(t-=Math.PI/2),n*Math.sin(t)]}Fy.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,n){this._curve.point(n*Math.sin(t),n*-Math.cos(t))}};var Vy=Array.prototype.slice;function $y(t){return t.source}function Wy(t){return t.target}function Zy(t){var n=$y,e=Wy,r=Dy,i=qy,o=null;function a(){var a,u=Vy.call(arguments),c=n.apply(this,u),f=e.apply(this,u);if(o||(o=a=to()),t(o,+r.apply(this,(u[0]=c,u)),+i.apply(this,u),+r.apply(this,(u[0]=f,u)),+i.apply(this,u)),a)return o=null,a+""||null}return a.source=function(t){return arguments.length?(n=t,a):n},a.target=function(t){return arguments.length?(e=t,a):e},a.x=function(t){return arguments.length?(r="function"==typeof t?t:dy(+t),a):r},a.y=function(t){return arguments.length?(i="function"==typeof t?t:dy(+t),a):i},a.context=function(t){return arguments.length?(o=null==t?null:t,a):o},a}function Qy(t,n,e,r,i){t.moveTo(n,e),t.bezierCurveTo(n=(n+r)/2,e,n,i,r,i)}function Ky(t,n,e,r,i){t.moveTo(n,e),t.bezierCurveTo(n,e=(e+i)/2,r,e,r,i)}function Jy(t,n,e,r,i){var o=Gy(n,e),a=Gy(n,e=(e+i)/2),u=Gy(r,e),c=Gy(r,i);t.moveTo(o[0],o[1]),t.bezierCurveTo(a[0],a[1],u[0],u[1],c[0],c[1])}var t_={draw:function(t,n){var e=Math.sqrt(n/wy);t.moveTo(e,0),t.arc(0,0,e,0,Ny)}},n_={draw:function(t,n){var e=Math.sqrt(n/5)/2;t.moveTo(-3*e,-e),t.lineTo(-e,-e),t.lineTo(-e,-3*e),t.lineTo(e,-3*e),t.lineTo(e,-e),t.lineTo(3*e,-e),t.lineTo(3*e,e),t.lineTo(e,e),t.lineTo(e,3*e),t.lineTo(-e,3*e),t.lineTo(-e,e),t.lineTo(-3*e,e),t.closePath()}},e_=Math.sqrt(1/3),r_=2*e_,i_={draw:function(t,n){var e=Math.sqrt(n/r_),r=e*e_;t.moveTo(0,-e),t.lineTo(r,0),t.lineTo(0,e),t.lineTo(-r,0),t.closePath()}},o_=Math.sin(wy/10)/Math.sin(7*wy/10),a_=Math.sin(Ny/10)*o_,u_=-Math.cos(Ny/10)*o_,c_={draw:function(t,n){var e=Math.sqrt(.8908130915292852*n),r=a_*e,i=u_*e;t.moveTo(0,-e),t.lineTo(r,i);for(var o=1;o<5;++o){var a=Ny*o/5,u=Math.cos(a),c=Math.sin(a);t.lineTo(c*e,-u*e),t.lineTo(u*r-c*i,c*r+u*i)}t.closePath()}},f_={draw:function(t,n){var e=Math.sqrt(n),r=-e/2;t.rect(r,r,e,e)}},s_=Math.sqrt(3),l_={draw:function(t,n){var e=-Math.sqrt(n/(3*s_));t.moveTo(0,2*e),t.lineTo(-s_*e,-e),t.lineTo(s_*e,-e),t.closePath()}},h_=Math.sqrt(3)/2,d_=1/Math.sqrt(12),p_=3*(d_/2+1),v_={draw:function(t,n){var e=Math.sqrt(n/p_),r=e/2,i=e*d_,o=r,a=e*d_+e,u=-o,c=a;t.moveTo(r,i),t.lineTo(o,a),t.lineTo(u,c),t.lineTo(-.5*r-h_*i,h_*r+-.5*i),t.lineTo(-.5*o-h_*a,h_*o+-.5*a),t.lineTo(-.5*u-h_*c,h_*u+-.5*c),t.lineTo(-.5*r+h_*i,-.5*i-h_*r),t.lineTo(-.5*o+h_*a,-.5*a-h_*o),t.lineTo(-.5*u+h_*c,-.5*c-h_*u),t.closePath()}},g_=[t_,n_,i_,f_,c_,l_,v_];function y_(){}function __(t,n,e){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+n)/6,(t._y0+4*t._y1+e)/6)}function b_(t){this._context=t}function m_(t){this._context=t}function x_(t){this._context=t}function w_(t,n){this._basis=new b_(t),this._beta=n}b_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:__(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:__(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},m_.prototype={areaStart:y_,areaEnd:y_,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x2=t,this._y2=n;break;case 1:this._point=2,this._x3=t,this._y3=n;break;case 2:this._point=3,this._x4=t,this._y4=n,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+n)/6);break;default:__(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},x_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var e=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+n)/6;this._line?this._context.lineTo(e,r):this._context.moveTo(e,r);break;case 3:this._point=4;default:__(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},w_.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,n=this._y,e=t.length-1;if(e>0)for(var r,i=t[0],o=n[0],a=t[e]-i,u=n[e]-o,c=-1;++c<=e;)r=c/e,this._basis.point(this._beta*t[c]+(1-this._beta)*(i+r*a),this._beta*n[c]+(1-this._beta)*(o+r*u));this._x=this._y=null,this._basis.lineEnd()},point:function(t,n){this._x.push(+t),this._y.push(+n)}};var M_=function t(n){function e(t){return 1===n?new b_(t):new w_(t,n)}return e.beta=function(n){return t(+n)},e}(.85);function N_(t,n,e){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-n),t._y2+t._k*(t._y1-e),t._x2,t._y2)}function T_(t,n){this._context=t,this._k=(1-n)/6}T_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:N_(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2,this._x1=t,this._y1=n;break;case 2:this._point=3;default:N_(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var A_=function t(n){function e(t){return new T_(t,n)}return e.tension=function(n){return t(+n)},e}(0);function S_(t,n){this._context=t,this._k=(1-n)/6}S_.prototype={areaStart:y_,areaEnd:y_,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:N_(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var k_=function t(n){function e(t){return new S_(t,n)}return e.tension=function(n){return t(+n)},e}(0);function E_(t,n){this._context=t,this._k=(1-n)/6}E_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:N_(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var C_=function t(n){function e(t){return new E_(t,n)}return e.tension=function(n){return t(+n)},e}(0);function P_(t,n,e){var r=t._x1,i=t._y1,o=t._x2,a=t._y2;if(t._l01_a>xy){var u=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,c=3*t._l01_a*(t._l01_a+t._l12_a);r=(r*u-t._x0*t._l12_2a+t._x2*t._l01_2a)/c,i=(i*u-t._y0*t._l12_2a+t._y2*t._l01_2a)/c}if(t._l23_a>xy){var f=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,s=3*t._l23_a*(t._l23_a+t._l12_a);o=(o*f+t._x1*t._l23_2a-n*t._l12_2a)/s,a=(a*f+t._y1*t._l23_2a-e*t._l12_2a)/s}t._context.bezierCurveTo(r,i,o,a,t._x2,t._y2)}function z_(t,n){this._context=t,this._alpha=n}z_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3;default:P_(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var R_=function t(n){function e(t){return n?new z_(t,n):new T_(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function D_(t,n){this._context=t,this._alpha=n}D_.prototype={areaStart:y_,areaEnd:y_,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:P_(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var q_=function t(n){function e(t){return n?new D_(t,n):new S_(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function L_(t,n){this._context=t,this._alpha=n}L_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:P_(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var U_=function t(n){function e(t){return n?new L_(t,n):new E_(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function O_(t){this._context=t}function B_(t){return t<0?-1:1}function Y_(t,n,e){var r=t._x1-t._x0,i=n-t._x1,o=(t._y1-t._y0)/(r||i<0&&-0),a=(e-t._y1)/(i||r<0&&-0),u=(o*i+a*r)/(r+i);return(B_(o)+B_(a))*Math.min(Math.abs(o),Math.abs(a),.5*Math.abs(u))||0}function F_(t,n){var e=t._x1-t._x0;return e?(3*(t._y1-t._y0)/e-n)/2:n}function I_(t,n,e){var r=t._x0,i=t._y0,o=t._x1,a=t._y1,u=(o-r)/3;t._context.bezierCurveTo(r+u,i+u*n,o-u,a-u*e,o,a)}function H_(t){this._context=t}function j_(t){this._context=new X_(t)}function X_(t){this._context=t}function G_(t){this._context=t}function V_(t){var n,e,r=t.length-1,i=new Array(r),o=new Array(r),a=new Array(r);for(i[0]=0,o[0]=2,a[0]=t[0]+2*t[1],n=1;n=0;--n)i[n]=(a[n]-i[n+1])/o[n];for(o[r-1]=(t[r]+i[r-1])/2,n=0;n1)for(var e,r,i,o=1,a=t[n[0]],u=a.length;o=0;)e[n]=n;return e}function Q_(t,n){return t[n]}function K_(t){var n=t.map(J_);return Z_(t).sort(function(t,e){return n[t]-n[e]})}function J_(t){for(var n,e=-1,r=0,i=t.length,o=-1/0;++eo&&(o=n,r=e);return r}function tb(t){var n=t.map(nb);return Z_(t).sort(function(t,e){return n[t]-n[e]})}function nb(t){for(var n,e=0,r=-1,i=t.length;++r0)){if(o/=h,h<0){if(o0){if(o>l)return;o>s&&(s=o)}if(o=r-c,h||!(o<0)){if(o/=h,h<0){if(o>l)return;o>s&&(s=o)}else if(h>0){if(o0)){if(o/=d,d<0){if(o0){if(o>l)return;o>s&&(s=o)}if(o=i-f,d||!(o<0)){if(o/=d,d<0){if(o>l)return;o>s&&(s=o)}else if(d>0){if(o0||l<1)||(s>0&&(t[0]=[c+s*h,f+s*d]),l<1&&(t[1]=[c+l*h,f+l*d]),!0)}}}}}function pb(t,n,e,r,i){var o=t[1];if(o)return!0;var a,u,c=t[0],f=t.left,s=t.right,l=f[0],h=f[1],d=s[0],p=s[1],v=(l+d)/2,g=(h+p)/2;if(p===h){if(v=r)return;if(l>d){if(c){if(c[1]>=i)return}else c=[v,e];o=[v,i]}else{if(c){if(c[1]1)if(l>d){if(c){if(c[1]>=i)return}else c=[(e-u)/a,e];o=[(i-u)/a,i]}else{if(c){if(c[1]=r)return}else c=[n,a*n+u];o=[r,a*r+u]}else{if(c){if(c[0]=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,n),this._context.lineTo(t,n);else{var e=this._x*(1-this._t)+t*this._t;this._context.lineTo(e,this._y),this._context.lineTo(e,n)}}this._x=t,this._y=n}},ob.prototype={constructor:ob,insert:function(t,n){var e,r,i;if(t){if(n.P=t,n.N=t.N,t.N&&(t.N.P=n),t.N=n,t.R){for(t=t.R;t.L;)t=t.L;t.L=n}else t.R=n;e=t}else this._?(t=fb(this._),n.P=null,n.N=t,t.P=t.L=n,e=t):(n.P=n.N=null,this._=n,e=null);for(n.L=n.R=null,n.U=e,n.C=!0,t=n;e&&e.C;)e===(r=e.U).L?(i=r.R)&&i.C?(e.C=i.C=!1,r.C=!0,t=r):(t===e.R&&(ub(this,e),e=(t=e).U),e.C=!1,r.C=!0,cb(this,r)):(i=r.L)&&i.C?(e.C=i.C=!1,r.C=!0,t=r):(t===e.L&&(cb(this,e),e=(t=e).U),e.C=!1,r.C=!0,ub(this,r)),e=t.U;this._.C=!1},remove:function(t){t.N&&(t.N.P=t.P),t.P&&(t.P.N=t.N),t.N=t.P=null;var n,e,r,i=t.U,o=t.L,a=t.R;if(e=o?a?fb(a):o:a,i?i.L===t?i.L=e:i.R=e:this._=e,o&&a?(r=e.C,e.C=t.C,e.L=o,o.U=e,e!==a?(i=e.U,e.U=t.U,t=e.R,i.L=t,e.R=a,a.U=e):(e.U=i,i=e,t=e.R)):(r=t.C,t=e),t&&(t.U=i),!r)if(t&&t.C)t.C=!1;else{do{if(t===this._)break;if(t===i.L){if((n=i.R).C&&(n.C=!1,i.C=!0,ub(this,i),n=i.R),n.L&&n.L.C||n.R&&n.R.C){n.R&&n.R.C||(n.L.C=!1,n.C=!0,cb(this,n),n=i.R),n.C=i.C,i.C=n.R.C=!1,ub(this,i),t=this._;break}}else if((n=i.L).C&&(n.C=!1,i.C=!0,cb(this,i),n=i.L),n.L&&n.L.C||n.R&&n.R.C){n.L&&n.L.C||(n.R.C=!1,n.C=!0,ub(this,n),n=i.L),n.C=i.C,i.C=n.L.C=!1,cb(this,i),t=this._;break}n.C=!0,t=i,i=i.U}while(!t.C);t&&(t.C=!1)}}};var _b,bb=[];function mb(){ab(this),this.x=this.y=this.arc=this.site=this.cy=null}function xb(t){var n=t.P,e=t.N;if(n&&e){var r=n.site,i=t.site,o=e.site;if(r!==o){var a=i[0],u=i[1],c=r[0]-a,f=r[1]-u,s=o[0]-a,l=o[1]-u,h=2*(c*l-f*s);if(!(h>=-Lb)){var d=c*c+f*f,p=s*s+l*l,v=(l*d-f*p)/h,g=(c*p-s*d)/h,y=bb.pop()||new mb;y.arc=t,y.site=i,y.x=v+a,y.y=(y.cy=g+u)+Math.sqrt(v*v+g*g),t.circle=y;for(var _=null,b=Rb._;b;)if(y.yqb)u=u.L;else{if(!((i=o-Cb(u,a))>qb)){r>-qb?(n=u.P,e=u):i>-qb?(n=u,e=u.N):n=e=u;break}if(!u.R){n=u;break}u=u.R}!function(t){zb[t.index]={site:t,halfedges:[]}}(t);var c=Tb(t);if(Pb.insert(n,c),n||e){if(n===e)return wb(n),e=Tb(n.site),Pb.insert(c,e),c.edge=e.edge=sb(n.site,c.site),xb(n),void xb(e);if(e){wb(n),wb(e);var f=n.site,s=f[0],l=f[1],h=t[0]-s,d=t[1]-l,p=e.site,v=p[0]-s,g=p[1]-l,y=2*(h*g-d*v),_=h*h+d*d,b=v*v+g*g,m=[(g*_-d*b)/y+s,(h*b-v*_)/y+l];hb(e.edge,f,p,m),c.edge=sb(f,t,null,m),e.edge=sb(t,p,null,m),xb(n),xb(e)}else c.edge=sb(n.site,c.site)}}function Eb(t,n){var e=t.site,r=e[0],i=e[1],o=i-n;if(!o)return r;var a=t.P;if(!a)return-1/0;var u=(e=a.site)[0],c=e[1],f=c-n;if(!f)return u;var s=u-r,l=1/o-1/f,h=s/f;return l?(-h+Math.sqrt(h*h-2*l*(s*s/(-2*f)-c+f/2+i-o/2)))/l+r:(r+u)/2}function Cb(t,n){var e=t.N;if(e)return Eb(e,n);var r=t.site;return r[1]===n?r[0]:1/0}var Pb,zb,Rb,Db,qb=1e-6,Lb=1e-12;function Ub(t,n,e){return(t[0]-e[0])*(n[1]-t[1])-(t[0]-n[0])*(e[1]-t[1])}function Ob(t,n){return n[1]-t[1]||n[0]-t[0]}function Bb(t,n){var e,r,i,o=t.sort(Ob).pop();for(Db=[],zb=new Array(t.length),Pb=new ob,Rb=new ob;;)if(i=_b,o&&(!i||o[1]qb||Math.abs(i[0][1]-i[1][1])>qb)||delete Db[o]}(a,u,c,f),function(t,n,e,r){var i,o,a,u,c,f,s,l,h,d,p,v,g=zb.length,y=!0;for(i=0;iqb||Math.abs(v-h)>qb)&&(c.splice(u,0,Db.push(lb(a,d,Math.abs(p-t)qb?[t,Math.abs(l-t)qb?[Math.abs(h-r)qb?[e,Math.abs(l-e)qb?[Math.abs(h-n)=u)return null;var c=t-i.site[0],f=n-i.site[1],s=c*c+f*f;do{i=o.cells[r=a],a=null,i.halfedges.forEach(function(e){var r=o.edges[e],u=r.left;if(u!==i.site&&u||(u=r.right)){var c=t-u[0],f=n-u[1],l=c*c+f*f;lr?(r+i)/2:Math.min(0,r)||Math.max(0,i),a>o?(o+a)/2:Math.min(0,o)||Math.max(0,a))}jb.prototype=Ib.prototype,t.active=function(t,n){var e,r,i=t.__transition;if(i)for(r in n=null==n?null:n+"",i)if((e=i[r]).state>mr&&e.name===n)return new Lr([[t]],gi,n,+r);return null},t.arc=function(){var t=Ay,n=Sy,e=dy(0),r=null,i=ky,o=Ey,a=Cy,u=null;function c(){var c,f,s=+t.apply(this,arguments),l=+n.apply(this,arguments),h=i.apply(this,arguments)-My,d=o.apply(this,arguments)-My,p=py(d-h),v=d>h;if(u||(u=c=to()),lxy)if(p>Ny-xy)u.moveTo(l*gy(h),l*by(h)),u.arc(0,0,l,h,d,!v),s>xy&&(u.moveTo(s*gy(d),s*by(d)),u.arc(0,0,s,d,h,v));else{var g,y,_=h,b=d,m=h,x=d,w=p,M=p,N=a.apply(this,arguments)/2,T=N>xy&&(r?+r.apply(this,arguments):my(s*s+l*l)),A=_y(py(l-s)/2,+e.apply(this,arguments)),S=A,k=A;if(T>xy){var E=Ty(T/s*by(N)),C=Ty(T/l*by(N));(w-=2*E)>xy?(m+=E*=v?1:-1,x-=E):(w=0,m=x=(h+d)/2),(M-=2*C)>xy?(_+=C*=v?1:-1,b-=C):(M=0,_=b=(h+d)/2)}var P=l*gy(_),z=l*by(_),R=s*gy(x),D=s*by(x);if(A>xy){var q,L=l*gy(b),U=l*by(b),O=s*gy(m),B=s*by(m);if(p1?0:t<-1?wy:Math.acos(t)}((Y*I+F*H)/(my(Y*Y+F*F)*my(I*I+H*H)))/2),X=my(q[0]*q[0]+q[1]*q[1]);S=_y(A,(s-X)/(j-1)),k=_y(A,(l-X)/(j+1))}}M>xy?k>xy?(g=Py(O,B,P,z,l,k,v),y=Py(L,U,R,D,l,k,v),u.moveTo(g.cx+g.x01,g.cy+g.y01),kxy&&w>xy?S>xy?(g=Py(R,D,L,U,s,-S,v),y=Py(P,z,O,B,s,-S,v),u.lineTo(g.cx+g.x01,g.cy+g.y01),S>a,f=i+2*u>>a,s=_o(20);function l(r){var i=new Float32Array(c*f),l=new Float32Array(c*f);r.forEach(function(r,o,s){var l=+t(r,o,s)+u>>a,h=+n(r,o,s)+u>>a,d=+e(r,o,s);l>=0&&l=0&&h>a),Ao({width:c,height:f,data:l},{width:c,height:f,data:i},o>>a),To({width:c,height:f,data:i},{width:c,height:f,data:l},o>>a),Ao({width:c,height:f,data:l},{width:c,height:f,data:i},o>>a),To({width:c,height:f,data:i},{width:c,height:f,data:l},o>>a),Ao({width:c,height:f,data:l},{width:c,height:f,data:i},o>>a);var d=s(i);if(!Array.isArray(d)){var p=T(i);d=w(0,p,d),(d=g(0,Math.floor(p/d)*d,d)).shift()}return No().thresholds(d).size([c,f])(i).map(h)}function h(t){return t.value*=Math.pow(2,-2*a),t.coordinates.forEach(d),t}function d(t){t.forEach(p)}function p(t){t.forEach(v)}function v(t){t[0]=t[0]*Math.pow(2,a)-u,t[1]=t[1]*Math.pow(2,a)-u}function y(){return c=r+2*(u=3*o)>>a,f=i+2*u>>a,l}return l.x=function(n){return arguments.length?(t="function"==typeof n?n:_o(+n),l):t},l.y=function(t){return arguments.length?(n="function"==typeof t?t:_o(+t),l):n},l.weight=function(t){return arguments.length?(e="function"==typeof t?t:_o(+t),l):e},l.size=function(t){if(!arguments.length)return[r,i];var n=Math.ceil(t[0]),e=Math.ceil(t[1]);if(!(n>=0||n>=0))throw new Error("invalid size");return r=n,i=e,y()},l.cellSize=function(t){if(!arguments.length)return 1<=1))throw new Error("invalid cell size");return a=Math.floor(Math.log(t)/Math.LN2),y()},l.thresholds=function(t){return arguments.length?(s="function"==typeof t?t:Array.isArray(t)?_o(go.call(t)):_o(t),l):s},l.bandwidth=function(t){if(!arguments.length)return Math.sqrt(o*(o+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return o=Math.round((Math.sqrt(4*t*t+1)-1)/2),y()},l},t.contours=No,t.create=function(t){return Rt(Z(t).call(document.documentElement))},t.creator=Z,t.cross=function(t,n,e){var r,i,o,u,c=t.length,f=n.length,s=new Array(c*f);for(null==e&&(e=a),r=o=0;rt?1:n>=t?0:NaN},t.deviation=f,t.dispatch=I,t.drag=function(){var n,e,r,i,o=Vt,a=$t,u=Wt,c=Zt,f={},s=I("start","drag","end"),l=0,h=0;function d(t){t.on("mousedown.drag",p).filter(c).on("touchstart.drag",y).on("touchmove.drag",_).on("touchend.drag touchcancel.drag",b).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(){if(!i&&o.apply(this,arguments)){var u=m("mouse",a.apply(this,arguments),Bt,this,arguments);u&&(Rt(t.event.view).on("mousemove.drag",v,!0).on("mouseup.drag",g,!0),Ht(t.event.view),Ft(),r=!1,n=t.event.clientX,e=t.event.clientY,u("start"))}}function v(){if(It(),!r){var i=t.event.clientX-n,o=t.event.clientY-e;r=i*i+o*o>h}f.mouse("drag")}function g(){Rt(t.event.view).on("mousemove.drag mouseup.drag",null),jt(t.event.view,r),It(),f.mouse("end")}function y(){if(o.apply(this,arguments)){var n,e,r=t.event.changedTouches,i=a.apply(this,arguments),u=r.length;for(n=0;nc+d||if+d||ou.index){var p=c-a.x-a.vx,v=f-a.y-a.vy,g=p*p+v*v;gt.r&&(t.r=t[n].r)}function u(){if(n){var r,i,o=n.length;for(e=new Array(o),r=0;r=a)){(t.data!==n||t.next)&&(0===s&&(d+=(s=la())*s),0===l&&(d+=(l=la())*l),d1?(null==e?u.remove(t):u.set(t,d(e)),n):u.get(t)},find:function(n,e,r){var i,o,a,u,c,f=0,s=t.length;for(null==r?r=1/0:r*=r,f=0;f1?(f.on(t,e),n):f.on(t)}}},t.forceX=function(t){var n,e,r,i=sa(.1);function o(t){for(var i,o=0,a=n.length;o=.12&&i<.234&&r>=-.425&&r<-.214?u:i>=.166&&i<.234&&r>=-.214&&r<-.115?c:a).invert(t)},s.stream=function(e){return t&&n===e?t:(r=[a.stream(n=e),u.stream(e),c.stream(e)],i=r.length,t={point:function(t,n){for(var e=-1;++eNc(r[0],r[1])&&(r[1]=i[1]),Nc(i[0],r[1])>Nc(r[0],r[1])&&(r[0]=i[0])):o.push(r=i);for(a=-1/0,n=0,r=o[e=o.length-1];n<=e;r=i,++n)i=o[n],(u=Nc(r[1],i[0]))>a&&(a=u,Hu=i[0],Xu=r[1])}return Qu=Ku=null,Hu===1/0||ju===1/0?[[NaN,NaN],[NaN,NaN]]:[[Hu,ju],[Xu,Gu]]},t.geoCentroid=function(t){Ju=tc=nc=ec=rc=ic=oc=ac=uc=cc=fc=0,Mu(t,Sc);var n=uc,e=cc,r=fc,i=n*n+e*e+r*r;return i2?t[2]+90:90]):[(t=e())[0],t[1],t[2]-90]},e([0,0,90]).scale(159.155)},t.geoTransverseMercatorRaw=yl,t.gray=function(t,n){return new Yn(t,0,0,null==n?1:n)},t.hcl=Gn,t.hierarchy=wl,t.histogram=function(){var t=v,n=s,e=M;function r(r){var o,a,u=r.length,c=new Array(u);for(o=0;ol;)h.pop(),--d;var p,v=new Array(d+1);for(o=0;o<=d;++o)(p=v[o]=[]).x0=o>0?h[o-1]:s,p.x1=o1)&&(t-=Math.floor(t));var n=Math.abs(t-.5);return iy.h=360*t-100,iy.s=1.5-1.5*n,iy.l=.8-.9*n,iy+""},t.interpolateRdBu=sg,t.interpolateRdGy=hg,t.interpolateRdPu=Dg,t.interpolateRdYlBu=pg,t.interpolateRdYlGn=gg,t.interpolateReds=Kg,t.interpolateRgb=de,t.interpolateRgbBasis=ve,t.interpolateRgbBasisClosed=ge,t.interpolateRound=Te,t.interpolateSinebow=function(t){var n;return t=(.5-t)*Math.PI,oy.r=255*(n=Math.sin(t))*n,oy.g=255*(n=Math.sin(t+ay))*n,oy.b=255*(n=Math.sin(t+uy))*n,oy+""},t.interpolateSpectral=_g,t.interpolateString=Me,t.interpolateTransformCss=De,t.interpolateTransformSvg=qe,t.interpolateTurbo=function(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+t*(1172.33-t*(10793.56-t*(33300.12-t*(38394.49-14825.05*t)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+t*(557.33+t*(1225.33-t*(3574.96-t*(1073.77+707.56*t)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+t*(3211.1-t*(15327.97-t*(27814-t*(22569.18-6838.66*t)))))))+")"},t.interpolateViridis=fy,t.interpolateWarm=ey,t.interpolateYlGn=Og,t.interpolateYlGnBu=Lg,t.interpolateYlOrBr=Yg,t.interpolateYlOrRd=Ig,t.interpolateZoom=Fe,t.interrupt=Cr,t.interval=function(t,n,e){var r=new sr,i=n;return null==n?(r.restart(t,n,e),r):(n=+n,e=null==e?cr():+e,r.restart(function o(a){a+=i,r.restart(o,i+=n,e),t(a)},n,e),r)},t.isoFormat=Av,t.isoParse=Sv,t.json=function(t,n){return fetch(t,n).then(oa)},t.keys=function(t){var n=[];for(var e in t)n.push(e);return n},t.lab=Bn,t.lch=function(t,n,e,r){return 1===arguments.length?Xn(t):new Vn(e,n,t,null==r?1:r)},t.line=Ly,t.lineRadial=jy,t.linkHorizontal=function(){return Zy(Qy)},t.linkRadial=function(){var t=Zy(Jy);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t},t.linkVertical=function(){return Zy(Ky)},t.local=qt,t.map=uo,t.matcher=nt,t.max=T,t.mean=function(t,n){var e,r=t.length,i=r,o=-1,a=0;if(null==n)for(;++o=r.length)return null!=t&&e.sort(t),null!=n?n(e):e;for(var c,f,s,l=-1,h=e.length,d=r[i++],p=uo(),v=a();++lr.length)return e;var a,u=i[o-1];return null!=n&&o>=r.length?a=e.entries():(a=[],e.each(function(n,e){a.push({key:e,values:t(n,o)})})),null!=u?a.sort(function(t,n){return u(t.key,n.key)}):a}(o(t,0,so,lo),0)},key:function(t){return r.push(t),e},sortKeys:function(t){return i[r.length-1]=t,e},sortValues:function(n){return t=n,e},rollup:function(t){return n=t,e}}},t.now=cr,t.pack=function(){var t=null,n=1,e=1,r=Hl;function i(i){return i.x=n/2,i.y=e/2,t?i.eachBefore(Gl(t)).eachAfter(Vl(r,.5)).eachBefore($l(1)):i.eachBefore(Gl(Xl)).eachAfter(Vl(Hl,1)).eachAfter(Vl(r,i.r/Math.min(n,e))).eachBefore($l(Math.min(n,e)/(2*i.r))),i}return i.radius=function(n){return arguments.length?(t=Fl(n),i):t},i.size=function(t){return arguments.length?(n=+t[0],e=+t[1],i):[n,e]},i.padding=function(t){return arguments.length?(r="function"==typeof t?t:jl(+t),i):r},i},t.packEnclose=kl,t.packSiblings=function(t){return Yl(t),t},t.pairs=function(t,n){null==n&&(n=a);for(var e=0,r=t.length-1,i=t[0],o=new Array(r<0?0:r);e0&&(d+=l);for(null!=n?p.sort(function(t,e){return n(v[t],v[e])}):null!=e&&p.sort(function(t,n){return e(a[t],a[n])}),u=0,f=d?(y-h*b)/d:0;u0?l*f:0)+b,v[c]={data:a[c],index:u,value:l,startAngle:g,endAngle:s,padAngle:_};return v}return a.value=function(n){return arguments.length?(t="function"==typeof n?n:dy(+n),a):t},a.sortValues=function(t){return arguments.length?(n=t,e=null,a):n},a.sort=function(t){return arguments.length?(e=t,n=null,a):e},a.startAngle=function(t){return arguments.length?(r="function"==typeof t?t:dy(+t),a):r},a.endAngle=function(t){return arguments.length?(i="function"==typeof t?t:dy(+t),a):i},a.padAngle=function(t){return arguments.length?(o="function"==typeof t?t:dy(+t),a):o},a},t.piecewise=function(t,n){for(var e=0,r=n.length-1,i=n[0],o=new Array(r<0?0:r);eu!=f>u&&a<(c-e)*(u-r)/(f-r)+e&&(s=!s),c=e,f=r;return s},t.polygonHull=function(t){if((e=t.length)<3)return null;var n,e,r=new Array(e),i=new Array(e);for(n=0;n=0;--n)f.push(t[r[o[n]][2]]);for(n=+u;n0?a[n-1]:r[0],n=o?[a[o-1],r]:[a[n-1],a[n]]},c.unknown=function(t){return arguments.length?(n=t,c):c},c.thresholds=function(){return a.slice()},c.copy=function(){return t().domain([e,r]).range(u).unknown(n)},Mh.apply(Ih(c),arguments)},t.scaleSequential=function t(){var n=Ih(Ov()(Rh));return n.copy=function(){return Bv(n,t())},Nh.apply(n,arguments)},t.scaleSequentialLog=function t(){var n=Zh(Ov()).domain([1,10]);return n.copy=function(){return Bv(n,t()).base(n.base())},Nh.apply(n,arguments)},t.scaleSequentialPow=Yv,t.scaleSequentialQuantile=function t(){var e=[],r=Rh;function o(t){if(!isNaN(t=+t))return r((i(e,t)-1)/(e.length-1))}return o.domain=function(t){if(!arguments.length)return e.slice();e=[];for(var r,i=0,a=t.length;i0)for(var e,r,i,o,a,u,c=0,f=t[n[0]].length;c=0?(r[0]=o,r[1]=o+=i):i<0?(r[1]=a,r[0]=a+=i):r[0]=o},t.stackOffsetExpand=function(t,n){if((r=t.length)>0){for(var e,r,i,o=0,a=t[0].length;o0){for(var e,r=0,i=t[n[0]],o=i.length;r0&&(r=(e=t[n[0]]).length)>0){for(var e,r,i,o=0,a=1;a0)throw new Error("cycle");return o}return e.id=function(n){return arguments.length?(t=Il(n),e):t},e.parentId=function(t){return arguments.length?(n=Il(t),e):n},e},t.style=ft,t.sum=function(t,n){var e,r=t.length,i=-1,o=0;if(null==n)for(;++i=0;--i)u.push(e=n.children[i]=new uh(r[i],i)),e.parent=n;return(a.parent=new uh(null,0)).children=[a],a}(i);if(c.eachAfter(o),c.parent.m=-c.z,c.eachBefore(a),r)i.eachBefore(u);else{var f=i,s=i,l=i;i.eachBefore(function(t){t.xs.x&&(s=t),t.depth>l.depth&&(l=t)});var h=f===s?1:t(f,s)/2,d=h-f.x,p=n/(s.x+h+d),v=e/(l.depth||1);i.eachBefore(function(t){t.x=(t.x+d)*p,t.y=t.depth*v})}return i}function o(n){var e=n.children,r=n.parent.children,i=n.i?r[n.i-1]:null;if(e){!function(t){for(var n,e=0,r=0,i=t.children,o=i.length;--o>=0;)(n=i[o]).z+=e,n.m+=e,e+=n.s+(r+=n.c)}(n);var o=(e[0].z+e[e.length-1].z)/2;i?(n.z=i.z+t(n._,i._),n.m=n.z-o):n.z=o}else i&&(n.z=i.z+t(n._,i._));n.parent.A=function(n,e,r){if(e){for(var i,o=n,a=n,u=e,c=o.parent.children[0],f=o.m,s=a.m,l=u.m,h=c.m;u=ih(u),o=rh(o),u&&o;)c=rh(c),(a=ih(a)).a=n,(i=u.z+l-o.z-f+t(u._,o._))>0&&(oh(ah(u,n,r),n,i),f+=i,s+=i),l+=u.m,f+=o.m,h+=c.m,s+=a.m;u&&!ih(a)&&(a.t=u,a.m+=l-s),o&&!rh(c)&&(c.t=o,c.m+=f-h,r=n)}return r}(n,i,n.parent.A||r[0])}function a(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function u(t){t.x*=n,t.y=t.depth*e}return i.separation=function(n){return arguments.length?(t=n,i):t},i.size=function(t){return arguments.length?(r=!1,n=+t[0],e=+t[1],i):r?null:[n,e]},i.nodeSize=function(t){return arguments.length?(r=!0,n=+t[0],e=+t[1],i):r?[n,e]:null},i},t.treemap=function(){var t=lh,n=!1,e=1,r=1,i=[0],o=Hl,a=Hl,u=Hl,c=Hl,f=Hl;function s(t){return t.x0=t.y0=0,t.x1=e,t.y1=r,t.eachBefore(l),i=[0],n&&t.eachBefore(Wl),t}function l(n){var e=i[n.depth],r=n.x0+e,s=n.y0+e,l=n.x1-e,h=n.y1-e;l=e-1){var s=u[n];return s.x0=i,s.y0=o,s.x1=a,void(s.y1=c)}for(var l=f[n],h=r/2+l,d=n+1,p=e-1;d>>1;f[v]c-o){var _=(i*y+a*g)/r;t(n,d,g,i,o,_,c),t(d,e,y,_,o,a,c)}else{var b=(o*y+c*g)/r;t(n,d,g,i,o,a,b),t(d,e,y,i,b,a,c)}}(0,c,t.value,n,e,r,i)},t.treemapDice=Zl,t.treemapResquarify=hh,t.treemapSlice=ch,t.treemapSliceDice=function(t,n,e,r,i){(1&t.depth?ch:Zl)(t,n,e,r,i)},t.treemapSquarify=lh,t.tsv=ia,t.tsvFormat=Wo,t.tsvFormatBody=Zo,t.tsvFormatRows=Qo,t.tsvParse=Vo,t.tsvParseRows=$o,t.utcDay=Hd,t.utcDays=jd,t.utcFriday=Qd,t.utcFridays=ip,t.utcHour=Fd,t.utcHours=Id,t.utcMillisecond=cd,t.utcMilliseconds=fd,t.utcMinute=Bd,t.utcMinutes=Yd,t.utcMonday=Vd,t.utcMondays=tp,t.utcMonth=ap,t.utcMonths=up,t.utcSaturday=Kd,t.utcSaturdays=op,t.utcSecond=hd,t.utcSeconds=dd,t.utcSunday=Gd,t.utcSundays=Jd,t.utcThursday=Zd,t.utcThursdays=rp,t.utcTuesday=$d,t.utcTuesdays=np,t.utcWednesday=Wd,t.utcWednesdays=ep,t.utcWeek=Gd,t.utcWeeks=Jd,t.utcYear=cp,t.utcYears=fp,t.values=function(t){var n=[];for(var e in t)n.push(t[e]);return n},t.variance=c,t.version="5.11.0",t.voronoi=function(){var t=rb,n=ib,e=null;function r(r){return new Bb(r.map(function(e,i){var o=[Math.round(t(e,i,r)/qb)*qb,Math.round(n(e,i,r)/qb)*qb];return o.index=i,o.data=e,o}),e)}return r.polygons=function(t){return r(t).polygons()},r.links=function(t){return r(t).links()},r.triangles=function(t){return r(t).triangles()},r.x=function(n){return arguments.length?(t="function"==typeof n?n:eb(+n),r):t},r.y=function(t){return arguments.length?(n="function"==typeof t?t:eb(+t),r):n},r.extent=function(t){return arguments.length?(e=null==t?null:[[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]],r):e&&[[e[0][0],e[0][1]],[e[1][0],e[1][1]]]},r.size=function(t){return arguments.length?(e=null==t?null:[[0,0],[+t[0],+t[1]]],r):e&&[e[1][0]-e[0][0],e[1][1]-e[0][1]]},r},t.window=ct,t.xml=ua,t.zip=function(){return k(arguments)},t.zoom=function(){var n,e,r=Vb,i=$b,o=Kb,a=Zb,u=Qb,c=[0,1/0],f=[[-1/0,-1/0],[1/0,1/0]],s=250,l=Fe,h=I("start","zoom","end"),d=500,p=150,v=0;function g(t){t.property("__zoom",Wb).on("wheel.zoom",M).on("mousedown.zoom",N).on("dblclick.zoom",T).filter(u).on("touchstart.zoom",A).on("touchmove.zoom",S).on("touchend.zoom touchcancel.zoom",k).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function y(t,n){return(n=Math.max(c[0],Math.min(c[1],n)))===t.k?t:new Ib(n,t.x,t.y)}function _(t,n,e){var r=n[0]-e[0]*t.k,i=n[1]-e[1]*t.k;return r===t.x&&i===t.y?t:new Ib(t.k,r,i)}function b(t){return[(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function m(t,n,e){t.on("start.zoom",function(){x(this,arguments).start()}).on("interrupt.zoom end.zoom",function(){x(this,arguments).end()}).tween("zoom",function(){var t=this,r=arguments,o=x(t,r),a=i.apply(t,r),u=null==e?b(a):"function"==typeof e?e.apply(t,r):e,c=Math.max(a[1][0]-a[0][0],a[1][1]-a[0][1]),f=t.__zoom,s="function"==typeof n?n.apply(t,r):n,h=l(f.invert(u).concat(c/f.k),s.invert(u).concat(c/s.k));return function(t){if(1===t)t=s;else{var n=h(t),e=c/n[2];t=new Ib(e,u[0]-n[0]*e,u[1]-n[1]*e)}o.zoom(null,t)}})}function x(t,n,e){return!e&&t.__zooming||new w(t,n)}function w(t,n){this.that=t,this.args=n,this.active=0,this.extent=i.apply(t,n),this.taps=0}function M(){if(r.apply(this,arguments)){var t=x(this,arguments),n=this.__zoom,e=Math.max(c[0],Math.min(c[1],n.k*Math.pow(2,a.apply(this,arguments)))),i=Bt(this);if(t.wheel)t.mouse[0][0]===i[0]&&t.mouse[0][1]===i[1]||(t.mouse[1]=n.invert(t.mouse[0]=i)),clearTimeout(t.wheel);else{if(n.k===e)return;t.mouse=[i,n.invert(i)],Cr(this),t.start()}Gb(),t.wheel=setTimeout(function(){t.wheel=null,t.end()},p),t.zoom("mouse",o(_(y(n,e),t.mouse[0],t.mouse[1]),t.extent,f))}}function N(){if(!e&&r.apply(this,arguments)){var n=x(this,arguments,!0),i=Rt(t.event.view).on("mousemove.zoom",function(){if(Gb(),!n.moved){var e=t.event.clientX-u,r=t.event.clientY-c;n.moved=e*e+r*r>v}n.zoom("mouse",o(_(n.that.__zoom,n.mouse[0]=Bt(n.that),n.mouse[1]),n.extent,f))},!0).on("mouseup.zoom",function(){i.on("mousemove.zoom mouseup.zoom",null),jt(t.event.view,n.moved),Gb(),n.end()},!0),a=Bt(this),u=t.event.clientX,c=t.event.clientY;Ht(t.event.view),Xb(),n.mouse=[a,this.__zoom.invert(a)],Cr(this),n.start()}}function T(){if(r.apply(this,arguments)){var n=this.__zoom,e=Bt(this),a=n.invert(e),u=n.k*(t.event.shiftKey?.5:2),c=o(_(y(n,u),e,a),i.apply(this,arguments),f);Gb(),s>0?Rt(this).transition().duration(s).call(m,c,e):Rt(this).call(g.transform,c)}}function A(){if(r.apply(this,arguments)){var e,i,o,a,u=t.event.touches,c=u.length,f=x(this,arguments,t.event.changedTouches.length===c);for(Xb(),i=0;i + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["math"] = factory(); + else + root["math"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 19); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return factory; }); +/* unused harmony export sortFactories */ +/* unused harmony export create */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isFactory; }); +/* unused harmony export assertDependencies */ +/* unused harmony export isOptionalDependency */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return stripOptionalNotation; }); +/* harmony import */ var _array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); +/* harmony import */ var _object__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); + + +/** + * Create a factory function, which can be used to inject dependencies. + * + * The created functions are memoized, a consecutive call of the factory + * with the exact same inputs will return the same function instance. + * The memoized cache is exposed on `factory.cache` and can be cleared + * if needed. + * + * Example: + * + * const name = 'log' + * const dependencies = ['config', 'typed', 'divideScalar', 'Complex'] + * + * export const createLog = factory(name, dependencies, ({ typed, config, divideScalar, Complex }) => { + * // ... create the function log here and return it + * } + * + * @param {string} name Name of the function to be created + * @param {string[]} dependencies The names of all required dependencies + * @param {function} create Callback function called with an object with all dependencies + * @param {Object} [meta] Optional object with meta information that will be attached + * to the created factory function as property `meta`. + * @returns {function} + */ + +function factory(name, dependencies, create, meta) { + function assertAndCreate(scope) { + // we only pass the requested dependencies to the factory function + // to prevent functions to rely on dependencies that are not explicitly + // requested. + var deps = Object(_object__WEBPACK_IMPORTED_MODULE_1__[/* pickShallow */ "j"])(scope, dependencies.map(stripOptionalNotation)); + assertDependencies(name, dependencies, scope); + return create(deps); + } + + assertAndCreate.isFactory = true; + assertAndCreate.fn = name; + assertAndCreate.dependencies = dependencies.slice().sort(); + + if (meta) { + assertAndCreate.meta = meta; + } + + return assertAndCreate; +} +/** + * Sort all factories such that when loading in order, the dependencies are resolved. + * + * @param {Array} factories + * @returns {Array} Returns a new array with the sorted factories. + */ + +function sortFactories(factories) { + var factoriesByName = {}; + factories.forEach(function (factory) { + factoriesByName[factory.fn] = factory; + }); + + function containsDependency(factory, dependency) { + // TODO: detect circular references + if (isFactory(factory)) { + if (Object(_array__WEBPACK_IMPORTED_MODULE_0__[/* contains */ "b"])(factory.dependencies, dependency.fn || dependency.name)) { + return true; + } + + if (factory.dependencies.some(function (d) { + return containsDependency(factoriesByName[d], dependency); + })) { + return true; + } + } + + return false; + } + + var sorted = []; + + function addFactory(factory) { + var index = 0; + + while (index < sorted.length && !containsDependency(sorted[index], factory)) { + index++; + } + + sorted.splice(index, 0, factory); + } // sort regular factory functions + + + factories.filter(isFactory).forEach(addFactory); // sort legacy factory functions AFTER the regular factory functions + + factories.filter(function (factory) { + return !isFactory(factory); + }).forEach(addFactory); + return sorted; +} // TODO: comment or cleanup if unused in the end + +function create(factories) { + var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + sortFactories(factories).forEach(function (factory) { + return factory(scope); + }); + return scope; +} +/** + * Test whether an object is a factory. This is the case when it has + * properties name, dependencies, and a function create. + * @param {*} obj + * @returns {boolean} + */ + +function isFactory(obj) { + return typeof obj === 'function' && typeof obj.fn === 'string' && Array.isArray(obj.dependencies); +} +/** + * Assert that all dependencies of a list with dependencies are available in the provided scope. + * + * Will throw an exception when there are dependencies missing. + * + * @param {string} name Name for the function to be created. Used to generate a useful error message + * @param {string[]} dependencies + * @param {Object} scope + */ + +function assertDependencies(name, dependencies, scope) { + var allDefined = dependencies.filter(function (dependency) { + return !isOptionalDependency(dependency); + }) // filter optionals + .every(function (dependency) { + return scope[dependency] !== undefined; + }); + + if (!allDefined) { + var missingDependencies = dependencies.filter(function (dependency) { + return scope[dependency] === undefined; + }); // TODO: create a custom error class for this, a MathjsError or something like that + + throw new Error("Cannot create function \"".concat(name, "\", ") + "some dependencies are missing: ".concat(missingDependencies.map(function (d) { + return "\"".concat(d, "\""); + }).join(', '), ".")); + } +} +function isOptionalDependency(dependency) { + return dependency && dependency[0] === '?'; +} +function stripOptionalNotation(dependency) { + return dependency && dependency[0] === '?' ? dependency.slice(1) : dependency; +} + +/***/ }), +/* 1 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "y", function() { return isNumber; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return isBigNumber; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return isComplex; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return isFraction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "L", function() { return isUnit; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "I", function() { return isString; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isArray; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "v", function() { return isMatrix; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return isCollection; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return isDenseMatrix; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "H", function() { return isSparseMatrix; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "D", function() { return isRange; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "t", function() { return isIndex; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return isBoolean; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "G", function() { return isResultSet; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return isHelp; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return isFunction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return isDate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "F", function() { return isRegExp; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "z", function() { return isObject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "x", function() { return isNull; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "K", function() { return isUndefined; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isAccessorNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return isArrayNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return isAssignmentNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return isBlockNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return isConditionalNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return isConstantNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return isFunctionAssignmentNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return isFunctionNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "u", function() { return isIndexNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "w", function() { return isNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "A", function() { return isObjectNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "B", function() { return isOperatorNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "C", function() { return isParenthesisNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "E", function() { return isRangeNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "J", function() { return isSymbolNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return isChain; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "M", function() { return typeOf; }); +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +// type checks for all known types +// +// note that: +// +// - check by duck-typing on a property like `isUnit`, instead of checking instanceof. +// instanceof cannot be used because that would not allow to pass data from +// one instance of math.js to another since each has it's own instance of Unit. +// - check the `isUnit` property via the constructor, so there will be no +// matches for "fake" instances like plain objects with a property `isUnit`. +// That is important for security reasons. +// - It must not be possible to override the type checks used internally, +// for security reasons, so these functions are not exposed in the expression +// parser. +function isNumber(x) { + return typeof x === 'number'; +} +function isBigNumber(x) { + return x && x.constructor.prototype.isBigNumber === true || false; +} +function isComplex(x) { + return x && _typeof(x) === 'object' && Object.getPrototypeOf(x).isComplex === true || false; +} +function isFraction(x) { + return x && _typeof(x) === 'object' && Object.getPrototypeOf(x).isFraction === true || false; +} +function isUnit(x) { + return x && x.constructor.prototype.isUnit === true || false; +} +function isString(x) { + return typeof x === 'string'; +} +var isArray = Array.isArray; +function isMatrix(x) { + return x && x.constructor.prototype.isMatrix === true || false; +} +/** + * Test whether a value is a collection: an Array or Matrix + * @param {*} x + * @returns {boolean} isCollection + */ + +function isCollection(x) { + return Array.isArray(x) || isMatrix(x); +} +function isDenseMatrix(x) { + return x && x.isDenseMatrix && x.constructor.prototype.isMatrix === true || false; +} +function isSparseMatrix(x) { + return x && x.isSparseMatrix && x.constructor.prototype.isMatrix === true || false; +} +function isRange(x) { + return x && x.constructor.prototype.isRange === true || false; +} +function isIndex(x) { + return x && x.constructor.prototype.isIndex === true || false; +} +function isBoolean(x) { + return typeof x === 'boolean'; +} +function isResultSet(x) { + return x && x.constructor.prototype.isResultSet === true || false; +} +function isHelp(x) { + return x && x.constructor.prototype.isHelp === true || false; +} +function isFunction(x) { + return typeof x === 'function'; +} +function isDate(x) { + return x instanceof Date; +} +function isRegExp(x) { + return x instanceof RegExp; +} +function isObject(x) { + return !!(x && _typeof(x) === 'object' && x.constructor === Object && !isComplex(x) && !isFraction(x)); +} +function isNull(x) { + return x === null; +} +function isUndefined(x) { + return x === undefined; +} +function isAccessorNode(x) { + return x && x.isAccessorNode === true && x.constructor.prototype.isNode === true || false; +} +function isArrayNode(x) { + return x && x.isArrayNode === true && x.constructor.prototype.isNode === true || false; +} +function isAssignmentNode(x) { + return x && x.isAssignmentNode === true && x.constructor.prototype.isNode === true || false; +} +function isBlockNode(x) { + return x && x.isBlockNode === true && x.constructor.prototype.isNode === true || false; +} +function isConditionalNode(x) { + return x && x.isConditionalNode === true && x.constructor.prototype.isNode === true || false; +} +function isConstantNode(x) { + return x && x.isConstantNode === true && x.constructor.prototype.isNode === true || false; +} +function isFunctionAssignmentNode(x) { + return x && x.isFunctionAssignmentNode === true && x.constructor.prototype.isNode === true || false; +} +function isFunctionNode(x) { + return x && x.isFunctionNode === true && x.constructor.prototype.isNode === true || false; +} +function isIndexNode(x) { + return x && x.isIndexNode === true && x.constructor.prototype.isNode === true || false; +} +function isNode(x) { + return x && x.isNode === true && x.constructor.prototype.isNode === true || false; +} +function isObjectNode(x) { + return x && x.isObjectNode === true && x.constructor.prototype.isNode === true || false; +} +function isOperatorNode(x) { + return x && x.isOperatorNode === true && x.constructor.prototype.isNode === true || false; +} +function isParenthesisNode(x) { + return x && x.isParenthesisNode === true && x.constructor.prototype.isNode === true || false; +} +function isRangeNode(x) { + return x && x.isRangeNode === true && x.constructor.prototype.isNode === true || false; +} +function isSymbolNode(x) { + return x && x.isSymbolNode === true && x.constructor.prototype.isNode === true || false; +} +function isChain(x) { + return x && x.constructor.prototype.isChain === true || false; +} +function typeOf(x) { + var t = _typeof(x); + + if (t === 'object') { + // JavaScript types + if (x === null) return 'null'; + if (Array.isArray(x)) return 'Array'; + if (x instanceof Date) return 'Date'; + if (x instanceof RegExp) return 'RegExp'; // math.js types + + if (isBigNumber(x)) return 'BigNumber'; + if (isComplex(x)) return 'Complex'; + if (isFraction(x)) return 'Fraction'; + if (isMatrix(x)) return 'Matrix'; + if (isUnit(x)) return 'Unit'; + if (isIndex(x)) return 'Index'; + if (isRange(x)) return 'Range'; + if (isResultSet(x)) return 'ResultSet'; + if (isNode(x)) return x.type; + if (isChain(x)) return 'Chain'; + if (isHelp(x)) return 'Help'; + return 'Object'; + } + + if (t === 'function') return 'Function'; + return t; // can be 'string', 'number', 'boolean', ... +} + +/***/ }), +/* 2 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return arraySize; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return validate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return validateIndex; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return resize; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return reshape; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return squeeze; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return unsqueeze; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return flatten; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return map; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return forEach; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return filter; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return filterRegExp; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return join; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return identify; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return generalize; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return getArrayDataType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return last; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return initial; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return contains; }); +/* harmony import */ var _number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); +/* harmony import */ var _is__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1); +/* harmony import */ var _string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5); +/* harmony import */ var _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6); +/* harmony import */ var _error_IndexError__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(10); + + + + + +/** + * Calculate the size of a multi dimensional array. + * This function checks the size of the first entry, it does not validate + * whether all dimensions match. (use function `validate` for that) + * @param {Array} x + * @Return {Number[]} size + */ + +function arraySize(x) { + var s = []; + + while (Array.isArray(x)) { + s.push(x.length); + x = x[0]; + } + + return s; +} +/** + * Recursively validate whether each element in a multi dimensional array + * has a size corresponding to the provided size array. + * @param {Array} array Array to be validated + * @param {number[]} size Array with the size of each dimension + * @param {number} dim Current dimension + * @throws DimensionError + * @private + */ + +function _validate(array, size, dim) { + var i; + var len = array.length; + + if (len !== size[dim]) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](len, size[dim]); + } + + if (dim < size.length - 1) { + // recursively validate each child array + var dimNext = dim + 1; + + for (i = 0; i < len; i++) { + var child = array[i]; + + if (!Array.isArray(child)) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](size.length - 1, size.length, '<'); + } + + _validate(array[i], size, dimNext); + } + } else { + // last dimension. none of the childs may be an array + for (i = 0; i < len; i++) { + if (Array.isArray(array[i])) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](size.length + 1, size.length, '>'); + } + } + } +} +/** + * Validate whether each element in a multi dimensional array has + * a size corresponding to the provided size array. + * @param {Array} array Array to be validated + * @param {number[]} size Array with the size of each dimension + * @throws DimensionError + */ + + +function validate(array, size) { + var isScalar = size.length === 0; + + if (isScalar) { + // scalar + if (Array.isArray(array)) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](array.length, 0); + } + } else { + // array + _validate(array, size, 0); + } +} +/** + * Test whether index is an integer number with index >= 0 and index < length + * when length is provided + * @param {number} index Zero-based index + * @param {number} [length] Length of the array + */ + +function validateIndex(index, length) { + if (!Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(index) || !Object(_number__WEBPACK_IMPORTED_MODULE_0__[/* isInteger */ "i"])(index)) { + throw new TypeError('Index must be an integer (value: ' + index + ')'); + } + + if (index < 0 || typeof length === 'number' && index >= length) { + throw new _error_IndexError__WEBPACK_IMPORTED_MODULE_4__[/* IndexError */ "a"](index, length); + } +} +/** + * Resize a multi dimensional array. The resized array is returned. + * @param {Array} array Array to be resized + * @param {Array.} size Array with the size of each dimension + * @param {*} [defaultValue=0] Value to be filled in in new entries, + * zero by default. Specify for example `null`, + * to clearly see entries that are not explicitly + * set. + * @return {Array} array The resized array + */ + +function resize(array, size, defaultValue) { + // TODO: add support for scalars, having size=[] ? + // check the type of the arguments + if (!Array.isArray(array) || !Array.isArray(size)) { + throw new TypeError('Array expected'); + } + + if (size.length === 0) { + throw new Error('Resizing to scalar is not supported'); + } // check whether size contains positive integers + + + size.forEach(function (value) { + if (!Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(value) || !Object(_number__WEBPACK_IMPORTED_MODULE_0__[/* isInteger */ "i"])(value) || value < 0) { + throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + Object(_string__WEBPACK_IMPORTED_MODULE_2__[/* format */ "d"])(size) + ')'); + } + }); // recursively resize the array + + var _defaultValue = defaultValue !== undefined ? defaultValue : 0; + + _resize(array, size, 0, _defaultValue); + + return array; +} +/** + * Recursively resize a multi dimensional array + * @param {Array} array Array to be resized + * @param {number[]} size Array with the size of each dimension + * @param {number} dim Current dimension + * @param {*} [defaultValue] Value to be filled in in new entries, + * undefined by default. + * @private + */ + +function _resize(array, size, dim, defaultValue) { + var i; + var elem; + var oldLen = array.length; + var newLen = size[dim]; + var minLen = Math.min(oldLen, newLen); // apply new length + + array.length = newLen; + + if (dim < size.length - 1) { + // non-last dimension + var dimNext = dim + 1; // resize existing child arrays + + for (i = 0; i < minLen; i++) { + // resize child array + elem = array[i]; + + if (!Array.isArray(elem)) { + elem = [elem]; // add a dimension + + array[i] = elem; + } + + _resize(elem, size, dimNext, defaultValue); + } // create new child arrays + + + for (i = minLen; i < newLen; i++) { + // get child array + elem = []; + array[i] = elem; // resize new child array + + _resize(elem, size, dimNext, defaultValue); + } + } else { + // last dimension + // remove dimensions of existing values + for (i = 0; i < minLen; i++) { + while (Array.isArray(array[i])) { + array[i] = array[i][0]; + } + } // fill new elements with the default value + + + for (i = minLen; i < newLen; i++) { + array[i] = defaultValue; + } + } +} +/** + * Re-shape a multi dimensional array to fit the specified dimensions + * @param {Array} array Array to be reshaped + * @param {Array.} sizes List of sizes for each dimension + * @returns {Array} Array whose data has been formatted to fit the + * specified dimensions + * + * @throws {DimensionError} If the product of the new dimension sizes does + * not equal that of the old ones + */ + + +function reshape(array, sizes) { + var flatArray = flatten(array); + var newArray; + + function product(arr) { + return arr.reduce(function (prev, curr) { + return prev * curr; + }); + } + + if (!Array.isArray(array) || !Array.isArray(sizes)) { + throw new TypeError('Array expected'); + } + + if (sizes.length === 0) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](0, product(arraySize(array)), '!='); + } + + var totalSize = 1; + + for (var sizeIndex = 0; sizeIndex < sizes.length; sizeIndex++) { + totalSize *= sizes[sizeIndex]; + } + + if (flatArray.length !== totalSize) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](product(sizes), product(arraySize(array)), '!='); + } + + try { + newArray = _reshape(flatArray, sizes); + } catch (e) { + if (e instanceof _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"]) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](product(sizes), product(arraySize(array)), '!='); + } + + throw e; + } + + return newArray; +} +/** + * Iteratively re-shape a multi dimensional array to fit the specified dimensions + * @param {Array} array Array to be reshaped + * @param {Array.} sizes List of sizes for each dimension + * @returns {Array} Array whose data has been formatted to fit the + * specified dimensions + */ + +function _reshape(array, sizes) { + // testing if there are enough elements for the requested shape + var tmpArray = array; + var tmpArray2; // for each dimensions starting by the last one and ignoring the first one + + for (var sizeIndex = sizes.length - 1; sizeIndex > 0; sizeIndex--) { + var size = sizes[sizeIndex]; + tmpArray2 = []; // aggregate the elements of the current tmpArray in elements of the requested size + + var length = tmpArray.length / size; + + for (var i = 0; i < length; i++) { + tmpArray2.push(tmpArray.slice(i * size, (i + 1) * size)); + } // set it as the new tmpArray for the next loop turn or for return + + + tmpArray = tmpArray2; + } + + return tmpArray; +} +/** + * Squeeze a multi dimensional array + * @param {Array} array + * @param {Array} [size] + * @returns {Array} returns the array itself + */ + + +function squeeze(array, size) { + var s = size || arraySize(array); // squeeze outer dimensions + + while (Array.isArray(array) && array.length === 1) { + array = array[0]; + s.shift(); + } // find the first dimension to be squeezed + + + var dims = s.length; + + while (s[dims - 1] === 1) { + dims--; + } // squeeze inner dimensions + + + if (dims < s.length) { + array = _squeeze(array, dims, 0); + s.length = dims; + } + + return array; +} +/** + * Recursively squeeze a multi dimensional array + * @param {Array} array + * @param {number} dims Required number of dimensions + * @param {number} dim Current dimension + * @returns {Array | *} Returns the squeezed array + * @private + */ + +function _squeeze(array, dims, dim) { + var i, ii; + + if (dim < dims) { + var next = dim + 1; + + for (i = 0, ii = array.length; i < ii; i++) { + array[i] = _squeeze(array[i], dims, next); + } + } else { + while (Array.isArray(array)) { + array = array[0]; + } + } + + return array; +} +/** + * Unsqueeze a multi dimensional array: add dimensions when missing + * + * Paramter `size` will be mutated to match the new, unqueezed matrix size. + * + * @param {Array} array + * @param {number} dims Desired number of dimensions of the array + * @param {number} [outer] Number of outer dimensions to be added + * @param {Array} [size] Current size of array. + * @returns {Array} returns the array itself + * @private + */ + + +function unsqueeze(array, dims, outer, size) { + var s = size || arraySize(array); // unsqueeze outer dimensions + + if (outer) { + for (var i = 0; i < outer; i++) { + array = [array]; + s.unshift(1); + } + } // unsqueeze inner dimensions + + + array = _unsqueeze(array, dims, 0); + + while (s.length < dims) { + s.push(1); + } + + return array; +} +/** + * Recursively unsqueeze a multi dimensional array + * @param {Array} array + * @param {number} dims Required number of dimensions + * @param {number} dim Current dimension + * @returns {Array | *} Returns the squeezed array + * @private + */ + +function _unsqueeze(array, dims, dim) { + var i, ii; + + if (Array.isArray(array)) { + var next = dim + 1; + + for (i = 0, ii = array.length; i < ii; i++) { + array[i] = _unsqueeze(array[i], dims, next); + } + } else { + for (var d = dim; d < dims; d++) { + array = [array]; + } + } + + return array; +} +/** + * Flatten a multi dimensional array, put all elements in a one dimensional + * array + * @param {Array} array A multi dimensional array + * @return {Array} The flattened array (1 dimensional) + */ + + +function flatten(array) { + if (!Array.isArray(array)) { + // if not an array, return as is + return array; + } + + var flat = []; + array.forEach(function callback(value) { + if (Array.isArray(value)) { + value.forEach(callback); // traverse through sub-arrays recursively + } else { + flat.push(value); + } + }); + return flat; +} +/** + * A safe map + * @param {Array} array + * @param {function} callback + */ + +function map(array, callback) { + return Array.prototype.map.call(array, callback); +} +/** + * A safe forEach + * @param {Array} array + * @param {function} callback + */ + +function forEach(array, callback) { + Array.prototype.forEach.call(array, callback); +} +/** + * A safe filter + * @param {Array} array + * @param {function} callback + */ + +function filter(array, callback) { + if (arraySize(array).length !== 1) { + throw new Error('Only one dimensional matrices supported'); + } + + return Array.prototype.filter.call(array, callback); +} +/** + * Filter values in a callback given a regular expression + * @param {Array} array + * @param {RegExp} regexp + * @return {Array} Returns the filtered array + * @private + */ + +function filterRegExp(array, regexp) { + if (arraySize(array).length !== 1) { + throw new Error('Only one dimensional matrices supported'); + } + + return Array.prototype.filter.call(array, function (entry) { + return regexp.test(entry); + }); +} +/** + * A safe join + * @param {Array} array + * @param {string} separator + */ + +function join(array, separator) { + return Array.prototype.join.call(array, separator); +} +/** + * Assign a numeric identifier to every element of a sorted array + * @param {Array} a An array + * @return {Array} An array of objects containing the original value and its identifier + */ + +function identify(a) { + if (!Array.isArray(a)) { + throw new TypeError('Array input expected'); + } + + if (a.length === 0) { + return a; + } + + var b = []; + var count = 0; + b[0] = { + value: a[0], + identifier: 0 + }; + + for (var i = 1; i < a.length; i++) { + if (a[i] === a[i - 1]) { + count++; + } else { + count = 0; + } + + b.push({ + value: a[i], + identifier: count + }); + } + + return b; +} +/** + * Remove the numeric identifier from the elements + * @param {array} a An array + * @return {array} An array of values without identifiers + */ + +function generalize(a) { + if (!Array.isArray(a)) { + throw new TypeError('Array input expected'); + } + + if (a.length === 0) { + return a; + } + + var b = []; + + for (var i = 0; i < a.length; i++) { + b.push(a[i].value); + } + + return b; +} +/** + * Check the datatype of a given object + * This is a low level implementation that should only be used by + * parent Matrix classes such as SparseMatrix or DenseMatrix + * This method does not validate Array Matrix shape + * @param {Array} array + * @param {function} typeOf Callback function to use to determine the type of a value + * @return string + */ + +function getArrayDataType(array, typeOf) { + var type; // to hold type info + + var length = 0; // to hold length value to ensure it has consistent sizes + + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var isArray = Array.isArray(item); // Saving the target matrix row size + + if (i === 0 && isArray) { + length = item.length; + } // If the current item is an array but the length does not equal the targetVectorSize + + + if (isArray && item.length !== length) { + return undefined; + } + + var itemType = isArray ? getArrayDataType(item, typeOf) // recurse into a nested array + : typeOf(item); + + if (type === undefined) { + type = itemType; // first item + } else if (type !== itemType) { + return 'mixed'; + } else {// we're good, everything has the same type so far + } + } + + return type; +} +/** + * Return the last item from an array + * @param array + * @returns {*} + */ + +function last(array) { + return array[array.length - 1]; +} +/** + * Get all but the last element of array. + */ + +function initial(array) { + return array.slice(0, array.length - 1); +} +/** + * Test whether an array or string contains an item + * @param {Array | string} array + * @param {*} item + * @return {boolean} + */ + +function contains(array, item) { + return array.indexOf(item) !== -1; +} + +/***/ }), +/* 3 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return clone; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return mapObject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return extend; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return deepExtend; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return deepStrictEqual; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return deepFlatten; }); +/* unused harmony export canDefineProperty */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return lazy; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return traverse; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return hasOwnProperty; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return isLegacyFactory; }); +/* unused harmony export get */ +/* unused harmony export set */ +/* unused harmony export pick */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return pickShallow; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return values; }); +/* harmony import */ var _is__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + + +/** + * Clone an object + * + * clone(x) + * + * Can clone any primitive type, array, and object. + * If x has a function clone, this function will be invoked to clone the object. + * + * @param {*} x + * @return {*} clone + */ + +function clone(x) { + var type = _typeof(x); // immutable primitive types + + + if (type === 'number' || type === 'string' || type === 'boolean' || x === null || x === undefined) { + return x; + } // use clone function of the object when available + + + if (typeof x.clone === 'function') { + return x.clone(); + } // array + + + if (Array.isArray(x)) { + return x.map(function (value) { + return clone(value); + }); + } + + if (x instanceof Date) return new Date(x.valueOf()); + if (Object(_is__WEBPACK_IMPORTED_MODULE_0__[/* isBigNumber */ "e"])(x)) return x; // bignumbers are immutable + + if (x instanceof RegExp) throw new TypeError('Cannot clone ' + x); // TODO: clone a RegExp + // object + + return mapObject(x, clone); +} +/** + * Apply map to all properties of an object + * @param {Object} object + * @param {function} callback + * @return {Object} Returns a copy of the object with mapped properties + */ + +function mapObject(object, callback) { + var clone = {}; + + for (var key in object) { + if (hasOwnProperty(object, key)) { + clone[key] = callback(object[key]); + } + } + + return clone; +} +/** + * Extend object a with the properties of object b + * @param {Object} a + * @param {Object} b + * @return {Object} a + */ + +function extend(a, b) { + for (var prop in b) { + if (hasOwnProperty(b, prop)) { + a[prop] = b[prop]; + } + } + + return a; +} +/** + * Deep extend an object a with the properties of object b + * @param {Object} a + * @param {Object} b + * @returns {Object} + */ + +function deepExtend(a, b) { + // TODO: add support for Arrays to deepExtend + if (Array.isArray(b)) { + throw new TypeError('Arrays are not supported by deepExtend'); + } + + for (var prop in b) { + if (hasOwnProperty(b, prop)) { + if (b[prop] && b[prop].constructor === Object) { + if (a[prop] === undefined) { + a[prop] = {}; + } + + if (a[prop] && a[prop].constructor === Object) { + deepExtend(a[prop], b[prop]); + } else { + a[prop] = b[prop]; + } + } else if (Array.isArray(b[prop])) { + throw new TypeError('Arrays are not supported by deepExtend'); + } else { + a[prop] = b[prop]; + } + } + } + + return a; +} +/** + * Deep test equality of all fields in two pairs of arrays or objects. + * Compares values and functions strictly (ie. 2 is not the same as '2'). + * @param {Array | Object} a + * @param {Array | Object} b + * @returns {boolean} + */ + +function deepStrictEqual(a, b) { + var prop, i, len; + + if (Array.isArray(a)) { + if (!Array.isArray(b)) { + return false; + } + + if (a.length !== b.length) { + return false; + } + + for (i = 0, len = a.length; i < len; i++) { + if (!deepStrictEqual(a[i], b[i])) { + return false; + } + } + + return true; + } else if (typeof a === 'function') { + return a === b; + } else if (a instanceof Object) { + if (Array.isArray(b) || !(b instanceof Object)) { + return false; + } + + for (prop in a) { + // noinspection JSUnfilteredForInLoop + if (!(prop in b) || !deepStrictEqual(a[prop], b[prop])) { + return false; + } + } + + for (prop in b) { + // noinspection JSUnfilteredForInLoop + if (!(prop in a) || !deepStrictEqual(a[prop], b[prop])) { + return false; + } + } + + return true; + } else { + return a === b; + } +} +/** + * Recursively flatten a nested object. + * @param {Object} nestedObject + * @return {Object} Returns the flattened object + */ + +function deepFlatten(nestedObject) { + var flattenedObject = {}; + + _deepFlatten(nestedObject, flattenedObject); + + return flattenedObject; +} // helper function used by deepFlatten + +function _deepFlatten(nestedObject, flattenedObject) { + for (var prop in nestedObject) { + if (hasOwnProperty(nestedObject, prop)) { + var value = nestedObject[prop]; + + if (_typeof(value) === 'object' && value !== null) { + _deepFlatten(value, flattenedObject); + } else { + flattenedObject[prop] = value; + } + } + } +} +/** + * Test whether the current JavaScript engine supports Object.defineProperty + * @returns {boolean} returns true if supported + */ + + +function canDefineProperty() { + // test needed for broken IE8 implementation + try { + if (Object.defineProperty) { + Object.defineProperty({}, 'x', { + get: function get() {} + }); + return true; + } + } catch (e) {} + + return false; +} +/** + * Attach a lazy loading property to a constant. + * The given function `fn` is called once when the property is first requested. + * + * @param {Object} object Object where to add the property + * @param {string} prop Property name + * @param {Function} valueResolver Function returning the property value. Called + * without arguments. + */ + +function lazy(object, prop, valueResolver) { + var _uninitialized = true; + + var _value; + + Object.defineProperty(object, prop, { + get: function get() { + if (_uninitialized) { + _value = valueResolver(); + _uninitialized = false; + } + + return _value; + }, + set: function set(value) { + _value = value; + _uninitialized = false; + }, + configurable: true, + enumerable: true + }); +} +/** + * Traverse a path into an object. + * When a namespace is missing, it will be created + * @param {Object} object + * @param {string | string[]} path A dot separated string like 'name.space' + * @return {Object} Returns the object at the end of the path + */ + +function traverse(object, path) { + if (path && typeof path === 'string') { + return traverse(object, path.split('.')); + } + + var obj = object; + + if (path) { + for (var i = 0; i < path.length; i++) { + var key = path[i]; + + if (!(key in obj)) { + obj[key] = {}; + } + + obj = obj[key]; + } + } + + return obj; +} +/** + * A safe hasOwnProperty + * @param {Object} object + * @param {string} property + */ + +function hasOwnProperty(object, property) { + return object && Object.hasOwnProperty.call(object, property); +} +/** + * Test whether an object is a factory. a factory has fields: + * + * - factory: function (type: Object, config: Object, load: function, typed: function [, math: Object]) (required) + * - name: string (optional) + * - path: string A dot separated path (optional) + * - math: boolean If true (false by default), the math namespace is passed + * as fifth argument of the factory function + * + * @param {*} object + * @returns {boolean} + */ + +function isLegacyFactory(object) { + return object && typeof object.factory === 'function'; +} +/** + * Get a nested property from an object + * @param {Object} object + * @param {string | string[]} path + * @returns {Object} + */ + +function get(object, path) { + if (typeof path === 'string') { + if (isPath(path)) { + return get(object, path.split('.')); + } else { + return object[path]; + } + } + + var child = object; + + for (var i = 0; i < path.length; i++) { + var key = path[i]; + child = child ? child[key] : undefined; + } + + return child; +} +/** + * Set a nested property in an object + * Mutates the object itself + * If the path doesn't exist, it will be created + * @param {Object} object + * @param {string | string[]} path + * @param {*} value + * @returns {Object} + */ + +function set(object, path, value) { + if (typeof path === 'string') { + if (isPath(path)) { + return set(object, path.split('.'), value); + } else { + object[path] = value; + return object; + } + } + + var child = object; + + for (var i = 0; i < path.length - 1; i++) { + var key = path[i]; + + if (child[key] === undefined) { + child[key] = {}; + } + + child = child[key]; + } + + if (path.length > 0) { + var lastKey = path[path.length - 1]; + child[lastKey] = value; + } + + return object; +} +/** + * Create an object composed of the picked object properties + * @param {Object} object + * @param {string[]} properties + * @param {function} [transform] Optional value to transform a value when picking it + * @return {Object} + */ + +function pick(object, properties, transform) { + var copy = {}; + + for (var i = 0; i < properties.length; i++) { + var key = properties[i]; + var value = get(object, key); + + if (value !== undefined) { + set(copy, key, transform ? transform(value, key) : value); + } + } + + return copy; +} +/** + * Shallow version of pick, creating an object composed of the picked object properties + * but not for nested properties + * @param {Object} object + * @param {string[]} properties + * @return {Object} + */ + +function pickShallow(object, properties) { + var copy = {}; + + for (var i = 0; i < properties.length; i++) { + var key = properties[i]; + var value = object[key]; + + if (value !== undefined) { + copy[key] = value; + } + } + + return copy; +} +function values(object) { + return Object.keys(object).map(function (key) { + return object[key]; + }); +} // helper function to test whether a string contains a path like 'user.name' + +function isPath(str) { + return str.indexOf('.') !== -1; +} + +/***/ }), +/* 4 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return isInteger; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return sign; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return log2; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return log10; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return log1p; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return cbrt; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return expm1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return format; }); +/* unused harmony export splitNumber */ +/* unused harmony export toEngineering */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return toFixed; }); +/* unused harmony export toExponential */ +/* unused harmony export toPrecision */ +/* unused harmony export roundDigits */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return digits; }); +/* unused harmony export DBL_EPSILON */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return nearlyEqual; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return acosh; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return asinh; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return atanh; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return cosh; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return sinh; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return tanh; }); +/* harmony import */ var _object__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); +/* harmony import */ var _is__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1); + + +/** + * @typedef {{sign: '+' | '-' | '', coefficients: number[], exponent: number}} SplitValue + */ + +/** + * Check if a number is integer + * @param {number | boolean} value + * @return {boolean} isInteger + */ + +function isInteger(value) { + if (typeof value === 'boolean') { + return true; + } + + return isFinite(value) ? value === Math.round(value) : false; // Note: we use ==, not ===, as we can have Booleans as well +} +/** + * Calculate the sign of a number + * @param {number} x + * @returns {number} + */ + +var sign = /* #__PURE__ */Math.sign || function (x) { + if (x > 0) { + return 1; + } else if (x < 0) { + return -1; + } else { + return 0; + } +}; +/** + * Calculate the base-2 logarithm of a number + * @param {number} x + * @returns {number} + */ + +var log2 = /* #__PURE__ */Math.log2 || function log2(x) { + return Math.log(x) / Math.LN2; +}; +/** + * Calculate the base-10 logarithm of a number + * @param {number} x + * @returns {number} + */ + +var log10 = /* #__PURE__ */Math.log10 || function log10(x) { + return Math.log(x) / Math.LN10; +}; +/** + * Calculate the natural logarithm of a number + 1 + * @param {number} x + * @returns {number} + */ + +var log1p = /* #__PURE__ */Math.log1p || function (x) { + return Math.log(x + 1); +}; +/** + * Calculate cubic root for a number + * + * Code from es6-shim.js: + * https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1564-L1577 + * + * @param {number} x + * @returns {number} Returns the cubic root of x + */ + +var cbrt = /* #__PURE__ */Math.cbrt || function cbrt(x) { + if (x === 0) { + return x; + } + + var negate = x < 0; + var result; + + if (negate) { + x = -x; + } + + if (isFinite(x)) { + result = Math.exp(Math.log(x) / 3); // from https://en.wikipedia.org/wiki/Cube_root#Numerical_methods + + result = (x / (result * result) + 2 * result) / 3; + } else { + result = x; + } + + return negate ? -result : result; +}; +/** + * Calculates exponentiation minus 1 + * @param {number} x + * @return {number} res + */ + +var expm1 = /* #__PURE__ */Math.expm1 || function expm1(x) { + return x >= 2e-4 || x <= -2e-4 ? Math.exp(x) - 1 : x + x * x / 2 + x * x * x / 6; +}; +/** + * Convert a number to a formatted string representation. + * + * Syntax: + * + * format(value) + * format(value, options) + * format(value, precision) + * format(value, fn) + * + * Where: + * + * {number} value The value to be formatted + * {Object} options An object with formatting options. Available options: + * {string} notation + * Number notation. Choose from: + * 'fixed' Always use regular number notation. + * For example '123.40' and '14000000' + * 'exponential' Always use exponential notation. + * For example '1.234e+2' and '1.4e+7' + * 'engineering' Always use engineering notation. + * For example '123.4e+0' and '14.0e+6' + * 'auto' (default) Regular number notation for numbers + * having an absolute value between + * `lowerExp` and `upperExp` bounds, and + * uses exponential notation elsewhere. + * Lower bound is included, upper bound + * is excluded. + * For example '123.4' and '1.4e7'. + * {number} precision A number between 0 and 16 to round + * the digits of the number. + * In case of notations 'exponential', + * 'engineering', and 'auto', + * `precision` defines the total + * number of significant digits returned. + * In case of notation 'fixed', + * `precision` defines the number of + * significant digits after the decimal + * point. + * `precision` is undefined by default, + * not rounding any digits. + * {number} lowerExp Exponent determining the lower boundary + * for formatting a value with an exponent + * when `notation='auto`. + * Default value is `-3`. + * {number} upperExp Exponent determining the upper boundary + * for formatting a value with an exponent + * when `notation='auto`. + * Default value is `5`. + * {Function} fn A custom formatting function. Can be used to override the + * built-in notations. Function `fn` is called with `value` as + * parameter and must return a string. Is useful for example to + * format all values inside a matrix in a particular way. + * + * Examples: + * + * format(6.4) // '6.4' + * format(1240000) // '1.24e6' + * format(1/3) // '0.3333333333333333' + * format(1/3, 3) // '0.333' + * format(21385, 2) // '21000' + * format(12.071, {notation: 'fixed'}) // '12' + * format(2.3, {notation: 'fixed', precision: 2}) // '2.30' + * format(52.8, {notation: 'exponential'}) // '5.28e+1' + * format(12345678, {notation: 'engineering'}) // '12.345678e+6' + * + * @param {number} value + * @param {Object | Function | number} [options] + * @return {string} str The formatted value + */ + +function format(value, options) { + if (typeof options === 'function') { + // handle format(value, fn) + return options(value); + } // handle special cases + + + if (value === Infinity) { + return 'Infinity'; + } else if (value === -Infinity) { + return '-Infinity'; + } else if (isNaN(value)) { + return 'NaN'; + } // default values for options + + + var notation = 'auto'; + var precision; + + if (options) { + // determine notation from options + if (options.notation) { + notation = options.notation; + } // determine precision from options + + + if (Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(options)) { + precision = options; + } else if (Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(options.precision)) { + precision = options.precision; + } + } // handle the various notations + + + switch (notation) { + case 'fixed': + return toFixed(value, precision); + + case 'exponential': + return toExponential(value, precision); + + case 'engineering': + return toEngineering(value, precision); + + case 'auto': + // TODO: clean up some day. Deprecated since: 2018-01-24 + // @deprecated upper and lower are replaced with upperExp and lowerExp since v4.0.0 + if (options && options.exponential && (options.exponential.lower !== undefined || options.exponential.upper !== undefined)) { + var fixedOptions = Object(_object__WEBPACK_IMPORTED_MODULE_0__[/* mapObject */ "i"])(options, function (x) { + return x; + }); + fixedOptions.exponential = undefined; + + if (options.exponential.lower !== undefined) { + fixedOptions.lowerExp = Math.round(Math.log(options.exponential.lower) / Math.LN10); + } + + if (options.exponential.upper !== undefined) { + fixedOptions.upperExp = Math.round(Math.log(options.exponential.upper) / Math.LN10); + } + + console.warn('Deprecation warning: Formatting options exponential.lower and exponential.upper ' + '(minimum and maximum value) ' + 'are replaced with exponential.lowerExp and exponential.upperExp ' + '(minimum and maximum exponent) since version 4.0.0. ' + 'Replace ' + JSON.stringify(options) + ' with ' + JSON.stringify(fixedOptions)); + return toPrecision(value, precision, fixedOptions); + } // remove trailing zeros after the decimal point + + + return toPrecision(value, precision, options && options).replace(/((\.\d*?)(0+))($|e)/, function () { + var digits = arguments[2]; + var e = arguments[4]; + return digits !== '.' ? digits + e : e; + }); + + default: + throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", or "fixed".'); + } +} +/** + * Split a number into sign, coefficients, and exponent + * @param {number | string} value + * @return {SplitValue} + * Returns an object containing sign, coefficients, and exponent + */ + +function splitNumber(value) { + // parse the input value + var match = String(value).toLowerCase().match(/^0*?(-?)(\d+\.?\d*)(e([+-]?\d+))?$/); + + if (!match) { + throw new SyntaxError('Invalid number ' + value); + } + + var sign = match[1]; + var digits = match[2]; + var exponent = parseFloat(match[4] || '0'); + var dot = digits.indexOf('.'); + exponent += dot !== -1 ? dot - 1 : digits.length - 1; + var coefficients = digits.replace('.', '') // remove the dot (must be removed before removing leading zeros) + .replace(/^0*/, function (zeros) { + // remove leading zeros, add their count to the exponent + exponent -= zeros.length; + return ''; + }).replace(/0*$/, '') // remove trailing zeros + .split('').map(function (d) { + return parseInt(d); + }); + + if (coefficients.length === 0) { + coefficients.push(0); + exponent++; + } + + return { + sign: sign, + coefficients: coefficients, + exponent: exponent + }; +} +/** + * Format a number in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3' + * @param {number | string} value + * @param {number} [precision] Optional number of significant figures to return. + */ + +function toEngineering(value, precision) { + if (isNaN(value) || !isFinite(value)) { + return String(value); + } + + var split = splitNumber(value); + var rounded = roundDigits(split, precision); + var e = rounded.exponent; + var c = rounded.coefficients; // find nearest lower multiple of 3 for exponent + + var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3; + + if (Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(precision)) { + // add zeroes to give correct sig figs + while (precision > c.length || e - newExp + 1 > c.length) { + c.push(0); + } + } else { + // concatenate coefficients with necessary zeros + // add zeros if necessary (for example: 1e+8 -> 100e+6) + var missingZeros = Math.abs(e - newExp) - (c.length - 1); + + for (var i = 0; i < missingZeros; i++) { + c.push(0); + } + } // find difference in exponents + + + var expDiff = Math.abs(e - newExp); + var decimalIdx = 1; // push decimal index over by expDiff times + + while (expDiff > 0) { + decimalIdx++; + expDiff--; + } // if all coefficient values are zero after the decimal point and precision is unset, don't add a decimal value. + // otherwise concat with the rest of the coefficients + + + var decimals = c.slice(decimalIdx).join(''); + var decimalVal = Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(precision) && decimals.length || decimals.match(/[1-9]/) ? '.' + decimals : ''; + var str = c.slice(0, decimalIdx).join('') + decimalVal + 'e' + (e >= 0 ? '+' : '') + newExp.toString(); + return rounded.sign + str; +} +/** + * Format a number with fixed notation. + * @param {number | string} value + * @param {number} [precision=undefined] Optional number of decimals after the + * decimal point. null by default. + */ + +function toFixed(value, precision) { + if (isNaN(value) || !isFinite(value)) { + return String(value); + } + + var splitValue = splitNumber(value); + var rounded = typeof precision === 'number' ? roundDigits(splitValue, splitValue.exponent + 1 + precision) : splitValue; + var c = rounded.coefficients; + var p = rounded.exponent + 1; // exponent may have changed + // append zeros if needed + + var pp = p + (precision || 0); + + if (c.length < pp) { + c = c.concat(zeros(pp - c.length)); + } // prepend zeros if needed + + + if (p < 0) { + c = zeros(-p + 1).concat(c); + p = 1; + } // insert a dot if needed + + + if (p < c.length) { + c.splice(p, 0, p === 0 ? '0.' : '.'); + } + + return rounded.sign + c.join(''); +} +/** + * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3' + * @param {number | string} value + * @param {number} [precision] Number of digits in formatted output. + * If not provided, the maximum available digits + * is used. + */ + +function toExponential(value, precision) { + if (isNaN(value) || !isFinite(value)) { + return String(value); + } // round if needed, else create a clone + + + var split = splitNumber(value); + var rounded = precision ? roundDigits(split, precision) : split; + var c = rounded.coefficients; + var e = rounded.exponent; // append zeros if needed + + if (c.length < precision) { + c = c.concat(zeros(precision - c.length)); + } // format as `C.CCCe+EEE` or `C.CCCe-EEE` + + + var first = c.shift(); + return rounded.sign + first + (c.length > 0 ? '.' + c.join('') : '') + 'e' + (e >= 0 ? '+' : '') + e; +} +/** + * Format a number with a certain precision + * @param {number | string} value + * @param {number} [precision=undefined] Optional number of digits. + * @param {{lowerExp: number | undefined, upperExp: number | undefined}} [options] + * By default: + * lowerExp = -3 (incl) + * upper = +5 (excl) + * @return {string} + */ + +function toPrecision(value, precision, options) { + if (isNaN(value) || !isFinite(value)) { + return String(value); + } // determine lower and upper bound for exponential notation. + + + var lowerExp = options && options.lowerExp !== undefined ? options.lowerExp : -3; + var upperExp = options && options.upperExp !== undefined ? options.upperExp : 5; + var split = splitNumber(value); + var rounded = precision ? roundDigits(split, precision) : split; + + if (rounded.exponent < lowerExp || rounded.exponent >= upperExp) { + // exponential notation + return toExponential(value, precision); + } else { + var c = rounded.coefficients; + var e = rounded.exponent; // append trailing zeros + + if (c.length < precision) { + c = c.concat(zeros(precision - c.length)); + } // append trailing zeros + // TODO: simplify the next statement + + + c = c.concat(zeros(e - c.length + 1 + (c.length < precision ? precision - c.length : 0))); // prepend zeros + + c = zeros(-e).concat(c); + var dot = e > 0 ? e : 0; + + if (dot < c.length - 1) { + c.splice(dot + 1, 0, '.'); + } + + return rounded.sign + c.join(''); + } +} +/** + * Round the number of digits of a number * + * @param {SplitValue} split A value split with .splitNumber(value) + * @param {number} precision A positive integer + * @return {SplitValue} + * Returns an object containing sign, coefficients, and exponent + * with rounded digits + */ + +function roundDigits(split, precision) { + // create a clone + var rounded = { + sign: split.sign, + coefficients: split.coefficients, + exponent: split.exponent + }; + var c = rounded.coefficients; // prepend zeros if needed + + while (precision <= 0) { + c.unshift(0); + rounded.exponent++; + precision++; + } + + if (c.length > precision) { + var removed = c.splice(precision, c.length - precision); + + if (removed[0] >= 5) { + var i = precision - 1; + c[i]++; + + while (c[i] === 10) { + c.pop(); + + if (i === 0) { + c.unshift(0); + rounded.exponent++; + i++; + } + + i--; + c[i]++; + } + } + } + + return rounded; +} +/** + * Create an array filled with zeros. + * @param {number} length + * @return {Array} + */ + +function zeros(length) { + var arr = []; + + for (var i = 0; i < length; i++) { + arr.push(0); + } + + return arr; +} +/** + * Count the number of significant digits of a number. + * + * For example: + * 2.34 returns 3 + * 0.0034 returns 2 + * 120.5e+30 returns 4 + * + * @param {number} value + * @return {number} digits Number of significant digits + */ + + +function digits(value) { + return value.toExponential().replace(/e.*$/, '') // remove exponential notation + .replace(/^0\.?0*|\./, '') // remove decimal point and leading zeros + .length; +} +/** + * Minimum number added to one that makes the result different than one + */ + +var DBL_EPSILON = Number.EPSILON || 2.2204460492503130808472633361816E-16; +/** + * Compares two floating point numbers. + * @param {number} x First value to compare + * @param {number} y Second value to compare + * @param {number} [epsilon] The maximum relative difference between x and y + * If epsilon is undefined or null, the function will + * test whether x and y are exactly equal. + * @return {boolean} whether the two numbers are nearly equal +*/ + +function nearlyEqual(x, y, epsilon) { + // if epsilon is null or undefined, test whether x and y are exactly equal + if (epsilon === null || epsilon === undefined) { + return x === y; + } + + if (x === y) { + return true; + } // NaN + + + if (isNaN(x) || isNaN(y)) { + return false; + } // at this point x and y should be finite + + + if (isFinite(x) && isFinite(y)) { + // check numbers are very close, needed when comparing numbers near zero + var diff = Math.abs(x - y); + + if (diff < DBL_EPSILON) { + return true; + } else { + // use relative error + return diff <= Math.max(Math.abs(x), Math.abs(y)) * epsilon; + } + } // Infinite and Number or negative Infinite and positive Infinite cases + + + return false; +} +/** + * Calculate the hyperbolic arccos of a number + * @param {number} x + * @return {number} + */ + +var acosh = Math.acosh || function (x) { + return Math.log(Math.sqrt(x * x - 1) + x); +}; +var asinh = Math.asinh || function (x) { + return Math.log(Math.sqrt(x * x + 1) + x); +}; +/** + * Calculate the hyperbolic arctangent of a number + * @param {number} x + * @return {number} + */ + +var atanh = Math.atanh || function (x) { + return Math.log((1 + x) / (1 - x)) / 2; +}; +/** + * Calculate the hyperbolic cosine of a number + * @param {number} x + * @returns {number} + */ + +var cosh = Math.cosh || function (x) { + return (Math.exp(x) + Math.exp(-x)) / 2; +}; +/** + * Calculate the hyperbolic sine of a number + * @param {number} x + * @returns {number} + */ + +var sinh = Math.sinh || function (x) { + return (Math.exp(x) - Math.exp(-x)) / 2; +}; +/** + * Calculate the hyperbolic tangent of a number + * @param {number} x + * @returns {number} + */ + +var tanh = Math.tanh || function (x) { + var e = Math.exp(2 * x); + return (e - 1) / (e + 1); +}; + +/***/ }), +/* 5 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ endsWith; }); +__webpack_require__.d(__webpack_exports__, "d", function() { return /* binding */ string_format; }); +__webpack_require__.d(__webpack_exports__, "e", function() { return /* binding */ stringify; }); +__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ string_escape; }); +__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ compareText; }); + +// EXTERNAL MODULE: ./src/utils/is.js +var is = __webpack_require__(1); + +// EXTERNAL MODULE: ./src/utils/number.js +var number = __webpack_require__(4); + +// EXTERNAL MODULE: ./src/utils/object.js +var object = __webpack_require__(3); + +// CONCATENATED MODULE: ./src/utils/bignumber/formatter.js + +/** + * Convert a BigNumber to a formatted string representation. + * + * Syntax: + * + * format(value) + * format(value, options) + * format(value, precision) + * format(value, fn) + * + * Where: + * + * {number} value The value to be formatted + * {Object} options An object with formatting options. Available options: + * {string} notation + * Number notation. Choose from: + * 'fixed' Always use regular number notation. + * For example '123.40' and '14000000' + * 'exponential' Always use exponential notation. + * For example '1.234e+2' and '1.4e+7' + * 'auto' (default) Regular number notation for numbers + * having an absolute value between + * `lower` and `upper` bounds, and uses + * exponential notation elsewhere. + * Lower bound is included, upper bound + * is excluded. + * For example '123.4' and '1.4e7'. + * {number} precision A number between 0 and 16 to round + * the digits of the number. + * In case of notations 'exponential', + * 'engineering', and 'auto', + * `precision` defines the total + * number of significant digits returned. + * In case of notation 'fixed', + * `precision` defines the number of + * significant digits after the decimal + * point. + * `precision` is undefined by default. + * {number} lowerExp Exponent determining the lower boundary + * for formatting a value with an exponent + * when `notation='auto`. + * Default value is `-3`. + * {number} upperExp Exponent determining the upper boundary + * for formatting a value with an exponent + * when `notation='auto`. + * Default value is `5`. + * {Function} fn A custom formatting function. Can be used to override the + * built-in notations. Function `fn` is called with `value` as + * parameter and must return a string. Is useful for example to + * format all values inside a matrix in a particular way. + * + * Examples: + * + * format(6.4) // '6.4' + * format(1240000) // '1.24e6' + * format(1/3) // '0.3333333333333333' + * format(1/3, 3) // '0.333' + * format(21385, 2) // '21000' + * format(12e8, {notation: 'fixed'}) // returns '1200000000' + * format(2.3, {notation: 'fixed', precision: 4}) // returns '2.3000' + * format(52.8, {notation: 'exponential'}) // returns '5.28e+1' + * format(12400, {notation: 'engineering'}) // returns '12.400e+3' + * + * @param {BigNumber} value + * @param {Object | Function | number} [options] + * @return {string} str The formatted value + */ + +function format(value, options) { + if (typeof options === 'function') { + // handle format(value, fn) + return options(value); + } // handle special cases + + + if (!value.isFinite()) { + return value.isNaN() ? 'NaN' : value.gt(0) ? 'Infinity' : '-Infinity'; + } // default values for options + + + var notation = 'auto'; + var precision; + + if (options !== undefined) { + // determine notation from options + if (options.notation) { + notation = options.notation; + } // determine precision from options + + + if (typeof options === 'number') { + precision = options; + } else if (options.precision) { + precision = options.precision; + } + } // handle the various notations + + + switch (notation) { + case 'fixed': + return toFixed(value, precision); + + case 'exponential': + return toExponential(value, precision); + + case 'engineering': + return toEngineering(value, precision); + + case 'auto': + { + // TODO: clean up some day. Deprecated since: 2018-01-24 + // @deprecated upper and lower are replaced with upperExp and lowerExp since v4.0.0 + if (options && options.exponential && (options.exponential.lower !== undefined || options.exponential.upper !== undefined)) { + var fixedOptions = Object(object["i" /* mapObject */])(options, function (x) { + return x; + }); + fixedOptions.exponential = undefined; + + if (options.exponential.lower !== undefined) { + fixedOptions.lowerExp = Math.round(Math.log(options.exponential.lower) / Math.LN10); + } + + if (options.exponential.upper !== undefined) { + fixedOptions.upperExp = Math.round(Math.log(options.exponential.upper) / Math.LN10); + } + + console.warn('Deprecation warning: Formatting options exponential.lower and exponential.upper ' + '(minimum and maximum value) ' + 'are replaced with exponential.lowerExp and exponential.upperExp ' + '(minimum and maximum exponent) since version 4.0.0. ' + 'Replace ' + JSON.stringify(options) + ' with ' + JSON.stringify(fixedOptions)); + return format(value, fixedOptions); + } // determine lower and upper bound for exponential notation. + // TODO: implement support for upper and lower to be BigNumbers themselves + + + var lowerExp = options && options.lowerExp !== undefined ? options.lowerExp : -3; + var upperExp = options && options.upperExp !== undefined ? options.upperExp : 5; // handle special case zero + + if (value.isZero()) return '0'; // determine whether or not to output exponential notation + + var str; + var rounded = value.toSignificantDigits(precision); + var exp = rounded.e; + + if (exp >= lowerExp && exp < upperExp) { + // normal number notation + str = rounded.toFixed(); + } else { + // exponential notation + str = toExponential(value, precision); + } // remove trailing zeros after the decimal point + + + return str.replace(/((\.\d*?)(0+))($|e)/, function () { + var digits = arguments[2]; + var e = arguments[4]; + return digits !== '.' ? digits + e : e; + }); + } + + default: + throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", or "fixed".'); + } +} +/** + * Format a BigNumber in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3' + * @param {BigNumber | string} value + * @param {number} [precision] Optional number of significant figures to return. + */ + +function toEngineering(value, precision) { + // find nearest lower multiple of 3 for exponent + var e = value.e; + var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3; // find difference in exponents, and calculate the value without exponent + + var valueWithoutExp = value.mul(Math.pow(10, -newExp)); + var valueStr = valueWithoutExp.toPrecision(precision); + + if (valueStr.indexOf('e') !== -1) { + valueStr = valueWithoutExp.toString(); + } + + return valueStr + 'e' + (e >= 0 ? '+' : '') + newExp.toString(); +} +/** + * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3' + * @param {BigNumber} value + * @param {number} [precision] Number of digits in formatted output. + * If not provided, the maximum available digits + * is used. + * @returns {string} str + */ + +function toExponential(value, precision) { + if (precision !== undefined) { + return value.toExponential(precision - 1); // Note the offset of one + } else { + return value.toExponential(); + } +} +/** + * Format a number with fixed notation. + * @param {BigNumber} value + * @param {number} [precision=undefined] Optional number of decimals after the + * decimal point. Undefined by default. + */ + +function toFixed(value, precision) { + return value.toFixed(precision); +} +// CONCATENATED MODULE: ./src/utils/string.js +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + + + + +/** + * Check if a text ends with a certain string. + * @param {string} text + * @param {string} search + */ + +function endsWith(text, search) { + var start = text.length - search.length; + var end = text.length; + return text.substring(start, end) === search; +} +/** + * Format a value of any type into a string. + * + * Usage: + * math.format(value) + * math.format(value, precision) + * + * When value is a function: + * + * - When the function has a property `syntax`, it returns this + * syntax description. + * - In other cases, a string `'function'` is returned. + * + * When `value` is an Object: + * + * - When the object contains a property `format` being a function, this + * function is invoked as `value.format(options)` and the result is returned. + * - When the object has its own `toString` method, this method is invoked + * and the result is returned. + * - In other cases the function will loop over all object properties and + * return JSON object notation like '{"a": 2, "b": 3}'. + * + * Example usage: + * math.format(2/7) // '0.2857142857142857' + * math.format(math.pi, 3) // '3.14' + * math.format(new Complex(2, 3)) // '2 + 3i' + * math.format('hello') // '"hello"' + * + * @param {*} value Value to be stringified + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @return {string} str + */ + +function string_format(value, options) { + if (typeof value === 'number') { + return Object(number["h" /* format */])(value, options); + } + + if (Object(is["e" /* isBigNumber */])(value)) { + return format(value, options); + } // note: we use unsafe duck-typing here to check for Fractions, this is + // ok here since we're only invoking toString or concatenating its values + + + if (looksLikeFraction(value)) { + if (!options || options.fraction !== 'decimal') { + // output as ratio, like '1/3' + return value.s * value.n + '/' + value.d; + } else { + // output as decimal, like '0.(3)' + return value.toString(); + } + } + + if (Array.isArray(value)) { + return formatArray(value, options); + } + + if (Object(is["I" /* isString */])(value)) { + return '"' + value + '"'; + } + + if (typeof value === 'function') { + return value.syntax ? String(value.syntax) : 'function'; + } + + if (value && _typeof(value) === 'object') { + if (typeof value.format === 'function') { + return value.format(options); + } else if (value && value.toString(options) !== {}.toString()) { + // this object has a non-native toString method, use that one + return value.toString(options); + } else { + var entries = Object.keys(value).map(function (key) { + return '"' + key + '": ' + string_format(value[key], options); + }); + return '{' + entries.join(', ') + '}'; + } + } + + return String(value); +} +/** + * Stringify a value into a string enclosed in double quotes. + * Unescaped double quotes and backslashes inside the value are escaped. + * @param {*} value + * @return {string} + */ + +function stringify(value) { + var text = String(value); + var escaped = ''; + var i = 0; + + while (i < text.length) { + var c = text.charAt(i); + + if (c === '\\') { + escaped += c; + i++; + c = text.charAt(i); + + if (c === '' || '"\\/bfnrtu'.indexOf(c) === -1) { + escaped += '\\'; // no valid escape character -> escape it + } + + escaped += c; + } else if (c === '"') { + escaped += '\\"'; + } else { + escaped += c; + } + + i++; + } + + return '"' + escaped + '"'; +} +/** + * Escape special HTML characters + * @param {*} value + * @return {string} + */ + +function string_escape(value) { + var text = String(value); + text = text.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>'); + return text; +} +/** + * Recursively format an n-dimensional matrix + * Example output: "[[1, 2], [3, 4]]" + * @param {Array} array + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @returns {string} str + */ + +function formatArray(array, options) { + if (Array.isArray(array)) { + var str = '['; + var len = array.length; + + for (var i = 0; i < len; i++) { + if (i !== 0) { + str += ', '; + } + + str += formatArray(array[i], options); + } + + str += ']'; + return str; + } else { + return string_format(array, options); + } +} +/** + * Check whether a value looks like a Fraction (unsafe duck-type check) + * @param {*} value + * @return {boolean} + */ + + +function looksLikeFraction(value) { + return value && _typeof(value) === 'object' && typeof value.s === 'number' && typeof value.n === 'number' && typeof value.d === 'number' || false; +} +/** + * Compare two strings + * @param {string} x + * @param {string} y + * @returns {number} + */ + + +function compareText(x, y) { + // we don't want to convert numbers to string, only accept string input + if (!Object(is["I" /* isString */])(x)) { + throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + Object(is["M" /* typeOf */])(x) + ', index: 0)'); + } + + if (!Object(is["I" /* isString */])(y)) { + throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + Object(is["M" /* typeOf */])(y) + ', index: 1)'); + } + + return x === y ? 0 : x > y ? 1 : -1; +} + +/***/ }), +/* 6 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DimensionError; }); +/** + * Create a range error with the message: + * 'Dimension mismatch ( != )' + * @param {number | number[]} actual The actual size + * @param {number | number[]} expected The expected size + * @param {string} [relation='!='] Optional relation between actual + * and expected size: '!=', '<', etc. + * @extends RangeError + */ +function DimensionError(actual, expected, relation) { + if (!(this instanceof DimensionError)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.actual = actual; + this.expected = expected; + this.relation = relation; + this.message = 'Dimension mismatch (' + (Array.isArray(actual) ? '[' + actual.join(', ') + ']' : actual) + ' ' + (this.relation || '!=') + ' ' + (Array.isArray(expected) ? '[' + expected.join(', ') + ']' : expected) + ')'; + this.stack = new Error().stack; +} +DimensionError.prototype = new RangeError(); +DimensionError.prototype.constructor = RangeError; +DimensionError.prototype.name = 'DimensionError'; +DimensionError.prototype.isDimensionError = true; + +/***/ }), +/* 7 */, +/* 8 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return warnOnce; }); +/** + * Log a console.warn message only once + */ +var warnOnce = function () { + var messages = {}; + return function warnOnce() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var message = args.join(', '); + + if (!messages[message]) { + var _console; + + messages[message] = true; + + (_console = console).warn.apply(_console, ['Warning:'].concat(args)); + } + }; +}(); + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/** + * @license Complex.js v2.0.11 11/02/2016 + * + * Copyright (c) 2016, Robert Eisele (robert@xarg.org) + * Dual licensed under the MIT or GPL Version 2 licenses. + **/ + +/** + * + * This class allows the manipulation of complex numbers. + * You can pass a complex number in different formats. Either as object, double, string or two integer parameters. + * + * Object form + * { re: , im: } + * { arg: , abs: } + * { phi: , r: } + * + * Array / Vector form + * [ real, imaginary ] + * + * Double form + * 99.3 - Single double value + * + * String form + * '23.1337' - Simple real number + * '15+3i' - a simple complex number + * '3-i' - a simple complex number + * + * Example: + * + * var c = new Complex('99.3+8i'); + * c.mul({r: 3, i: 9}).div(4.9).sub(3, 2); + * + */ + +(function(root) { + + 'use strict'; + + var cosh = function(x) { + return (Math.exp(x) + Math.exp(-x)) * 0.5; + }; + + var sinh = function(x) { + return (Math.exp(x) - Math.exp(-x)) * 0.5; + }; + + /** + * Calculates cos(x) - 1 using Taylor series if x is small. + * + * @param {number} x + * @returns {number} cos(x) - 1 + */ + + var cosm1 = function(x) { + var limit = Math.PI/4; + if (x < -limit || x > limit) { + return (Math.cos(x) - 1.0); + } + + var xx = x * x; + return xx * + (-0.5 + xx * + (1/24 + xx * + (-1/720 + xx * + (1/40320 + xx * + (-1/3628800 + xx * + (1/4790014600 + xx * + (-1/87178291200 + xx * + (1/20922789888000) + ) + ) + ) + ) + ) + ) + ) + }; + + var hypot = function(x, y) { + + var a = Math.abs(x); + var b = Math.abs(y); + + if (a < 3000 && b < 3000) { + return Math.sqrt(a * a + b * b); + } + + if (a < b) { + a = b; + b = x / y; + } else { + b = y / x; + } + return a * Math.sqrt(1 + b * b); + }; + + var parser_exit = function() { + throw SyntaxError('Invalid Param'); + }; + + /** + * Calculates log(sqrt(a^2+b^2)) in a way to avoid overflows + * + * @param {number} a + * @param {number} b + * @returns {number} + */ + function logHypot(a, b) { + + var _a = Math.abs(a); + var _b = Math.abs(b); + + if (a === 0) { + return Math.log(_b); + } + + if (b === 0) { + return Math.log(_a); + } + + if (_a < 3000 && _b < 3000) { + return Math.log(a * a + b * b) * 0.5; + } + + /* I got 4 ideas to compute this property without overflow: + * + * Testing 1000000 times with random samples for a,b ∈ [1, 1000000000] against a big decimal library to get an error estimate + * + * 1. Only eliminate the square root: (OVERALL ERROR: 3.9122483030951116e-11) + + Math.log(a * a + b * b) / 2 + + * + * + * 2. Try to use the non-overflowing pythagoras: (OVERALL ERROR: 8.889760039210159e-10) + + var fn = function(a, b) { + a = Math.abs(a); + b = Math.abs(b); + var t = Math.min(a, b); + a = Math.max(a, b); + t = t / a; + + return Math.log(a) + Math.log(1 + t * t) / 2; + }; + + * 3. Abuse the identity cos(atan(y/x) = x / sqrt(x^2+y^2): (OVERALL ERROR: 3.4780178737037204e-10) + + Math.log(a / Math.cos(Math.atan2(b, a))) + + * 4. Use 3. and apply log rules: (OVERALL ERROR: 1.2014087502620896e-9) + + Math.log(a) - Math.log(Math.cos(Math.atan2(b, a))) + + */ + + return Math.log(a / Math.cos(Math.atan2(b, a))); + } + + var parse = function(a, b) { + + var z = {'re': 0, 'im': 0}; + + if (a === undefined || a === null) { + z['re'] = + z['im'] = 0; + } else if (b !== undefined) { + z['re'] = a; + z['im'] = b; + } else + switch (typeof a) { + + case 'object': + + if ('im' in a && 're' in a) { + z['re'] = a['re']; + z['im'] = a['im']; + } else if ('abs' in a && 'arg' in a) { + if (!Number.isFinite(a['abs']) && Number.isFinite(a['arg'])) { + return Complex['INFINITY']; + } + z['re'] = a['abs'] * Math.cos(a['arg']); + z['im'] = a['abs'] * Math.sin(a['arg']); + } else if ('r' in a && 'phi' in a) { + if (!Number.isFinite(a['r']) && Number.isFinite(a['phi'])) { + return Complex['INFINITY']; + } + z['re'] = a['r'] * Math.cos(a['phi']); + z['im'] = a['r'] * Math.sin(a['phi']); + } else if (a.length === 2) { // Quick array check + z['re'] = a[0]; + z['im'] = a[1]; + } else { + parser_exit(); + } + break; + + case 'string': + + z['im'] = /* void */ + z['re'] = 0; + + var tokens = a.match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g); + var plus = 1; + var minus = 0; + + if (tokens === null) { + parser_exit(); + } + + for (var i = 0; i < tokens.length; i++) { + + var c = tokens[i]; + + if (c === ' ' || c === '\t' || c === '\n') { + /* void */ + } else if (c === '+') { + plus++; + } else if (c === '-') { + minus++; + } else if (c === 'i' || c === 'I') { + + if (plus + minus === 0) { + parser_exit(); + } + + if (tokens[i + 1] !== ' ' && !isNaN(tokens[i + 1])) { + z['im'] += parseFloat((minus % 2 ? '-' : '') + tokens[i + 1]); + i++; + } else { + z['im'] += parseFloat((minus % 2 ? '-' : '') + '1'); + } + plus = minus = 0; + + } else { + + if (plus + minus === 0 || isNaN(c)) { + parser_exit(); + } + + if (tokens[i + 1] === 'i' || tokens[i + 1] === 'I') { + z['im'] += parseFloat((minus % 2 ? '-' : '') + c); + i++; + } else { + z['re'] += parseFloat((minus % 2 ? '-' : '') + c); + } + plus = minus = 0; + } + } + + // Still something on the stack + if (plus + minus > 0) { + parser_exit(); + } + break; + + case 'number': + z['im'] = 0; + z['re'] = a; + break; + + default: + parser_exit(); + } + + if (isNaN(z['re']) || isNaN(z['im'])) { + // If a calculation is NaN, we treat it as NaN and don't throw + //parser_exit(); + } + + return z; + }; + + /** + * @constructor + * @returns {Complex} + */ + function Complex(a, b) { + + if (!(this instanceof Complex)) { + return new Complex(a, b); + } + + var z = parse(a, b); + + this['re'] = z['re']; + this['im'] = z['im']; + } + + Complex.prototype = { + + 're': 0, + 'im': 0, + + /** + * Calculates the sign of a complex number, which is a normalized complex + * + * @returns {Complex} + */ + 'sign': function() { + + var abs = this['abs'](); + + return new Complex( + this['re'] / abs, + this['im'] / abs); + }, + + /** + * Adds two complex numbers + * + * @returns {Complex} + */ + 'add': function(a, b) { + + var z = new Complex(a, b); + + // Infinity + Infinity = NaN + if (this['isInfinite']() && z['isInfinite']()) { + return Complex['NAN']; + } + + // Infinity + z = Infinity { where z != Infinity } + if (this['isInfinite']() || z['isInfinite']()) { + return Complex['INFINITY']; + } + + return new Complex( + this['re'] + z['re'], + this['im'] + z['im']); + }, + + /** + * Subtracts two complex numbers + * + * @returns {Complex} + */ + 'sub': function(a, b) { + + var z = new Complex(a, b); + + // Infinity - Infinity = NaN + if (this['isInfinite']() && z['isInfinite']()) { + return Complex['NAN']; + } + + // Infinity - z = Infinity { where z != Infinity } + if (this['isInfinite']() || z['isInfinite']()) { + return Complex['INFINITY']; + } + + return new Complex( + this['re'] - z['re'], + this['im'] - z['im']); + }, + + /** + * Multiplies two complex numbers + * + * @returns {Complex} + */ + 'mul': function(a, b) { + + var z = new Complex(a, b); + + // Infinity * 0 = NaN + if ((this['isInfinite']() && z['isZero']()) || (this['isZero']() && z['isInfinite']())) { + return Complex['NAN']; + } + + // Infinity * z = Infinity { where z != 0 } + if (this['isInfinite']() || z['isInfinite']()) { + return Complex['INFINITY']; + } + + // Short circuit for real values + if (z['im'] === 0 && this['im'] === 0) { + return new Complex(this['re'] * z['re'], 0); + } + + return new Complex( + this['re'] * z['re'] - this['im'] * z['im'], + this['re'] * z['im'] + this['im'] * z['re']); + }, + + /** + * Divides two complex numbers + * + * @returns {Complex} + */ + 'div': function(a, b) { + + var z = new Complex(a, b); + + // 0 / 0 = NaN and Infinity / Infinity = NaN + if ((this['isZero']() && z['isZero']()) || (this['isInfinite']() && z['isInfinite']())) { + return Complex['NAN']; + } + + // Infinity / 0 = Infinity + if (this['isInfinite']() || z['isZero']()) { + return Complex['INFINITY']; + } + + // 0 / Infinity = 0 + if (this['isZero']() || z['isInfinite']()) { + return Complex['ZERO']; + } + + a = this['re']; + b = this['im']; + + var c = z['re']; + var d = z['im']; + var t, x; + + if (0 === d) { + // Divisor is real + return new Complex(a / c, b / c); + } + + if (Math.abs(c) < Math.abs(d)) { + + x = c / d; + t = c * x + d; + + return new Complex( + (a * x + b) / t, + (b * x - a) / t); + + } else { + + x = d / c; + t = d * x + c; + + return new Complex( + (a + b * x) / t, + (b - a * x) / t); + } + }, + + /** + * Calculate the power of two complex numbers + * + * @returns {Complex} + */ + 'pow': function(a, b) { + + var z = new Complex(a, b); + + a = this['re']; + b = this['im']; + + if (z['isZero']()) { + return Complex['ONE']; + } + + // If the exponent is real + if (z['im'] === 0) { + + if (b === 0 && a >= 0) { + + return new Complex(Math.pow(a, z['re']), 0); + + } else if (a === 0) { // If base is fully imaginary + + switch ((z['re'] % 4 + 4) % 4) { + case 0: + return new Complex(Math.pow(b, z['re']), 0); + case 1: + return new Complex(0, Math.pow(b, z['re'])); + case 2: + return new Complex(-Math.pow(b, z['re']), 0); + case 3: + return new Complex(0, -Math.pow(b, z['re'])); + } + } + } + + /* I couldn't find a good formula, so here is a derivation and optimization + * + * z_1^z_2 = (a + bi)^(c + di) + * = exp((c + di) * log(a + bi) + * = pow(a^2 + b^2, (c + di) / 2) * exp(i(c + di)atan2(b, a)) + * =>... + * Re = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * cos(d * log(a^2 + b^2) / 2 + c * atan2(b, a)) + * Im = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * sin(d * log(a^2 + b^2) / 2 + c * atan2(b, a)) + * + * =>... + * Re = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * cos(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a)) + * Im = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * sin(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a)) + * + * => + * Re = exp(c * logsq2 - d * arg(z_1)) * cos(d * logsq2 + c * arg(z_1)) + * Im = exp(c * logsq2 - d * arg(z_1)) * sin(d * logsq2 + c * arg(z_1)) + * + */ + + if (a === 0 && b === 0 && z['re'] > 0 && z['im'] >= 0) { + return Complex['ZERO']; + } + + var arg = Math.atan2(b, a); + var loh = logHypot(a, b); + + a = Math.exp(z['re'] * loh - z['im'] * arg); + b = z['im'] * loh + z['re'] * arg; + return new Complex( + a * Math.cos(b), + a * Math.sin(b)); + }, + + /** + * Calculate the complex square root + * + * @returns {Complex} + */ + 'sqrt': function() { + + var a = this['re']; + var b = this['im']; + var r = this['abs'](); + + var re, im; + + if (a >= 0) { + + if (b === 0) { + return new Complex(Math.sqrt(a), 0); + } + + re = 0.5 * Math.sqrt(2.0 * (r + a)); + } else { + re = Math.abs(b) / Math.sqrt(2 * (r - a)); + } + + if (a <= 0) { + im = 0.5 * Math.sqrt(2.0 * (r - a)); + } else { + im = Math.abs(b) / Math.sqrt(2 * (r + a)); + } + + return new Complex(re, b < 0 ? -im : im); + }, + + /** + * Calculate the complex exponent + * + * @returns {Complex} + */ + 'exp': function() { + + var tmp = Math.exp(this['re']); + + if (this['im'] === 0) { + //return new Complex(tmp, 0); + } + return new Complex( + tmp * Math.cos(this['im']), + tmp * Math.sin(this['im'])); + }, + + /** + * Calculate the complex exponent and subtracts one. + * + * This may be more accurate than `Complex(x).exp().sub(1)` if + * `x` is small. + * + * @returns {Complex} + */ + 'expm1': function() { + + /** + * exp(a + i*b) - 1 + = exp(a) * (cos(b) + j*sin(b)) - 1 + = expm1(a)*cos(b) + cosm1(b) + j*exp(a)*sin(b) + */ + + var a = this['re']; + var b = this['im']; + + return new Complex( + Math.expm1(a) * Math.cos(b) + cosm1(b), + Math.exp(a) * Math.sin(b)); + }, + + /** + * Calculate the natural log + * + * @returns {Complex} + */ + 'log': function() { + + var a = this['re']; + var b = this['im']; + + if (b === 0 && a > 0) { + //return new Complex(Math.log(a), 0); + } + + return new Complex( + logHypot(a, b), + Math.atan2(b, a)); + }, + + /** + * Calculate the magnitude of the complex number + * + * @returns {number} + */ + 'abs': function() { + + return hypot(this['re'], this['im']); + }, + + /** + * Calculate the angle of the complex number + * + * @returns {number} + */ + 'arg': function() { + + return Math.atan2(this['im'], this['re']); + }, + + /** + * Calculate the sine of the complex number + * + * @returns {Complex} + */ + 'sin': function() { + + // sin(c) = (e^b - e^(-b)) / (2i) + + var a = this['re']; + var b = this['im']; + + return new Complex( + Math.sin(a) * cosh(b), + Math.cos(a) * sinh(b)); + }, + + /** + * Calculate the cosine + * + * @returns {Complex} + */ + 'cos': function() { + + // cos(z) = (e^b + e^(-b)) / 2 + + var a = this['re']; + var b = this['im']; + + return new Complex( + Math.cos(a) * cosh(b), + -Math.sin(a) * sinh(b)); + }, + + /** + * Calculate the tangent + * + * @returns {Complex} + */ + 'tan': function() { + + // tan(c) = (e^(ci) - e^(-ci)) / (i(e^(ci) + e^(-ci))) + + var a = 2 * this['re']; + var b = 2 * this['im']; + var d = Math.cos(a) + cosh(b); + + return new Complex( + Math.sin(a) / d, + sinh(b) / d); + }, + + /** + * Calculate the cotangent + * + * @returns {Complex} + */ + 'cot': function() { + + // cot(c) = i(e^(ci) + e^(-ci)) / (e^(ci) - e^(-ci)) + + var a = 2 * this['re']; + var b = 2 * this['im']; + var d = Math.cos(a) - cosh(b); + + return new Complex( + -Math.sin(a) / d, + sinh(b) / d); + }, + + /** + * Calculate the secant + * + * @returns {Complex} + */ + 'sec': function() { + + // sec(c) = 2 / (e^(ci) + e^(-ci)) + + var a = this['re']; + var b = this['im']; + var d = 0.5 * cosh(2 * b) + 0.5 * Math.cos(2 * a); + + return new Complex( + Math.cos(a) * cosh(b) / d, + Math.sin(a) * sinh(b) / d); + }, + + /** + * Calculate the cosecans + * + * @returns {Complex} + */ + 'csc': function() { + + // csc(c) = 2i / (e^(ci) - e^(-ci)) + + var a = this['re']; + var b = this['im']; + var d = 0.5 * cosh(2 * b) - 0.5 * Math.cos(2 * a); + + return new Complex( + Math.sin(a) * cosh(b) / d, + -Math.cos(a) * sinh(b) / d); + }, + + /** + * Calculate the complex arcus sinus + * + * @returns {Complex} + */ + 'asin': function() { + + // asin(c) = -i * log(ci + sqrt(1 - c^2)) + + var a = this['re']; + var b = this['im']; + + var t1 = new Complex( + b * b - a * a + 1, + -2 * a * b)['sqrt'](); + + var t2 = new Complex( + t1['re'] - b, + t1['im'] + a)['log'](); + + return new Complex(t2['im'], -t2['re']); + }, + + /** + * Calculate the complex arcus cosinus + * + * @returns {Complex} + */ + 'acos': function() { + + // acos(c) = i * log(c - i * sqrt(1 - c^2)) + + var a = this['re']; + var b = this['im']; + + var t1 = new Complex( + b * b - a * a + 1, + -2 * a * b)['sqrt'](); + + var t2 = new Complex( + t1['re'] - b, + t1['im'] + a)['log'](); + + return new Complex(Math.PI / 2 - t2['im'], t2['re']); + }, + + /** + * Calculate the complex arcus tangent + * + * @returns {Complex} + */ + 'atan': function() { + + // atan(c) = i / 2 log((i + x) / (i - x)) + + var a = this['re']; + var b = this['im']; + + if (a === 0) { + + if (b === 1) { + return new Complex(0, Infinity); + } + + if (b === -1) { + return new Complex(0, -Infinity); + } + } + + var d = a * a + (1.0 - b) * (1.0 - b); + + var t1 = new Complex( + (1 - b * b - a * a) / d, + -2 * a / d).log(); + + return new Complex(-0.5 * t1['im'], 0.5 * t1['re']); + }, + + /** + * Calculate the complex arcus cotangent + * + * @returns {Complex} + */ + 'acot': function() { + + // acot(c) = i / 2 log((c - i) / (c + i)) + + var a = this['re']; + var b = this['im']; + + if (b === 0) { + return new Complex(Math.atan2(1, a), 0); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).atan() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).atan(); + }, + + /** + * Calculate the complex arcus secant + * + * @returns {Complex} + */ + 'asec': function() { + + // asec(c) = -i * log(1 / c + sqrt(1 - i / c^2)) + + var a = this['re']; + var b = this['im']; + + if (a === 0 && b === 0) { + return new Complex(0, Infinity); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).acos() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).acos(); + }, + + /** + * Calculate the complex arcus cosecans + * + * @returns {Complex} + */ + 'acsc': function() { + + // acsc(c) = -i * log(i / c + sqrt(1 - 1 / c^2)) + + var a = this['re']; + var b = this['im']; + + if (a === 0 && b === 0) { + return new Complex(Math.PI / 2, Infinity); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).asin() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).asin(); + }, + + /** + * Calculate the complex sinh + * + * @returns {Complex} + */ + 'sinh': function() { + + // sinh(c) = (e^c - e^-c) / 2 + + var a = this['re']; + var b = this['im']; + + return new Complex( + sinh(a) * Math.cos(b), + cosh(a) * Math.sin(b)); + }, + + /** + * Calculate the complex cosh + * + * @returns {Complex} + */ + 'cosh': function() { + + // cosh(c) = (e^c + e^-c) / 2 + + var a = this['re']; + var b = this['im']; + + return new Complex( + cosh(a) * Math.cos(b), + sinh(a) * Math.sin(b)); + }, + + /** + * Calculate the complex tanh + * + * @returns {Complex} + */ + 'tanh': function() { + + // tanh(c) = (e^c - e^-c) / (e^c + e^-c) + + var a = 2 * this['re']; + var b = 2 * this['im']; + var d = cosh(a) + Math.cos(b); + + return new Complex( + sinh(a) / d, + Math.sin(b) / d); + }, + + /** + * Calculate the complex coth + * + * @returns {Complex} + */ + 'coth': function() { + + // coth(c) = (e^c + e^-c) / (e^c - e^-c) + + var a = 2 * this['re']; + var b = 2 * this['im']; + var d = cosh(a) - Math.cos(b); + + return new Complex( + sinh(a) / d, + -Math.sin(b) / d); + }, + + /** + * Calculate the complex coth + * + * @returns {Complex} + */ + 'csch': function() { + + // csch(c) = 2 / (e^c - e^-c) + + var a = this['re']; + var b = this['im']; + var d = Math.cos(2 * b) - cosh(2 * a); + + return new Complex( + -2 * sinh(a) * Math.cos(b) / d, + 2 * cosh(a) * Math.sin(b) / d); + }, + + /** + * Calculate the complex sech + * + * @returns {Complex} + */ + 'sech': function() { + + // sech(c) = 2 / (e^c + e^-c) + + var a = this['re']; + var b = this['im']; + var d = Math.cos(2 * b) + cosh(2 * a); + + return new Complex( + 2 * cosh(a) * Math.cos(b) / d, + -2 * sinh(a) * Math.sin(b) / d); + }, + + /** + * Calculate the complex asinh + * + * @returns {Complex} + */ + 'asinh': function() { + + // asinh(c) = log(c + sqrt(c^2 + 1)) + + var tmp = this['im']; + this['im'] = -this['re']; + this['re'] = tmp; + var res = this['asin'](); + + this['re'] = -this['im']; + this['im'] = tmp; + tmp = res['re']; + + res['re'] = -res['im']; + res['im'] = tmp; + return res; + }, + + /** + * Calculate the complex asinh + * + * @returns {Complex} + */ + 'acosh': function() { + + // acosh(c) = log(c + sqrt(c^2 - 1)) + + var res = this['acos'](); + if (res['im'] <= 0) { + var tmp = res['re']; + res['re'] = -res['im']; + res['im'] = tmp; + } else { + var tmp = res['im']; + res['im'] = -res['re']; + res['re'] = tmp; + } + return res; + }, + + /** + * Calculate the complex atanh + * + * @returns {Complex} + */ + 'atanh': function() { + + // atanh(c) = log((1+c) / (1-c)) / 2 + + var a = this['re']; + var b = this['im']; + + var noIM = a > 1 && b === 0; + var oneMinus = 1 - a; + var onePlus = 1 + a; + var d = oneMinus * oneMinus + b * b; + + var x = (d !== 0) + ? new Complex( + (onePlus * oneMinus - b * b) / d, + (b * oneMinus + onePlus * b) / d) + : new Complex( + (a !== -1) ? (a / 0) : 0, + (b !== 0) ? (b / 0) : 0); + + var temp = x['re']; + x['re'] = logHypot(x['re'], x['im']) / 2; + x['im'] = Math.atan2(x['im'], temp) / 2; + if (noIM) { + x['im'] = -x['im']; + } + return x; + }, + + /** + * Calculate the complex acoth + * + * @returns {Complex} + */ + 'acoth': function() { + + // acoth(c) = log((c+1) / (c-1)) / 2 + + var a = this['re']; + var b = this['im']; + + if (a === 0 && b === 0) { + return new Complex(0, Math.PI / 2); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).atanh() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).atanh(); + }, + + /** + * Calculate the complex acsch + * + * @returns {Complex} + */ + 'acsch': function() { + + // acsch(c) = log((1+sqrt(1+c^2))/c) + + var a = this['re']; + var b = this['im']; + + if (b === 0) { + + return new Complex( + (a !== 0) + ? Math.log(a + Math.sqrt(a * a + 1)) + : Infinity, 0); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).asinh() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).asinh(); + }, + + /** + * Calculate the complex asech + * + * @returns {Complex} + */ + 'asech': function() { + + // asech(c) = log((1+sqrt(1-c^2))/c) + + var a = this['re']; + var b = this['im']; + + if (this['isZero']()) { + return Complex['INFINITY']; + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).acosh() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).acosh(); + }, + + /** + * Calculate the complex inverse 1/z + * + * @returns {Complex} + */ + 'inverse': function() { + + // 1 / 0 = Infinity and 1 / Infinity = 0 + if (this['isZero']()) { + return Complex['INFINITY']; + } + + if (this['isInfinite']()) { + return Complex['ZERO']; + } + + var a = this['re']; + var b = this['im']; + + var d = a * a + b * b; + + return new Complex(a / d, -b / d); + }, + + /** + * Returns the complex conjugate + * + * @returns {Complex} + */ + 'conjugate': function() { + + return new Complex(this['re'], -this['im']); + }, + + /** + * Gets the negated complex number + * + * @returns {Complex} + */ + 'neg': function() { + + return new Complex(-this['re'], -this['im']); + }, + + /** + * Ceils the actual complex number + * + * @returns {Complex} + */ + 'ceil': function(places) { + + places = Math.pow(10, places || 0); + + return new Complex( + Math.ceil(this['re'] * places) / places, + Math.ceil(this['im'] * places) / places); + }, + + /** + * Floors the actual complex number + * + * @returns {Complex} + */ + 'floor': function(places) { + + places = Math.pow(10, places || 0); + + return new Complex( + Math.floor(this['re'] * places) / places, + Math.floor(this['im'] * places) / places); + }, + + /** + * Ceils the actual complex number + * + * @returns {Complex} + */ + 'round': function(places) { + + places = Math.pow(10, places || 0); + + return new Complex( + Math.round(this['re'] * places) / places, + Math.round(this['im'] * places) / places); + }, + + /** + * Compares two complex numbers + * + * **Note:** new Complex(Infinity).equals(Infinity) === false + * + * @returns {boolean} + */ + 'equals': function(a, b) { + + var z = new Complex(a, b); + + return Math.abs(z['re'] - this['re']) <= Complex['EPSILON'] && + Math.abs(z['im'] - this['im']) <= Complex['EPSILON']; + }, + + /** + * Clones the actual object + * + * @returns {Complex} + */ + 'clone': function() { + + return new Complex(this['re'], this['im']); + }, + + /** + * Gets a string of the actual complex number + * + * @returns {string} + */ + 'toString': function() { + + var a = this['re']; + var b = this['im']; + var ret = ''; + + if (this['isNaN']()) { + return 'NaN'; + } + + if (this['isZero']()) { + return '0'; + } + + if (this['isInfinite']()) { + return 'Infinity'; + } + + if (a !== 0) { + ret += a; + } + + if (b !== 0) { + + if (a !== 0) { + ret += b < 0 ? ' - ' : ' + '; + } else if (b < 0) { + ret += '-'; + } + + b = Math.abs(b); + + if (1 !== b) { + ret += b; + } + ret += 'i'; + } + + if (!ret) + return '0'; + + return ret; + }, + + /** + * Returns the actual number as a vector + * + * @returns {Array} + */ + 'toVector': function() { + + return [this['re'], this['im']]; + }, + + /** + * Returns the actual real value of the current object + * + * @returns {number|null} + */ + 'valueOf': function() { + + if (this['im'] === 0) { + return this['re']; + } + return null; + }, + + /** + * Determines whether a complex number is not on the Riemann sphere. + * + * @returns {boolean} + */ + 'isNaN': function() { + return isNaN(this['re']) || isNaN(this['im']); + }, + + /** + * Determines whether or not a complex number is at the zero pole of the + * Riemann sphere. + * + * @returns {boolean} + */ + 'isZero': function() { + return ( + (this['re'] === 0 || this['re'] === -0) && + (this['im'] === 0 || this['im'] === -0) + ); + }, + + /** + * Determines whether a complex number is not at the infinity pole of the + * Riemann sphere. + * + * @returns {boolean} + */ + 'isFinite': function() { + return isFinite(this['re']) && isFinite(this['im']); + }, + + /** + * Determines whether or not a complex number is at the infinity pole of the + * Riemann sphere. + * + * @returns {boolean} + */ + 'isInfinite': function() { + return !(this['isNaN']() || this['isFinite']()); + } + }; + + Complex['ZERO'] = new Complex(0, 0); + Complex['ONE'] = new Complex(1, 0); + Complex['I'] = new Complex(0, 1); + Complex['PI'] = new Complex(Math.PI, 0); + Complex['E'] = new Complex(Math.E, 0); + Complex['INFINITY'] = new Complex(Infinity, Infinity); + Complex['NAN'] = new Complex(NaN, NaN); + Complex['EPSILON'] = 1e-16; + + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { + return Complex; + }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} + +})(this); + + +/***/ }), +/* 10 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return IndexError; }); +/** + * Create a range error with the message: + * 'Index out of range (index < min)' + * 'Index out of range (index < max)' + * + * @param {number} index The actual index + * @param {number} [min=0] Minimum index (included) + * @param {number} [max] Maximum index (excluded) + * @extends RangeError + */ +function IndexError(index, min, max) { + if (!(this instanceof IndexError)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.index = index; + + if (arguments.length < 3) { + this.min = 0; + this.max = min; + } else { + this.min = min; + this.max = max; + } + + if (this.min !== undefined && this.index < this.min) { + this.message = 'Index out of range (' + this.index + ' < ' + this.min + ')'; + } else if (this.max !== undefined && this.index >= this.max) { + this.message = 'Index out of range (' + this.index + ' > ' + (this.max - 1) + ')'; + } else { + this.message = 'Index out of range (' + this.index + ')'; + } + + this.stack = new Error().stack; +} +IndexError.prototype = new RangeError(); +IndexError.prototype.constructor = RangeError; +IndexError.prototype.name = 'IndexError'; +IndexError.prototype.isIndexError = true; + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/** + * @license Fraction.js v4.0.12 09/09/2015 + * http://www.xarg.org/2014/03/rational-numbers-in-javascript/ + * + * Copyright (c) 2015, Robert Eisele (robert@xarg.org) + * Dual licensed under the MIT or GPL Version 2 licenses. + **/ + + +/** + * + * This class offers the possibility to calculate fractions. + * You can pass a fraction in different formats. Either as array, as double, as string or as an integer. + * + * Array/Object form + * [ 0 => , 1 => ] + * [ n => , d => ] + * + * Integer form + * - Single integer value + * + * Double form + * - Single double value + * + * String form + * 123.456 - a simple double + * 123/456 - a string fraction + * 123.'456' - a double with repeating decimal places + * 123.(456) - synonym + * 123.45'6' - a double with repeating last place + * 123.45(6) - synonym + * + * Example: + * + * var f = new Fraction("9.4'31'"); + * f.mul([-4, 3]).div(4.9); + * + */ + +(function(root) { + + "use strict"; + + // Maximum search depth for cyclic rational numbers. 2000 should be more than enough. + // Example: 1/7 = 0.(142857) has 6 repeating decimal places. + // If MAX_CYCLE_LEN gets reduced, long cycles will not be detected and toString() only gets the first 10 digits + var MAX_CYCLE_LEN = 2000; + + // Parsed data to avoid calling "new" all the time + var P = { + "s": 1, + "n": 0, + "d": 1 + }; + + function createError(name) { + + function errorConstructor() { + var temp = Error.apply(this, arguments); + temp['name'] = this['name'] = name; + this['stack'] = temp['stack']; + this['message'] = temp['message']; + } + + /** + * Error constructor + * + * @constructor + */ + function IntermediateInheritor() {} + IntermediateInheritor.prototype = Error.prototype; + errorConstructor.prototype = new IntermediateInheritor(); + + return errorConstructor; + } + + var DivisionByZero = Fraction['DivisionByZero'] = createError('DivisionByZero'); + var InvalidParameter = Fraction['InvalidParameter'] = createError('InvalidParameter'); + + function assign(n, s) { + + if (isNaN(n = parseInt(n, 10))) { + throwInvalidParam(); + } + return n * s; + } + + function throwInvalidParam() { + throw new InvalidParameter(); + } + + var parse = function(p1, p2) { + + var n = 0, d = 1, s = 1; + var v = 0, w = 0, x = 0, y = 1, z = 1; + + var A = 0, B = 1; + var C = 1, D = 1; + + var N = 10000000; + var M; + + if (p1 === undefined || p1 === null) { + /* void */ + } else if (p2 !== undefined) { + n = p1; + d = p2; + s = n * d; + } else + switch (typeof p1) { + + case "object": + { + if ("d" in p1 && "n" in p1) { + n = p1["n"]; + d = p1["d"]; + if ("s" in p1) + n *= p1["s"]; + } else if (0 in p1) { + n = p1[0]; + if (1 in p1) + d = p1[1]; + } else { + throwInvalidParam(); + } + s = n * d; + break; + } + case "number": + { + if (p1 < 0) { + s = p1; + p1 = -p1; + } + + if (p1 % 1 === 0) { + n = p1; + } else if (p1 > 0) { // check for != 0, scale would become NaN (log(0)), which converges really slow + + if (p1 >= 1) { + z = Math.pow(10, Math.floor(1 + Math.log(p1) / Math.LN10)); + p1 /= z; + } + + // Using Farey Sequences + // http://www.johndcook.com/blog/2010/10/20/best-rational-approximation/ + + while (B <= N && D <= N) { + M = (A + C) / (B + D); + + if (p1 === M) { + if (B + D <= N) { + n = A + C; + d = B + D; + } else if (D > B) { + n = C; + d = D; + } else { + n = A; + d = B; + } + break; + + } else { + + if (p1 > M) { + A += C; + B += D; + } else { + C += A; + D += B; + } + + if (B > N) { + n = C; + d = D; + } else { + n = A; + d = B; + } + } + } + n *= z; + } else if (isNaN(p1) || isNaN(p2)) { + d = n = NaN; + } + break; + } + case "string": + { + B = p1.match(/\d+|./g); + + if (B === null) + throwInvalidParam(); + + if (B[A] === '-') {// Check for minus sign at the beginning + s = -1; + A++; + } else if (B[A] === '+') {// Check for plus sign at the beginning + A++; + } + + if (B.length === A + 1) { // Check if it's just a simple number "1234" + w = assign(B[A++], s); + } else if (B[A + 1] === '.' || B[A] === '.') { // Check if it's a decimal number + + if (B[A] !== '.') { // Handle 0.5 and .5 + v = assign(B[A++], s); + } + A++; + + // Check for decimal places + if (A + 1 === B.length || B[A + 1] === '(' && B[A + 3] === ')' || B[A + 1] === "'" && B[A + 3] === "'") { + w = assign(B[A], s); + y = Math.pow(10, B[A].length); + A++; + } + + // Check for repeating places + if (B[A] === '(' && B[A + 2] === ')' || B[A] === "'" && B[A + 2] === "'") { + x = assign(B[A + 1], s); + z = Math.pow(10, B[A + 1].length) - 1; + A += 3; + } + + } else if (B[A + 1] === '/' || B[A + 1] === ':') { // Check for a simple fraction "123/456" or "123:456" + w = assign(B[A], s); + y = assign(B[A + 2], 1); + A += 3; + } else if (B[A + 3] === '/' && B[A + 1] === ' ') { // Check for a complex fraction "123 1/2" + v = assign(B[A], s); + w = assign(B[A + 2], s); + y = assign(B[A + 4], 1); + A += 5; + } + + if (B.length <= A) { // Check for more tokens on the stack + d = y * z; + s = /* void */ + n = x + d * v + z * w; + break; + } + + /* Fall through on error */ + } + default: + throwInvalidParam(); + } + + if (d === 0) { + throw new DivisionByZero(); + } + + P["s"] = s < 0 ? -1 : 1; + P["n"] = Math.abs(n); + P["d"] = Math.abs(d); + }; + + function modpow(b, e, m) { + + var r = 1; + for (; e > 0; b = (b * b) % m, e >>= 1) { + + if (e & 1) { + r = (r * b) % m; + } + } + return r; + } + + + function cycleLen(n, d) { + + for (; d % 2 === 0; + d /= 2) { + } + + for (; d % 5 === 0; + d /= 5) { + } + + if (d === 1) // Catch non-cyclic numbers + return 0; + + // If we would like to compute really large numbers quicker, we could make use of Fermat's little theorem: + // 10^(d-1) % d == 1 + // However, we don't need such large numbers and MAX_CYCLE_LEN should be the capstone, + // as we want to translate the numbers to strings. + + var rem = 10 % d; + var t = 1; + + for (; rem !== 1; t++) { + rem = rem * 10 % d; + + if (t > MAX_CYCLE_LEN) + return 0; // Returning 0 here means that we don't print it as a cyclic number. It's likely that the answer is `d-1` + } + return t; + } + + + function cycleStart(n, d, len) { + + var rem1 = 1; + var rem2 = modpow(10, len, d); + + for (var t = 0; t < 300; t++) { // s < ~log10(Number.MAX_VALUE) + // Solve 10^s == 10^(s+t) (mod d) + + if (rem1 === rem2) + return t; + + rem1 = rem1 * 10 % d; + rem2 = rem2 * 10 % d; + } + return 0; + } + + function gcd(a, b) { + + if (!a) + return b; + if (!b) + return a; + + while (1) { + a %= b; + if (!a) + return b; + b %= a; + if (!b) + return a; + } + }; + + /** + * Module constructor + * + * @constructor + * @param {number|Fraction=} a + * @param {number=} b + */ + function Fraction(a, b) { + + if (!(this instanceof Fraction)) { + return new Fraction(a, b); + } + + parse(a, b); + + if (Fraction['REDUCE']) { + a = gcd(P["d"], P["n"]); // Abuse a + } else { + a = 1; + } + + this["s"] = P["s"]; + this["n"] = P["n"] / a; + this["d"] = P["d"] / a; + } + + /** + * Boolean global variable to be able to disable automatic reduction of the fraction + * + */ + Fraction['REDUCE'] = 1; + + Fraction.prototype = { + + "s": 1, + "n": 0, + "d": 1, + + /** + * Calculates the absolute value + * + * Ex: new Fraction(-4).abs() => 4 + **/ + "abs": function() { + + return new Fraction(this["n"], this["d"]); + }, + + /** + * Inverts the sign of the current fraction + * + * Ex: new Fraction(-4).neg() => 4 + **/ + "neg": function() { + + return new Fraction(-this["s"] * this["n"], this["d"]); + }, + + /** + * Adds two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => 467 / 30 + **/ + "add": function(a, b) { + + parse(a, b); + return new Fraction( + this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Subtracts two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => -427 / 30 + **/ + "sub": function(a, b) { + + parse(a, b); + return new Fraction( + this["s"] * this["n"] * P["d"] - P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Multiplies two rational numbers + * + * Ex: new Fraction("-17.(345)").mul(3) => 5776 / 111 + **/ + "mul": function(a, b) { + + parse(a, b); + return new Fraction( + this["s"] * P["s"] * this["n"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Divides two rational numbers + * + * Ex: new Fraction("-17.(345)").inverse().div(3) + **/ + "div": function(a, b) { + + parse(a, b); + return new Fraction( + this["s"] * P["s"] * this["n"] * P["d"], + this["d"] * P["n"] + ); + }, + + /** + * Clones the actual object + * + * Ex: new Fraction("-17.(345)").clone() + **/ + "clone": function() { + return new Fraction(this); + }, + + /** + * Calculates the modulo of two rational numbers - a more precise fmod + * + * Ex: new Fraction('4.(3)').mod([7, 8]) => (13/3) % (7/8) = (5/6) + **/ + "mod": function(a, b) { + + if (isNaN(this['n']) || isNaN(this['d'])) { + return new Fraction(NaN); + } + + if (a === undefined) { + return new Fraction(this["s"] * this["n"] % this["d"], 1); + } + + parse(a, b); + if (0 === P["n"] && 0 === this["d"]) { + Fraction(0, 0); // Throw DivisionByZero + } + + /* + * First silly attempt, kinda slow + * + return that["sub"]({ + "n": num["n"] * Math.floor((this.n / this.d) / (num.n / num.d)), + "d": num["d"], + "s": this["s"] + });*/ + + /* + * New attempt: a1 / b1 = a2 / b2 * q + r + * => b2 * a1 = a2 * b1 * q + b1 * b2 * r + * => (b2 * a1 % a2 * b1) / (b1 * b2) + */ + return new Fraction( + this["s"] * (P["d"] * this["n"]) % (P["n"] * this["d"]), + P["d"] * this["d"] + ); + }, + + /** + * Calculates the fractional gcd of two rational numbers + * + * Ex: new Fraction(5,8).gcd(3,7) => 1/56 + */ + "gcd": function(a, b) { + + parse(a, b); + + // gcd(a / b, c / d) = gcd(a, c) / lcm(b, d) + + return new Fraction(gcd(P["n"], this["n"]) * gcd(P["d"], this["d"]), P["d"] * this["d"]); + }, + + /** + * Calculates the fractional lcm of two rational numbers + * + * Ex: new Fraction(5,8).lcm(3,7) => 15 + */ + "lcm": function(a, b) { + + parse(a, b); + + // lcm(a / b, c / d) = lcm(a, c) / gcd(b, d) + + if (P["n"] === 0 && this["n"] === 0) { + return new Fraction; + } + return new Fraction(P["n"] * this["n"], gcd(P["n"], this["n"]) * gcd(P["d"], this["d"])); + }, + + /** + * Calculates the ceil of a rational number + * + * Ex: new Fraction('4.(3)').ceil() => (5 / 1) + **/ + "ceil": function(places) { + + places = Math.pow(10, places || 0); + + if (isNaN(this["n"]) || isNaN(this["d"])) { + return new Fraction(NaN); + } + return new Fraction(Math.ceil(places * this["s"] * this["n"] / this["d"]), places); + }, + + /** + * Calculates the floor of a rational number + * + * Ex: new Fraction('4.(3)').floor() => (4 / 1) + **/ + "floor": function(places) { + + places = Math.pow(10, places || 0); + + if (isNaN(this["n"]) || isNaN(this["d"])) { + return new Fraction(NaN); + } + return new Fraction(Math.floor(places * this["s"] * this["n"] / this["d"]), places); + }, + + /** + * Rounds a rational numbers + * + * Ex: new Fraction('4.(3)').round() => (4 / 1) + **/ + "round": function(places) { + + places = Math.pow(10, places || 0); + + if (isNaN(this["n"]) || isNaN(this["d"])) { + return new Fraction(NaN); + } + return new Fraction(Math.round(places * this["s"] * this["n"] / this["d"]), places); + }, + + /** + * Gets the inverse of the fraction, means numerator and denumerator are exchanged + * + * Ex: new Fraction([-3, 4]).inverse() => -4 / 3 + **/ + "inverse": function() { + + return new Fraction(this["s"] * this["d"], this["n"]); + }, + + /** + * Calculates the fraction to some integer exponent + * + * Ex: new Fraction(-1,2).pow(-3) => -8 + */ + "pow": function(m) { + + if (m < 0) { + return new Fraction(Math.pow(this['s'] * this["d"], -m), Math.pow(this["n"], -m)); + } else { + return new Fraction(Math.pow(this['s'] * this["n"], m), Math.pow(this["d"], m)); + } + }, + + /** + * Check if two rational numbers are the same + * + * Ex: new Fraction(19.6).equals([98, 5]); + **/ + "equals": function(a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] === P["s"] * P["n"] * this["d"]; // Same as compare() === 0 + }, + + /** + * Check if two rational numbers are the same + * + * Ex: new Fraction(19.6).equals([98, 5]); + **/ + "compare": function(a, b) { + + parse(a, b); + var t = (this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]); + return (0 < t) - (t < 0); + }, + + "simplify": function(eps) { + + // First naive implementation, needs improvement + + if (isNaN(this['n']) || isNaN(this['d'])) { + return this; + } + + var cont = this['abs']()['toContinued'](); + + eps = eps || 0.001; + + function rec(a) { + if (a.length === 1) + return new Fraction(a[0]); + return rec(a.slice(1))['inverse']()['add'](a[0]); + } + + for (var i = 0; i < cont.length; i++) { + var tmp = rec(cont.slice(0, i + 1)); + if (tmp['sub'](this['abs']())['abs']().valueOf() < eps) { + return tmp['mul'](this['s']); + } + } + return this; + }, + + /** + * Check if two rational numbers are divisible + * + * Ex: new Fraction(19.6).divisible(1.5); + */ + "divisible": function(a, b) { + + parse(a, b); + return !(!(P["n"] * this["d"]) || ((this["n"] * P["d"]) % (P["n"] * this["d"]))); + }, + + /** + * Returns a decimal representation of the fraction + * + * Ex: new Fraction("100.'91823'").valueOf() => 100.91823918239183 + **/ + 'valueOf': function() { + + return this["s"] * this["n"] / this["d"]; + }, + + /** + * Returns a string-fraction representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toFraction() => "4 1/3" + **/ + 'toFraction': function(excludeWhole) { + + var whole, str = ""; + var n = this["n"]; + var d = this["d"]; + if (this["s"] < 0) { + str += '-'; + } + + if (d === 1) { + str += n; + } else { + + if (excludeWhole && (whole = Math.floor(n / d)) > 0) { + str += whole; + str += " "; + n %= d; + } + + str += n; + str += '/'; + str += d; + } + return str; + }, + + /** + * Returns a latex representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toLatex() => "\frac{4}{3}" + **/ + 'toLatex': function(excludeWhole) { + + var whole, str = ""; + var n = this["n"]; + var d = this["d"]; + if (this["s"] < 0) { + str += '-'; + } + + if (d === 1) { + str += n; + } else { + + if (excludeWhole && (whole = Math.floor(n / d)) > 0) { + str += whole; + n %= d; + } + + str += "\\frac{"; + str += n; + str += '}{'; + str += d; + str += '}'; + } + return str; + }, + + /** + * Returns an array of continued fraction elements + * + * Ex: new Fraction("7/8").toContinued() => [0,1,7] + */ + 'toContinued': function() { + + var t; + var a = this['n']; + var b = this['d']; + var res = []; + + if (isNaN(this['n']) || isNaN(this['d'])) { + return res; + } + + do { + res.push(Math.floor(a / b)); + t = a % b; + a = b; + b = t; + } while (a !== 1); + + return res; + }, + + /** + * Creates a string representation of a fraction with all digits + * + * Ex: new Fraction("100.'91823'").toString() => "100.(91823)" + **/ + 'toString': function(dec) { + + var g; + var N = this["n"]; + var D = this["d"]; + + if (isNaN(N) || isNaN(D)) { + return "NaN"; + } + + if (!Fraction['REDUCE']) { + g = gcd(N, D); + N /= g; + D /= g; + } + + dec = dec || 15; // 15 = decimal places when no repitation + + var cycLen = cycleLen(N, D); // Cycle length + var cycOff = cycleStart(N, D, cycLen); // Cycle start + + var str = this['s'] === -1 ? "-" : ""; + + str += N / D | 0; + + N %= D; + N *= 10; + + if (N) + str += "."; + + if (cycLen) { + + for (var i = cycOff; i--; ) { + str += N / D | 0; + N %= D; + N *= 10; + } + str += "("; + for (var i = cycLen; i--; ) { + str += N / D | 0; + N %= D; + N *= 10; + } + str += ")"; + } else { + for (var i = dec; N && i--; ) { + str += N / D | 0; + N %= D; + N *= 10; + } + } + return str; + } + }; + + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { + return Fraction; + }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} + +})(this); + + +/***/ }), +/* 12 */ +/***/ (function(module, exports) { + +/* + * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license + * Author: Jim Palmer (based on chunking idea from Dave Koelle) + */ +/*jshint unused:false */ +module.exports = function naturalSort (a, b) { + "use strict"; + var re = /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi, + sre = /(^[ ]*|[ ]*$)/g, + dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/, + hre = /^0x[0-9a-f]+$/i, + ore = /^0/, + i = function(s) { return naturalSort.insensitive && ('' + s).toLowerCase() || '' + s; }, + // convert all to strings strip whitespace + x = i(a).replace(sre, '') || '', + y = i(b).replace(sre, '') || '', + // chunk/tokenize + xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), + yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), + // numeric, hex or date detection + xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && x.match(dre) && Date.parse(x)), + yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null, + oFxNcL, oFyNcL; + // first try and sort Hex codes or Dates + if (yD) { + if ( xD < yD ) { return -1; } + else if ( xD > yD ) { return 1; } + } + // natural sorting through split numeric strings and default strings + for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) { + // find floats not starting with '0', string or 0 if not defined (Clint Priest) + oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0; + oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0; + // handle numeric vs string comparison - number < string - (Kyle Adams) + if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; } + // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2' + else if (typeof oFxNcL !== typeof oFyNcL) { + oFxNcL += ''; + oFyNcL += ''; + } + if (oFxNcL < oFyNcL) { return -1; } + if (oFxNcL > oFyNcL) { return 1; } + } + return 0; +}; + + +/***/ }), +/* 13 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ArgumentsError; }); +/** + * Create a syntax error with the message: + * 'Wrong number of arguments in function ( provided, - expected)' + * @param {string} fn Function name + * @param {number} count Actual argument count + * @param {number} min Minimum required argument count + * @param {number} [max] Maximum required argument count + * @extends Error + */ +function ArgumentsError(fn, count, min, max) { + if (!(this instanceof ArgumentsError)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.fn = fn; + this.count = count; + this.min = min; + this.max = max; + this.message = 'Wrong number of arguments in function ' + fn + ' (' + count + ' provided, ' + min + (max !== undefined && max !== null ? '-' + max : '') + ' expected)'; + this.stack = new Error().stack; +} +ArgumentsError.prototype = new Error(); +ArgumentsError.prototype.constructor = Error; +ArgumentsError.prototype.name = 'ArgumentsError'; +ArgumentsError.prototype.isArgumentsError = true; + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/** + * typed-function + * + * Type checking for JavaScript functions + * + * https://github.com/josdejong/typed-function + */ + + +(function (root, factory) { + if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function () { + + function ok () { + return true; + } + + function notOk () { + return false; + } + + function undef () { + return undefined; + } + + /** + * @typedef {{ + * params: Param[], + * fn: function + * }} Signature + * + * @typedef {{ + * types: Type[], + * restParam: boolean + * }} Param + * + * @typedef {{ + * name: string, + * typeIndex: number, + * test: function, + * conversion?: ConversionDef, + * conversionIndex: number, + * }} Type + * + * @typedef {{ + * from: string, + * to: string, + * convert: function (*) : * + * }} ConversionDef + * + * @typedef {{ + * name: string, + * test: function(*) : boolean + * }} TypeDef + */ + + // create a new instance of typed-function + function create () { + // data type tests + var _types = [ + { name: 'number', test: function (x) { return typeof x === 'number' } }, + { name: 'string', test: function (x) { return typeof x === 'string' } }, + { name: 'boolean', test: function (x) { return typeof x === 'boolean' } }, + { name: 'Function', test: function (x) { return typeof x === 'function'} }, + { name: 'Array', test: Array.isArray }, + { name: 'Date', test: function (x) { return x instanceof Date } }, + { name: 'RegExp', test: function (x) { return x instanceof RegExp } }, + { name: 'Object', test: function (x) { + return typeof x === 'object' && x !== null && x.constructor === Object + }}, + { name: 'null', test: function (x) { return x === null } }, + { name: 'undefined', test: function (x) { return x === undefined } } + ]; + + var anyType = { + name: 'any', + test: ok + } + + // types which need to be ignored + var _ignore = []; + + // type conversions + var _conversions = []; + + // This is a temporary object, will be replaced with a typed function at the end + var typed = { + types: _types, + conversions: _conversions, + ignore: _ignore + }; + + /** + * Find the test function for a type + * @param {String} typeName + * @return {TypeDef} Returns the type definition when found, + * Throws a TypeError otherwise + */ + function findTypeByName (typeName) { + var entry = findInArray(typed.types, function (entry) { + return entry.name === typeName; + }); + + if (entry) { + return entry; + } + + if (typeName === 'any') { // special baked-in case 'any' + return anyType; + } + + var hint = findInArray(typed.types, function (entry) { + return entry.name.toLowerCase() === typeName.toLowerCase(); + }); + + throw new TypeError('Unknown type "' + typeName + '"' + + (hint ? ('. Did you mean "' + hint.name + '"?') : '')); + } + + /** + * Find the index of a type definition. Handles special case 'any' + * @param {TypeDef} type + * @return {number} + */ + function findTypeIndex(type) { + if (type === anyType) { + return 999; + } + + return typed.types.indexOf(type); + } + + /** + * Find a type that matches a value. + * @param {*} value + * @return {string} Returns the name of the first type for which + * the type test matches the value. + */ + function findTypeName(value) { + var entry = findInArray(typed.types, function (entry) { + return entry.test(value); + }); + + if (entry) { + return entry.name; + } + + throw new TypeError('Value has unknown type. Value: ' + value); + } + + /** + * Find a specific signature from a (composed) typed function, for example: + * + * typed.find(fn, ['number', 'string']) + * typed.find(fn, 'number, string') + * + * Function find only only works for exact matches. + * + * @param {Function} fn A typed-function + * @param {string | string[]} signature Signature to be found, can be + * an array or a comma separated string. + * @return {Function} Returns the matching signature, or + * throws an error when no signature + * is found. + */ + function find (fn, signature) { + if (!fn.signatures) { + throw new TypeError('Function is no typed-function'); + } + + // normalize input + var arr; + if (typeof signature === 'string') { + arr = signature.split(','); + for (var i = 0; i < arr.length; i++) { + arr[i] = arr[i].trim(); + } + } + else if (Array.isArray(signature)) { + arr = signature; + } + else { + throw new TypeError('String array or a comma separated string expected'); + } + + var str = arr.join(','); + + // find an exact match + var match = fn.signatures[str]; + if (match) { + return match; + } + + // TODO: extend find to match non-exact signatures + + throw new TypeError('Signature not found (signature: ' + (fn.name || 'unnamed') + '(' + arr.join(', ') + '))'); + } + + /** + * Convert a given value to another data type. + * @param {*} value + * @param {string} type + */ + function convert (value, type) { + var from = findTypeName(value); + + // check conversion is needed + if (type === from) { + return value; + } + + for (var i = 0; i < typed.conversions.length; i++) { + var conversion = typed.conversions[i]; + if (conversion.from === from && conversion.to === type) { + return conversion.convert(value); + } + } + + throw new Error('Cannot convert from ' + from + ' to ' + type); + } + + /** + * Stringify parameters in a normalized way + * @param {Param[]} params + * @return {string} + */ + function stringifyParams (params) { + return params + .map(function (param) { + var typeNames = param.types.map(getTypeName); + + return (param.restParam ? '...' : '') + typeNames.join('|'); + }) + .join(','); + } + + /** + * Parse a parameter, like "...number | boolean" + * @param {string} param + * @param {ConversionDef[]} conversions + * @return {Param} param + */ + function parseParam (param, conversions) { + var restParam = param.indexOf('...') === 0; + var types = (!restParam) + ? param + : (param.length > 3) + ? param.slice(3) + : 'any'; + + var typeNames = types.split('|').map(trim) + .filter(notEmpty) + .filter(notIgnore); + + var matchingConversions = filterConversions(conversions, typeNames); + + var exactTypes = typeNames.map(function (typeName) { + var type = findTypeByName(typeName); + + return { + name: typeName, + typeIndex: findTypeIndex(type), + test: type.test, + conversion: null, + conversionIndex: -1 + }; + }); + + var convertibleTypes = matchingConversions.map(function (conversion) { + var type = findTypeByName(conversion.from); + + return { + name: conversion.from, + typeIndex: findTypeIndex(type), + test: type.test, + conversion: conversion, + conversionIndex: conversions.indexOf(conversion) + }; + }); + + return { + types: exactTypes.concat(convertibleTypes), + restParam: restParam + }; + } + + /** + * Parse a signature with comma separated parameters, + * like "number | boolean, ...string" + * @param {string} signature + * @param {function} fn + * @param {ConversionDef[]} conversions + * @return {Signature | null} signature + */ + function parseSignature (signature, fn, conversions) { + var params = []; + + if (signature.trim() !== '') { + params = signature + .split(',') + .map(trim) + .map(function (param, index, array) { + var parsedParam = parseParam(param, conversions); + + if (parsedParam.restParam && (index !== array.length - 1)) { + throw new SyntaxError('Unexpected rest parameter "' + param + '": ' + + 'only allowed for the last parameter'); + } + + return parsedParam; + }); + } + + if (params.some(isInvalidParam)) { + // invalid signature: at least one parameter has no types + // (they may have been filtered) + return null; + } + + return { + params: params, + fn: fn + }; + } + + /** + * Test whether a set of params contains a restParam + * @param {Param[]} params + * @return {boolean} Returns true when the last parameter is a restParam + */ + function hasRestParam(params) { + var param = last(params) + return param ? param.restParam : false; + } + + /** + * Test whether a parameter contains conversions + * @param {Param} param + * @return {boolean} Returns true when at least one of the parameters + * contains a conversion. + */ + function hasConversions(param) { + return param.types.some(function (type) { + return type.conversion != null; + }); + } + + /** + * Create a type test for a single parameter, which can have one or multiple + * types. + * @param {Param} param + * @return {function(x: *) : boolean} Returns a test function + */ + function compileTest(param) { + if (!param || param.types.length === 0) { + // nothing to do + return ok; + } + else if (param.types.length === 1) { + return findTypeByName(param.types[0].name).test; + } + else if (param.types.length === 2) { + var test0 = findTypeByName(param.types[0].name).test; + var test1 = findTypeByName(param.types[1].name).test; + return function or(x) { + return test0(x) || test1(x); + } + } + else { // param.types.length > 2 + var tests = param.types.map(function (type) { + return findTypeByName(type.name).test; + }) + return function or(x) { + for (var i = 0; i < tests.length; i++) { + if (tests[i](x)) { + return true; + } + } + return false; + } + } + } + + /** + * Create a test for all parameters of a signature + * @param {Param[]} params + * @return {function(args: Array<*>) : boolean} + */ + function compileTests(params) { + var tests, test0, test1; + + if (hasRestParam(params)) { + // variable arguments like '...number' + tests = initial(params).map(compileTest); + var varIndex = tests.length; + var lastTest = compileTest(last(params)); + var testRestParam = function (args) { + for (var i = varIndex; i < args.length; i++) { + if (!lastTest(args[i])) { + return false; + } + } + return true; + } + + return function testArgs(args) { + for (var i = 0; i < tests.length; i++) { + if (!tests[i](args[i])) { + return false; + } + } + return testRestParam(args) && (args.length >= varIndex + 1); + }; + } + else { + // no variable arguments + if (params.length === 0) { + return function testArgs(args) { + return args.length === 0; + }; + } + else if (params.length === 1) { + test0 = compileTest(params[0]); + return function testArgs(args) { + return test0(args[0]) && args.length === 1; + }; + } + else if (params.length === 2) { + test0 = compileTest(params[0]); + test1 = compileTest(params[1]); + return function testArgs(args) { + return test0(args[0]) && test1(args[1]) && args.length === 2; + }; + } + else { // arguments.length > 2 + tests = params.map(compileTest); + return function testArgs(args) { + for (var i = 0; i < tests.length; i++) { + if (!tests[i](args[i])) { + return false; + } + } + return args.length === tests.length; + }; + } + } + } + + /** + * Find the parameter at a specific index of a signature. + * Handles rest parameters. + * @param {Signature} signature + * @param {number} index + * @return {Param | null} Returns the matching parameter when found, + * null otherwise. + */ + function getParamAtIndex(signature, index) { + return index < signature.params.length + ? signature.params[index] + : hasRestParam(signature.params) + ? last(signature.params) + : null + } + + /** + * Get all type names of a parameter + * @param {Signature} signature + * @param {number} index + * @param {boolean} excludeConversions + * @return {string[]} Returns an array with type names + */ + function getExpectedTypeNames (signature, index, excludeConversions) { + var param = getParamAtIndex(signature, index); + var types = param + ? excludeConversions + ? param.types.filter(isExactType) + : param.types + : []; + + return types.map(getTypeName); + } + + /** + * Returns the name of a type + * @param {Type} type + * @return {string} Returns the type name + */ + function getTypeName(type) { + return type.name; + } + + /** + * Test whether a type is an exact type or conversion + * @param {Type} type + * @return {boolean} Returns true when + */ + function isExactType(type) { + return type.conversion === null || type.conversion === undefined; + } + + /** + * Helper function for creating error messages: create an array with + * all available types on a specific argument index. + * @param {Signature[]} signatures + * @param {number} index + * @return {string[]} Returns an array with available types + */ + function mergeExpectedParams(signatures, index) { + var typeNames = uniq(flatMap(signatures, function (signature) { + return getExpectedTypeNames(signature, index, false); + })); + + return (typeNames.indexOf('any') !== -1) ? ['any'] : typeNames; + } + + /** + * Create + * @param {string} name The name of the function + * @param {array.<*>} args The actual arguments passed to the function + * @param {Signature[]} signatures A list with available signatures + * @return {TypeError} Returns a type error with additional data + * attached to it in the property `data` + */ + function createError(name, args, signatures) { + var err, expected; + var _name = name || 'unnamed'; + + // test for wrong type at some index + var matchingSignatures = signatures; + var index; + for (index = 0; index < args.length; index++) { + var nextMatchingDefs = matchingSignatures.filter(function (signature) { + var test = compileTest(getParamAtIndex(signature, index)); + return (index < signature.params.length || hasRestParam(signature.params)) && + test(args[index]); + }); + + if (nextMatchingDefs.length === 0) { + // no matching signatures anymore, throw error "wrong type" + expected = mergeExpectedParams(matchingSignatures, index); + if (expected.length > 0) { + var actualType = findTypeName(args[index]); + + err = new TypeError('Unexpected type of argument in function ' + _name + + ' (expected: ' + expected.join(' or ') + + ', actual: ' + actualType + ', index: ' + index + ')'); + err.data = { + category: 'wrongType', + fn: _name, + index: index, + actual: actualType, + expected: expected + } + return err; + } + } + else { + matchingSignatures = nextMatchingDefs; + } + } + + // test for too few arguments + var lengths = matchingSignatures.map(function (signature) { + return hasRestParam(signature.params) ? Infinity : signature.params.length; + }); + if (args.length < Math.min.apply(null, lengths)) { + expected = mergeExpectedParams(matchingSignatures, index); + err = new TypeError('Too few arguments in function ' + _name + + ' (expected: ' + expected.join(' or ') + + ', index: ' + args.length + ')'); + err.data = { + category: 'tooFewArgs', + fn: _name, + index: args.length, + expected: expected + } + return err; + } + + // test for too many arguments + var maxLength = Math.max.apply(null, lengths); + if (args.length > maxLength) { + err = new TypeError('Too many arguments in function ' + _name + + ' (expected: ' + maxLength + ', actual: ' + args.length + ')'); + err.data = { + category: 'tooManyArgs', + fn: _name, + index: args.length, + expectedLength: maxLength + } + return err; + } + + err = new TypeError('Arguments of type "' + args.join(', ') + + '" do not match any of the defined signatures of function ' + _name + '.'); + err.data = { + category: 'mismatch', + actual: args.map(findTypeName) + } + return err; + } + + /** + * Find the lowest index of all exact types of a parameter (no conversions) + * @param {Param} param + * @return {number} Returns the index of the lowest type in typed.types + */ + function getLowestTypeIndex (param) { + var min = 999; + + for (var i = 0; i < param.types.length; i++) { + if (isExactType(param.types[i])) { + min = Math.min(min, param.types[i].typeIndex); + } + } + + return min; + } + + /** + * Find the lowest index of the conversion of all types of the parameter + * having a conversion + * @param {Param} param + * @return {number} Returns the lowest index of the conversions of this type + */ + function getLowestConversionIndex (param) { + var min = 999; + + for (var i = 0; i < param.types.length; i++) { + if (!isExactType(param.types[i])) { + min = Math.min(min, param.types[i].conversionIndex); + } + } + + return min; + } + + /** + * Compare two params + * @param {Param} param1 + * @param {Param} param2 + * @return {number} returns a negative number when param1 must get a lower + * index than param2, a positive number when the opposite, + * or zero when both are equal + */ + function compareParams (param1, param2) { + var c; + + // compare having a rest parameter or not + c = param1.restParam - param2.restParam; + if (c !== 0) { + return c; + } + + // compare having conversions or not + c = hasConversions(param1) - hasConversions(param2); + if (c !== 0) { + return c; + } + + // compare the index of the types + c = getLowestTypeIndex(param1) - getLowestTypeIndex(param2); + if (c !== 0) { + return c; + } + + // compare the index of any conversion + return getLowestConversionIndex(param1) - getLowestConversionIndex(param2); + } + + /** + * Compare two signatures + * @param {Signature} signature1 + * @param {Signature} signature2 + * @return {number} returns a negative number when param1 must get a lower + * index than param2, a positive number when the opposite, + * or zero when both are equal + */ + function compareSignatures (signature1, signature2) { + var len = Math.min(signature1.params.length, signature2.params.length); + var i; + var c; + + // compare whether the params have conversions at all or not + c = signature1.params.some(hasConversions) - signature2.params.some(hasConversions) + if (c !== 0) { + return c; + } + + // next compare whether the params have conversions one by one + for (i = 0; i < len; i++) { + c = hasConversions(signature1.params[i]) - hasConversions(signature2.params[i]); + if (c !== 0) { + return c; + } + } + + // compare the types of the params one by one + for (i = 0; i < len; i++) { + c = compareParams(signature1.params[i], signature2.params[i]); + if (c !== 0) { + return c; + } + } + + // compare the number of params + return signature1.params.length - signature2.params.length; + } + + /** + * Get params containing all types that can be converted to the defined types. + * + * @param {ConversionDef[]} conversions + * @param {string[]} typeNames + * @return {ConversionDef[]} Returns the conversions that are available + * for every type (if any) + */ + function filterConversions(conversions, typeNames) { + var matches = {}; + + conversions.forEach(function (conversion) { + if (typeNames.indexOf(conversion.from) === -1 && + typeNames.indexOf(conversion.to) !== -1 && + !matches[conversion.from]) { + matches[conversion.from] = conversion; + } + }); + + return Object.keys(matches).map(function (from) { + return matches[from]; + }); + } + + /** + * Preprocess arguments before calling the original function: + * - if needed convert the parameters + * - in case of rest parameters, move the rest parameters into an Array + * @param {Param[]} params + * @param {function} fn + * @return {function} Returns a wrapped function + */ + function compileArgsPreprocessing(params, fn) { + var fnConvert = fn; + + // TODO: can we make this wrapper function smarter/simpler? + + if (params.some(hasConversions)) { + var restParam = hasRestParam(params); + var compiledConversions = params.map(compileArgConversion) + + fnConvert = function convertArgs() { + var args = []; + var last = restParam ? arguments.length - 1 : arguments.length; + for (var i = 0; i < last; i++) { + args[i] = compiledConversions[i](arguments[i]); + } + if (restParam) { + args[last] = arguments[last].map(compiledConversions[last]); + } + + return fn.apply(null, args); + } + } + + var fnPreprocess = fnConvert; + if (hasRestParam(params)) { + var offset = params.length - 1; + + fnPreprocess = function preprocessRestParams () { + return fnConvert.apply(null, + slice(arguments, 0, offset).concat([slice(arguments, offset)])); + } + } + + return fnPreprocess; + } + + /** + * Compile conversion for a parameter to the right type + * @param {Param} param + * @return {function} Returns the wrapped function that will convert arguments + * + */ + function compileArgConversion(param) { + var test0, test1, conversion0, conversion1; + var tests = []; + var conversions = []; + + param.types.forEach(function (type) { + if (type.conversion) { + tests.push(findTypeByName(type.conversion.from).test); + conversions.push(type.conversion.convert); + } + }); + + // create optimized conversion functions depending on the number of conversions + switch (conversions.length) { + case 0: + return function convertArg(arg) { + return arg; + } + + case 1: + test0 = tests[0] + conversion0 = conversions[0]; + return function convertArg(arg) { + if (test0(arg)) { + return conversion0(arg) + } + return arg; + } + + case 2: + test0 = tests[0] + test1 = tests[1] + conversion0 = conversions[0]; + conversion1 = conversions[1]; + return function convertArg(arg) { + if (test0(arg)) { + return conversion0(arg) + } + if (test1(arg)) { + return conversion1(arg) + } + return arg; + } + + default: + return function convertArg(arg) { + for (var i = 0; i < conversions.length; i++) { + if (tests[i](arg)) { + return conversions[i](arg); + } + } + return arg; + } + } + } + + /** + * Convert an array with signatures into a map with signatures, + * where signatures with union types are split into separate signatures + * + * Throws an error when there are conflicting types + * + * @param {Signature[]} signatures + * @return {Object.} Returns a map with signatures + * as key and the original function + * of this signature as value. + */ + function createSignaturesMap(signatures) { + var signaturesMap = {}; + signatures.forEach(function (signature) { + if (!signature.params.some(hasConversions)) { + splitParams(signature.params, true).forEach(function (params) { + signaturesMap[stringifyParams(params)] = signature.fn; + }); + } + }); + + return signaturesMap; + } + + /** + * Split params with union types in to separate params. + * + * For example: + * + * splitParams([['Array', 'Object'], ['string', 'RegExp']) + * // returns: + * // [ + * // ['Array', 'string'], + * // ['Array', 'RegExp'], + * // ['Object', 'string'], + * // ['Object', 'RegExp'] + * // ] + * + * @param {Param[]} params + * @param {boolean} ignoreConversionTypes + * @return {Param[]} + */ + function splitParams(params, ignoreConversionTypes) { + function _splitParams(params, index, types) { + if (index < params.length) { + var param = params[index] + var filteredTypes = ignoreConversionTypes + ? param.types.filter(isExactType) + : param.types; + var typeGroups + + if (param.restParam) { + // split the types of a rest parameter in two: + // one with only exact types, and one with exact types and conversions + var exactTypes = filteredTypes.filter(isExactType) + typeGroups = exactTypes.length < filteredTypes.length + ? [exactTypes, filteredTypes] + : [filteredTypes] + + } + else { + // split all the types of a regular parameter into one type per group + typeGroups = filteredTypes.map(function (type) { + return [type] + }) + } + + // recurse over the groups with types + return flatMap(typeGroups, function (typeGroup) { + return _splitParams(params, index + 1, types.concat([typeGroup])); + }); + + } + else { + // we've reached the end of the parameters. Now build a new Param + var splittedParams = types.map(function (type, typeIndex) { + return { + types: type, + restParam: (typeIndex === params.length - 1) && hasRestParam(params) + } + }); + + return [splittedParams]; + } + } + + return _splitParams(params, 0, []); + } + + /** + * Test whether two signatures have a conflicting signature + * @param {Signature} signature1 + * @param {Signature} signature2 + * @return {boolean} Returns true when the signatures conflict, false otherwise. + */ + function hasConflictingParams(signature1, signature2) { + var ii = Math.max(signature1.params.length, signature2.params.length); + + for (var i = 0; i < ii; i++) { + var typesNames1 = getExpectedTypeNames(signature1, i, true); + var typesNames2 = getExpectedTypeNames(signature2, i, true); + + if (!hasOverlap(typesNames1, typesNames2)) { + return false; + } + } + + var len1 = signature1.params.length; + var len2 = signature2.params.length; + var restParam1 = hasRestParam(signature1.params); + var restParam2 = hasRestParam(signature2.params); + + return restParam1 + ? restParam2 ? (len1 === len2) : (len2 >= len1) + : restParam2 ? (len1 >= len2) : (len1 === len2) + } + + /** + * Create a typed function + * @param {String} name The name for the typed function + * @param {Object.} signaturesMap + * An object with one or + * multiple signatures as key, and the + * function corresponding to the + * signature as value. + * @return {function} Returns the created typed function. + */ + function createTypedFunction(name, signaturesMap) { + if (Object.keys(signaturesMap).length === 0) { + throw new SyntaxError('No signatures provided'); + } + + // parse the signatures, and check for conflicts + var parsedSignatures = []; + Object.keys(signaturesMap) + .map(function (signature) { + return parseSignature(signature, signaturesMap[signature], typed.conversions); + }) + .filter(notNull) + .forEach(function (parsedSignature) { + // check whether this parameter conflicts with already parsed signatures + var conflictingSignature = findInArray(parsedSignatures, function (s) { + return hasConflictingParams(s, parsedSignature) + }); + if (conflictingSignature) { + throw new TypeError('Conflicting signatures "' + + stringifyParams(conflictingSignature.params) + '" and "' + + stringifyParams(parsedSignature.params) + '".'); + } + + parsedSignatures.push(parsedSignature); + }); + + // split and filter the types of the signatures, and then order them + var signatures = flatMap(parsedSignatures, function (parsedSignature) { + var params = parsedSignature ? splitParams(parsedSignature.params, false) : [] + + return params.map(function (params) { + return { + params: params, + fn: parsedSignature.fn + }; + }); + }).filter(notNull); + + signatures.sort(compareSignatures); + + // we create a highly optimized checks for the first couple of signatures with max 2 arguments + var ok0 = signatures[0] && signatures[0].params.length <= 2 && !hasRestParam(signatures[0].params); + var ok1 = signatures[1] && signatures[1].params.length <= 2 && !hasRestParam(signatures[1].params); + var ok2 = signatures[2] && signatures[2].params.length <= 2 && !hasRestParam(signatures[2].params); + var ok3 = signatures[3] && signatures[3].params.length <= 2 && !hasRestParam(signatures[3].params); + var ok4 = signatures[4] && signatures[4].params.length <= 2 && !hasRestParam(signatures[4].params); + var ok5 = signatures[5] && signatures[5].params.length <= 2 && !hasRestParam(signatures[5].params); + var allOk = ok0 && ok1 && ok2 && ok3 && ok4 && ok5; + + // compile the tests + var tests = signatures.map(function (signature) { + return compileTests(signature.params); + }); + + var test00 = ok0 ? compileTest(signatures[0].params[0]) : notOk; + var test10 = ok1 ? compileTest(signatures[1].params[0]) : notOk; + var test20 = ok2 ? compileTest(signatures[2].params[0]) : notOk; + var test30 = ok3 ? compileTest(signatures[3].params[0]) : notOk; + var test40 = ok4 ? compileTest(signatures[4].params[0]) : notOk; + var test50 = ok5 ? compileTest(signatures[5].params[0]) : notOk; + + var test01 = ok0 ? compileTest(signatures[0].params[1]) : notOk; + var test11 = ok1 ? compileTest(signatures[1].params[1]) : notOk; + var test21 = ok2 ? compileTest(signatures[2].params[1]) : notOk; + var test31 = ok3 ? compileTest(signatures[3].params[1]) : notOk; + var test41 = ok4 ? compileTest(signatures[4].params[1]) : notOk; + var test51 = ok5 ? compileTest(signatures[5].params[1]) : notOk; + + // compile the functions + var fns = signatures.map(function(signature) { + return compileArgsPreprocessing(signature.params, signature.fn) + }); + + var fn0 = ok0 ? fns[0] : undef; + var fn1 = ok1 ? fns[1] : undef; + var fn2 = ok2 ? fns[2] : undef; + var fn3 = ok3 ? fns[3] : undef; + var fn4 = ok4 ? fns[4] : undef; + var fn5 = ok5 ? fns[5] : undef; + + var len0 = ok0 ? signatures[0].params.length : -1; + var len1 = ok1 ? signatures[1].params.length : -1; + var len2 = ok2 ? signatures[2].params.length : -1; + var len3 = ok3 ? signatures[3].params.length : -1; + var len4 = ok4 ? signatures[4].params.length : -1; + var len5 = ok5 ? signatures[5].params.length : -1; + + // simple and generic, but also slow + var iStart = allOk ? 6 : 0; + var iEnd = signatures.length; + var generic = function generic() { + 'use strict'; + + for (var i = iStart; i < iEnd; i++) { + if (tests[i](arguments)) { + return fns[i].apply(null, arguments); + } + } + + throw createError(name, arguments, signatures); + } + + // create the typed function + // fast, specialized version. Falls back to the slower, generic one if needed + var fn = function fn(arg0, arg1) { + 'use strict'; + + if (arguments.length === len0 && test00(arg0) && test01(arg1)) { return fn0.apply(null, arguments); } + if (arguments.length === len1 && test10(arg0) && test11(arg1)) { return fn1.apply(null, arguments); } + if (arguments.length === len2 && test20(arg0) && test21(arg1)) { return fn2.apply(null, arguments); } + if (arguments.length === len3 && test30(arg0) && test31(arg1)) { return fn3.apply(null, arguments); } + if (arguments.length === len4 && test40(arg0) && test41(arg1)) { return fn4.apply(null, arguments); } + if (arguments.length === len5 && test50(arg0) && test51(arg1)) { return fn5.apply(null, arguments); } + + return generic.apply(null, arguments); + } + + // attach name the typed function + try { + Object.defineProperty(fn, 'name', {value: name}); + } + catch (err) { + // old browsers do not support Object.defineProperty and some don't support setting the name property + // the function name is not essential for the functioning, it's mostly useful for debugging, + // so it's fine to have unnamed functions. + } + + // attach signatures to the function + fn.signatures = createSignaturesMap(signatures); + + return fn; + } + + /** + * Test whether a type should be NOT be ignored + * @param {string} typeName + * @return {boolean} + */ + function notIgnore(typeName) { + return typed.ignore.indexOf(typeName) === -1; + } + + /** + * trim a string + * @param {string} str + * @return {string} + */ + function trim(str) { + return str.trim(); + } + + /** + * Test whether a string is not empty + * @param {string} str + * @return {boolean} + */ + function notEmpty(str) { + return !!str; + } + + /** + * test whether a value is not strict equal to null + * @param {*} value + * @return {boolean} + */ + function notNull(value) { + return value !== null; + } + + /** + * Test whether a parameter has no types defined + * @param {Param} param + * @return {boolean} + */ + function isInvalidParam (param) { + return param.types.length === 0; + } + + /** + * Return all but the last items of an array + * @param {Array} arr + * @return {Array} + */ + function initial(arr) { + return arr.slice(0, arr.length - 1); + } + + /** + * return the last item of an array + * @param {Array} arr + * @return {*} + */ + function last(arr) { + return arr[arr.length - 1]; + } + + /** + * Slice an array or function Arguments + * @param {Array | Arguments | IArguments} arr + * @param {number} start + * @param {number} [end] + * @return {Array} + */ + function slice(arr, start, end) { + return Array.prototype.slice.call(arr, start, end); + } + + /** + * Test whether an array contains some item + * @param {Array} array + * @param {*} item + * @return {boolean} Returns true if array contains item, false if not. + */ + function contains(array, item) { + return array.indexOf(item) !== -1; + } + + /** + * Test whether two arrays have overlapping items + * @param {Array} array1 + * @param {Array} array2 + * @return {boolean} Returns true when at least one item exists in both arrays + */ + function hasOverlap(array1, array2) { + for (var i = 0; i < array1.length; i++) { + if (contains(array2, array1[i])) { + return true; + } + } + + return false; + } + + /** + * Return the first item from an array for which test(arr[i]) returns true + * @param {Array} arr + * @param {function} test + * @return {* | undefined} Returns the first matching item + * or undefined when there is no match + */ + function findInArray(arr, test) { + for (var i = 0; i < arr.length; i++) { + if (test(arr[i])) { + return arr[i]; + } + } + return undefined; + } + + /** + * Filter unique items of an array with strings + * @param {string[]} arr + * @return {string[]} + */ + function uniq(arr) { + var entries = {} + for (var i = 0; i < arr.length; i++) { + entries[arr[i]] = true; + } + return Object.keys(entries); + } + + /** + * Flat map the result invoking a callback for every item in an array. + * https://gist.github.com/samgiles/762ee337dff48623e729 + * @param {Array} arr + * @param {function} callback + * @return {Array} + */ + function flatMap(arr, callback) { + return Array.prototype.concat.apply([], arr.map(callback)); + } + + /** + * Retrieve the function name from a set of typed functions, + * and check whether the name of all functions match (if given) + * @param {function[]} fns + */ + function getName (fns) { + var name = ''; + + for (var i = 0; i < fns.length; i++) { + var fn = fns[i]; + + // check whether the names are the same when defined + if ((typeof fn.signatures === 'object' || typeof fn.signature === 'string') && fn.name !== '') { + if (name === '') { + name = fn.name; + } + else if (name !== fn.name) { + var err = new Error('Function names do not match (expected: ' + name + ', actual: ' + fn.name + ')'); + err.data = { + actual: fn.name, + expected: name + }; + throw err; + } + } + } + + return name; + } + + // extract and merge all signatures of a list with typed functions + function extractSignatures(fns) { + var err; + var signaturesMap = {}; + + function validateUnique(_signature, _fn) { + if (signaturesMap.hasOwnProperty(_signature) && _fn !== signaturesMap[_signature]) { + err = new Error('Signature "' + _signature + '" is defined twice'); + err.data = {signature: _signature}; + throw err; + // else: both signatures point to the same function, that's fine + } + } + + for (var i = 0; i < fns.length; i++) { + var fn = fns[i]; + + // test whether this is a typed-function + if (typeof fn.signatures === 'object') { + // merge the signatures + for (var signature in fn.signatures) { + if (fn.signatures.hasOwnProperty(signature)) { + validateUnique(signature, fn.signatures[signature]); + signaturesMap[signature] = fn.signatures[signature]; + } + } + } + else if (typeof fn.signature === 'string') { + validateUnique(fn.signature, fn); + signaturesMap[fn.signature] = fn; + } + else { + err = new TypeError('Function is no typed-function (index: ' + i + ')'); + err.data = {index: i}; + throw err; + } + } + + return signaturesMap; + } + + typed = createTypedFunction('typed', { + 'string, Object': createTypedFunction, + 'Object': function (signaturesMap) { + // find existing name + var fns = []; + for (var signature in signaturesMap) { + if (signaturesMap.hasOwnProperty(signature)) { + fns.push(signaturesMap[signature]); + } + } + var name = getName(fns); + return createTypedFunction(name, signaturesMap); + }, + '...Function': function (fns) { + return createTypedFunction(getName(fns), extractSignatures(fns)); + }, + 'string, ...Function': function (name, fns) { + return createTypedFunction(name, extractSignatures(fns)); + } + }); + + typed.create = create; + typed.types = _types; + typed.conversions = _conversions; + typed.ignore = _ignore; + typed.convert = convert; + typed.find = find; + + /** + * add a type + * @param {{name: string, test: function}} type + * @param {boolean} [beforeObjectTest=true] + * If true, the new test will be inserted before + * the test with name 'Object' (if any), since + * tests for Object match Array and classes too. + */ + typed.addType = function (type, beforeObjectTest) { + if (!type || typeof type.name !== 'string' || typeof type.test !== 'function') { + throw new TypeError('Object with properties {name: string, test: function} expected'); + } + + if (beforeObjectTest !== false) { + for (var i = 0; i < typed.types.length; i++) { + if (typed.types[i].name === 'Object') { + typed.types.splice(i, 0, type); + return + } + } + } + + typed.types.push(type); + }; + + // add a conversion + typed.addConversion = function (conversion) { + if (!conversion + || typeof conversion.from !== 'string' + || typeof conversion.to !== 'string' + || typeof conversion.convert !== 'function') { + throw new TypeError('Object with properties {from: string, to: string, convert: function} expected'); + } + + typed.conversions.push(conversion); + }; + + return typed; + } + + return create(); +})); + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +var width = 256;// each RC4 output is 0 <= x < 256 +var chunks = 6;// at least six RC4 outputs for each double +var digits = 52;// there are 52 significant digits in a double +var pool = [];// pool: entropy pool starts empty +var GLOBAL = typeof global === 'undefined' ? window : global; + +// +// The following constants are related to IEEE 754 limits. +// +var startdenom = Math.pow(width, chunks), + significance = Math.pow(2, digits), + overflow = significance * 2, + mask = width - 1; + + +var oldRandom = Math.random; + +// +// seedrandom() +// This is the seedrandom function described above. +// +module.exports = function(seed, options) { + if (options && options.global === true) { + options.global = false; + Math.random = module.exports(seed, options); + options.global = true; + return Math.random; + } + var use_entropy = (options && options.entropy) || false; + var key = []; + + // Flatten the seed string or build one from local entropy if needed. + var shortseed = mixkey(flatten( + use_entropy ? [seed, tostring(pool)] : + 0 in arguments ? seed : autoseed(), 3), key); + + // Use the seed to initialize an ARC4 generator. + var arc4 = new ARC4(key); + + // Mix the randomness into accumulated entropy. + mixkey(tostring(arc4.S), pool); + + // Override Math.random + + // This function returns a random double in [0, 1) that contains + // randomness in every bit of the mantissa of the IEEE 754 value. + + return function() { // Closure to return a random double: + var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48 + d = startdenom, // and denominator d = 2 ^ 48. + x = 0; // and no 'extra last byte'. + while (n < significance) { // Fill up all significant digits by + n = (n + x) * width; // shifting numerator and + d *= width; // denominator and generating a + x = arc4.g(1); // new least-significant-byte. + } + while (n >= overflow) { // To avoid rounding up, before adding + n /= 2; // last byte, shift everything + d /= 2; // right using integer Math until + x >>>= 1; // we have exactly the desired bits. + } + return (n + x) / d; // Form the number within [0, 1). + }; +}; + +module.exports.resetGlobal = function () { + Math.random = oldRandom; +}; + +// +// ARC4 +// +// An ARC4 implementation. The constructor takes a key in the form of +// an array of at most (width) integers that should be 0 <= x < (width). +// +// The g(count) method returns a pseudorandom integer that concatenates +// the next (count) outputs from ARC4. Its return value is a number x +// that is in the range 0 <= x < (width ^ count). +// +/** @constructor */ +function ARC4(key) { + var t, keylen = key.length, + me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; + + // The empty key [] is treated as [0]. + if (!keylen) { key = [keylen++]; } + + // Set up S using the standard key scheduling algorithm. + while (i < width) { + s[i] = i++; + } + for (i = 0; i < width; i++) { + s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))]; + s[j] = t; + } + + // The "g" method returns the next (count) outputs as one number. + (me.g = function(count) { + // Using instance members instead of closure state nearly doubles speed. + var t, r = 0, + i = me.i, j = me.j, s = me.S; + while (count--) { + t = s[i = mask & (i + 1)]; + r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))]; + } + me.i = i; me.j = j; + return r; + // For robust unpredictability discard an initial batch of values. + // See http://www.rsa.com/rsalabs/node.asp?id=2009 + })(width); +} + +// +// flatten() +// Converts an object tree to nested arrays of strings. +// +function flatten(obj, depth) { + var result = [], typ = (typeof obj)[0], prop; + if (depth && typ == 'o') { + for (prop in obj) { + try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} + } + } + return (result.length ? result : typ == 's' ? obj : obj + '\0'); +} + +// +// mixkey() +// Mixes a string seed into a key that is an array of integers, and +// returns a shortened string seed that is equivalent to the result key. +// +function mixkey(seed, key) { + var stringseed = seed + '', smear, j = 0; + while (j < stringseed.length) { + key[mask & j] = + mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++)); + } + return tostring(key); +} + +// +// autoseed() +// Returns an object for autoseeding, using window.crypto if available. +// +/** @param {Uint8Array=} seed */ +function autoseed(seed) { + try { + GLOBAL.crypto.getRandomValues(seed = new Uint8Array(width)); + return tostring(seed); + } catch (e) { + return [+new Date, GLOBAL, GLOBAL.navigator && GLOBAL.navigator.plugins, + GLOBAL.screen, tostring(pool)]; + } +} + +// +// tostring() +// Converts an array of charcodes to a string +// +function tostring(a) { + return String.fromCharCode.apply(0, a); +} + +// +// When seedrandom.js is loaded, we immediately mix a few bits +// from the built-in RNG into the entropy pool. Because we do +// not want to intefere with determinstic PRNG state later, +// seedrandom will not call Math.random on its own again after +// initialization. +// +mixkey(Math.random(), pool); + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(20))) + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_RESULT__;;(function (globalScope) { + 'use strict'; + + + /* + * decimal.js v10.2.0 + * An arbitrary-precision Decimal type for JavaScript. + * https://github.com/MikeMcl/decimal.js + * Copyright (c) 2019 Michael Mclaughlin + * MIT Licence + */ + + + // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ // + + + // The maximum exponent magnitude. + // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`. + var EXP_LIMIT = 9e15, // 0 to 9e15 + + // The limit on the value of `precision`, and on the value of the first argument to + // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`. + MAX_DIGITS = 1e9, // 0 to 1e9 + + // Base conversion alphabet. + NUMERALS = '0123456789abcdef', + + // The natural logarithm of 10 (1025 digits). + LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058', + + // Pi (1025 digits). + PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789', + + + // The initial configuration properties of the Decimal constructor. + DEFAULTS = { + + // These values must be integers within the stated ranges (inclusive). + // Most of these values can be changed at run-time using the `Decimal.config` method. + + // The maximum number of significant digits of the result of a calculation or base conversion. + // E.g. `Decimal.config({ precision: 20 });` + precision: 20, // 1 to MAX_DIGITS + + // The rounding mode used when rounding to `precision`. + // + // ROUND_UP 0 Away from zero. + // ROUND_DOWN 1 Towards zero. + // ROUND_CEIL 2 Towards +Infinity. + // ROUND_FLOOR 3 Towards -Infinity. + // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + // + // E.g. + // `Decimal.rounding = 4;` + // `Decimal.rounding = Decimal.ROUND_HALF_UP;` + rounding: 4, // 0 to 8 + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend (JavaScript %). + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 The IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive. + // + // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian + // division (9) are commonly used for the modulus operation. The other rounding modes can also + // be used, but they may not give useful results. + modulo: 1, // 0 to 9 + + // The exponent value at and beneath which `toString` returns exponential notation. + // JavaScript numbers: -7 + toExpNeg: -7, // 0 to -EXP_LIMIT + + // The exponent value at and above which `toString` returns exponential notation. + // JavaScript numbers: 21 + toExpPos: 21, // 0 to EXP_LIMIT + + // The minimum exponent value, beneath which underflow to zero occurs. + // JavaScript numbers: -324 (5e-324) + minE: -EXP_LIMIT, // -1 to -EXP_LIMIT + + // The maximum exponent value, above which overflow to Infinity occurs. + // JavaScript numbers: 308 (1.7976931348623157e+308) + maxE: EXP_LIMIT, // 1 to EXP_LIMIT + + // Whether to use cryptographically-secure random number generation, if available. + crypto: false // true/false + }, + + + // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- // + + + Decimal, inexact, noConflict, quadrant, + external = true, + + decimalError = '[DecimalError] ', + invalidArgument = decimalError + 'Invalid argument: ', + precisionLimitExceeded = decimalError + 'Precision limit exceeded', + cryptoUnavailable = decimalError + 'crypto unavailable', + + mathfloor = Math.floor, + mathpow = Math.pow, + + isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i, + isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i, + isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i, + isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, + + BASE = 1e7, + LOG_BASE = 7, + MAX_SAFE_INTEGER = 9007199254740991, + + LN10_PRECISION = LN10.length - 1, + PI_PRECISION = PI.length - 1, + + // Decimal.prototype object + P = { name: '[object Decimal]' }; + + + // Decimal prototype methods + + + /* + * absoluteValue abs + * ceil + * comparedTo cmp + * cosine cos + * cubeRoot cbrt + * decimalPlaces dp + * dividedBy div + * dividedToIntegerBy divToInt + * equals eq + * floor + * greaterThan gt + * greaterThanOrEqualTo gte + * hyperbolicCosine cosh + * hyperbolicSine sinh + * hyperbolicTangent tanh + * inverseCosine acos + * inverseHyperbolicCosine acosh + * inverseHyperbolicSine asinh + * inverseHyperbolicTangent atanh + * inverseSine asin + * inverseTangent atan + * isFinite + * isInteger isInt + * isNaN + * isNegative isNeg + * isPositive isPos + * isZero + * lessThan lt + * lessThanOrEqualTo lte + * logarithm log + * [maximum] [max] + * [minimum] [min] + * minus sub + * modulo mod + * naturalExponential exp + * naturalLogarithm ln + * negated neg + * plus add + * precision sd + * round + * sine sin + * squareRoot sqrt + * tangent tan + * times mul + * toBinary + * toDecimalPlaces toDP + * toExponential + * toFixed + * toFraction + * toHexadecimal toHex + * toNearest + * toNumber + * toOctal + * toPower pow + * toPrecision + * toSignificantDigits toSD + * toString + * truncated trunc + * valueOf toJSON + */ + + + /* + * Return a new Decimal whose value is the absolute value of this Decimal. + * + */ + P.absoluteValue = P.abs = function () { + var x = new this.constructor(this); + if (x.s < 0) x.s = 1; + return finalise(x); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the + * direction of positive Infinity. + * + */ + P.ceil = function () { + return finalise(new this.constructor(this), this.e + 1, 2); + }; + + + /* + * Return + * 1 if the value of this Decimal is greater than the value of `y`, + * -1 if the value of this Decimal is less than the value of `y`, + * 0 if they have the same value, + * NaN if the value of either Decimal is NaN. + * + */ + P.comparedTo = P.cmp = function (y) { + var i, j, xdL, ydL, + x = this, + xd = x.d, + yd = (y = new x.constructor(y)).d, + xs = x.s, + ys = y.s; + + // Either NaN or ±Infinity? + if (!xd || !yd) { + return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1; + } + + // Either zero? + if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0; + + // Signs differ? + if (xs !== ys) return xs; + + // Compare exponents. + if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1; + + xdL = xd.length; + ydL = yd.length; + + // Compare digit by digit. + for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) { + if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1; + } + + // Compare lengths. + return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1; + }; + + + /* + * Return a new Decimal whose value is the cosine of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * cos(0) = 1 + * cos(-0) = 1 + * cos(Infinity) = NaN + * cos(-Infinity) = NaN + * cos(NaN) = NaN + * + */ + P.cosine = P.cos = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.d) return new Ctor(NaN); + + // cos(0) = cos(-0) = 1 + if (!x.d[0]) return new Ctor(1); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; + Ctor.rounding = 1; + + x = cosine(Ctor, toLessThanHalfPi(Ctor, x)); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true); + }; + + + /* + * + * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * cbrt(0) = 0 + * cbrt(-0) = -0 + * cbrt(1) = 1 + * cbrt(-1) = -1 + * cbrt(N) = N + * cbrt(-I) = -I + * cbrt(I) = I + * + * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3)) + * + */ + P.cubeRoot = P.cbrt = function () { + var e, m, n, r, rep, s, sd, t, t3, t3plusx, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + external = false; + + // Initial estimate. + s = x.s * mathpow(x.s * x, 1 / 3); + + // Math.cbrt underflow/overflow? + // Pass x to Math.pow as integer, then adjust the exponent of the result. + if (!s || Math.abs(s) == 1 / 0) { + n = digitsToString(x.d); + e = x.e; + + // Adjust n exponent so it is a multiple of 3 away from x exponent. + if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00'); + s = mathpow(n, 1 / 3); + + // Rarely, e may be one less than the result exponent value. + e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new Ctor(n); + r.s = x.s; + } else { + r = new Ctor(s.toString()); + } + + sd = (e = Ctor.precision) + 3; + + // Halley's method. + // TODO? Compare Newton's method. + for (;;) { + t = r; + t3 = t.times(t).times(t); + t3plusx = t3.plus(x); + r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1); + + // TODO? Replace with for-loop and checkRoundingDigits. + if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { + n = n.slice(sd - 3, sd + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999 + // , i.e. approaching a rounding boundary, continue the iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the exact result as the + // nines may infinitely repeat. + if (!rep) { + finalise(t, e + 1, 0); + + if (t.times(t).times(t).eq(x)) { + r = t; + break; + } + } + + sd += 4; + rep = 1; + } else { + + // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. + // If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + finalise(r, e + 1, 1); + m = !r.times(r).times(r).eq(x); + } + + break; + } + } + } + + external = true; + + return finalise(r, e, Ctor.rounding, m); + }; + + + /* + * Return the number of decimal places of the value of this Decimal. + * + */ + P.decimalPlaces = P.dp = function () { + var w, + d = this.d, + n = NaN; + + if (d) { + w = d.length - 1; + n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last word. + w = d[w]; + if (w) for (; w % 10 == 0; w /= 10) n--; + if (n < 0) n = 0; + } + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + */ + P.dividedBy = P.div = function (y) { + return divide(this, new this.constructor(y)); + }; + + + /* + * Return a new Decimal whose value is the integer part of dividing the value of this Decimal + * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`. + * + */ + P.dividedToIntegerBy = P.divToInt = function (y) { + var x = this, + Ctor = x.constructor; + return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding); + }; + + + /* + * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. + * + */ + P.equals = P.eq = function (y) { + return this.cmp(y) === 0; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the + * direction of negative Infinity. + * + */ + P.floor = function () { + return finalise(new this.constructor(this), this.e + 1, 3); + }; + + + /* + * Return true if the value of this Decimal is greater than the value of `y`, otherwise return + * false. + * + */ + P.greaterThan = P.gt = function (y) { + return this.cmp(y) > 0; + }; + + + /* + * Return true if the value of this Decimal is greater than or equal to the value of `y`, + * otherwise return false. + * + */ + P.greaterThanOrEqualTo = P.gte = function (y) { + var k = this.cmp(y); + return k == 1 || k === 0; + }; + + + /* + * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [1, Infinity] + * + * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ... + * + * cosh(0) = 1 + * cosh(-0) = 1 + * cosh(Infinity) = Infinity + * cosh(-Infinity) = Infinity + * cosh(NaN) = NaN + * + * x time taken (ms) result + * 1000 9 9.8503555700852349694e+433 + * 10000 25 4.4034091128314607936e+4342 + * 100000 171 1.4033316802130615897e+43429 + * 1000000 3817 1.5166076984010437725e+434294 + * 10000000 abandoned after 2 minute wait + * + * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x)) + * + */ + P.hyperbolicCosine = P.cosh = function () { + var k, n, pr, rm, len, + x = this, + Ctor = x.constructor, + one = new Ctor(1); + + if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN); + if (x.isZero()) return one; + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; + Ctor.rounding = 1; + len = x.d.length; + + // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1 + // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4)) + + // Estimate the optimum number of times to use the argument reduction. + // TODO? Estimation reused from cosine() and may not be optimal here. + if (len < 32) { + k = Math.ceil(len / 3); + n = (1 / tinyPow(4, k)).toString(); + } else { + k = 16; + n = '2.3283064365386962890625e-10'; + } + + x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true); + + // Reverse argument reduction + var cosh2_x, + i = k, + d8 = new Ctor(8); + for (; i--;) { + cosh2_x = x.times(x); + x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8)))); + } + + return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true); + }; + + + /* + * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ... + * + * sinh(0) = 0 + * sinh(-0) = -0 + * sinh(Infinity) = Infinity + * sinh(-Infinity) = -Infinity + * sinh(NaN) = NaN + * + * x time taken (ms) + * 10 2 ms + * 100 5 ms + * 1000 14 ms + * 10000 82 ms + * 100000 886 ms 1.4033316802130615897e+43429 + * 200000 2613 ms + * 300000 5407 ms + * 400000 8824 ms + * 500000 13026 ms 8.7080643612718084129e+217146 + * 1000000 48543 ms + * + * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x)) + * + */ + P.hyperbolicSine = P.sinh = function () { + var k, pr, rm, len, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; + Ctor.rounding = 1; + len = x.d.length; + + if (len < 3) { + x = taylorSeries(Ctor, 2, x, x, true); + } else { + + // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x)) + // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3)) + // 3 multiplications and 1 addition + + // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x))) + // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5))) + // 4 multiplications and 2 additions + + // Estimate the optimum number of times to use the argument reduction. + k = 1.4 * Math.sqrt(len); + k = k > 16 ? 16 : k | 0; + + x = x.times(1 / tinyPow(5, k)); + x = taylorSeries(Ctor, 2, x, x, true); + + // Reverse argument reduction + var sinh2_x, + d5 = new Ctor(5), + d16 = new Ctor(16), + d20 = new Ctor(20); + for (; k--;) { + sinh2_x = x.times(x); + x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20)))); + } + } + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(x, pr, rm, true); + }; + + + /* + * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * tanh(x) = sinh(x) / cosh(x) + * + * tanh(0) = 0 + * tanh(-0) = -0 + * tanh(Infinity) = 1 + * tanh(-Infinity) = -1 + * tanh(NaN) = NaN + * + */ + P.hyperbolicTangent = P.tanh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(x.s); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 7; + Ctor.rounding = 1; + + return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm); + }; + + + /* + * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of + * this Decimal. + * + * Domain: [-1, 1] + * Range: [0, pi] + * + * acos(x) = pi/2 - asin(x) + * + * acos(0) = pi/2 + * acos(-0) = pi/2 + * acos(1) = 0 + * acos(-1) = pi + * acos(1/2) = pi/3 + * acos(-1/2) = 2*pi/3 + * acos(|x| > 1) = NaN + * acos(NaN) = NaN + * + */ + P.inverseCosine = P.acos = function () { + var halfPi, + x = this, + Ctor = x.constructor, + k = x.abs().cmp(1), + pr = Ctor.precision, + rm = Ctor.rounding; + + if (k !== -1) { + return k === 0 + // |x| is 1 + ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0) + // |x| > 1 or x is NaN + : new Ctor(NaN); + } + + if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5); + + // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3 + + Ctor.precision = pr + 6; + Ctor.rounding = 1; + + x = x.asin(); + halfPi = getPi(Ctor, pr + 4, rm).times(0.5); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return halfPi.minus(x); + }; + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the + * value of this Decimal. + * + * Domain: [1, Infinity] + * Range: [0, Infinity] + * + * acosh(x) = ln(x + sqrt(x^2 - 1)) + * + * acosh(x < 1) = NaN + * acosh(NaN) = NaN + * acosh(Infinity) = Infinity + * acosh(-Infinity) = NaN + * acosh(0) = NaN + * acosh(-0) = NaN + * acosh(1) = 0 + * acosh(-1) = NaN + * + */ + P.inverseHyperbolicCosine = P.acosh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN); + if (!x.isFinite()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4; + Ctor.rounding = 1; + external = false; + + x = x.times(x).minus(1).sqrt().plus(x); + + external = true; + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.ln(); + }; + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value + * of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * asinh(x) = ln(x + sqrt(x^2 + 1)) + * + * asinh(NaN) = NaN + * asinh(Infinity) = Infinity + * asinh(-Infinity) = -Infinity + * asinh(0) = 0 + * asinh(-0) = -0 + * + */ + P.inverseHyperbolicSine = P.asinh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6; + Ctor.rounding = 1; + external = false; + + x = x.times(x).plus(1).sqrt().plus(x); + + external = true; + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.ln(); + }; + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the + * value of this Decimal. + * + * Domain: [-1, 1] + * Range: [-Infinity, Infinity] + * + * atanh(x) = 0.5 * ln((1 + x) / (1 - x)) + * + * atanh(|x| > 1) = NaN + * atanh(NaN) = NaN + * atanh(Infinity) = NaN + * atanh(-Infinity) = NaN + * atanh(0) = 0 + * atanh(-0) = -0 + * atanh(1) = Infinity + * atanh(-1) = -Infinity + * + */ + P.inverseHyperbolicTangent = P.atanh = function () { + var pr, rm, wpr, xsd, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN); + + pr = Ctor.precision; + rm = Ctor.rounding; + xsd = x.sd(); + + if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true); + + Ctor.precision = wpr = xsd - x.e; + + x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1); + + Ctor.precision = pr + 4; + Ctor.rounding = 1; + + x = x.ln(); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.times(0.5); + }; + + + /* + * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi/2, pi/2] + * + * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2))) + * + * asin(0) = 0 + * asin(-0) = -0 + * asin(1/2) = pi/6 + * asin(-1/2) = -pi/6 + * asin(1) = pi/2 + * asin(-1) = -pi/2 + * asin(|x| > 1) = NaN + * asin(NaN) = NaN + * + * TODO? Compare performance of Taylor series. + * + */ + P.inverseSine = P.asin = function () { + var halfPi, k, + pr, rm, + x = this, + Ctor = x.constructor; + + if (x.isZero()) return new Ctor(x); + + k = x.abs().cmp(1); + pr = Ctor.precision; + rm = Ctor.rounding; + + if (k !== -1) { + + // |x| is 1 + if (k === 0) { + halfPi = getPi(Ctor, pr + 4, rm).times(0.5); + halfPi.s = x.s; + return halfPi; + } + + // |x| > 1 or x is NaN + return new Ctor(NaN); + } + + // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6 + + Ctor.precision = pr + 6; + Ctor.rounding = 1; + + x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan(); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.times(2); + }; + + + /* + * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value + * of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi/2, pi/2] + * + * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... + * + * atan(0) = 0 + * atan(-0) = -0 + * atan(1) = pi/4 + * atan(-1) = -pi/4 + * atan(Infinity) = pi/2 + * atan(-Infinity) = -pi/2 + * atan(NaN) = NaN + * + */ + P.inverseTangent = P.atan = function () { + var i, j, k, n, px, t, r, wpr, x2, + x = this, + Ctor = x.constructor, + pr = Ctor.precision, + rm = Ctor.rounding; + + if (!x.isFinite()) { + if (!x.s) return new Ctor(NaN); + if (pr + 4 <= PI_PRECISION) { + r = getPi(Ctor, pr + 4, rm).times(0.5); + r.s = x.s; + return r; + } + } else if (x.isZero()) { + return new Ctor(x); + } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) { + r = getPi(Ctor, pr + 4, rm).times(0.25); + r.s = x.s; + return r; + } + + Ctor.precision = wpr = pr + 10; + Ctor.rounding = 1; + + // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x); + + // Argument reduction + // Ensure |x| < 0.42 + // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2))) + + k = Math.min(28, wpr / LOG_BASE + 2 | 0); + + for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1)); + + external = false; + + j = Math.ceil(wpr / LOG_BASE); + n = 1; + x2 = x.times(x); + r = new Ctor(x); + px = x; + + // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... + for (; i !== -1;) { + px = px.times(x2); + t = r.minus(px.div(n += 2)); + + px = px.times(x2); + r = t.plus(px.div(n += 2)); + + if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;); + } + + if (k) r = r.times(2 << (k - 1)); + + external = true; + + return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true); + }; + + + /* + * Return true if the value of this Decimal is a finite number, otherwise return false. + * + */ + P.isFinite = function () { + return !!this.d; + }; + + + /* + * Return true if the value of this Decimal is an integer, otherwise return false. + * + */ + P.isInteger = P.isInt = function () { + return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2; + }; + + + /* + * Return true if the value of this Decimal is NaN, otherwise return false. + * + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this Decimal is negative, otherwise return false. + * + */ + P.isNegative = P.isNeg = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this Decimal is positive, otherwise return false. + * + */ + P.isPositive = P.isPos = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this Decimal is 0 or -0, otherwise return false. + * + */ + P.isZero = function () { + return !!this.d && this.d[0] === 0; + }; + + + /* + * Return true if the value of this Decimal is less than `y`, otherwise return false. + * + */ + P.lessThan = P.lt = function (y) { + return this.cmp(y) < 0; + }; + + + /* + * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. + * + */ + P.lessThanOrEqualTo = P.lte = function (y) { + return this.cmp(y) < 1; + }; + + + /* + * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * If no base is specified, return log[10](arg). + * + * log[base](arg) = ln(arg) / ln(base) + * + * The result will always be correctly rounded if the base of the log is 10, and 'almost always' + * otherwise: + * + * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen + * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error + * between the result and the correctly rounded result will be one ulp (unit in the last place). + * + * log[-b](a) = NaN + * log[0](a) = NaN + * log[1](a) = NaN + * log[NaN](a) = NaN + * log[Infinity](a) = NaN + * log[b](0) = -Infinity + * log[b](-0) = -Infinity + * log[b](-a) = NaN + * log[b](1) = 0 + * log[b](Infinity) = Infinity + * log[b](NaN) = NaN + * + * [base] {number|string|Decimal} The base of the logarithm. + * + */ + P.logarithm = P.log = function (base) { + var isBase10, d, denominator, k, inf, num, sd, r, + arg = this, + Ctor = arg.constructor, + pr = Ctor.precision, + rm = Ctor.rounding, + guard = 5; + + // Default base is 10. + if (base == null) { + base = new Ctor(10); + isBase10 = true; + } else { + base = new Ctor(base); + d = base.d; + + // Return NaN if base is negative, or non-finite, or is 0 or 1. + if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN); + + isBase10 = base.eq(10); + } + + d = arg.d; + + // Is arg negative, non-finite, 0 or 1? + if (arg.s < 0 || !d || !d[0] || arg.eq(1)) { + return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0); + } + + // The result will have a non-terminating decimal expansion if base is 10 and arg is not an + // integer power of 10. + if (isBase10) { + if (d.length > 1) { + inf = true; + } else { + for (k = d[0]; k % 10 === 0;) k /= 10; + inf = k !== 1; + } + } + + external = false; + sd = pr + guard; + num = naturalLogarithm(arg, sd); + denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); + + // The result will have 5 rounding digits. + r = divide(num, denominator, sd, 1); + + // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000, + // calculate 10 further digits. + // + // If the result is known to have an infinite decimal expansion, repeat this until it is clear + // that the result is above or below the boundary. Otherwise, if after calculating the 10 + // further digits, the last 14 are nines, round up and assume the result is exact. + // Also assume the result is exact if the last 14 are zero. + // + // Example of a result that will be incorrectly rounded: + // log[1048576](4503599627370502) = 2.60000000000000009610279511444746... + // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it + // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so + // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal + // place is still 2.6. + if (checkRoundingDigits(r.d, k = pr, rm)) { + + do { + sd += 10; + num = naturalLogarithm(arg, sd); + denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); + r = divide(num, denominator, sd, 1); + + if (!inf) { + + // Check for 14 nines from the 2nd rounding digit, as the first may be 4. + if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) { + r = finalise(r, pr + 1, 0); + } + + break; + } + } while (checkRoundingDigits(r.d, k += 10, rm)); + } + + external = true; + + return finalise(r, pr, rm); + }; + + + /* + * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal. + * + * arguments {number|string|Decimal} + * + P.max = function () { + Array.prototype.push.call(arguments, this); + return maxOrMin(this.constructor, arguments, 'lt'); + }; + */ + + + /* + * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal. + * + * arguments {number|string|Decimal} + * + P.min = function () { + Array.prototype.push.call(arguments, this); + return maxOrMin(this.constructor, arguments, 'gt'); + }; + */ + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.minus = P.sub = function (y) { + var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // If either is not finite... + if (!x.d || !y.d) { + + // Return NaN if either is NaN. + if (!x.s || !y.s) y = new Ctor(NaN); + + // Return y negated if x is finite and y is ±Infinity. + else if (x.d) y.s = -y.s; + + // Return x if y is finite and x is ±Infinity. + // Return x if both are ±Infinity with different signs. + // Return NaN if both are ±Infinity with the same sign. + else y = new Ctor(y.d || x.s !== y.s ? x : NaN); + + return y; + } + + // If signs differ... + if (x.s != y.s) { + y.s = -y.s; + return x.plus(y); + } + + xd = x.d; + yd = y.d; + pr = Ctor.precision; + rm = Ctor.rounding; + + // If either is zero... + if (!xd[0] || !yd[0]) { + + // Return y negated if x is zero and y is non-zero. + if (yd[0]) y.s = -y.s; + + // Return x if y is zero and x is non-zero. + else if (xd[0]) y = new Ctor(x); + + // Return zero if both are zero. + // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity. + else return new Ctor(rm === 3 ? -0 : 0); + + return external ? finalise(y, pr, rm) : y; + } + + // x and y are finite, non-zero numbers with the same sign. + + // Calculate base 1e7 exponents. + e = mathfloor(y.e / LOG_BASE); + xe = mathfloor(x.e / LOG_BASE); + + xd = xd.slice(); + k = xe - e; + + // If base 1e7 exponents differ... + if (k) { + xLTy = k < 0; + + if (xLTy) { + d = xd; + k = -k; + len = yd.length; + } else { + d = yd; + e = xe; + len = xd.length; + } + + // Numbers with massively different exponents would result in a very high number of + // zeros needing to be prepended, but this can be avoided while still ensuring correct + // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`. + i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2; + + if (k > i) { + k = i; + d.length = 1; + } + + // Prepend zeros to equalise exponents. + d.reverse(); + for (i = k; i--;) d.push(0); + d.reverse(); + + // Base 1e7 exponents equal. + } else { + + // Check digits to determine which is the bigger number. + + i = xd.length; + len = yd.length; + xLTy = i < len; + if (xLTy) len = i; + + for (i = 0; i < len; i++) { + if (xd[i] != yd[i]) { + xLTy = xd[i] < yd[i]; + break; + } + } + + k = 0; + } + + if (xLTy) { + d = xd; + xd = yd; + yd = d; + y.s = -y.s; + } + + len = xd.length; + + // Append zeros to `xd` if shorter. + // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length. + for (i = yd.length - len; i > 0; --i) xd[len++] = 0; + + // Subtract yd from xd. + for (i = yd.length; i > k;) { + + if (xd[--i] < yd[i]) { + for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1; + --xd[j]; + xd[i] += BASE; + } + + xd[i] -= yd[i]; + } + + // Remove trailing zeros. + for (; xd[--len] === 0;) xd.pop(); + + // Remove leading zeros and adjust exponent accordingly. + for (; xd[0] === 0; xd.shift()) --e; + + // Zero? + if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0); + + y.d = xd; + y.e = getBase10Exponent(xd, e); + + return external ? finalise(y, pr, rm) : y; + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * The result depends on the modulo mode. + * + */ + P.modulo = P.mod = function (y) { + var q, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0. + if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN); + + // Return x if y is ±Infinity or x is ±0. + if (!y.d || x.d && !x.d[0]) { + return finalise(new Ctor(x), Ctor.precision, Ctor.rounding); + } + + // Prevent rounding of intermediate calculations. + external = false; + + if (Ctor.modulo == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // result = x - q * y where 0 <= result < abs(y) + q = divide(x, y.abs(), 0, 3, 1); + q.s *= y.s; + } else { + q = divide(x, y, 0, Ctor.modulo, 1); + } + + q = q.times(y); + + external = true; + + return x.minus(q); + }; + + + /* + * Return a new Decimal whose value is the natural exponential of the value of this Decimal, + * i.e. the base e raised to the power the value of this Decimal, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.naturalExponential = P.exp = function () { + return naturalExponential(this); + }; + + + /* + * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, + * rounded to `precision` significant digits using rounding mode `rounding`. + * + */ + P.naturalLogarithm = P.ln = function () { + return naturalLogarithm(this); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by + * -1. + * + */ + P.negated = P.neg = function () { + var x = new this.constructor(this); + x.s = -x.s; + return finalise(x); + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.plus = P.add = function (y) { + var carry, d, e, i, k, len, pr, rm, xd, yd, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // If either is not finite... + if (!x.d || !y.d) { + + // Return NaN if either is NaN. + if (!x.s || !y.s) y = new Ctor(NaN); + + // Return x if y is finite and x is ±Infinity. + // Return x if both are ±Infinity with the same sign. + // Return NaN if both are ±Infinity with different signs. + // Return y if x is finite and y is ±Infinity. + else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN); + + return y; + } + + // If signs differ... + if (x.s != y.s) { + y.s = -y.s; + return x.minus(y); + } + + xd = x.d; + yd = y.d; + pr = Ctor.precision; + rm = Ctor.rounding; + + // If either is zero... + if (!xd[0] || !yd[0]) { + + // Return x if y is zero. + // Return y if y is non-zero. + if (!yd[0]) y = new Ctor(x); + + return external ? finalise(y, pr, rm) : y; + } + + // x and y are finite, non-zero numbers with the same sign. + + // Calculate base 1e7 exponents. + k = mathfloor(x.e / LOG_BASE); + e = mathfloor(y.e / LOG_BASE); + + xd = xd.slice(); + i = k - e; + + // If base 1e7 exponents differ... + if (i) { + + if (i < 0) { + d = xd; + i = -i; + len = yd.length; + } else { + d = yd; + e = k; + len = xd.length; + } + + // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1. + k = Math.ceil(pr / LOG_BASE); + len = k > len ? k + 1 : len + 1; + + if (i > len) { + i = len; + d.length = 1; + } + + // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts. + d.reverse(); + for (; i--;) d.push(0); + d.reverse(); + } + + len = xd.length; + i = yd.length; + + // If yd is longer than xd, swap xd and yd so xd points to the longer array. + if (len - i < 0) { + i = len; + d = yd; + yd = xd; + xd = d; + } + + // Only start adding at yd.length - 1 as the further digits of xd can be left as they are. + for (carry = 0; i;) { + carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0; + xd[i] %= BASE; + } + + if (carry) { + xd.unshift(carry); + ++e; + } + + // Remove trailing zeros. + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + for (len = xd.length; xd[--len] == 0;) xd.pop(); + + y.d = xd; + y.e = getBase10Exponent(xd, e); + + return external ? finalise(y, pr, rm) : y; + }; + + + /* + * Return the number of significant digits of the value of this Decimal. + * + * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. + * + */ + P.precision = P.sd = function (z) { + var k, + x = this; + + if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z); + + if (x.d) { + k = getPrecision(x.d); + if (z && x.e + 1 > k) k = x.e + 1; + } else { + k = NaN; + } + + return k; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using + * rounding mode `rounding`. + * + */ + P.round = function () { + var x = this, + Ctor = x.constructor; + + return finalise(new Ctor(x), x.e + 1, Ctor.rounding); + }; + + + /* + * Return a new Decimal whose value is the sine of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * sin(x) = x - x^3/3! + x^5/5! - ... + * + * sin(0) = 0 + * sin(-0) = -0 + * sin(Infinity) = NaN + * sin(-Infinity) = NaN + * sin(NaN) = NaN + * + */ + P.sine = P.sin = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; + Ctor.rounding = 1; + + x = sine(Ctor, toLessThanHalfPi(Ctor, x)); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true); + }; + + + /* + * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + */ + P.squareRoot = P.sqrt = function () { + var m, n, sd, r, rep, t, + x = this, + d = x.d, + e = x.e, + s = x.s, + Ctor = x.constructor; + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !d || !d[0]) { + return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0); + } + + external = false; + + // Initial estimate. + s = Math.sqrt(+x); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = digitsToString(d); + + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(n); + e = mathfloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '1e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new Ctor(n); + } else { + r = new Ctor(s.toString()); + } + + sd = (e = Ctor.precision) + 3; + + // Newton-Raphson iteration. + for (;;) { + t = r; + r = t.plus(divide(x, t, sd + 2, 1)).times(0.5); + + // TODO? Replace with for-loop and checkRoundingDigits. + if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { + n = n.slice(sd - 3, sd + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or + // 4999, i.e. approaching a rounding boundary, continue the iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the exact result as the + // nines may infinitely repeat. + if (!rep) { + finalise(t, e + 1, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + sd += 4; + rep = 1; + } else { + + // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. + // If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + finalise(r, e + 1, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + + external = true; + + return finalise(r, e, Ctor.rounding, m); + }; + + + /* + * Return a new Decimal whose value is the tangent of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * tan(0) = 0 + * tan(-0) = -0 + * tan(Infinity) = NaN + * tan(-Infinity) = NaN + * tan(NaN) = NaN + * + */ + P.tangent = P.tan = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 10; + Ctor.rounding = 1; + + x = x.sin(); + x.s = 1; + x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true); + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + */ + P.times = P.mul = function (y) { + var carry, e, i, k, r, rL, t, xdL, ydL, + x = this, + Ctor = x.constructor, + xd = x.d, + yd = (y = new Ctor(y)).d; + + y.s *= x.s; + + // If either is NaN, ±Infinity or ±0... + if (!xd || !xd[0] || !yd || !yd[0]) { + + return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd + + // Return NaN if either is NaN. + // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity. + ? NaN + + // Return ±Infinity if either is ±Infinity. + // Return ±0 if either is ±0. + : !xd || !yd ? y.s / 0 : y.s * 0); + } + + e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE); + xdL = xd.length; + ydL = yd.length; + + // Ensure xd points to the longer array. + if (xdL < ydL) { + r = xd; + xd = yd; + yd = r; + rL = xdL; + xdL = ydL; + ydL = rL; + } + + // Initialise the result array with zeros. + r = []; + rL = xdL + ydL; + for (i = rL; i--;) r.push(0); + + // Multiply! + for (i = ydL; --i >= 0;) { + carry = 0; + for (k = xdL + i; k > i;) { + t = r[k] + yd[i] * xd[k - i - 1] + carry; + r[k--] = t % BASE | 0; + carry = t / BASE | 0; + } + + r[k] = (r[k] + carry) % BASE | 0; + } + + // Remove trailing zeros. + for (; !r[--rL];) r.pop(); + + if (carry) ++e; + else r.shift(); + + y.d = r; + y.e = getBase10Exponent(r, e); + + return external ? finalise(y, Ctor.precision, Ctor.rounding) : y; + }; + + + /* + * Return a string representing the value of this Decimal in base 2, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toBinary = function (sd, rm) { + return toStringBinary(this, 2, sd, rm); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` + * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. + * + * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toDecimalPlaces = P.toDP = function (dp, rm) { + var x = this, + Ctor = x.constructor; + + x = new Ctor(x); + if (dp === void 0) return x; + + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + return finalise(x, dp + x.e + 1, rm); + }; + + + /* + * Return a string representing the value of this Decimal in exponential notation rounded to + * `dp` fixed decimal places using rounding mode `rounding`. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toExponential = function (dp, rm) { + var str, + x = this, + Ctor = x.constructor; + + if (dp === void 0) { + str = finiteToString(x, true); + } else { + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + x = finalise(new Ctor(x), dp + 1, rm); + str = finiteToString(x, true, dp + 1); + } + + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a string representing the value of this Decimal in normal (fixed-point) notation to + * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is + * omitted. + * + * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. + * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. + * (-0).toFixed(3) is '0.000'. + * (-0.5).toFixed(0) is '-0'. + * + */ + P.toFixed = function (dp, rm) { + var str, y, + x = this, + Ctor = x.constructor; + + if (dp === void 0) { + str = finiteToString(x); + } else { + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + y = finalise(new Ctor(x), dp + x.e + 1, rm); + str = finiteToString(y, false, dp + y.e + 1); + } + + // To determine whether to add the minus sign look at the value before it was rounded, + // i.e. look at `x` rather than `y`. + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return an array representing the value of this Decimal as a simple fraction with an integer + * numerator and an integer denominator. + * + * The denominator will be a positive non-zero value less than or equal to the specified maximum + * denominator. If a maximum denominator is not specified, the denominator will be the lowest + * value necessary to represent the number exactly. + * + * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity. + * + */ + P.toFraction = function (maxD) { + var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r, + x = this, + xd = x.d, + Ctor = x.constructor; + + if (!xd) return new Ctor(x); + + n1 = d0 = new Ctor(1); + d1 = n0 = new Ctor(0); + + d = new Ctor(d1); + e = d.e = getPrecision(xd) - x.e - 1; + k = e % LOG_BASE; + d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k); + + if (maxD == null) { + + // d is 10**e, the minimum max-denominator needed. + maxD = e > 0 ? d : n1; + } else { + n = new Ctor(maxD); + if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n); + maxD = n.gt(d) ? (e > 0 ? d : n1) : n; + } + + external = false; + n = new Ctor(digitsToString(xd)); + pr = Ctor.precision; + Ctor.precision = e = xd.length * LOG_BASE * 2; + + for (;;) { + q = divide(n, d, 0, 1, 1); + d2 = d0.plus(q.times(d1)); + if (d2.cmp(maxD) == 1) break; + d0 = d1; + d1 = d2; + d2 = n1; + n1 = n0.plus(q.times(d2)); + n0 = d2; + d2 = d; + d = n.minus(q.times(d2)); + n = d2; + } + + d2 = divide(maxD.minus(d0), d1, 0, 1, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + + // Determine which fraction is closer to x, n0/d0 or n1/d1? + r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1 + ? [n1, d1] : [n0, d0]; + + Ctor.precision = pr; + external = true; + + return r; + }; + + + /* + * Return a string representing the value of this Decimal in base 16, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toHexadecimal = P.toHex = function (sd, rm) { + return toStringBinary(this, 16, sd, rm); + }; + + + /* + * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding + * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal. + * + * The return value will always have the same sign as this Decimal, unless either this Decimal + * or `y` is NaN, in which case the return value will be also be NaN. + * + * The return value is not affected by the value of `precision`. + * + * y {number|string|Decimal} The magnitude to round to a multiple of. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toNearest() rounding mode not an integer: {rm}' + * 'toNearest() rounding mode out of range: {rm}' + * + */ + P.toNearest = function (y, rm) { + var x = this, + Ctor = x.constructor; + + x = new Ctor(x); + + if (y == null) { + + // If x is not finite, return x. + if (!x.d) return x; + + y = new Ctor(1); + rm = Ctor.rounding; + } else { + y = new Ctor(y); + if (rm === void 0) { + rm = Ctor.rounding; + } else { + checkInt32(rm, 0, 8); + } + + // If x is not finite, return x if y is not NaN, else NaN. + if (!x.d) return y.s ? x : y; + + // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN. + if (!y.d) { + if (y.s) y.s = x.s; + return y; + } + } + + // If y is not zero, calculate the nearest multiple of y to x. + if (y.d[0]) { + external = false; + x = divide(x, y, 0, rm, 1).times(y); + external = true; + finalise(x); + + // If y is zero, return zero with the sign of x. + } else { + y.s = x.s; + x = y; + } + + return x; + }; + + + /* + * Return the value of this Decimal converted to a number primitive. + * Zero keeps its sign. + * + */ + P.toNumber = function () { + return +this; + }; + + + /* + * Return a string representing the value of this Decimal in base 8, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toOctal = function (sd, rm) { + return toStringBinary(this, 8, sd, rm); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded + * to `precision` significant digits using rounding mode `rounding`. + * + * ECMAScript compliant. + * + * pow(x, NaN) = NaN + * pow(x, ±0) = 1 + + * pow(NaN, non-zero) = NaN + * pow(abs(x) > 1, +Infinity) = +Infinity + * pow(abs(x) > 1, -Infinity) = +0 + * pow(abs(x) == 1, ±Infinity) = NaN + * pow(abs(x) < 1, +Infinity) = +0 + * pow(abs(x) < 1, -Infinity) = +Infinity + * pow(+Infinity, y > 0) = +Infinity + * pow(+Infinity, y < 0) = +0 + * pow(-Infinity, odd integer > 0) = -Infinity + * pow(-Infinity, even integer > 0) = +Infinity + * pow(-Infinity, odd integer < 0) = -0 + * pow(-Infinity, even integer < 0) = +0 + * pow(+0, y > 0) = +0 + * pow(+0, y < 0) = +Infinity + * pow(-0, odd integer > 0) = -0 + * pow(-0, even integer > 0) = +0 + * pow(-0, odd integer < 0) = -Infinity + * pow(-0, even integer < 0) = +Infinity + * pow(finite x < 0, finite non-integer) = NaN + * + * For non-integer or very large exponents pow(x, y) is calculated using + * + * x^y = exp(y*ln(x)) + * + * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the + * probability of an incorrectly rounded result + * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14 + * i.e. 1 in 250,000,000,000,000 + * + * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place). + * + * y {number|string|Decimal} The power to which to raise this Decimal. + * + */ + P.toPower = P.pow = function (y) { + var e, k, pr, r, rm, s, + x = this, + Ctor = x.constructor, + yn = +(y = new Ctor(y)); + + // Either ±Infinity, NaN or ±0? + if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn)); + + x = new Ctor(x); + + if (x.eq(1)) return x; + + pr = Ctor.precision; + rm = Ctor.rounding; + + if (y.eq(1)) return finalise(x, pr, rm); + + // y exponent + e = mathfloor(y.e / LOG_BASE); + + // If y is a small integer use the 'exponentiation by squaring' algorithm. + if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) { + r = intPow(Ctor, x, k, pr); + return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm); + } + + s = x.s; + + // if x is negative + if (s < 0) { + + // if y is not an integer + if (e < y.d.length - 1) return new Ctor(NaN); + + // Result is positive if x is negative and the last digit of integer y is even. + if ((y.d[e] & 1) == 0) s = 1; + + // if x.eq(-1) + if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) { + x.s = s; + return x; + } + } + + // Estimate result exponent. + // x^y = 10^e, where e = y * log10(x) + // log10(x) = log10(x_significand) + x_exponent + // log10(x_significand) = ln(x_significand) / ln(10) + k = mathpow(+x, yn); + e = k == 0 || !isFinite(k) + ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1)) + : new Ctor(k + '').e; + + // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1. + + // Overflow/underflow? + if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0); + + external = false; + Ctor.rounding = x.s = 1; + + // Estimate the extra guard digits needed to ensure five correct rounding digits from + // naturalLogarithm(x). Example of failure without these extra digits (precision: 10): + // new Decimal(2.32456).pow('2087987436534566.46411') + // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815 + k = Math.min(12, (e + '').length); + + // r = x^y = exp(y*ln(x)) + r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr); + + // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40) + if (r.d) { + + // Truncate to the required precision plus five rounding digits. + r = finalise(r, pr + 5, 1); + + // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate + // the result. + if (checkRoundingDigits(r.d, pr, rm)) { + e = pr + 10; + + // Truncate to the increased precision plus five rounding digits. + r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1); + + // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9). + if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) { + r = finalise(r, pr + 1, 0); + } + } + } + + r.s = s; + external = true; + Ctor.rounding = rm; + + return finalise(r, pr, rm); + }; + + + /* + * Return a string representing the value of this Decimal rounded to `sd` significant digits + * using rounding mode `rounding`. + * + * Return exponential notation if `sd` is less than the number of digits necessary to represent + * the integer part of the value in normal notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toPrecision = function (sd, rm) { + var str, + x = this, + Ctor = x.constructor; + + if (sd === void 0) { + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + } else { + checkInt32(sd, 1, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + x = finalise(new Ctor(x), sd, rm); + str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd); + } + + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` + * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if + * omitted. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toSD() digits out of range: {sd}' + * 'toSD() digits not an integer: {sd}' + * 'toSD() rounding mode not an integer: {rm}' + * 'toSD() rounding mode out of range: {rm}' + * + */ + P.toSignificantDigits = P.toSD = function (sd, rm) { + var x = this, + Ctor = x.constructor; + + if (sd === void 0) { + sd = Ctor.precision; + rm = Ctor.rounding; + } else { + checkInt32(sd, 1, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + } + + return finalise(new Ctor(x), sd, rm); + }; + + + /* + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + P.toString = function () { + var x = this, + Ctor = x.constructor, + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal truncated to a whole number. + * + */ + P.truncated = P.trunc = function () { + return finalise(new this.constructor(this), this.e + 1, 1); + }; + + + /* + * Return a string representing the value of this Decimal. + * Unlike `toString`, negative zero will include the minus sign. + * + */ + P.valueOf = P.toJSON = function () { + var x = this, + Ctor = x.constructor, + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + + return x.isNeg() ? '-' + str : str; + }; + + + /* + // Add aliases to match BigDecimal method names. + // P.add = P.plus; + P.subtract = P.minus; + P.multiply = P.times; + P.divide = P.div; + P.remainder = P.mod; + P.compareTo = P.cmp; + P.negate = P.neg; + */ + + + // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers. + + + /* + * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower, + * finiteToString, naturalExponential, naturalLogarithm + * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest, + * P.toPrecision, P.toSignificantDigits, toStringBinary, random + * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm + * convertBase toStringBinary, parseOther + * cos P.cos + * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy, + * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction, + * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm, + * taylorSeries, atan2, parseOther + * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh, + * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus, + * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot, + * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed, + * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits, + * P.truncated, divide, getLn10, getPi, naturalExponential, + * naturalLogarithm, ceil, floor, round, trunc + * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf, + * toStringBinary + * getBase10Exponent P.minus, P.plus, P.times, parseOther + * getLn10 P.logarithm, naturalLogarithm + * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2 + * getPrecision P.precision, P.toFraction + * getZeroString digitsToString, finiteToString + * intPow P.toPower, parseOther + * isOdd toLessThanHalfPi + * maxOrMin max, min + * naturalExponential P.naturalExponential, P.toPower + * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm, + * P.toPower, naturalExponential + * nonFiniteToString finiteToString, toStringBinary + * parseDecimal Decimal + * parseOther Decimal + * sin P.sin + * taylorSeries P.cosh, P.sinh, cos, sin + * toLessThanHalfPi P.cos, P.sin + * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal + * truncate intPow + * + * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi, + * naturalLogarithm, config, parseOther, random, Decimal + */ + + + function digitsToString(d) { + var i, k, ws, + indexOfLastWord = d.length - 1, + str = '', + w = d[0]; + + if (indexOfLastWord > 0) { + str += w; + for (i = 1; i < indexOfLastWord; i++) { + ws = d[i] + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + str += ws; + } + + w = d[i]; + ws = w + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + } else if (w === 0) { + return '0'; + } + + // Remove trailing zeros of last w. + for (; w % 10 === 0;) w /= 10; + + return str + w; + } + + + function checkInt32(i, min, max) { + if (i !== ~~i || i < min || i > max) { + throw Error(invalidArgument + i); + } + } + + + /* + * Check 5 rounding digits if `repeating` is null, 4 otherwise. + * `repeating == null` if caller is `log` or `pow`, + * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`. + */ + function checkRoundingDigits(d, i, rm, repeating) { + var di, k, r, rd; + + // Get the length of the first word of the array d. + for (k = d[0]; k >= 10; k /= 10) --i; + + // Is the rounding digit in the first word of d? + if (--i < 0) { + i += LOG_BASE; + di = 0; + } else { + di = Math.ceil((i + 1) / LOG_BASE); + i %= LOG_BASE; + } + + // i is the index (0 - 6) of the rounding digit. + // E.g. if within the word 3487563 the first rounding digit is 5, + // then i = 4, k = 1000, rd = 3487563 % 1000 = 563 + k = mathpow(10, LOG_BASE - i); + rd = d[di] % k | 0; + + if (repeating == null) { + if (i < 3) { + if (i == 0) rd = rd / 100 | 0; + else if (i == 1) rd = rd / 10 | 0; + r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0; + } else { + r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) && + (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 || + (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0; + } + } else { + if (i < 4) { + if (i == 0) rd = rd / 1000 | 0; + else if (i == 1) rd = rd / 100 | 0; + else if (i == 2) rd = rd / 10 | 0; + r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999; + } else { + r = ((repeating || rm < 4) && rd + 1 == k || + (!repeating && rm > 3) && rd + 1 == k / 2) && + (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1; + } + } + + return r; + } + + + // Convert string of `baseIn` to an array of numbers of `baseOut`. + // Eg. convertBase('255', 10, 16) returns [15, 15]. + // Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. + function convertBase(str, baseIn, baseOut) { + var j, + arr = [0], + arrL, + i = 0, + strL = str.length; + + for (; i < strL;) { + for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn; + arr[0] += NUMERALS.indexOf(str.charAt(i++)); + for (j = 0; j < arr.length; j++) { + if (arr[j] > baseOut - 1) { + if (arr[j + 1] === void 0) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + + /* + * cos(x) = 1 - x^2/2! + x^4/4! - ... + * |x| < pi/2 + * + */ + function cosine(Ctor, x) { + var k, y, + len = x.d.length; + + // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1 + // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1 + + // Estimate the optimum number of times to use the argument reduction. + if (len < 32) { + k = Math.ceil(len / 3); + y = (1 / tinyPow(4, k)).toString(); + } else { + k = 16; + y = '2.3283064365386962890625e-10'; + } + + Ctor.precision += k; + + x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1)); + + // Reverse argument reduction + for (var i = k; i--;) { + var cos2x = x.times(x); + x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1); + } + + Ctor.precision -= k; + + return x; + } + + + /* + * Perform division in the specified base. + */ + var divide = (function () { + + // Assumes non-zero x and k, and hence non-zero result. + function multiplyInteger(x, k, base) { + var temp, + carry = 0, + i = x.length; + + for (x = x.slice(); i--;) { + temp = x[i] * k + carry; + x[i] = temp % base | 0; + carry = temp / base | 0; + } + + if (carry) x.unshift(carry); + + return x; + } + + function compare(a, b, aL, bL) { + var i, r; + + if (aL != bL) { + r = aL > bL ? 1 : -1; + } else { + for (i = r = 0; i < aL; i++) { + if (a[i] != b[i]) { + r = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return r; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1;) a.shift(); + } + + return function (x, y, pr, rm, dp, base) { + var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, + yL, yz, + Ctor = x.constructor, + sign = x.s == y.s ? 1 : -1, + xd = x.d, + yd = y.d; + + // Either NaN, Infinity or 0? + if (!xd || !xd[0] || !yd || !yd[0]) { + + return new Ctor(// Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN : + + // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0. + xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0); + } + + if (base) { + logBase = 1; + e = x.e - y.e; + } else { + base = BASE; + logBase = LOG_BASE; + e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase); + } + + yL = yd.length; + xL = xd.length; + q = new Ctor(sign); + qd = q.d = []; + + // Result exponent may be one less than e. + // The digit array of a Decimal from toStringBinary may have trailing zeros. + for (i = 0; yd[i] == (xd[i] || 0); i++); + + if (yd[i] > (xd[i] || 0)) e--; + + if (pr == null) { + sd = pr = Ctor.precision; + rm = Ctor.rounding; + } else if (dp) { + sd = pr + (x.e - y.e) + 1; + } else { + sd = pr; + } + + if (sd < 0) { + qd.push(1); + more = true; + } else { + + // Convert precision in number of base 10 digits to base 1e7 digits. + sd = sd / logBase + 2 | 0; + i = 0; + + // divisor < 1e7 + if (yL == 1) { + k = 0; + yd = yd[0]; + sd++; + + // k is the carry. + for (; (i < xL || k) && sd--; i++) { + t = k * base + (xd[i] || 0); + qd[i] = t / yd | 0; + k = t % yd | 0; + } + + more = k || i < xL; + + // divisor >= 1e7 + } else { + + // Normalise xd and yd so highest order digit of yd is >= base/2 + k = base / (yd[0] + 1) | 0; + + if (k > 1) { + yd = multiplyInteger(yd, k, base); + xd = multiplyInteger(xd, k, base); + yL = yd.length; + xL = xd.length; + } + + xi = yL; + rem = xd.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL;) rem[remL++] = 0; + + yz = yd.slice(); + yz.unshift(0); + yd0 = yd[0]; + + if (yd[1] >= base / 2) ++yd0; + + do { + k = 0; + + // Compare divisor and remainder. + cmp = compare(yd, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, k. + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // k will be how many times the divisor goes into the current remainder. + k = rem0 / yd0 | 0; + + // Algorithm: + // 1. product = divisor * trial digit (k) + // 2. if product > remainder: product -= divisor, k-- + // 3. remainder -= product + // 4. if product was < remainder at 2: + // 5. compare new remainder and divisor + // 6. If remainder > divisor: remainder -= divisor, k++ + + if (k > 1) { + if (k >= base) k = base - 1; + + // product = divisor * trial digit. + prod = multiplyInteger(yd, k, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + cmp = compare(prod, rem, prodL, remL); + + // product > remainder. + if (cmp == 1) { + k--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yd, prodL, base); + } + } else { + + // cmp is -1. + // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1 + // to avoid it. If k is 1 there is a need to compare yd and rem again below. + if (k == 0) cmp = k = 1; + prod = yd.slice(); + } + + prodL = prod.length; + if (prodL < remL) prod.unshift(0); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + + // If product was < previous remainder. + if (cmp == -1) { + remL = rem.length; + + // Compare divisor and new remainder. + cmp = compare(yd, rem, yL, remL); + + // If divisor < new remainder, subtract divisor from remainder. + if (cmp < 1) { + k++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yd, remL, base); + } + } + + remL = rem.length; + } else if (cmp === 0) { + k++; + rem = [0]; + } // if cmp === 1, k will be 0 + + // Add the next digit, k, to the result array. + qd[i++] = k; + + // Update the remainder. + if (cmp && rem[0]) { + rem[remL++] = xd[xi] || 0; + } else { + rem = [xd[xi]]; + remL = 1; + } + + } while ((xi++ < xL || rem[0] !== void 0) && sd--); + + more = rem[0] !== void 0; + } + + // Leading zero? + if (!qd[0]) qd.shift(); + } + + // logBase is 1 when divide is being used for base conversion. + if (logBase == 1) { + q.e = e; + inexact = more; + } else { + + // To calculate q.e, first get the number of digits of qd[0]. + for (i = 1, k = qd[0]; k >= 10; k /= 10) i++; + q.e = i + e * logBase - 1; + + finalise(q, dp ? pr + q.e + 1 : pr, rm, more); + } + + return q; + }; + })(); + + + /* + * Round `x` to `sd` significant digits using rounding mode `rm`. + * Check for over/under-flow. + */ + function finalise(x, sd, rm, isTruncated) { + var digits, i, j, k, rd, roundUp, w, xd, xdi, + Ctor = x.constructor; + + // Don't round if sd is null or undefined. + out: if (sd != null) { + xd = x.d; + + // Infinity/NaN. + if (!xd) return x; + + // rd: the rounding digit, i.e. the digit after the digit that may be rounded up. + // w: the word of xd containing rd, a base 1e7 number. + // xdi: the index of w within xd. + // digits: the number of digits of w. + // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if + // they had leading zeros) + // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero). + + // Get the length of the first word of the digits array xd. + for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++; + i = sd - digits; + + // Is the rounding digit in the first word of xd? + if (i < 0) { + i += LOG_BASE; + j = sd; + w = xd[xdi = 0]; + + // Get the rounding digit at index j of w. + rd = w / mathpow(10, digits - j - 1) % 10 | 0; + } else { + xdi = Math.ceil((i + 1) / LOG_BASE); + k = xd.length; + if (xdi >= k) { + if (isTruncated) { + + // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`. + for (; k++ <= xdi;) xd.push(0); + w = rd = 0; + digits = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + w = k = xd[xdi]; + + // Get the number of digits of w. + for (digits = 1; k >= 10; k /= 10) digits++; + + // Get the index of rd within w. + i %= LOG_BASE; + + // Get the index of rd within w, adjusted for leading zeros. + // The number of leading zeros of w is given by LOG_BASE - digits. + j = i - LOG_BASE + digits; + + // Get the rounding digit at index j of w. + rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0; + } + } + + // Are there any non-zero digits after the rounding digit? + isTruncated = isTruncated || sd < 0 || + xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1)); + + // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right + // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression + // will give 714. + + roundUp = rm < 4 + ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xd[0]) { + xd.length = 0; + if (roundUp) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE); + x.e = -sd || 0; + } else { + + // Zero. + xd[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xd.length = xdi; + k = 1; + xdi--; + } else { + xd.length = xdi + 1; + k = mathpow(10, LOG_BASE - i); + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of w. + xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0; + } + + if (roundUp) { + for (;;) { + + // Is the digit to be rounded up in the first word of xd? + if (xdi == 0) { + + // i will be the length of xd[0] before k is added. + for (i = 1, j = xd[0]; j >= 10; j /= 10) i++; + j = xd[0] += k; + for (k = 1; j >= 10; j /= 10) k++; + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xd[0] == BASE) xd[0] = 1; + } + + break; + } else { + xd[xdi] += k; + if (xd[xdi] != BASE) break; + xd[xdi--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xd.length; xd[--i] === 0;) xd.pop(); + } + + if (external) { + + // Overflow? + if (x.e > Ctor.maxE) { + + // Infinity. + x.d = null; + x.e = NaN; + + // Underflow? + } else if (x.e < Ctor.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + // Ctor.underflow = true; + } // else Ctor.underflow = false; + } + + return x; + } + + + function finiteToString(x, isExp, sd) { + if (!x.isFinite()) return nonFiniteToString(x); + var k, + e = x.e, + str = digitsToString(x.d), + len = str.length; + + if (isExp) { + if (sd && (k = sd - len) > 0) { + str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k); + } else if (len > 1) { + str = str.charAt(0) + '.' + str.slice(1); + } + + str = str + (x.e < 0 ? 'e' : 'e+') + x.e; + } else if (e < 0) { + str = '0.' + getZeroString(-e - 1) + str; + if (sd && (k = sd - len) > 0) str += getZeroString(k); + } else if (e >= len) { + str += getZeroString(e + 1 - len); + if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k); + } else { + if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k); + if (sd && (k = sd - len) > 0) { + if (e + 1 === len) str += '.'; + str += getZeroString(k); + } + } + + return str; + } + + + // Calculate the base 10 exponent from the base 1e7 exponent. + function getBase10Exponent(digits, e) { + var w = digits[0]; + + // Add the number of digits of the first word of the digits array. + for ( e *= LOG_BASE; w >= 10; w /= 10) e++; + return e; + } + + + function getLn10(Ctor, sd, pr) { + if (sd > LN10_PRECISION) { + + // Reset global state in case the exception is caught. + external = true; + if (pr) Ctor.precision = pr; + throw Error(precisionLimitExceeded); + } + return finalise(new Ctor(LN10), sd, 1, true); + } + + + function getPi(Ctor, sd, rm) { + if (sd > PI_PRECISION) throw Error(precisionLimitExceeded); + return finalise(new Ctor(PI), sd, rm, true); + } + + + function getPrecision(digits) { + var w = digits.length - 1, + len = w * LOG_BASE + 1; + + w = digits[w]; + + // If non-zero... + if (w) { + + // Subtract the number of trailing zeros of the last word. + for (; w % 10 == 0; w /= 10) len--; + + // Add the number of digits of the first word. + for (w = digits[0]; w >= 10; w /= 10) len++; + } + + return len; + } + + + function getZeroString(k) { + var zs = ''; + for (; k--;) zs += '0'; + return zs; + } + + + /* + * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an + * integer of type number. + * + * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`. + * + */ + function intPow(Ctor, x, n, pr) { + var isTruncated, + r = new Ctor(1), + + // Max n of 9007199254740991 takes 53 loop iterations. + // Maximum digits array length; leaves [28, 34] guard digits. + k = Math.ceil(pr / LOG_BASE + 4); + + external = false; + + for (;;) { + if (n % 2) { + r = r.times(x); + if (truncate(r.d, k)) isTruncated = true; + } + + n = mathfloor(n / 2); + if (n === 0) { + + // To ensure correct rounding when r.d is truncated, increment the last word if it is zero. + n = r.d.length - 1; + if (isTruncated && r.d[n] === 0) ++r.d[n]; + break; + } + + x = x.times(x); + truncate(x.d, k); + } + + external = true; + + return r; + } + + + function isOdd(n) { + return n.d[n.d.length - 1] & 1; + } + + + /* + * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'. + */ + function maxOrMin(Ctor, args, ltgt) { + var y, + x = new Ctor(args[0]), + i = 0; + + for (; ++i < args.length;) { + y = new Ctor(args[i]); + if (!y.s) { + x = y; + break; + } else if (x[ltgt](y)) { + x = y; + } + } + + return x; + } + + + /* + * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant + * digits. + * + * Taylor/Maclaurin series. + * + * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ... + * + * Argument reduction: + * Repeat x = x / 32, k += 5, until |x| < 0.1 + * exp(x) = exp(x / 2^k)^(2^k) + * + * Previously, the argument was initially reduced by + * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10) + * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was + * found to be slower than just dividing repeatedly by 32 as above. + * + * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000 + * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000 + * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324) + * + * exp(Infinity) = Infinity + * exp(-Infinity) = 0 + * exp(NaN) = NaN + * exp(±0) = 1 + * + * exp(x) is non-terminating for any finite, non-zero x. + * + * The result will always be correctly rounded. + * + */ + function naturalExponential(x, sd) { + var denominator, guard, j, pow, sum, t, wpr, + rep = 0, + i = 0, + k = 0, + Ctor = x.constructor, + rm = Ctor.rounding, + pr = Ctor.precision; + + // 0/NaN/Infinity? + if (!x.d || !x.d[0] || x.e > 17) { + + return new Ctor(x.d + ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0 + : x.s ? x.s < 0 ? 0 : x : 0 / 0); + } + + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } + + t = new Ctor(0.03125); + + // while abs(x) >= 0.1 + while (x.e > -2) { + + // x = x / 2^5 + x = x.times(t); + k += 5; + } + + // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision + // necessary to ensure the first 4 rounding digits are correct. + guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0; + wpr += guard; + denominator = pow = sum = new Ctor(1); + Ctor.precision = wpr; + + for (;;) { + pow = finalise(pow.times(x), wpr, 1); + denominator = denominator.times(++i); + t = sum.plus(divide(pow, denominator, wpr, 1)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + j = k; + while (j--) sum = finalise(sum.times(sum), wpr, 1); + + // Check to see if the first 4 rounding digits are [49]999. + // If so, repeat the summation with a higher precision, otherwise + // e.g. with precision: 18, rounding: 1 + // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123) + // `wpr - guard` is the index of first rounding digit. + if (sd == null) { + + if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { + Ctor.precision = wpr += 10; + denominator = pow = t = new Ctor(1); + i = 0; + rep++; + } else { + return finalise(sum, Ctor.precision = pr, rm, external = true); + } + } else { + Ctor.precision = pr; + return sum; + } + } + + sum = t; + } + } + + + /* + * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant + * digits. + * + * ln(-n) = NaN + * ln(0) = -Infinity + * ln(-0) = -Infinity + * ln(1) = 0 + * ln(Infinity) = Infinity + * ln(-Infinity) = NaN + * ln(NaN) = NaN + * + * ln(n) (n != 1) is non-terminating. + * + */ + function naturalLogarithm(y, sd) { + var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2, + n = 1, + guard = 10, + x = y, + xd = x.d, + Ctor = x.constructor, + rm = Ctor.rounding, + pr = Ctor.precision; + + // Is x negative or Infinity, NaN, 0 or 1? + if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) { + return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x); + } + + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } + + Ctor.precision = wpr += guard; + c = digitsToString(xd); + c0 = c.charAt(0); + + if (Math.abs(e = x.e) < 1.5e15) { + + // Argument reduction. + // The series converges faster the closer the argument is to 1, so using + // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b + // multiply the argument by itself until the leading digits of the significand are 7, 8, 9, + // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can + // later be divided by this number, then separate out the power of 10 using + // ln(a*10^b) = ln(a) + b*ln(10). + + // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14). + //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) { + // max n is 6 (gives 0.7 - 1.3) + while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) { + x = x.times(y); + c = digitsToString(x.d); + c0 = c.charAt(0); + n++; + } + + e = x.e; + + if (c0 > 1) { + x = new Ctor('0.' + c); + e++; + } else { + x = new Ctor(c0 + '.' + c.slice(1)); + } + } else { + + // The argument reduction method above may result in overflow if the argument y is a massive + // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this + // function using ln(x*10^e) = ln(x) + e*ln(10). + t = getLn10(Ctor, wpr + 2, pr).times(e + ''); + x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t); + Ctor.precision = pr; + + return sd == null ? finalise(x, pr, rm, external = true) : x; + } + + // x1 is x reduced to a value near 1. + x1 = x; + + // Taylor series. + // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...) + // where x = (y - 1)/(y + 1) (|x| < 1) + sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1); + x2 = finalise(x.times(x), wpr, 1); + denominator = 3; + + for (;;) { + numerator = finalise(numerator.times(x2), wpr, 1); + t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + sum = sum.times(2); + + // Reverse the argument reduction. Check that e is not 0 because, besides preventing an + // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0. + if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + '')); + sum = divide(sum, new Ctor(n), wpr, 1); + + // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has + // been repeated previously) and the first 4 rounding digits 9999? + // If so, restart the summation with a higher precision, otherwise + // e.g. with precision: 12, rounding: 1 + // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463. + // `wpr - guard` is the index of first rounding digit. + if (sd == null) { + if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { + Ctor.precision = wpr += guard; + t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1); + x2 = finalise(x.times(x), wpr, 1); + denominator = rep = 1; + } else { + return finalise(sum, Ctor.precision = pr, rm, external = true); + } + } else { + Ctor.precision = pr; + return sum; + } + } + + sum = t; + denominator += 2; + } + } + + + // ±Infinity, NaN. + function nonFiniteToString(x) { + // Unsigned. + return String(x.s * x.s / 0); + } + + + /* + * Parse the value of a new Decimal `x` from string `str`. + */ + function parseDecimal(x, str) { + var e, i, len; + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(len - 1) === 48; --len); + str = str.slice(i, len); + + if (str) { + len -= i; + x.e = e = e - i - 1; + x.d = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first word of the digits array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; + + if (i < len) { + if (i) x.d.push(+str.slice(0, i)); + for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE)); + str = str.slice(i); + i = LOG_BASE - str.length; + } else { + i -= len; + } + + for (; i--;) str += '0'; + x.d.push(+str); + + if (external) { + + // Overflow? + if (x.e > x.constructor.maxE) { + + // Infinity. + x.d = null; + x.e = NaN; + + // Underflow? + } else if (x.e < x.constructor.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + // x.constructor.underflow = true; + } // else x.constructor.underflow = false; + } + } else { + + // Zero. + x.e = 0; + x.d = [0]; + } + + return x; + } + + + /* + * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value. + */ + function parseOther(x, str) { + var base, Ctor, divisor, i, isFloat, len, p, xd, xe; + + if (str === 'Infinity' || str === 'NaN') { + if (!+str) x.s = NaN; + x.e = NaN; + x.d = null; + return x; + } + + if (isHex.test(str)) { + base = 16; + str = str.toLowerCase(); + } else if (isBinary.test(str)) { + base = 2; + } else if (isOctal.test(str)) { + base = 8; + } else { + throw Error(invalidArgument + str); + } + + // Is there a binary exponent part? + i = str.search(/p/i); + + if (i > 0) { + p = +str.slice(i + 1); + str = str.substring(2, i); + } else { + str = str.slice(2); + } + + // Convert `str` as an integer then divide the result by `base` raised to a power such that the + // fraction part will be restored. + i = str.indexOf('.'); + isFloat = i >= 0; + Ctor = x.constructor; + + if (isFloat) { + str = str.replace('.', ''); + len = str.length; + i = len - i; + + // log[10](16) = 1.2041... , log[10](88) = 1.9444.... + divisor = intPow(Ctor, new Ctor(base), i, i * 2); + } + + xd = convertBase(str, base, BASE); + xe = xd.length - 1; + + // Remove trailing zeros. + for (i = xe; xd[i] === 0; --i) xd.pop(); + if (i < 0) return new Ctor(x.s * 0); + x.e = getBase10Exponent(xd, xe); + x.d = xd; + external = false; + + // At what precision to perform the division to ensure exact conversion? + // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount) + // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412 + // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits. + // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount + // Therefore using 4 * the number of digits of str will always be enough. + if (isFloat) x = divide(x, divisor, len * 4); + + // Multiply by the binary exponent part if present. + if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p)); + external = true; + + return x; + } + + + /* + * sin(x) = x - x^3/3! + x^5/5! - ... + * |x| < pi/2 + * + */ + function sine(Ctor, x) { + var k, + len = x.d.length; + + if (len < 3) return taylorSeries(Ctor, 2, x, x); + + // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x) + // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5) + // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20)) + + // Estimate the optimum number of times to use the argument reduction. + k = 1.4 * Math.sqrt(len); + k = k > 16 ? 16 : k | 0; + + x = x.times(1 / tinyPow(5, k)); + x = taylorSeries(Ctor, 2, x, x); + + // Reverse argument reduction + var sin2_x, + d5 = new Ctor(5), + d16 = new Ctor(16), + d20 = new Ctor(20); + for (; k--;) { + sin2_x = x.times(x); + x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20)))); + } + + return x; + } + + + // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`. + function taylorSeries(Ctor, n, x, y, isHyperbolic) { + var j, t, u, x2, + i = 1, + pr = Ctor.precision, + k = Math.ceil(pr / LOG_BASE); + + external = false; + x2 = x.times(x); + u = new Ctor(y); + + for (;;) { + t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1); + u = isHyperbolic ? y.plus(t) : y.minus(t); + y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1); + t = u.plus(y); + + if (t.d[k] !== void 0) { + for (j = k; t.d[j] === u.d[j] && j--;); + if (j == -1) break; + } + + j = u; + u = y; + y = t; + t = j; + i++; + } + + external = true; + t.d.length = k + 1; + + return t; + } + + + // Exponent e must be positive and non-zero. + function tinyPow(b, e) { + var n = b; + while (--e) n *= b; + return n; + } + + + // Return the absolute value of `x` reduced to less than or equal to half pi. + function toLessThanHalfPi(Ctor, x) { + var t, + isNeg = x.s < 0, + pi = getPi(Ctor, Ctor.precision, 1), + halfPi = pi.times(0.5); + + x = x.abs(); + + if (x.lte(halfPi)) { + quadrant = isNeg ? 4 : 1; + return x; + } + + t = x.divToInt(pi); + + if (t.isZero()) { + quadrant = isNeg ? 3 : 2; + } else { + x = x.minus(t.times(pi)); + + // 0 <= x < pi + if (x.lte(halfPi)) { + quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1); + return x; + } + + quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2); + } + + return x.minus(pi).abs(); + } + + + /* + * Return the value of Decimal `x` as a string in base `baseOut`. + * + * If the optional `sd` argument is present include a binary exponent suffix. + */ + function toStringBinary(x, baseOut, sd, rm) { + var base, e, i, k, len, roundUp, str, xd, y, + Ctor = x.constructor, + isExp = sd !== void 0; + + if (isExp) { + checkInt32(sd, 1, MAX_DIGITS); + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + } else { + sd = Ctor.precision; + rm = Ctor.rounding; + } + + if (!x.isFinite()) { + str = nonFiniteToString(x); + } else { + str = finiteToString(x); + i = str.indexOf('.'); + + // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required: + // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10)) + // minBinaryExponent = floor(decimalExponent * log[2](10)) + // log[2](10) = 3.321928094887362347870319429489390175864 + + if (isExp) { + base = 2; + if (baseOut == 16) { + sd = sd * 4 - 3; + } else if (baseOut == 8) { + sd = sd * 3 - 2; + } + } else { + base = baseOut; + } + + // Convert the number as an integer then divide the result by its base raised to a power such + // that the fraction part will be restored. + + // Non-integer. + if (i >= 0) { + str = str.replace('.', ''); + y = new Ctor(1); + y.e = str.length - i; + y.d = convertBase(finiteToString(y), 10, base); + y.e = y.d.length; + } + + xd = convertBase(str, 10, base); + e = len = xd.length; + + // Remove trailing zeros. + for (; xd[--len] == 0;) xd.pop(); + + if (!xd[0]) { + str = isExp ? '0p+0' : '0'; + } else { + if (i < 0) { + e--; + } else { + x = new Ctor(x); + x.d = xd; + x.e = e; + x = divide(x, y, sd, rm, 0, base); + xd = x.d; + e = x.e; + roundUp = inexact; + } + + // The rounding digit, i.e. the digit after the digit that may be rounded up. + i = xd[sd]; + k = base / 2; + roundUp = roundUp || xd[sd + 1] !== void 0; + + roundUp = rm < 4 + ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2)) + : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 || + rm === (x.s < 0 ? 8 : 7)); + + xd.length = sd; + + if (roundUp) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (; ++xd[--sd] > base - 1;) { + xd[sd] = 0; + if (!sd) { + ++e; + xd.unshift(1); + } + } + } + + // Determine trailing zeros. + for (len = xd.length; !xd[len - 1]; --len); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]); + + // Add binary exponent suffix? + if (isExp) { + if (len > 1) { + if (baseOut == 16 || baseOut == 8) { + i = baseOut == 16 ? 4 : 3; + for (--len; len % i; len++) str += '0'; + xd = convertBase(str, base, baseOut); + for (len = xd.length; !xd[len - 1]; --len); + + // xd[0] will always be be 1 + for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]); + } else { + str = str.charAt(0) + '.' + str.slice(1); + } + } + + str = str + (e < 0 ? 'p' : 'p+') + e; + } else if (e < 0) { + for (; ++e;) str = '0' + str; + str = '0.' + str; + } else { + if (++e > len) for (e -= len; e-- ;) str += '0'; + else if (e < len) str = str.slice(0, e) + '.' + str.slice(e); + } + } + + str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str; + } + + return x.s < 0 ? '-' + str : str; + } + + + // Does not strip trailing zeros. + function truncate(arr, len) { + if (arr.length > len) { + arr.length = len; + return true; + } + } + + + // Decimal methods + + + /* + * abs + * acos + * acosh + * add + * asin + * asinh + * atan + * atanh + * atan2 + * cbrt + * ceil + * clone + * config + * cos + * cosh + * div + * exp + * floor + * hypot + * ln + * log + * log2 + * log10 + * max + * min + * mod + * mul + * pow + * random + * round + * set + * sign + * sin + * sinh + * sqrt + * sub + * tan + * tanh + * trunc + */ + + + /* + * Return a new Decimal whose value is the absolute value of `x`. + * + * x {number|string|Decimal} + * + */ + function abs(x) { + return new this(x).abs(); + } + + + /* + * Return a new Decimal whose value is the arccosine in radians of `x`. + * + * x {number|string|Decimal} + * + */ + function acos(x) { + return new this(x).acos(); + } + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function acosh(x) { + return new this(x).acosh(); + } + + + /* + * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function add(x, y) { + return new this(x).plus(y); + } + + + /* + * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function asin(x) { + return new this(x).asin(); + } + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function asinh(x) { + return new this(x).asinh(); + } + + + /* + * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function atan(x) { + return new this(x).atan(); + } + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function atanh(x) { + return new this(x).atanh(); + } + + + /* + * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi + * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi, pi] + * + * y {number|string|Decimal} The y-coordinate. + * x {number|string|Decimal} The x-coordinate. + * + * atan2(±0, -0) = ±pi + * atan2(±0, +0) = ±0 + * atan2(±0, -x) = ±pi for x > 0 + * atan2(±0, x) = ±0 for x > 0 + * atan2(-y, ±0) = -pi/2 for y > 0 + * atan2(y, ±0) = pi/2 for y > 0 + * atan2(±y, -Infinity) = ±pi for finite y > 0 + * atan2(±y, +Infinity) = ±0 for finite y > 0 + * atan2(±Infinity, x) = ±pi/2 for finite x + * atan2(±Infinity, -Infinity) = ±3*pi/4 + * atan2(±Infinity, +Infinity) = ±pi/4 + * atan2(NaN, x) = NaN + * atan2(y, NaN) = NaN + * + */ + function atan2(y, x) { + y = new this(y); + x = new this(x); + var r, + pr = this.precision, + rm = this.rounding, + wpr = pr + 4; + + // Either NaN + if (!y.s || !x.s) { + r = new this(NaN); + + // Both ±Infinity + } else if (!y.d && !x.d) { + r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75); + r.s = y.s; + + // x is ±Infinity or y is ±0 + } else if (!x.d || y.isZero()) { + r = x.s < 0 ? getPi(this, pr, rm) : new this(0); + r.s = y.s; + + // y is ±Infinity or x is ±0 + } else if (!y.d || x.isZero()) { + r = getPi(this, wpr, 1).times(0.5); + r.s = y.s; + + // Both non-zero and finite + } else if (x.s < 0) { + this.precision = wpr; + this.rounding = 1; + r = this.atan(divide(y, x, wpr, 1)); + x = getPi(this, wpr, 1); + this.precision = pr; + this.rounding = rm; + r = y.s < 0 ? r.minus(x) : r.plus(x); + } else { + r = this.atan(divide(y, x, wpr, 1)); + } + + return r; + } + + + /* + * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function cbrt(x) { + return new this(x).cbrt(); + } + + + /* + * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`. + * + * x {number|string|Decimal} + * + */ + function ceil(x) { + return finalise(x = new this(x), x.e + 1, 2); + } + + + /* + * Configure global settings for a Decimal constructor. + * + * `obj` is an object with one or more of the following properties, + * + * precision {number} + * rounding {number} + * toExpNeg {number} + * toExpPos {number} + * maxE {number} + * minE {number} + * modulo {number} + * crypto {boolean|number} + * defaults {true} + * + * E.g. Decimal.config({ precision: 20, rounding: 4 }) + * + */ + function config(obj) { + if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected'); + var i, p, v, + useDefaults = obj.defaults === true, + ps = [ + 'precision', 1, MAX_DIGITS, + 'rounding', 0, 8, + 'toExpNeg', -EXP_LIMIT, 0, + 'toExpPos', 0, EXP_LIMIT, + 'maxE', 0, EXP_LIMIT, + 'minE', -EXP_LIMIT, 0, + 'modulo', 0, 9 + ]; + + for (i = 0; i < ps.length; i += 3) { + if (p = ps[i], useDefaults) this[p] = DEFAULTS[p]; + if ((v = obj[p]) !== void 0) { + if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v; + else throw Error(invalidArgument + p + ': ' + v); + } + } + + if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p]; + if ((v = obj[p]) !== void 0) { + if (v === true || v === false || v === 0 || v === 1) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + this[p] = true; + } else { + throw Error(cryptoUnavailable); + } + } else { + this[p] = false; + } + } else { + throw Error(invalidArgument + p + ': ' + v); + } + } + + return this; + } + + + /* + * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function cos(x) { + return new this(x).cos(); + } + + + /* + * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function cosh(x) { + return new this(x).cosh(); + } + + + /* + * Create and return a Decimal constructor with the same configuration properties as this Decimal + * constructor. + * + */ + function clone(obj) { + var i, p, ps; + + /* + * The Decimal constructor and exported function. + * Return a new Decimal instance. + * + * v {number|string|Decimal} A numeric value. + * + */ + function Decimal(v) { + var e, i, t, + x = this; + + // Decimal called without new. + if (!(x instanceof Decimal)) return new Decimal(v); + + // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor + // which points to Object. + x.constructor = Decimal; + + // Duplicate. + if (v instanceof Decimal) { + x.s = v.s; + + if (external) { + if (!v.d || v.e > Decimal.maxE) { + + // Infinity. + x.e = NaN; + x.d = null; + } else if (v.e < Decimal.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + } else { + x.e = v.e; + x.d = v.d.slice(); + } + } else { + x.e = v.e; + x.d = v.d ? v.d.slice() : v.d; + } + + return; + } + + t = typeof v; + + if (t === 'number') { + if (v === 0) { + x.s = 1 / v < 0 ? -1 : 1; + x.e = 0; + x.d = [0]; + return; + } + + if (v < 0) { + v = -v; + x.s = -1; + } else { + x.s = 1; + } + + // Fast path for small integers. + if (v === ~~v && v < 1e7) { + for (e = 0, i = v; i >= 10; i /= 10) e++; + + if (external) { + if (e > Decimal.maxE) { + x.e = NaN; + x.d = null; + } else if (e < Decimal.minE) { + x.e = 0; + x.d = [0]; + } else { + x.e = e; + x.d = [v]; + } + } else { + x.e = e; + x.d = [v]; + } + + return; + + // Infinity, NaN. + } else if (v * 0 !== 0) { + if (!v) x.s = NaN; + x.e = NaN; + x.d = null; + return; + } + + return parseDecimal(x, v.toString()); + + } else if (t !== 'string') { + throw Error(invalidArgument + v); + } + + // Minus sign? + if ((i = v.charCodeAt(0)) === 45) { + v = v.slice(1); + x.s = -1; + } else { + // Plus sign? + if (i === 43) v = v.slice(1); + x.s = 1; + } + + return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); + } + + Decimal.prototype = P; + + Decimal.ROUND_UP = 0; + Decimal.ROUND_DOWN = 1; + Decimal.ROUND_CEIL = 2; + Decimal.ROUND_FLOOR = 3; + Decimal.ROUND_HALF_UP = 4; + Decimal.ROUND_HALF_DOWN = 5; + Decimal.ROUND_HALF_EVEN = 6; + Decimal.ROUND_HALF_CEIL = 7; + Decimal.ROUND_HALF_FLOOR = 8; + Decimal.EUCLID = 9; + + Decimal.config = Decimal.set = config; + Decimal.clone = clone; + Decimal.isDecimal = isDecimalInstance; + + Decimal.abs = abs; + Decimal.acos = acos; + Decimal.acosh = acosh; // ES6 + Decimal.add = add; + Decimal.asin = asin; + Decimal.asinh = asinh; // ES6 + Decimal.atan = atan; + Decimal.atanh = atanh; // ES6 + Decimal.atan2 = atan2; + Decimal.cbrt = cbrt; // ES6 + Decimal.ceil = ceil; + Decimal.cos = cos; + Decimal.cosh = cosh; // ES6 + Decimal.div = div; + Decimal.exp = exp; + Decimal.floor = floor; + Decimal.hypot = hypot; // ES6 + Decimal.ln = ln; + Decimal.log = log; + Decimal.log10 = log10; // ES6 + Decimal.log2 = log2; // ES6 + Decimal.max = max; + Decimal.min = min; + Decimal.mod = mod; + Decimal.mul = mul; + Decimal.pow = pow; + Decimal.random = random; + Decimal.round = round; + Decimal.sign = sign; // ES6 + Decimal.sin = sin; + Decimal.sinh = sinh; // ES6 + Decimal.sqrt = sqrt; + Decimal.sub = sub; + Decimal.tan = tan; + Decimal.tanh = tanh; // ES6 + Decimal.trunc = trunc; // ES6 + + if (obj === void 0) obj = {}; + if (obj) { + if (obj.defaults !== true) { + ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto']; + for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p]; + } + } + + Decimal.config(obj); + + return Decimal; + } + + + /* + * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function div(x, y) { + return new this(x).div(y); + } + + + /* + * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} The power to which to raise the base of the natural log. + * + */ + function exp(x) { + return new this(x).exp(); + } + + + /* + * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`. + * + * x {number|string|Decimal} + * + */ + function floor(x) { + return finalise(x = new this(x), x.e + 1, 3); + } + + + /* + * Return a new Decimal whose value is the square root of the sum of the squares of the arguments, + * rounded to `precision` significant digits using rounding mode `rounding`. + * + * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...) + * + * arguments {number|string|Decimal} + * + */ + function hypot() { + var i, n, + t = new this(0); + + external = false; + + for (i = 0; i < arguments.length;) { + n = new this(arguments[i++]); + if (!n.d) { + if (n.s) { + external = true; + return new this(1 / 0); + } + t = n; + } else if (t.d) { + t = t.plus(n.times(n)); + } + } + + external = true; + + return t.sqrt(); + } + + + /* + * Return true if object is a Decimal instance (where Decimal is any Decimal constructor), + * otherwise return false. + * + */ + function isDecimalInstance(obj) { + return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false; + } + + + /* + * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function ln(x) { + return new this(x).ln(); + } + + + /* + * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base + * is specified, rounded to `precision` significant digits using rounding mode `rounding`. + * + * log[y](x) + * + * x {number|string|Decimal} The argument of the logarithm. + * y {number|string|Decimal} The base of the logarithm. + * + */ + function log(x, y) { + return new this(x).log(y); + } + + + /* + * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function log2(x) { + return new this(x).log(2); + } + + + /* + * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function log10(x) { + return new this(x).log(10); + } + + + /* + * Return a new Decimal whose value is the maximum of the arguments. + * + * arguments {number|string|Decimal} + * + */ + function max() { + return maxOrMin(this, arguments, 'lt'); + } + + + /* + * Return a new Decimal whose value is the minimum of the arguments. + * + * arguments {number|string|Decimal} + * + */ + function min() { + return maxOrMin(this, arguments, 'gt'); + } + + + /* + * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function mod(x, y) { + return new this(x).mod(y); + } + + + /* + * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function mul(x, y) { + return new this(x).mul(y); + } + + + /* + * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} The base. + * y {number|string|Decimal} The exponent. + * + */ + function pow(x, y) { + return new this(x).pow(y); + } + + + /* + * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with + * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros + * are produced). + * + * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive. + * + */ + function random(sd) { + var d, e, k, n, + i = 0, + r = new this(1), + rd = []; + + if (sd === void 0) sd = this.precision; + else checkInt32(sd, 1, MAX_DIGITS); + + k = Math.ceil(sd / LOG_BASE); + + if (!this.crypto) { + for (; i < k;) rd[i++] = Math.random() * 1e7 | 0; + + // Browsers supporting crypto.getRandomValues. + } else if (crypto.getRandomValues) { + d = crypto.getRandomValues(new Uint32Array(k)); + + for (; i < k;) { + n = d[i]; + + // 0 <= n < 4294967296 + // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865). + if (n >= 4.29e9) { + d[i] = crypto.getRandomValues(new Uint32Array(1))[0]; + } else { + + // 0 <= n <= 4289999999 + // 0 <= (n % 1e7) <= 9999999 + rd[i++] = n % 1e7; + } + } + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + d = crypto.randomBytes(k *= 4); + + for (; i < k;) { + + // 0 <= n < 2147483648 + n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24); + + // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286). + if (n >= 2.14e9) { + crypto.randomBytes(4).copy(d, i); + } else { + + // 0 <= n <= 2139999999 + // 0 <= (n % 1e7) <= 9999999 + rd.push(n % 1e7); + i += 4; + } + } + + i = k / 4; + } else { + throw Error(cryptoUnavailable); + } + + k = rd[--i]; + sd %= LOG_BASE; + + // Convert trailing digits to zeros according to sd. + if (k && sd) { + n = mathpow(10, LOG_BASE - sd); + rd[i] = (k / n | 0) * n; + } + + // Remove trailing words which are zero. + for (; rd[i] === 0; i--) rd.pop(); + + // Zero? + if (i < 0) { + e = 0; + rd = [0]; + } else { + e = -1; + + // Remove leading words which are zero and adjust exponent accordingly. + for (; rd[0] === 0; e -= LOG_BASE) rd.shift(); + + // Count the digits of the first word of rd to determine leading zeros. + for (k = 1, n = rd[0]; n >= 10; n /= 10) k++; + + // Adjust the exponent for leading zeros of the first word of rd. + if (k < LOG_BASE) e -= LOG_BASE - k; + } + + r.e = e; + r.d = rd; + + return r; + } + + + /* + * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`. + * + * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL). + * + * x {number|string|Decimal} + * + */ + function round(x) { + return finalise(x = new this(x), x.e + 1, this.rounding); + } + + + /* + * Return + * 1 if x > 0, + * -1 if x < 0, + * 0 if x is 0, + * -0 if x is -0, + * NaN otherwise + * + * x {number|string|Decimal} + * + */ + function sign(x) { + x = new this(x); + return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN; + } + + + /* + * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function sin(x) { + return new this(x).sin(); + } + + + /* + * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function sinh(x) { + return new this(x).sinh(); + } + + + /* + * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function sqrt(x) { + return new this(x).sqrt(); + } + + + /* + * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function sub(x, y) { + return new this(x).sub(y); + } + + + /* + * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function tan(x) { + return new this(x).tan(); + } + + + /* + * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function tanh(x) { + return new this(x).tanh(); + } + + + /* + * Return a new Decimal whose value is `x` truncated to an integer. + * + * x {number|string|Decimal} + * + */ + function trunc(x) { + return finalise(x = new this(x), x.e + 1, 1); + } + + + // Create and configure initial Decimal constructor. + Decimal = clone(DEFAULTS); + + Decimal['default'] = Decimal.Decimal = Decimal; + + // Create the internal constants from their string values. + LN10 = new Decimal(LN10); + PI = new Decimal(PI); + + + // Export. + + + // AMD. + if (true) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { + return Decimal; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + // Node and other environments that support module.exports. + } else {} +})(this); + + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// Map the characters to escape to their escaped values. The list is derived +// from http://www.cespedes.org/blog/85/how-to-escape-latex-special-characters + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var defaultEscapes = { + "{": "\\{", + "}": "\\}", + "\\": "\\textbackslash{}", + "#": "\\#", + $: "\\$", + "%": "\\%", + "&": "\\&", + "^": "\\textasciicircum{}", + _: "\\_", + "~": "\\textasciitilde{}" +}; +var formatEscapes = { + "\u2013": "\\--", + "\u2014": "\\---", + " ": "~", + "\t": "\\qquad{}", + "\r\n": "\\newline{}", + "\n": "\\newline{}" +}; + +var defaultEscapeMapFn = function defaultEscapeMapFn(defaultEscapes, formatEscapes) { + return _extends({}, defaultEscapes, formatEscapes); +}; + +/** + * Escape a string to be used in LaTeX documents. + * @param {string} str the string to be escaped. + * @param {boolean} params.preserveFormatting whether formatting escapes should + * be performed (default: false). + * @param {function} params.escapeMapFn the function to modify the escape maps. + * @return {string} the escaped string, ready to be used in LaTeX. + */ +module.exports = function (str) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$preserveFormatti = _ref.preserveFormatting, + preserveFormatting = _ref$preserveFormatti === undefined ? false : _ref$preserveFormatti, + _ref$escapeMapFn = _ref.escapeMapFn, + escapeMapFn = _ref$escapeMapFn === undefined ? defaultEscapeMapFn : _ref$escapeMapFn; + + var runningStr = String(str); + var result = ""; + + var escapes = escapeMapFn(_extends({}, defaultEscapes), preserveFormatting ? _extends({}, formatEscapes) : {}); + var escapeKeys = Object.keys(escapes); // as it is reused later on + + // Algorithm: Go through the string character by character, if it matches + // with one of the special characters then we'll replace it with the escaped + // version. + + var _loop = function _loop() { + var specialCharFound = false; + escapeKeys.forEach(function (key, index) { + if (specialCharFound) { + return; + } + if (runningStr.length >= key.length && runningStr.slice(0, key.length) === key) { + result += escapes[escapeKeys[index]]; + runningStr = runningStr.slice(key.length, runningStr.length); + specialCharFound = true; + } + }); + if (!specialCharFound) { + result += runningStr.slice(0, 1); + runningStr = runningStr.slice(1, runningStr.length); + } + }; + + while (runningStr) { + _loop(); + } + return result; +}; + +/***/ }), +/* 18 */ +/***/ (function(module, exports) { + +function E () { + // Keep this empty so it's easier to inherit from + // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3) +} + +E.prototype = { + on: function (name, callback, ctx) { + var e = this.e || (this.e = {}); + + (e[name] || (e[name] = [])).push({ + fn: callback, + ctx: ctx + }); + + return this; + }, + + once: function (name, callback, ctx) { + var self = this; + function listener () { + self.off(name, listener); + callback.apply(ctx, arguments); + }; + + listener._ = callback + return this.on(name, listener, ctx); + }, + + emit: function (name) { + var data = [].slice.call(arguments, 1); + var evtArr = ((this.e || (this.e = {}))[name] || []).slice(); + var i = 0; + var len = evtArr.length; + + for (i; i < len; i++) { + evtArr[i].fn.apply(evtArr[i].ctx, data); + } + + return this; + }, + + off: function (name, callback) { + var e = this.e || (this.e = {}); + var evts = e[name]; + var liveEvents = []; + + if (evts && callback) { + for (var i = 0, len = evts.length; i < len; i++) { + if (evts[i].fn !== callback && evts[i].fn._ !== callback) + liveEvents.push(evts[i]); + } + } + + // Remove event from queue to prevent memory leak + // Suggested by https://github.com/lazd + // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910 + + (liveEvents.length) + ? e[name] = liveEvents + : delete e[name]; + + return this; + } +}; + +module.exports = E; +module.exports.TinyEmitter = E; + + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +var all = __webpack_require__(21); + +var _require = __webpack_require__(22), + create = _require.create; + +var defaultInstance = create(all); // TODO: not nice having to revert to CommonJS, find an ES6 solution + +module.exports = /* #__PURE__ */defaultInstance; + +/***/ }), +/* 20 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || new Function("return this")(); +} catch (e) { + // This works if the window reference is available + if (typeof window === "object") g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 21 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, "createTyped", function() { return /* reexport */ typed_createTyped; }); +__webpack_require__.d(__webpack_exports__, "createResultSet", function() { return /* reexport */ createResultSet; }); +__webpack_require__.d(__webpack_exports__, "createBigNumberClass", function() { return /* reexport */ createBigNumberClass; }); +__webpack_require__.d(__webpack_exports__, "createComplexClass", function() { return /* reexport */ createComplexClass; }); +__webpack_require__.d(__webpack_exports__, "createFractionClass", function() { return /* reexport */ createFractionClass; }); +__webpack_require__.d(__webpack_exports__, "createRangeClass", function() { return /* reexport */ createRangeClass; }); +__webpack_require__.d(__webpack_exports__, "createMatrixClass", function() { return /* reexport */ createMatrixClass; }); +__webpack_require__.d(__webpack_exports__, "createDenseMatrixClass", function() { return /* reexport */ createDenseMatrixClass; }); +__webpack_require__.d(__webpack_exports__, "createClone", function() { return /* reexport */ createClone; }); +__webpack_require__.d(__webpack_exports__, "createIsInteger", function() { return /* reexport */ createIsInteger; }); +__webpack_require__.d(__webpack_exports__, "createIsNegative", function() { return /* reexport */ createIsNegative; }); +__webpack_require__.d(__webpack_exports__, "createIsNumeric", function() { return /* reexport */ createIsNumeric; }); +__webpack_require__.d(__webpack_exports__, "createHasNumericValue", function() { return /* reexport */ createHasNumericValue; }); +__webpack_require__.d(__webpack_exports__, "createIsPositive", function() { return /* reexport */ createIsPositive; }); +__webpack_require__.d(__webpack_exports__, "createIsZero", function() { return /* reexport */ createIsZero; }); +__webpack_require__.d(__webpack_exports__, "createIsNaN", function() { return /* reexport */ createIsNaN; }); +__webpack_require__.d(__webpack_exports__, "createTypeOf", function() { return /* reexport */ createTypeOf; }); +__webpack_require__.d(__webpack_exports__, "createDeprecatedTypeof", function() { return /* reexport */ createDeprecatedTypeof; }); +__webpack_require__.d(__webpack_exports__, "createEqualScalar", function() { return /* reexport */ createEqualScalar; }); +__webpack_require__.d(__webpack_exports__, "createSparseMatrixClass", function() { return /* reexport */ createSparseMatrixClass; }); +__webpack_require__.d(__webpack_exports__, "createNumber", function() { return /* reexport */ createNumber; }); +__webpack_require__.d(__webpack_exports__, "createString", function() { return /* reexport */ createString; }); +__webpack_require__.d(__webpack_exports__, "createBoolean", function() { return /* reexport */ createBoolean; }); +__webpack_require__.d(__webpack_exports__, "createBignumber", function() { return /* reexport */ createBignumber; }); +__webpack_require__.d(__webpack_exports__, "createComplex", function() { return /* reexport */ createComplex; }); +__webpack_require__.d(__webpack_exports__, "createFraction", function() { return /* reexport */ createFraction; }); +__webpack_require__.d(__webpack_exports__, "createMatrix", function() { return /* reexport */ createMatrix; }); +__webpack_require__.d(__webpack_exports__, "createSplitUnit", function() { return /* reexport */ createSplitUnit; }); +__webpack_require__.d(__webpack_exports__, "createUnaryMinus", function() { return /* reexport */ createUnaryMinus; }); +__webpack_require__.d(__webpack_exports__, "createUnaryPlus", function() { return /* reexport */ createUnaryPlus; }); +__webpack_require__.d(__webpack_exports__, "createAbs", function() { return /* reexport */ createAbs; }); +__webpack_require__.d(__webpack_exports__, "createApply", function() { return /* reexport */ createApply; }); +__webpack_require__.d(__webpack_exports__, "createAddScalar", function() { return /* reexport */ createAddScalar; }); +__webpack_require__.d(__webpack_exports__, "createCbrt", function() { return /* reexport */ createCbrt; }); +__webpack_require__.d(__webpack_exports__, "createCeil", function() { return /* reexport */ createCeil; }); +__webpack_require__.d(__webpack_exports__, "createCube", function() { return /* reexport */ createCube; }); +__webpack_require__.d(__webpack_exports__, "createExp", function() { return /* reexport */ createExp; }); +__webpack_require__.d(__webpack_exports__, "createExpm1", function() { return /* reexport */ createExpm1; }); +__webpack_require__.d(__webpack_exports__, "createFix", function() { return /* reexport */ createFix; }); +__webpack_require__.d(__webpack_exports__, "createFloor", function() { return /* reexport */ createFloor; }); +__webpack_require__.d(__webpack_exports__, "createGcd", function() { return /* reexport */ createGcd; }); +__webpack_require__.d(__webpack_exports__, "createLcm", function() { return /* reexport */ createLcm; }); +__webpack_require__.d(__webpack_exports__, "createLog10", function() { return /* reexport */ createLog10; }); +__webpack_require__.d(__webpack_exports__, "createLog2", function() { return /* reexport */ createLog2; }); +__webpack_require__.d(__webpack_exports__, "createMod", function() { return /* reexport */ createMod; }); +__webpack_require__.d(__webpack_exports__, "createMultiplyScalar", function() { return /* reexport */ createMultiplyScalar; }); +__webpack_require__.d(__webpack_exports__, "createMultiply", function() { return /* reexport */ createMultiply; }); +__webpack_require__.d(__webpack_exports__, "createNthRoot", function() { return /* reexport */ createNthRoot; }); +__webpack_require__.d(__webpack_exports__, "createSign", function() { return /* reexport */ createSign; }); +__webpack_require__.d(__webpack_exports__, "createSqrt", function() { return /* reexport */ createSqrt; }); +__webpack_require__.d(__webpack_exports__, "createSquare", function() { return /* reexport */ createSquare; }); +__webpack_require__.d(__webpack_exports__, "createSubtract", function() { return /* reexport */ createSubtract; }); +__webpack_require__.d(__webpack_exports__, "createXgcd", function() { return /* reexport */ createXgcd; }); +__webpack_require__.d(__webpack_exports__, "createDotMultiply", function() { return /* reexport */ createDotMultiply; }); +__webpack_require__.d(__webpack_exports__, "createBitAnd", function() { return /* reexport */ createBitAnd; }); +__webpack_require__.d(__webpack_exports__, "createBitNot", function() { return /* reexport */ createBitNot; }); +__webpack_require__.d(__webpack_exports__, "createBitOr", function() { return /* reexport */ createBitOr; }); +__webpack_require__.d(__webpack_exports__, "createBitXor", function() { return /* reexport */ createBitXor; }); +__webpack_require__.d(__webpack_exports__, "createArg", function() { return /* reexport */ createArg; }); +__webpack_require__.d(__webpack_exports__, "createConj", function() { return /* reexport */ createConj; }); +__webpack_require__.d(__webpack_exports__, "createIm", function() { return /* reexport */ createIm; }); +__webpack_require__.d(__webpack_exports__, "createRe", function() { return /* reexport */ createRe; }); +__webpack_require__.d(__webpack_exports__, "createNot", function() { return /* reexport */ createNot; }); +__webpack_require__.d(__webpack_exports__, "createOr", function() { return /* reexport */ createOr; }); +__webpack_require__.d(__webpack_exports__, "createXor", function() { return /* reexport */ createXor; }); +__webpack_require__.d(__webpack_exports__, "createConcat", function() { return /* reexport */ createConcat; }); +__webpack_require__.d(__webpack_exports__, "createColumn", function() { return /* reexport */ createColumn; }); +__webpack_require__.d(__webpack_exports__, "createCross", function() { return /* reexport */ createCross; }); +__webpack_require__.d(__webpack_exports__, "createDiag", function() { return /* reexport */ createDiag; }); +__webpack_require__.d(__webpack_exports__, "createEye", function() { return /* reexport */ createEye; }); +__webpack_require__.d(__webpack_exports__, "createFilter", function() { return /* reexport */ createFilter; }); +__webpack_require__.d(__webpack_exports__, "createFlatten", function() { return /* reexport */ createFlatten; }); +__webpack_require__.d(__webpack_exports__, "createForEach", function() { return /* reexport */ createForEach; }); +__webpack_require__.d(__webpack_exports__, "createGetMatrixDataType", function() { return /* reexport */ createGetMatrixDataType; }); +__webpack_require__.d(__webpack_exports__, "createIdentity", function() { return /* reexport */ createIdentity; }); +__webpack_require__.d(__webpack_exports__, "createKron", function() { return /* reexport */ createKron; }); +__webpack_require__.d(__webpack_exports__, "createMap", function() { return /* reexport */ createMap; }); +__webpack_require__.d(__webpack_exports__, "createOnes", function() { return /* reexport */ createOnes; }); +__webpack_require__.d(__webpack_exports__, "createRange", function() { return /* reexport */ range_createRange; }); +__webpack_require__.d(__webpack_exports__, "createReshape", function() { return /* reexport */ createReshape; }); +__webpack_require__.d(__webpack_exports__, "createResize", function() { return /* reexport */ createResize; }); +__webpack_require__.d(__webpack_exports__, "createRow", function() { return /* reexport */ createRow; }); +__webpack_require__.d(__webpack_exports__, "createSize", function() { return /* reexport */ createSize; }); +__webpack_require__.d(__webpack_exports__, "createSqueeze", function() { return /* reexport */ createSqueeze; }); +__webpack_require__.d(__webpack_exports__, "createSubset", function() { return /* reexport */ createSubset; }); +__webpack_require__.d(__webpack_exports__, "createTranspose", function() { return /* reexport */ createTranspose; }); +__webpack_require__.d(__webpack_exports__, "createCtranspose", function() { return /* reexport */ createCtranspose; }); +__webpack_require__.d(__webpack_exports__, "createZeros", function() { return /* reexport */ createZeros; }); +__webpack_require__.d(__webpack_exports__, "createErf", function() { return /* reexport */ createErf; }); +__webpack_require__.d(__webpack_exports__, "createMode", function() { return /* reexport */ createMode; }); +__webpack_require__.d(__webpack_exports__, "createProd", function() { return /* reexport */ createProd; }); +__webpack_require__.d(__webpack_exports__, "createFormat", function() { return /* reexport */ createFormat; }); +__webpack_require__.d(__webpack_exports__, "createPrint", function() { return /* reexport */ createPrint; }); +__webpack_require__.d(__webpack_exports__, "createTo", function() { return /* reexport */ createTo; }); +__webpack_require__.d(__webpack_exports__, "createIsPrime", function() { return /* reexport */ createIsPrime; }); +__webpack_require__.d(__webpack_exports__, "createNumeric", function() { return /* reexport */ createNumeric; }); +__webpack_require__.d(__webpack_exports__, "createDivideScalar", function() { return /* reexport */ createDivideScalar; }); +__webpack_require__.d(__webpack_exports__, "createPow", function() { return /* reexport */ createPow; }); +__webpack_require__.d(__webpack_exports__, "createRound", function() { return /* reexport */ createRound; }); +__webpack_require__.d(__webpack_exports__, "createLog", function() { return /* reexport */ createLog; }); +__webpack_require__.d(__webpack_exports__, "createLog1p", function() { return /* reexport */ createLog1p; }); +__webpack_require__.d(__webpack_exports__, "createNthRoots", function() { return /* reexport */ createNthRoots; }); +__webpack_require__.d(__webpack_exports__, "createDotPow", function() { return /* reexport */ createDotPow; }); +__webpack_require__.d(__webpack_exports__, "createDotDivide", function() { return /* reexport */ createDotDivide; }); +__webpack_require__.d(__webpack_exports__, "createLsolve", function() { return /* reexport */ createLsolve; }); +__webpack_require__.d(__webpack_exports__, "createUsolve", function() { return /* reexport */ createUsolve; }); +__webpack_require__.d(__webpack_exports__, "createLeftShift", function() { return /* reexport */ createLeftShift; }); +__webpack_require__.d(__webpack_exports__, "createRightArithShift", function() { return /* reexport */ createRightArithShift; }); +__webpack_require__.d(__webpack_exports__, "createRightLogShift", function() { return /* reexport */ createRightLogShift; }); +__webpack_require__.d(__webpack_exports__, "createAnd", function() { return /* reexport */ createAnd; }); +__webpack_require__.d(__webpack_exports__, "createCompare", function() { return /* reexport */ createCompare; }); +__webpack_require__.d(__webpack_exports__, "createCompareNatural", function() { return /* reexport */ createCompareNatural; }); +__webpack_require__.d(__webpack_exports__, "createCompareText", function() { return /* reexport */ createCompareText; }); +__webpack_require__.d(__webpack_exports__, "createEqual", function() { return /* reexport */ createEqual; }); +__webpack_require__.d(__webpack_exports__, "createEqualText", function() { return /* reexport */ createEqualText; }); +__webpack_require__.d(__webpack_exports__, "createSmaller", function() { return /* reexport */ createSmaller; }); +__webpack_require__.d(__webpack_exports__, "createSmallerEq", function() { return /* reexport */ createSmallerEq; }); +__webpack_require__.d(__webpack_exports__, "createLarger", function() { return /* reexport */ createLarger; }); +__webpack_require__.d(__webpack_exports__, "createLargerEq", function() { return /* reexport */ createLargerEq; }); +__webpack_require__.d(__webpack_exports__, "createDeepEqual", function() { return /* reexport */ createDeepEqual; }); +__webpack_require__.d(__webpack_exports__, "createUnequal", function() { return /* reexport */ createUnequal; }); +__webpack_require__.d(__webpack_exports__, "createPartitionSelect", function() { return /* reexport */ createPartitionSelect; }); +__webpack_require__.d(__webpack_exports__, "createSort", function() { return /* reexport */ createSort; }); +__webpack_require__.d(__webpack_exports__, "createMax", function() { return /* reexport */ createMax; }); +__webpack_require__.d(__webpack_exports__, "createMin", function() { return /* reexport */ createMin; }); +__webpack_require__.d(__webpack_exports__, "createImmutableDenseMatrixClass", function() { return /* reexport */ createImmutableDenseMatrixClass; }); +__webpack_require__.d(__webpack_exports__, "createIndexClass", function() { return /* reexport */ createIndexClass; }); +__webpack_require__.d(__webpack_exports__, "createFibonacciHeapClass", function() { return /* reexport */ createFibonacciHeapClass; }); +__webpack_require__.d(__webpack_exports__, "createSpaClass", function() { return /* reexport */ createSpaClass; }); +__webpack_require__.d(__webpack_exports__, "createUnitClass", function() { return /* reexport */ createUnitClass; }); +__webpack_require__.d(__webpack_exports__, "createUnitFunction", function() { return /* reexport */ createUnitFunction; }); +__webpack_require__.d(__webpack_exports__, "createSparse", function() { return /* reexport */ createSparse; }); +__webpack_require__.d(__webpack_exports__, "createCreateUnit", function() { return /* reexport */ createCreateUnit; }); +__webpack_require__.d(__webpack_exports__, "createAcos", function() { return /* reexport */ createAcos; }); +__webpack_require__.d(__webpack_exports__, "createAcosh", function() { return /* reexport */ createAcosh; }); +__webpack_require__.d(__webpack_exports__, "createAcot", function() { return /* reexport */ createAcot; }); +__webpack_require__.d(__webpack_exports__, "createAcoth", function() { return /* reexport */ createAcoth; }); +__webpack_require__.d(__webpack_exports__, "createAcsc", function() { return /* reexport */ createAcsc; }); +__webpack_require__.d(__webpack_exports__, "createAcsch", function() { return /* reexport */ createAcsch; }); +__webpack_require__.d(__webpack_exports__, "createAsec", function() { return /* reexport */ createAsec; }); +__webpack_require__.d(__webpack_exports__, "createAsech", function() { return /* reexport */ createAsech; }); +__webpack_require__.d(__webpack_exports__, "createAsin", function() { return /* reexport */ createAsin; }); +__webpack_require__.d(__webpack_exports__, "createAsinh", function() { return /* reexport */ createAsinh; }); +__webpack_require__.d(__webpack_exports__, "createAtan", function() { return /* reexport */ createAtan; }); +__webpack_require__.d(__webpack_exports__, "createAtan2", function() { return /* reexport */ createAtan2; }); +__webpack_require__.d(__webpack_exports__, "createAtanh", function() { return /* reexport */ createAtanh; }); +__webpack_require__.d(__webpack_exports__, "createCos", function() { return /* reexport */ createCos; }); +__webpack_require__.d(__webpack_exports__, "createCosh", function() { return /* reexport */ createCosh; }); +__webpack_require__.d(__webpack_exports__, "createCot", function() { return /* reexport */ createCot; }); +__webpack_require__.d(__webpack_exports__, "createCoth", function() { return /* reexport */ createCoth; }); +__webpack_require__.d(__webpack_exports__, "createCsc", function() { return /* reexport */ createCsc; }); +__webpack_require__.d(__webpack_exports__, "createCsch", function() { return /* reexport */ createCsch; }); +__webpack_require__.d(__webpack_exports__, "createSec", function() { return /* reexport */ createSec; }); +__webpack_require__.d(__webpack_exports__, "createSech", function() { return /* reexport */ createSech; }); +__webpack_require__.d(__webpack_exports__, "createSin", function() { return /* reexport */ createSin; }); +__webpack_require__.d(__webpack_exports__, "createSinh", function() { return /* reexport */ createSinh; }); +__webpack_require__.d(__webpack_exports__, "createTan", function() { return /* reexport */ createTan; }); +__webpack_require__.d(__webpack_exports__, "createTanh", function() { return /* reexport */ createTanh; }); +__webpack_require__.d(__webpack_exports__, "createSetCartesian", function() { return /* reexport */ createSetCartesian; }); +__webpack_require__.d(__webpack_exports__, "createSetDifference", function() { return /* reexport */ createSetDifference; }); +__webpack_require__.d(__webpack_exports__, "createSetDistinct", function() { return /* reexport */ createSetDistinct; }); +__webpack_require__.d(__webpack_exports__, "createSetIntersect", function() { return /* reexport */ createSetIntersect; }); +__webpack_require__.d(__webpack_exports__, "createSetIsSubset", function() { return /* reexport */ createSetIsSubset; }); +__webpack_require__.d(__webpack_exports__, "createSetMultiplicity", function() { return /* reexport */ createSetMultiplicity; }); +__webpack_require__.d(__webpack_exports__, "createSetPowerset", function() { return /* reexport */ createSetPowerset; }); +__webpack_require__.d(__webpack_exports__, "createSetSize", function() { return /* reexport */ createSetSize; }); +__webpack_require__.d(__webpack_exports__, "createSetSymDifference", function() { return /* reexport */ createSetSymDifference; }); +__webpack_require__.d(__webpack_exports__, "createSetUnion", function() { return /* reexport */ createSetUnion; }); +__webpack_require__.d(__webpack_exports__, "createAdd", function() { return /* reexport */ createAdd; }); +__webpack_require__.d(__webpack_exports__, "createHypot", function() { return /* reexport */ createHypot; }); +__webpack_require__.d(__webpack_exports__, "createNorm", function() { return /* reexport */ createNorm; }); +__webpack_require__.d(__webpack_exports__, "createDot", function() { return /* reexport */ createDot; }); +__webpack_require__.d(__webpack_exports__, "createTrace", function() { return /* reexport */ createTrace; }); +__webpack_require__.d(__webpack_exports__, "createIndex", function() { return /* reexport */ createIndex; }); +__webpack_require__.d(__webpack_exports__, "createNode", function() { return /* reexport */ createNode; }); +__webpack_require__.d(__webpack_exports__, "createAccessorNode", function() { return /* reexport */ createAccessorNode; }); +__webpack_require__.d(__webpack_exports__, "createArrayNode", function() { return /* reexport */ createArrayNode; }); +__webpack_require__.d(__webpack_exports__, "createAssignmentNode", function() { return /* reexport */ createAssignmentNode; }); +__webpack_require__.d(__webpack_exports__, "createBlockNode", function() { return /* reexport */ createBlockNode; }); +__webpack_require__.d(__webpack_exports__, "createConditionalNode", function() { return /* reexport */ createConditionalNode; }); +__webpack_require__.d(__webpack_exports__, "createConstantNode", function() { return /* reexport */ ConstantNode_createConstantNode; }); +__webpack_require__.d(__webpack_exports__, "createFunctionAssignmentNode", function() { return /* reexport */ createFunctionAssignmentNode; }); +__webpack_require__.d(__webpack_exports__, "createIndexNode", function() { return /* reexport */ createIndexNode; }); +__webpack_require__.d(__webpack_exports__, "createObjectNode", function() { return /* reexport */ createObjectNode; }); +__webpack_require__.d(__webpack_exports__, "createOperatorNode", function() { return /* reexport */ createOperatorNode; }); +__webpack_require__.d(__webpack_exports__, "createParenthesisNode", function() { return /* reexport */ createParenthesisNode; }); +__webpack_require__.d(__webpack_exports__, "createRangeNode", function() { return /* reexport */ createRangeNode; }); +__webpack_require__.d(__webpack_exports__, "createRelationalNode", function() { return /* reexport */ createRelationalNode; }); +__webpack_require__.d(__webpack_exports__, "createSymbolNode", function() { return /* reexport */ createSymbolNode; }); +__webpack_require__.d(__webpack_exports__, "createFunctionNode", function() { return /* reexport */ createFunctionNode; }); +__webpack_require__.d(__webpack_exports__, "createParse", function() { return /* reexport */ createParse; }); +__webpack_require__.d(__webpack_exports__, "createCompile", function() { return /* reexport */ createCompile; }); +__webpack_require__.d(__webpack_exports__, "createEvaluate", function() { return /* reexport */ createEvaluate; }); +__webpack_require__.d(__webpack_exports__, "createDeprecatedEval", function() { return /* reexport */ createDeprecatedEval; }); +__webpack_require__.d(__webpack_exports__, "createParserClass", function() { return /* reexport */ createParserClass; }); +__webpack_require__.d(__webpack_exports__, "createParser", function() { return /* reexport */ createParser; }); +__webpack_require__.d(__webpack_exports__, "createLup", function() { return /* reexport */ createLup; }); +__webpack_require__.d(__webpack_exports__, "createQr", function() { return /* reexport */ createQr; }); +__webpack_require__.d(__webpack_exports__, "createSlu", function() { return /* reexport */ createSlu; }); +__webpack_require__.d(__webpack_exports__, "createLusolve", function() { return /* reexport */ createLusolve; }); +__webpack_require__.d(__webpack_exports__, "createHelpClass", function() { return /* reexport */ createHelpClass; }); +__webpack_require__.d(__webpack_exports__, "createChainClass", function() { return /* reexport */ createChainClass; }); +__webpack_require__.d(__webpack_exports__, "createHelp", function() { return /* reexport */ createHelp; }); +__webpack_require__.d(__webpack_exports__, "createChain", function() { return /* reexport */ createChain; }); +__webpack_require__.d(__webpack_exports__, "createDet", function() { return /* reexport */ createDet; }); +__webpack_require__.d(__webpack_exports__, "createInv", function() { return /* reexport */ createInv; }); +__webpack_require__.d(__webpack_exports__, "createEigs", function() { return /* reexport */ createEigs; }); +__webpack_require__.d(__webpack_exports__, "createExpm", function() { return /* reexport */ createExpm; }); +__webpack_require__.d(__webpack_exports__, "createSqrtm", function() { return /* reexport */ createSqrtm; }); +__webpack_require__.d(__webpack_exports__, "createDivide", function() { return /* reexport */ createDivide; }); +__webpack_require__.d(__webpack_exports__, "createDistance", function() { return /* reexport */ createDistance; }); +__webpack_require__.d(__webpack_exports__, "createIntersect", function() { return /* reexport */ createIntersect; }); +__webpack_require__.d(__webpack_exports__, "createSum", function() { return /* reexport */ createSum; }); +__webpack_require__.d(__webpack_exports__, "createMean", function() { return /* reexport */ createMean; }); +__webpack_require__.d(__webpack_exports__, "createMedian", function() { return /* reexport */ createMedian; }); +__webpack_require__.d(__webpack_exports__, "createMad", function() { return /* reexport */ createMad; }); +__webpack_require__.d(__webpack_exports__, "createVariance", function() { return /* reexport */ createVariance; }); +__webpack_require__.d(__webpack_exports__, "createDeprecatedVar", function() { return /* reexport */ createDeprecatedVar; }); +__webpack_require__.d(__webpack_exports__, "createQuantileSeq", function() { return /* reexport */ createQuantileSeq; }); +__webpack_require__.d(__webpack_exports__, "createStd", function() { return /* reexport */ createStd; }); +__webpack_require__.d(__webpack_exports__, "createCombinations", function() { return /* reexport */ createCombinations; }); +__webpack_require__.d(__webpack_exports__, "createCombinationsWithRep", function() { return /* reexport */ createCombinationsWithRep; }); +__webpack_require__.d(__webpack_exports__, "createGamma", function() { return /* reexport */ createGamma; }); +__webpack_require__.d(__webpack_exports__, "createFactorial", function() { return /* reexport */ createFactorial; }); +__webpack_require__.d(__webpack_exports__, "createKldivergence", function() { return /* reexport */ createKldivergence; }); +__webpack_require__.d(__webpack_exports__, "createMultinomial", function() { return /* reexport */ createMultinomial; }); +__webpack_require__.d(__webpack_exports__, "createPermutations", function() { return /* reexport */ createPermutations; }); +__webpack_require__.d(__webpack_exports__, "createPickRandom", function() { return /* reexport */ createPickRandom; }); +__webpack_require__.d(__webpack_exports__, "createRandom", function() { return /* reexport */ createRandom; }); +__webpack_require__.d(__webpack_exports__, "createRandomInt", function() { return /* reexport */ createRandomInt; }); +__webpack_require__.d(__webpack_exports__, "createStirlingS2", function() { return /* reexport */ createStirlingS2; }); +__webpack_require__.d(__webpack_exports__, "createBellNumbers", function() { return /* reexport */ createBellNumbers; }); +__webpack_require__.d(__webpack_exports__, "createCatalan", function() { return /* reexport */ createCatalan; }); +__webpack_require__.d(__webpack_exports__, "createComposition", function() { return /* reexport */ createComposition; }); +__webpack_require__.d(__webpack_exports__, "createSimplify", function() { return /* reexport */ createSimplify; }); +__webpack_require__.d(__webpack_exports__, "createDerivative", function() { return /* reexport */ createDerivative; }); +__webpack_require__.d(__webpack_exports__, "createRationalize", function() { return /* reexport */ createRationalize; }); +__webpack_require__.d(__webpack_exports__, "createReviver", function() { return /* reexport */ createReviver; }); +__webpack_require__.d(__webpack_exports__, "createReplacer", function() { return /* reexport */ createReplacer; }); +__webpack_require__.d(__webpack_exports__, "createE", function() { return /* reexport */ createE; }); +__webpack_require__.d(__webpack_exports__, "createUppercaseE", function() { return /* reexport */ createUppercaseE; }); +__webpack_require__.d(__webpack_exports__, "createFalse", function() { return /* reexport */ createFalse; }); +__webpack_require__.d(__webpack_exports__, "createI", function() { return /* reexport */ createI; }); +__webpack_require__.d(__webpack_exports__, "createInfinity", function() { return /* reexport */ createInfinity; }); +__webpack_require__.d(__webpack_exports__, "createLN10", function() { return /* reexport */ createLN10; }); +__webpack_require__.d(__webpack_exports__, "createLN2", function() { return /* reexport */ createLN2; }); +__webpack_require__.d(__webpack_exports__, "createLOG10E", function() { return /* reexport */ createLOG10E; }); +__webpack_require__.d(__webpack_exports__, "createLOG2E", function() { return /* reexport */ createLOG2E; }); +__webpack_require__.d(__webpack_exports__, "createNaN", function() { return /* reexport */ createNaN; }); +__webpack_require__.d(__webpack_exports__, "createNull", function() { return /* reexport */ createNull; }); +__webpack_require__.d(__webpack_exports__, "createPhi", function() { return /* reexport */ createPhi; }); +__webpack_require__.d(__webpack_exports__, "createPi", function() { return /* reexport */ createPi; }); +__webpack_require__.d(__webpack_exports__, "createUppercasePi", function() { return /* reexport */ createUppercasePi; }); +__webpack_require__.d(__webpack_exports__, "createSQRT1_2", function() { return /* reexport */ createSQRT1_2; }); +__webpack_require__.d(__webpack_exports__, "createSQRT2", function() { return /* reexport */ createSQRT2; }); +__webpack_require__.d(__webpack_exports__, "createTau", function() { return /* reexport */ createTau; }); +__webpack_require__.d(__webpack_exports__, "createTrue", function() { return /* reexport */ createTrue; }); +__webpack_require__.d(__webpack_exports__, "createVersion", function() { return /* reexport */ createVersion; }); +__webpack_require__.d(__webpack_exports__, "createAtomicMass", function() { return /* reexport */ createAtomicMass; }); +__webpack_require__.d(__webpack_exports__, "createAvogadro", function() { return /* reexport */ createAvogadro; }); +__webpack_require__.d(__webpack_exports__, "createBohrMagneton", function() { return /* reexport */ createBohrMagneton; }); +__webpack_require__.d(__webpack_exports__, "createBohrRadius", function() { return /* reexport */ createBohrRadius; }); +__webpack_require__.d(__webpack_exports__, "createBoltzmann", function() { return /* reexport */ createBoltzmann; }); +__webpack_require__.d(__webpack_exports__, "createClassicalElectronRadius", function() { return /* reexport */ createClassicalElectronRadius; }); +__webpack_require__.d(__webpack_exports__, "createConductanceQuantum", function() { return /* reexport */ createConductanceQuantum; }); +__webpack_require__.d(__webpack_exports__, "createCoulomb", function() { return /* reexport */ createCoulomb; }); +__webpack_require__.d(__webpack_exports__, "createDeuteronMass", function() { return /* reexport */ createDeuteronMass; }); +__webpack_require__.d(__webpack_exports__, "createEfimovFactor", function() { return /* reexport */ createEfimovFactor; }); +__webpack_require__.d(__webpack_exports__, "createElectricConstant", function() { return /* reexport */ createElectricConstant; }); +__webpack_require__.d(__webpack_exports__, "createElectronMass", function() { return /* reexport */ createElectronMass; }); +__webpack_require__.d(__webpack_exports__, "createElementaryCharge", function() { return /* reexport */ createElementaryCharge; }); +__webpack_require__.d(__webpack_exports__, "createFaraday", function() { return /* reexport */ createFaraday; }); +__webpack_require__.d(__webpack_exports__, "createFermiCoupling", function() { return /* reexport */ createFermiCoupling; }); +__webpack_require__.d(__webpack_exports__, "createFineStructure", function() { return /* reexport */ createFineStructure; }); +__webpack_require__.d(__webpack_exports__, "createFirstRadiation", function() { return /* reexport */ createFirstRadiation; }); +__webpack_require__.d(__webpack_exports__, "createGasConstant", function() { return /* reexport */ createGasConstant; }); +__webpack_require__.d(__webpack_exports__, "createGravitationConstant", function() { return /* reexport */ createGravitationConstant; }); +__webpack_require__.d(__webpack_exports__, "createGravity", function() { return /* reexport */ createGravity; }); +__webpack_require__.d(__webpack_exports__, "createHartreeEnergy", function() { return /* reexport */ createHartreeEnergy; }); +__webpack_require__.d(__webpack_exports__, "createInverseConductanceQuantum", function() { return /* reexport */ createInverseConductanceQuantum; }); +__webpack_require__.d(__webpack_exports__, "createKlitzing", function() { return /* reexport */ createKlitzing; }); +__webpack_require__.d(__webpack_exports__, "createLoschmidt", function() { return /* reexport */ createLoschmidt; }); +__webpack_require__.d(__webpack_exports__, "createMagneticConstant", function() { return /* reexport */ createMagneticConstant; }); +__webpack_require__.d(__webpack_exports__, "createMagneticFluxQuantum", function() { return /* reexport */ createMagneticFluxQuantum; }); +__webpack_require__.d(__webpack_exports__, "createMolarMass", function() { return /* reexport */ createMolarMass; }); +__webpack_require__.d(__webpack_exports__, "createMolarMassC12", function() { return /* reexport */ createMolarMassC12; }); +__webpack_require__.d(__webpack_exports__, "createMolarPlanckConstant", function() { return /* reexport */ createMolarPlanckConstant; }); +__webpack_require__.d(__webpack_exports__, "createMolarVolume", function() { return /* reexport */ createMolarVolume; }); +__webpack_require__.d(__webpack_exports__, "createNeutronMass", function() { return /* reexport */ createNeutronMass; }); +__webpack_require__.d(__webpack_exports__, "createNuclearMagneton", function() { return /* reexport */ createNuclearMagneton; }); +__webpack_require__.d(__webpack_exports__, "createPlanckCharge", function() { return /* reexport */ createPlanckCharge; }); +__webpack_require__.d(__webpack_exports__, "createPlanckConstant", function() { return /* reexport */ createPlanckConstant; }); +__webpack_require__.d(__webpack_exports__, "createPlanckLength", function() { return /* reexport */ createPlanckLength; }); +__webpack_require__.d(__webpack_exports__, "createPlanckMass", function() { return /* reexport */ createPlanckMass; }); +__webpack_require__.d(__webpack_exports__, "createPlanckTemperature", function() { return /* reexport */ createPlanckTemperature; }); +__webpack_require__.d(__webpack_exports__, "createPlanckTime", function() { return /* reexport */ createPlanckTime; }); +__webpack_require__.d(__webpack_exports__, "createProtonMass", function() { return /* reexport */ createProtonMass; }); +__webpack_require__.d(__webpack_exports__, "createQuantumOfCirculation", function() { return /* reexport */ createQuantumOfCirculation; }); +__webpack_require__.d(__webpack_exports__, "createReducedPlanckConstant", function() { return /* reexport */ createReducedPlanckConstant; }); +__webpack_require__.d(__webpack_exports__, "createRydberg", function() { return /* reexport */ createRydberg; }); +__webpack_require__.d(__webpack_exports__, "createSackurTetrode", function() { return /* reexport */ createSackurTetrode; }); +__webpack_require__.d(__webpack_exports__, "createSecondRadiation", function() { return /* reexport */ createSecondRadiation; }); +__webpack_require__.d(__webpack_exports__, "createSpeedOfLight", function() { return /* reexport */ createSpeedOfLight; }); +__webpack_require__.d(__webpack_exports__, "createStefanBoltzmann", function() { return /* reexport */ createStefanBoltzmann; }); +__webpack_require__.d(__webpack_exports__, "createThomsonCrossSection", function() { return /* reexport */ createThomsonCrossSection; }); +__webpack_require__.d(__webpack_exports__, "createVacuumImpedance", function() { return /* reexport */ createVacuumImpedance; }); +__webpack_require__.d(__webpack_exports__, "createWeakMixingAngle", function() { return /* reexport */ createWeakMixingAngle; }); +__webpack_require__.d(__webpack_exports__, "createWienDisplacement", function() { return /* reexport */ createWienDisplacement; }); +__webpack_require__.d(__webpack_exports__, "createApplyTransform", function() { return /* reexport */ createApplyTransform; }); +__webpack_require__.d(__webpack_exports__, "createColumnTransform", function() { return /* reexport */ createColumnTransform; }); +__webpack_require__.d(__webpack_exports__, "createFilterTransform", function() { return /* reexport */ createFilterTransform; }); +__webpack_require__.d(__webpack_exports__, "createForEachTransform", function() { return /* reexport */ createForEachTransform; }); +__webpack_require__.d(__webpack_exports__, "createIndexTransform", function() { return /* reexport */ createIndexTransform; }); +__webpack_require__.d(__webpack_exports__, "createMapTransform", function() { return /* reexport */ createMapTransform; }); +__webpack_require__.d(__webpack_exports__, "createMaxTransform", function() { return /* reexport */ createMaxTransform; }); +__webpack_require__.d(__webpack_exports__, "createMeanTransform", function() { return /* reexport */ createMeanTransform; }); +__webpack_require__.d(__webpack_exports__, "createMinTransform", function() { return /* reexport */ createMinTransform; }); +__webpack_require__.d(__webpack_exports__, "createRangeTransform", function() { return /* reexport */ createRangeTransform; }); +__webpack_require__.d(__webpack_exports__, "createRowTransform", function() { return /* reexport */ createRowTransform; }); +__webpack_require__.d(__webpack_exports__, "createSubsetTransform", function() { return /* reexport */ createSubsetTransform; }); +__webpack_require__.d(__webpack_exports__, "createConcatTransform", function() { return /* reexport */ createConcatTransform; }); +__webpack_require__.d(__webpack_exports__, "createStdTransform", function() { return /* reexport */ createStdTransform; }); +__webpack_require__.d(__webpack_exports__, "createSumTransform", function() { return /* reexport */ createSumTransform; }); +__webpack_require__.d(__webpack_exports__, "createVarianceTransform", function() { return /* reexport */ createVarianceTransform; }); + +// EXTERNAL MODULE: ./src/utils/is.js +var is = __webpack_require__(1); + +// EXTERNAL MODULE: ./node_modules/typed-function/typed-function.js +var typed_function = __webpack_require__(14); +var typed_function_default = /*#__PURE__*/__webpack_require__.n(typed_function); + +// EXTERNAL MODULE: ./src/utils/number.js +var utils_number = __webpack_require__(4); + +// EXTERNAL MODULE: ./src/utils/factory.js +var factory = __webpack_require__(0); + +// CONCATENATED MODULE: ./src/core/function/typed.js +/** + * Create a typed-function which checks the types of the arguments and + * can match them against multiple provided signatures. The typed-function + * automatically converts inputs in order to find a matching signature. + * Typed functions throw informative errors in case of wrong input arguments. + * + * See the library [typed-function](https://github.com/josdejong/typed-function) + * for detailed documentation. + * + * Syntax: + * + * math.typed(name, signatures) : function + * math.typed(signatures) : function + * + * Examples: + * + * // create a typed function with multiple types per argument (type union) + * const fn2 = typed({ + * 'number | boolean': function (b) { + * return 'b is a number or boolean' + * }, + * 'string, number | boolean': function (a, b) { + * return 'a is a string, b is a number or boolean' + * } + * }) + * + * // create a typed function with an any type argument + * const log = typed({ + * 'string, any': function (event, data) { + * console.log('event: ' + event + ', data: ' + JSON.stringify(data)) + * } + * }) + * + * @param {string} [name] Optional name for the typed-function + * @param {Object} signatures Object with one or multiple function signatures + * @returns {function} The created typed-function. + */ + + + + // returns a new instance of typed-function + +var _createTyped2 = function _createTyped() { + // initially, return the original instance of typed-function + // consecutively, return a new instance from typed.create. + _createTyped2 = typed_function_default.a.create; + return typed_function_default.a; +}; + +var typed_dependencies = ['?BigNumber', '?Complex', '?DenseMatrix', '?Fraction']; +/** + * Factory function for creating a new typed instance + * @param {Object} dependencies Object with data types like Complex and BigNumber + * @returns {Function} + */ + +var typed_createTyped = /* #__PURE__ */Object(factory["a" /* factory */])('typed', typed_dependencies, function createTyped(_ref) { + var BigNumber = _ref.BigNumber, + Complex = _ref.Complex, + DenseMatrix = _ref.DenseMatrix, + Fraction = _ref.Fraction; + + // TODO: typed-function must be able to silently ignore signatures with unknown data types + // get a new instance of typed-function + var typed = _createTyped2(); // define all types. The order of the types determines in which order function + // arguments are type-checked (so for performance it's important to put the + // most used types first). + + + typed.types = [{ + name: 'number', + test: is["y" /* isNumber */] + }, { + name: 'Complex', + test: is["j" /* isComplex */] + }, { + name: 'BigNumber', + test: is["e" /* isBigNumber */] + }, { + name: 'Fraction', + test: is["o" /* isFraction */] + }, { + name: 'Unit', + test: is["L" /* isUnit */] + }, { + name: 'string', + test: is["I" /* isString */] + }, { + name: 'Chain', + test: is["h" /* isChain */] + }, { + name: 'Array', + test: is["b" /* isArray */] + }, { + name: 'Matrix', + test: is["v" /* isMatrix */] + }, { + name: 'DenseMatrix', + test: is["n" /* isDenseMatrix */] + }, { + name: 'SparseMatrix', + test: is["H" /* isSparseMatrix */] + }, { + name: 'Range', + test: is["D" /* isRange */] + }, { + name: 'Index', + test: is["t" /* isIndex */] + }, { + name: 'boolean', + test: is["g" /* isBoolean */] + }, { + name: 'ResultSet', + test: is["G" /* isResultSet */] + }, { + name: 'Help', + test: is["s" /* isHelp */] + }, { + name: 'function', + test: is["p" /* isFunction */] + }, { + name: 'Date', + test: is["m" /* isDate */] + }, { + name: 'RegExp', + test: is["F" /* isRegExp */] + }, { + name: 'null', + test: is["x" /* isNull */] + }, { + name: 'undefined', + test: is["K" /* isUndefined */] + }, { + name: 'AccessorNode', + test: is["a" /* isAccessorNode */] + }, { + name: 'ArrayNode', + test: is["c" /* isArrayNode */] + }, { + name: 'AssignmentNode', + test: is["d" /* isAssignmentNode */] + }, { + name: 'BlockNode', + test: is["f" /* isBlockNode */] + }, { + name: 'ConditionalNode', + test: is["k" /* isConditionalNode */] + }, { + name: 'ConstantNode', + test: is["l" /* isConstantNode */] + }, { + name: 'FunctionNode', + test: is["r" /* isFunctionNode */] + }, { + name: 'FunctionAssignmentNode', + test: is["q" /* isFunctionAssignmentNode */] + }, { + name: 'IndexNode', + test: is["u" /* isIndexNode */] + }, { + name: 'Node', + test: is["w" /* isNode */] + }, { + name: 'ObjectNode', + test: is["A" /* isObjectNode */] + }, { + name: 'OperatorNode', + test: is["B" /* isOperatorNode */] + }, { + name: 'ParenthesisNode', + test: is["C" /* isParenthesisNode */] + }, { + name: 'RangeNode', + test: is["E" /* isRangeNode */] + }, { + name: 'SymbolNode', + test: is["J" /* isSymbolNode */] + }, { + name: 'Object', + test: is["z" /* isObject */] + } // order 'Object' last, it matches on other classes too + ]; + typed.conversions = [{ + from: 'number', + to: 'BigNumber', + convert: function convert(x) { + if (!BigNumber) { + throwNoBignumber(x); + } // note: conversion from number to BigNumber can fail if x has >15 digits + + + if (Object(utils_number["f" /* digits */])(x) > 15) { + throw new TypeError('Cannot implicitly convert a number with >15 significant digits to BigNumber ' + '(value: ' + x + '). ' + 'Use function bignumber(x) to convert to BigNumber.'); + } + + return new BigNumber(x); + } + }, { + from: 'number', + to: 'Complex', + convert: function convert(x) { + if (!Complex) { + throwNoComplex(x); + } + + return new Complex(x, 0); + } + }, { + from: 'number', + to: 'string', + convert: function convert(x) { + return x + ''; + } + }, { + from: 'BigNumber', + to: 'Complex', + convert: function convert(x) { + if (!Complex) { + throwNoComplex(x); + } + + return new Complex(x.toNumber(), 0); + } + }, { + from: 'Fraction', + to: 'BigNumber', + convert: function convert(x) { + throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' + 'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.'); + } + }, { + from: 'Fraction', + to: 'Complex', + convert: function convert(x) { + if (!Complex) { + throwNoComplex(x); + } + + return new Complex(x.valueOf(), 0); + } + }, { + from: 'number', + to: 'Fraction', + convert: function convert(x) { + if (!Fraction) { + throwNoFraction(x); + } + + var f = new Fraction(x); + + if (f.valueOf() !== x) { + throw new TypeError('Cannot implicitly convert a number to a Fraction when there will be a loss of precision ' + '(value: ' + x + '). ' + 'Use function fraction(x) to convert to Fraction.'); + } + + return f; + } + }, { + // FIXME: add conversion from Fraction to number, for example for `sqrt(fraction(1,3))` + // from: 'Fraction', + // to: 'number', + // convert: function (x) { + // return x.valueOf() + // } + // }, { + from: 'string', + to: 'number', + convert: function convert(x) { + var n = Number(x); + + if (isNaN(n)) { + throw new Error('Cannot convert "' + x + '" to a number'); + } + + return n; + } + }, { + from: 'string', + to: 'BigNumber', + convert: function convert(x) { + if (!BigNumber) { + throwNoBignumber(x); + } + + try { + return new BigNumber(x); + } catch (err) { + throw new Error('Cannot convert "' + x + '" to BigNumber'); + } + } + }, { + from: 'string', + to: 'Fraction', + convert: function convert(x) { + if (!Fraction) { + throwNoFraction(x); + } + + try { + return new Fraction(x); + } catch (err) { + throw new Error('Cannot convert "' + x + '" to Fraction'); + } + } + }, { + from: 'string', + to: 'Complex', + convert: function convert(x) { + if (!Complex) { + throwNoComplex(x); + } + + try { + return new Complex(x); + } catch (err) { + throw new Error('Cannot convert "' + x + '" to Complex'); + } + } + }, { + from: 'boolean', + to: 'number', + convert: function convert(x) { + return +x; + } + }, { + from: 'boolean', + to: 'BigNumber', + convert: function convert(x) { + if (!BigNumber) { + throwNoBignumber(x); + } + + return new BigNumber(+x); + } + }, { + from: 'boolean', + to: 'Fraction', + convert: function convert(x) { + if (!Fraction) { + throwNoFraction(x); + } + + return new Fraction(+x); + } + }, { + from: 'boolean', + to: 'string', + convert: function convert(x) { + return String(x); + } + }, { + from: 'Array', + to: 'Matrix', + convert: function convert(array) { + if (!DenseMatrix) { + throwNoMatrix(); + } + + return new DenseMatrix(array); + } + }, { + from: 'Matrix', + to: 'Array', + convert: function convert(matrix) { + return matrix.valueOf(); + } + }]; + return typed; +}); + +function throwNoBignumber(x) { + throw new Error("Cannot convert value ".concat(x, " into a BigNumber: no class 'BigNumber' provided")); +} + +function throwNoComplex(x) { + throw new Error("Cannot convert value ".concat(x, " into a Complex number: no class 'Complex' provided")); +} + +function throwNoMatrix() { + throw new Error('Cannot convert array into a Matrix: no class \'DenseMatrix\' provided'); +} + +function throwNoFraction(x) { + throw new Error("Cannot convert value ".concat(x, " into a Fraction, no class 'Fraction' provided.")); +} +// CONCATENATED MODULE: ./src/type/resultset/ResultSet.js + +var ResultSet_name = 'ResultSet'; +var ResultSet_dependencies = []; +var createResultSet = /* #__PURE__ */Object(factory["a" /* factory */])(ResultSet_name, ResultSet_dependencies, function () { + /** + * A ResultSet contains a list or results + * @class ResultSet + * @param {Array} entries + * @constructor ResultSet + */ + function ResultSet(entries) { + if (!(this instanceof ResultSet)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.entries = entries || []; + } + /** + * Attach type information + */ + + + ResultSet.prototype.type = 'ResultSet'; + ResultSet.prototype.isResultSet = true; + /** + * Returns the array with results hold by this ResultSet + * @memberof ResultSet + * @returns {Array} entries + */ + + ResultSet.prototype.valueOf = function () { + return this.entries; + }; + /** + * Returns the stringified results of the ResultSet + * @memberof ResultSet + * @returns {string} string + */ + + + ResultSet.prototype.toString = function () { + return '[' + this.entries.join(', ') + ']'; + }; + /** + * Get a JSON representation of the ResultSet + * @memberof ResultSet + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "ResultSet", "entries": [...]}` + */ + + + ResultSet.prototype.toJSON = function () { + return { + mathjs: 'ResultSet', + entries: this.entries + }; + }; + /** + * Instantiate a ResultSet from a JSON object + * @memberof ResultSet + * @param {Object} json A JSON object structured as: + * `{"mathjs": "ResultSet", "entries": [...]}` + * @return {ResultSet} + */ + + + ResultSet.fromJSON = function (json) { + return new ResultSet(json.entries); + }; + + return ResultSet; +}, { + isClass: true +}); +// EXTERNAL MODULE: ./node_modules/decimal.js/decimal.js +var decimal = __webpack_require__(16); +var decimal_default = /*#__PURE__*/__webpack_require__.n(decimal); + +// CONCATENATED MODULE: ./src/type/bignumber/BigNumber.js + + +var BigNumber_name = 'BigNumber'; +var BigNumber_dependencies = ['?on', 'config']; +var createBigNumberClass = /* #__PURE__ */Object(factory["a" /* factory */])(BigNumber_name, BigNumber_dependencies, function (_ref) { + var on = _ref.on, + config = _ref.config; + var BigNumber = decimal_default.a.clone({ + precision: config.precision + }); + /** + * Attach type information + */ + + BigNumber.prototype.type = 'BigNumber'; + BigNumber.prototype.isBigNumber = true; + /** + * Get a JSON representation of a BigNumber containing + * type information + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "BigNumber", "value": "0.2"}` + */ + + BigNumber.prototype.toJSON = function () { + return { + mathjs: 'BigNumber', + value: this.toString() + }; + }; + /** + * Instantiate a BigNumber from a JSON object + * @param {Object} json a JSON object structured as: + * `{"mathjs": "BigNumber", "value": "0.2"}` + * @return {BigNumber} + */ + + + BigNumber.fromJSON = function (json) { + return new BigNumber(json.value); + }; + + if (on) { + // listen for changed in the configuration, automatically apply changed precision + on('config', function (curr, prev) { + if (curr.precision !== prev.precision) { + BigNumber.config({ + precision: curr.precision + }); + } + }); + } + + return BigNumber; +}, { + isClass: true +}); +// EXTERNAL MODULE: ./node_modules/complex.js/complex.js +var complex_js_complex = __webpack_require__(9); +var complex_default = /*#__PURE__*/__webpack_require__.n(complex_js_complex); + +// CONCATENATED MODULE: ./src/type/complex/Complex.js +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + + + + + +var Complex_name = 'Complex'; +var Complex_dependencies = []; +var createComplexClass = /* #__PURE__ */Object(factory["a" /* factory */])(Complex_name, Complex_dependencies, function () { + /** + * Attach type information + */ + complex_default.a.prototype.type = 'Complex'; + complex_default.a.prototype.isComplex = true; + /** + * Get a JSON representation of the complex number + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "Complex", "re": 2, "im": 3}` + */ + + complex_default.a.prototype.toJSON = function () { + return { + mathjs: 'Complex', + re: this.re, + im: this.im + }; + }; + /* + * Return the value of the complex number in polar notation + * The angle phi will be set in the interval of [-pi, pi]. + * @return {{r: number, phi: number}} Returns and object with properties r and phi. + */ + + + complex_default.a.prototype.toPolar = function () { + return { + r: this.abs(), + phi: this.arg() + }; + }; + /** + * Get a string representation of the complex number, + * with optional formatting options. + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @return {string} str + */ + + + complex_default.a.prototype.format = function (options) { + var str = ''; + var im = this.im; + var re = this.re; + var strRe = Object(utils_number["h" /* format */])(this.re, options); + var strIm = Object(utils_number["h" /* format */])(this.im, options); // round either re or im when smaller than the configured precision + + var precision = Object(is["y" /* isNumber */])(options) ? options : options ? options.precision : null; + + if (precision !== null) { + var epsilon = Math.pow(10, -precision); + + if (Math.abs(re / im) < epsilon) { + re = 0; + } + + if (Math.abs(im / re) < epsilon) { + im = 0; + } + } + + if (im === 0) { + // real value + str = strRe; + } else if (re === 0) { + // purely complex value + if (im === 1) { + str = 'i'; + } else if (im === -1) { + str = '-i'; + } else { + str = strIm + 'i'; + } + } else { + // complex value + if (im < 0) { + if (im === -1) { + str = strRe + ' - i'; + } else { + str = strRe + ' - ' + strIm.substring(1) + 'i'; + } + } else { + if (im === 1) { + str = strRe + ' + i'; + } else { + str = strRe + ' + ' + strIm + 'i'; + } + } + } + + return str; + }; + /** + * Create a complex number from polar coordinates + * + * Usage: + * + * Complex.fromPolar(r: number, phi: number) : Complex + * Complex.fromPolar({r: number, phi: number}) : Complex + * + * @param {*} args... + * @return {Complex} + */ + + + complex_default.a.fromPolar = function (args) { + switch (arguments.length) { + case 1: + { + var arg = arguments[0]; + + if (_typeof(arg) === 'object') { + return complex_default()(arg); + } else { + throw new TypeError('Input has to be an object with r and phi keys.'); + } + } + + case 2: + { + var r = arguments[0]; + var phi = arguments[1]; + + if (Object(is["y" /* isNumber */])(r)) { + if (Object(is["L" /* isUnit */])(phi) && phi.hasBase('ANGLE')) { + // convert unit to a number in radians + phi = phi.toNumber('rad'); + } + + if (Object(is["y" /* isNumber */])(phi)) { + return new complex_default.a({ + r: r, + phi: phi + }); + } + + throw new TypeError('Phi is not a number nor an angle unit.'); + } else { + throw new TypeError('Radius r is not a number.'); + } + } + + default: + throw new SyntaxError('Wrong number of arguments in function fromPolar'); + } + }; + + complex_default.a.prototype.valueOf = complex_default.a.prototype.toString; + /** + * Create a Complex number from a JSON object + * @param {Object} json A JSON Object structured as + * {"mathjs": "Complex", "re": 2, "im": 3} + * All properties are optional, default values + * for `re` and `im` are 0. + * @return {Complex} Returns a new Complex number + */ + + complex_default.a.fromJSON = function (json) { + return new complex_default.a(json); + }; + /** + * Compare two complex numbers, `a` and `b`: + * + * - Returns 1 when the real part of `a` is larger than the real part of `b` + * - Returns -1 when the real part of `a` is smaller than the real part of `b` + * - Returns 1 when the real parts are equal + * and the imaginary part of `a` is larger than the imaginary part of `b` + * - Returns -1 when the real parts are equal + * and the imaginary part of `a` is smaller than the imaginary part of `b` + * - Returns 0 when both real and imaginary parts are equal. + * + * @params {Complex} a + * @params {Complex} b + * @returns {number} Returns the comparison result: -1, 0, or 1 + */ + + + complex_default.a.compare = function (a, b) { + if (a.re > b.re) { + return 1; + } + + if (a.re < b.re) { + return -1; + } + + if (a.im > b.im) { + return 1; + } + + if (a.im < b.im) { + return -1; + } + + return 0; + }; + + return complex_default.a; +}, { + isClass: true +}); +// EXTERNAL MODULE: ./node_modules/fraction.js/fraction.js +var fraction_js_fraction = __webpack_require__(11); +var fraction_default = /*#__PURE__*/__webpack_require__.n(fraction_js_fraction); + +// CONCATENATED MODULE: ./src/type/fraction/Fraction.js + + +var Fraction_name = 'Fraction'; +var Fraction_dependencies = []; +var createFractionClass = /* #__PURE__ */Object(factory["a" /* factory */])(Fraction_name, Fraction_dependencies, function () { + /** + * Attach type information + */ + fraction_default.a.prototype.type = 'Fraction'; + fraction_default.a.prototype.isFraction = true; + /** + * Get a JSON representation of a Fraction containing type information + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "Fraction", "n": 3, "d": 8}` + */ + + fraction_default.a.prototype.toJSON = function () { + return { + mathjs: 'Fraction', + n: this.s * this.n, + d: this.d + }; + }; + /** + * Instantiate a Fraction from a JSON object + * @param {Object} json a JSON object structured as: + * `{"mathjs": "Fraction", "n": 3, "d": 8}` + * @return {BigNumber} + */ + + + fraction_default.a.fromJSON = function (json) { + return new fraction_default.a(json); + }; + + return fraction_default.a; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/matrix/Range.js + + + +var Range_name = 'Range'; +var Range_dependencies = []; +var createRangeClass = /* #__PURE__ */Object(factory["a" /* factory */])(Range_name, Range_dependencies, function () { + /** + * Create a range. A range has a start, step, and end, and contains functions + * to iterate over the range. + * + * A range can be constructed as: + * + * const range = new Range(start, end) + * const range = new Range(start, end, step) + * + * To get the result of the range: + * range.forEach(function (x) { + * console.log(x) + * }) + * range.map(function (x) { + * return math.sin(x) + * }) + * range.toArray() + * + * Example usage: + * + * const c = new Range(2, 6) // 2:1:5 + * c.toArray() // [2, 3, 4, 5] + * const d = new Range(2, -3, -1) // 2:-1:-2 + * d.toArray() // [2, 1, 0, -1, -2] + * + * @class Range + * @constructor Range + * @param {number} start included lower bound + * @param {number} end excluded upper bound + * @param {number} [step] step size, default value is 1 + */ + function Range(start, end, step) { + if (!(this instanceof Range)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + var hasStart = start !== null && start !== undefined; + var hasEnd = end !== null && end !== undefined; + var hasStep = step !== null && step !== undefined; + + if (hasStart) { + if (Object(is["e" /* isBigNumber */])(start)) { + start = start.toNumber(); + } else if (typeof start !== 'number') { + throw new TypeError('Parameter start must be a number'); + } + } + + if (hasEnd) { + if (Object(is["e" /* isBigNumber */])(end)) { + end = end.toNumber(); + } else if (typeof end !== 'number') { + throw new TypeError('Parameter end must be a number'); + } + } + + if (hasStep) { + if (Object(is["e" /* isBigNumber */])(step)) { + step = step.toNumber(); + } else if (typeof step !== 'number') { + throw new TypeError('Parameter step must be a number'); + } + } + + this.start = hasStart ? parseFloat(start) : 0; + this.end = hasEnd ? parseFloat(end) : 0; + this.step = hasStep ? parseFloat(step) : 1; + } + /** + * Attach type information + */ + + + Range.prototype.type = 'Range'; + Range.prototype.isRange = true; + /** + * Parse a string into a range, + * The string contains the start, optional step, and end, separated by a colon. + * If the string does not contain a valid range, null is returned. + * For example str='0:2:11'. + * @memberof Range + * @param {string} str + * @return {Range | null} range + */ + + Range.parse = function (str) { + if (typeof str !== 'string') { + return null; + } + + var args = str.split(':'); + var nums = args.map(function (arg) { + return parseFloat(arg); + }); + var invalid = nums.some(function (num) { + return isNaN(num); + }); + + if (invalid) { + return null; + } + + switch (nums.length) { + case 2: + return new Range(nums[0], nums[1]); + + case 3: + return new Range(nums[0], nums[2], nums[1]); + + default: + return null; + } + }; + /** + * Create a clone of the range + * @return {Range} clone + */ + + + Range.prototype.clone = function () { + return new Range(this.start, this.end, this.step); + }; + /** + * Retrieve the size of the range. + * Returns an array containing one number, the number of elements in the range. + * @memberof Range + * @returns {number[]} size + */ + + + Range.prototype.size = function () { + var len = 0; + var start = this.start; + var step = this.step; + var end = this.end; + var diff = end - start; + + if (Object(utils_number["n" /* sign */])(step) === Object(utils_number["n" /* sign */])(diff)) { + len = Math.ceil(diff / step); + } else if (diff === 0) { + len = 0; + } + + if (isNaN(len)) { + len = 0; + } + + return [len]; + }; + /** + * Calculate the minimum value in the range + * @memberof Range + * @return {number | undefined} min + */ + + + Range.prototype.min = function () { + var size = this.size()[0]; + + if (size > 0) { + if (this.step > 0) { + // positive step + return this.start; + } else { + // negative step + return this.start + (size - 1) * this.step; + } + } else { + return undefined; + } + }; + /** + * Calculate the maximum value in the range + * @memberof Range + * @return {number | undefined} max + */ + + + Range.prototype.max = function () { + var size = this.size()[0]; + + if (size > 0) { + if (this.step > 0) { + // positive step + return this.start + (size - 1) * this.step; + } else { + // negative step + return this.start; + } + } else { + return undefined; + } + }; + /** + * Execute a callback function for each value in the range. + * @memberof Range + * @param {function} callback The callback method is invoked with three + * parameters: the value of the element, the index + * of the element, and the Range being traversed. + */ + + + Range.prototype.forEach = function (callback) { + var x = this.start; + var step = this.step; + var end = this.end; + var i = 0; + + if (step > 0) { + while (x < end) { + callback(x, [i], this); + x += step; + i++; + } + } else if (step < 0) { + while (x > end) { + callback(x, [i], this); + x += step; + i++; + } + } + }; + /** + * Execute a callback function for each value in the Range, and return the + * results as an array + * @memberof Range + * @param {function} callback The callback method is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + * @returns {Array} array + */ + + + Range.prototype.map = function (callback) { + var array = []; + this.forEach(function (value, index, obj) { + array[index[0]] = callback(value, index, obj); + }); + return array; + }; + /** + * Create an Array with a copy of the Ranges data + * @memberof Range + * @returns {Array} array + */ + + + Range.prototype.toArray = function () { + var array = []; + this.forEach(function (value, index) { + array[index[0]] = value; + }); + return array; + }; + /** + * Get the primitive value of the Range, a one dimensional array + * @memberof Range + * @returns {Array} array + */ + + + Range.prototype.valueOf = function () { + // TODO: implement a caching mechanism for range.valueOf() + return this.toArray(); + }; + /** + * Get a string representation of the range, with optional formatting options. + * Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11' + * @memberof Range + * @param {Object | number | function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @returns {string} str + */ + + + Range.prototype.format = function (options) { + var str = Object(utils_number["h" /* format */])(this.start, options); + + if (this.step !== 1) { + str += ':' + Object(utils_number["h" /* format */])(this.step, options); + } + + str += ':' + Object(utils_number["h" /* format */])(this.end, options); + return str; + }; + /** + * Get a string representation of the range. + * @memberof Range + * @returns {string} + */ + + + Range.prototype.toString = function () { + return this.format(); + }; + /** + * Get a JSON representation of the range + * @memberof Range + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` + */ + + + Range.prototype.toJSON = function () { + return { + mathjs: 'Range', + start: this.start, + end: this.end, + step: this.step + }; + }; + /** + * Instantiate a Range from a JSON object + * @memberof Range + * @param {Object} json A JSON object structured as: + * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` + * @return {Range} + */ + + + Range.fromJSON = function (json) { + return new Range(json.start, json.end, json.step); + }; + + return Range; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/matrix/Matrix.js + +var Matrix_name = 'Matrix'; +var Matrix_dependencies = []; +var createMatrixClass = /* #__PURE__ */Object(factory["a" /* factory */])(Matrix_name, Matrix_dependencies, function () { + /** + * @constructor Matrix + * + * A Matrix is a wrapper around an Array. A matrix can hold a multi dimensional + * array. A matrix can be constructed as: + * + * let matrix = math.matrix(data) + * + * Matrix contains the functions to resize, get and set values, get the size, + * clone the matrix and to convert the matrix to a vector, array, or scalar. + * Furthermore, one can iterate over the matrix using map and forEach. + * The internal Array of the Matrix can be accessed using the function valueOf. + * + * Example usage: + * + * let matrix = math.matrix([[1, 2], [3, 4]]) + * matix.size() // [2, 2] + * matrix.resize([3, 2], 5) + * matrix.valueOf() // [[1, 2], [3, 4], [5, 5]] + * matrix.subset([1,2]) // 3 (indexes are zero-based) + * + */ + function Matrix() { + if (!(this instanceof Matrix)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + } + /** + * Attach type information + */ + + + Matrix.prototype.type = 'Matrix'; + Matrix.prototype.isMatrix = true; + /** + * Get the Matrix storage constructor for the given format. + * + * @param {string} format The Matrix storage format. + * + * @return {Function} The Matrix storage constructor. + */ + + Matrix.storage = function (format) { + // TODO: deprecated since v6.0.0. Clean up some day + throw new Error('Matrix.storage is deprecated since v6.0.0. ' + 'Use the factory function math.matrix instead.'); + }; + /** + * Get the storage format used by the matrix. + * + * Usage: + * const format = matrix.storage() // retrieve storage format + * + * @return {string} The storage format. + */ + + + Matrix.prototype.storage = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke storage on a Matrix interface'); + }; + /** + * Get the datatype of the data stored in the matrix. + * + * Usage: + * const format = matrix.datatype() // retrieve matrix datatype + * + * @return {string} The datatype. + */ + + + Matrix.prototype.datatype = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke datatype on a Matrix interface'); + }; + /** + * Create a new Matrix With the type of the current matrix instance + * @param {Array | Object} data + * @param {string} [datatype] + */ + + + Matrix.prototype.create = function (data, datatype) { + throw new Error('Cannot invoke create on a Matrix interface'); + }; + /** + * Get a subset of the matrix, or replace a subset of the matrix. + * + * Usage: + * const subset = matrix.subset(index) // retrieve subset + * const value = matrix.subset(index, replacement) // replace subset + * + * @param {Index} index + * @param {Array | Matrix | *} [replacement] + * @param {*} [defaultValue=0] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be filled with zeros. + */ + + + Matrix.prototype.subset = function (index, replacement, defaultValue) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke subset on a Matrix interface'); + }; + /** + * Get a single element from the matrix. + * @param {number[]} index Zero-based index + * @return {*} value + */ + + + Matrix.prototype.get = function (index) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke get on a Matrix interface'); + }; + /** + * Replace a single element in the matrix. + * @param {number[]} index Zero-based index + * @param {*} value + * @param {*} [defaultValue] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be left undefined. + * @return {Matrix} self + */ + + + Matrix.prototype.set = function (index, value, defaultValue) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke set on a Matrix interface'); + }; + /** + * Resize the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (resize in place). + * + * @param {number[]} size The new size the matrix should have. + * @param {*} [defaultValue=0] Default value, filled in on new entries. + * If not provided, the matrix elements will + * be filled with zeros. + * @param {boolean} [copy] Return a resized copy of the matrix + * + * @return {Matrix} The resized matrix + */ + + + Matrix.prototype.resize = function (size, defaultValue) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke resize on a Matrix interface'); + }; + /** + * Reshape the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (reshape in place). + * + * @param {number[]} size The new size the matrix should have. + * @param {boolean} [copy] Return a reshaped copy of the matrix + * + * @return {Matrix} The reshaped matrix + */ + + + Matrix.prototype.reshape = function (size, defaultValue) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke reshape on a Matrix interface'); + }; + /** + * Create a clone of the matrix + * @return {Matrix} clone + */ + + + Matrix.prototype.clone = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke clone on a Matrix interface'); + }; + /** + * Retrieve the size of the matrix. + * @returns {number[]} size + */ + + + Matrix.prototype.size = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke size on a Matrix interface'); + }; + /** + * Create a new matrix with the results of the callback function executed on + * each entry of the matrix. + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + * @param {boolean} [skipZeros] Invoke callback function for non-zero values only. + * + * @return {Matrix} matrix + */ + + + Matrix.prototype.map = function (callback, skipZeros) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke map on a Matrix interface'); + }; + /** + * Execute a callback function on each entry of the matrix. + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + */ + + + Matrix.prototype.forEach = function (callback) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke forEach on a Matrix interface'); + }; + /** + * Create an Array with a copy of the data of the Matrix + * @returns {Array} array + */ + + + Matrix.prototype.toArray = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke toArray on a Matrix interface'); + }; + /** + * Get the primitive value of the Matrix: a multidimensional array + * @returns {Array} array + */ + + + Matrix.prototype.valueOf = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke valueOf on a Matrix interface'); + }; + /** + * Get a string representation of the matrix, with optional formatting options. + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @returns {string} str + */ + + + Matrix.prototype.format = function (options) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke format on a Matrix interface'); + }; + /** + * Get a string representation of the matrix + * @returns {string} str + */ + + + Matrix.prototype.toString = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke toString on a Matrix interface'); + }; + + return Matrix; +}, { + isClass: true +}); +// EXTERNAL MODULE: ./src/utils/array.js +var utils_array = __webpack_require__(2); + +// EXTERNAL MODULE: ./src/utils/string.js + 1 modules +var utils_string = __webpack_require__(5); + +// EXTERNAL MODULE: ./src/utils/object.js +var utils_object = __webpack_require__(3); + +// EXTERNAL MODULE: ./src/error/DimensionError.js +var DimensionError = __webpack_require__(6); + +// CONCATENATED MODULE: ./src/type/matrix/DenseMatrix.js + + + + + + + +var DenseMatrix_name = 'DenseMatrix'; +var DenseMatrix_dependencies = ['Matrix']; +var createDenseMatrixClass = /* #__PURE__ */Object(factory["a" /* factory */])(DenseMatrix_name, DenseMatrix_dependencies, function (_ref) { + var Matrix = _ref.Matrix; + + /** + * Dense Matrix implementation. A regular, dense matrix, supporting multi-dimensional matrices. This is the default matrix type. + * @class DenseMatrix + */ + function DenseMatrix(data, datatype) { + if (!(this instanceof DenseMatrix)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (datatype && !Object(is["I" /* isString */])(datatype)) { + throw new Error('Invalid datatype: ' + datatype); + } + + if (Object(is["v" /* isMatrix */])(data)) { + // check data is a DenseMatrix + if (data.type === 'DenseMatrix') { + // clone data & size + this._data = Object(utils_object["a" /* clone */])(data._data); + this._size = Object(utils_object["a" /* clone */])(data._size); + this._datatype = datatype || data._datatype; + } else { + // build data from existing matrix + this._data = data.toArray(); + this._size = data.size(); + this._datatype = datatype || data._datatype; + } + } else if (data && Object(is["b" /* isArray */])(data.data) && Object(is["b" /* isArray */])(data.size)) { + // initialize fields from JSON representation + this._data = data.data; + this._size = data.size; // verify the dimensions of the array + + Object(utils_array["r" /* validate */])(this._data, this._size); + this._datatype = datatype || data.datatype; + } else if (Object(is["b" /* isArray */])(data)) { + // replace nested Matrices with Arrays + this._data = preprocess(data); // get the dimensions of the array + + this._size = Object(utils_array["a" /* arraySize */])(this._data); // verify the dimensions of the array, TODO: compute size while processing array + + Object(utils_array["r" /* validate */])(this._data, this._size); // data type unknown + + this._datatype = datatype; + } else if (data) { + // unsupported type + throw new TypeError('Unsupported type of data (' + Object(is["M" /* typeOf */])(data) + ')'); + } else { + // nothing provided + this._data = []; + this._size = [0]; + this._datatype = datatype; + } + } + + DenseMatrix.prototype = new Matrix(); + /** + * Create a new DenseMatrix + */ + + DenseMatrix.prototype.createDenseMatrix = function (data, datatype) { + return new DenseMatrix(data, datatype); + }; + /** + * Attach type information + */ + + + DenseMatrix.prototype.type = 'DenseMatrix'; + DenseMatrix.prototype.isDenseMatrix = true; + /** + * Get the matrix type + * + * Usage: + * const matrixType = matrix.getDataType() // retrieves the matrix type + * + * @memberOf DenseMatrix + * @return {string} type information; if multiple types are found from the Matrix, it will return "mixed" + */ + + DenseMatrix.prototype.getDataType = function () { + return Object(utils_array["h" /* getArrayDataType */])(this._data, is["M" /* typeOf */]); + }; + /** + * Get the storage format used by the matrix. + * + * Usage: + * const format = matrix.storage() // retrieve storage format + * + * @memberof DenseMatrix + * @return {string} The storage format. + */ + + + DenseMatrix.prototype.storage = function () { + return 'dense'; + }; + /** + * Get the datatype of the data stored in the matrix. + * + * Usage: + * const format = matrix.datatype() // retrieve matrix datatype + * + * @memberof DenseMatrix + * @return {string} The datatype. + */ + + + DenseMatrix.prototype.datatype = function () { + return this._datatype; + }; + /** + * Create a new DenseMatrix + * @memberof DenseMatrix + * @param {Array} data + * @param {string} [datatype] + */ + + + DenseMatrix.prototype.create = function (data, datatype) { + return new DenseMatrix(data, datatype); + }; + /** + * Get a subset of the matrix, or replace a subset of the matrix. + * + * Usage: + * const subset = matrix.subset(index) // retrieve subset + * const value = matrix.subset(index, replacement) // replace subset + * + * @memberof DenseMatrix + * @param {Index} index + * @param {Array | Matrix | *} [replacement] + * @param {*} [defaultValue=0] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be filled with zeros. + */ + + + DenseMatrix.prototype.subset = function (index, replacement, defaultValue) { + switch (arguments.length) { + case 1: + return _get(this, index); + // intentional fall through + + case 2: + case 3: + return _set(this, index, replacement, defaultValue); + + default: + throw new SyntaxError('Wrong number of arguments'); + } + }; + /** + * Get a single element from the matrix. + * @memberof DenseMatrix + * @param {number[]} index Zero-based index + * @return {*} value + */ + + + DenseMatrix.prototype.get = function (index) { + if (!Object(is["b" /* isArray */])(index)) { + throw new TypeError('Array expected'); + } + + if (index.length !== this._size.length) { + throw new DimensionError["a" /* DimensionError */](index.length, this._size.length); + } // check index + + + for (var x = 0; x < index.length; x++) { + Object(utils_array["s" /* validateIndex */])(index[x], this._size[x]); + } + + var data = this._data; + + for (var i = 0, ii = index.length; i < ii; i++) { + var indexI = index[i]; + Object(utils_array["s" /* validateIndex */])(indexI, data.length); + data = data[indexI]; + } + + return data; + }; + /** + * Replace a single element in the matrix. + * @memberof DenseMatrix + * @param {number[]} index Zero-based index + * @param {*} value + * @param {*} [defaultValue] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be left undefined. + * @return {DenseMatrix} self + */ + + + DenseMatrix.prototype.set = function (index, value, defaultValue) { + if (!Object(is["b" /* isArray */])(index)) { + throw new TypeError('Array expected'); + } + + if (index.length < this._size.length) { + throw new DimensionError["a" /* DimensionError */](index.length, this._size.length, '<'); + } + + var i, ii, indexI; // enlarge matrix when needed + + var size = index.map(function (i) { + return i + 1; + }); + + _fit(this, size, defaultValue); // traverse over the dimensions + + + var data = this._data; + + for (i = 0, ii = index.length - 1; i < ii; i++) { + indexI = index[i]; + Object(utils_array["s" /* validateIndex */])(indexI, data.length); + data = data[indexI]; + } // set new value + + + indexI = index[index.length - 1]; + Object(utils_array["s" /* validateIndex */])(indexI, data.length); + data[indexI] = value; + return this; + }; + /** + * Get a submatrix of this matrix + * @memberof DenseMatrix + * @param {DenseMatrix} matrix + * @param {Index} index Zero-based index + * @private + */ + + + function _get(matrix, index) { + if (!Object(is["t" /* isIndex */])(index)) { + throw new TypeError('Invalid index'); + } + + var isScalar = index.isScalar(); + + if (isScalar) { + // return a scalar + return matrix.get(index.min()); + } else { + // validate dimensions + var size = index.size(); + + if (size.length !== matrix._size.length) { + throw new DimensionError["a" /* DimensionError */](size.length, matrix._size.length); + } // validate if any of the ranges in the index is out of range + + + var min = index.min(); + var max = index.max(); + + for (var i = 0, ii = matrix._size.length; i < ii; i++) { + Object(utils_array["s" /* validateIndex */])(min[i], matrix._size[i]); + Object(utils_array["s" /* validateIndex */])(max[i], matrix._size[i]); + } // retrieve submatrix + // TODO: more efficient when creating an empty matrix and setting _data and _size manually + + + return new DenseMatrix(_getSubmatrix(matrix._data, index, size.length, 0), matrix._datatype); + } + } + /** + * Recursively get a submatrix of a multi dimensional matrix. + * Index is not checked for correct number or length of dimensions. + * @memberof DenseMatrix + * @param {Array} data + * @param {Index} index + * @param {number} dims Total number of dimensions + * @param {number} dim Current dimension + * @return {Array} submatrix + * @private + */ + + + function _getSubmatrix(data, index, dims, dim) { + var last = dim === dims - 1; + var range = index.dimension(dim); + + if (last) { + return range.map(function (i) { + Object(utils_array["s" /* validateIndex */])(i, data.length); + return data[i]; + }).valueOf(); + } else { + return range.map(function (i) { + Object(utils_array["s" /* validateIndex */])(i, data.length); + var child = data[i]; + return _getSubmatrix(child, index, dims, dim + 1); + }).valueOf(); + } + } + /** + * Replace a submatrix in this matrix + * Indexes are zero-based. + * @memberof DenseMatrix + * @param {DenseMatrix} matrix + * @param {Index} index + * @param {DenseMatrix | Array | *} submatrix + * @param {*} defaultValue Default value, filled in on new entries when + * the matrix is resized. + * @return {DenseMatrix} matrix + * @private + */ + + + function _set(matrix, index, submatrix, defaultValue) { + if (!index || index.isIndex !== true) { + throw new TypeError('Invalid index'); + } // get index size and check whether the index contains a single value + + + var iSize = index.size(); + var isScalar = index.isScalar(); // calculate the size of the submatrix, and convert it into an Array if needed + + var sSize; + + if (Object(is["v" /* isMatrix */])(submatrix)) { + sSize = submatrix.size(); + submatrix = submatrix.valueOf(); + } else { + sSize = Object(utils_array["a" /* arraySize */])(submatrix); + } + + if (isScalar) { + // set a scalar + // check whether submatrix is a scalar + if (sSize.length !== 0) { + throw new TypeError('Scalar expected'); + } + + matrix.set(index.min(), submatrix, defaultValue); + } else { + // set a submatrix + // validate dimensions + if (iSize.length < matrix._size.length) { + throw new DimensionError["a" /* DimensionError */](iSize.length, matrix._size.length, '<'); + } + + if (sSize.length < iSize.length) { + // calculate number of missing outer dimensions + var i = 0; + var outer = 0; + + while (iSize[i] === 1 && sSize[i] === 1) { + i++; + } + + while (iSize[i] === 1) { + outer++; + i++; + } // unsqueeze both outer and inner dimensions + + + submatrix = Object(utils_array["q" /* unsqueeze */])(submatrix, iSize.length, outer, sSize); + } // check whether the size of the submatrix matches the index size + + + if (!Object(utils_object["d" /* deepStrictEqual */])(iSize, sSize)) { + throw new DimensionError["a" /* DimensionError */](iSize, sSize, '>'); + } // enlarge matrix when needed + + + var size = index.max().map(function (i) { + return i + 1; + }); + + _fit(matrix, size, defaultValue); // insert the sub matrix + + + var dims = iSize.length; + var dim = 0; + + _setSubmatrix(matrix._data, index, submatrix, dims, dim); + } + + return matrix; + } + /** + * Replace a submatrix of a multi dimensional matrix. + * @memberof DenseMatrix + * @param {Array} data + * @param {Index} index + * @param {Array} submatrix + * @param {number} dims Total number of dimensions + * @param {number} dim + * @private + */ + + + function _setSubmatrix(data, index, submatrix, dims, dim) { + var last = dim === dims - 1; + var range = index.dimension(dim); + + if (last) { + range.forEach(function (dataIndex, subIndex) { + Object(utils_array["s" /* validateIndex */])(dataIndex); + data[dataIndex] = submatrix[subIndex[0]]; + }); + } else { + range.forEach(function (dataIndex, subIndex) { + Object(utils_array["s" /* validateIndex */])(dataIndex); + + _setSubmatrix(data[dataIndex], index, submatrix[subIndex[0]], dims, dim + 1); + }); + } + } + /** + * Resize the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (resize in place). + * + * @memberof DenseMatrix + * @param {number[]} size The new size the matrix should have. + * @param {*} [defaultValue=0] Default value, filled in on new entries. + * If not provided, the matrix elements will + * be filled with zeros. + * @param {boolean} [copy] Return a resized copy of the matrix + * + * @return {Matrix} The resized matrix + */ + + + DenseMatrix.prototype.resize = function (size, defaultValue, copy) { + // validate arguments + if (!Object(is["b" /* isArray */])(size)) { + throw new TypeError('Array expected'); + } // matrix to resize + + + var m = copy ? this.clone() : this; // resize matrix + + return _resize(m, size, defaultValue); + }; + + function _resize(matrix, size, defaultValue) { + // check size + if (size.length === 0) { + // first value in matrix + var v = matrix._data; // go deep + + while (Object(is["b" /* isArray */])(v)) { + v = v[0]; + } + + return v; + } // resize matrix + + + matrix._size = size.slice(0); // copy the array + + matrix._data = Object(utils_array["o" /* resize */])(matrix._data, matrix._size, defaultValue); // return matrix + + return matrix; + } + /** + * Reshape the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (reshape in place). + * + * NOTE: This might be better suited to copy by default, instead of modifying + * in place. For now, it operates in place to remain consistent with + * resize(). + * + * @memberof DenseMatrix + * @param {number[]} size The new size the matrix should have. + * @param {boolean} [copy] Return a reshaped copy of the matrix + * + * @return {Matrix} The reshaped matrix + */ + + + DenseMatrix.prototype.reshape = function (size, copy) { + var m = copy ? this.clone() : this; + m._data = Object(utils_array["n" /* reshape */])(m._data, size); + m._size = size.slice(0); + return m; + }; + /** + * Enlarge the matrix when it is smaller than given size. + * If the matrix is larger or equal sized, nothing is done. + * @memberof DenseMatrix + * @param {DenseMatrix} matrix The matrix to be resized + * @param {number[]} size + * @param {*} defaultValue Default value, filled in on new entries. + * @private + */ + + + function _fit(matrix, size, defaultValue) { + var // copy the array + newSize = matrix._size.slice(0); + + var changed = false; // add dimensions when needed + + while (newSize.length < size.length) { + newSize.push(0); + changed = true; + } // enlarge size when needed + + + for (var i = 0, ii = size.length; i < ii; i++) { + if (size[i] > newSize[i]) { + newSize[i] = size[i]; + changed = true; + } + } + + if (changed) { + // resize only when size is changed + _resize(matrix, newSize, defaultValue); + } + } + /** + * Create a clone of the matrix + * @memberof DenseMatrix + * @return {DenseMatrix} clone + */ + + + DenseMatrix.prototype.clone = function () { + var m = new DenseMatrix({ + data: Object(utils_object["a" /* clone */])(this._data), + size: Object(utils_object["a" /* clone */])(this._size), + datatype: this._datatype + }); + return m; + }; + /** + * Retrieve the size of the matrix. + * @memberof DenseMatrix + * @returns {number[]} size + */ + + + DenseMatrix.prototype.size = function () { + return this._size.slice(0); // return a clone of _size + }; + /** + * Create a new matrix with the results of the callback function executed on + * each entry of the matrix. + * @memberof DenseMatrix + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + * + * @return {DenseMatrix} matrix + */ + + + DenseMatrix.prototype.map = function (callback) { + // matrix instance + var me = this; + + var recurse = function recurse(value, index) { + if (Object(is["b" /* isArray */])(value)) { + return value.map(function (child, i) { + return recurse(child, index.concat(i)); + }); + } else { + return callback(value, index, me); + } + }; // determine the new datatype when the original matrix has datatype defined + // TODO: should be done in matrix constructor instead + + + var data = recurse(this._data, []); + var datatype = this._datatype !== undefined ? Object(utils_array["h" /* getArrayDataType */])(data, is["M" /* typeOf */]) : undefined; + return new DenseMatrix(data, datatype); + }; + /** + * Execute a callback function on each entry of the matrix. + * @memberof DenseMatrix + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + */ + + + DenseMatrix.prototype.forEach = function (callback) { + // matrix instance + var me = this; + + var recurse = function recurse(value, index) { + if (Object(is["b" /* isArray */])(value)) { + value.forEach(function (child, i) { + recurse(child, index.concat(i)); + }); + } else { + callback(value, index, me); + } + }; + + recurse(this._data, []); + }; + /** + * Create an Array with a copy of the data of the DenseMatrix + * @memberof DenseMatrix + * @returns {Array} array + */ + + + DenseMatrix.prototype.toArray = function () { + return Object(utils_object["a" /* clone */])(this._data); + }; + /** + * Get the primitive value of the DenseMatrix: a multidimensional array + * @memberof DenseMatrix + * @returns {Array} array + */ + + + DenseMatrix.prototype.valueOf = function () { + return this._data; + }; + /** + * Get a string representation of the matrix, with optional formatting options. + * @memberof DenseMatrix + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @returns {string} str + */ + + + DenseMatrix.prototype.format = function (options) { + return Object(utils_string["d" /* format */])(this._data, options); + }; + /** + * Get a string representation of the matrix + * @memberof DenseMatrix + * @returns {string} str + */ + + + DenseMatrix.prototype.toString = function () { + return Object(utils_string["d" /* format */])(this._data); + }; + /** + * Get a JSON representation of the matrix + * @memberof DenseMatrix + * @returns {Object} + */ + + + DenseMatrix.prototype.toJSON = function () { + return { + mathjs: 'DenseMatrix', + data: this._data, + size: this._size, + datatype: this._datatype + }; + }; + /** + * Get the kth Matrix diagonal. + * + * @memberof DenseMatrix + * @param {number | BigNumber} [k=0] The kth diagonal where the vector will retrieved. + * + * @returns {Matrix} The matrix with the diagonal values. + */ + + + DenseMatrix.prototype.diagonal = function (k) { + // validate k if any + if (k) { + // convert BigNumber to a number + if (Object(is["e" /* isBigNumber */])(k)) { + k = k.toNumber(); + } // is must be an integer + + + if (!Object(is["y" /* isNumber */])(k) || !Object(utils_number["i" /* isInteger */])(k)) { + throw new TypeError('The parameter k must be an integer number'); + } + } else { + // default value + k = 0; + } + + var kSuper = k > 0 ? k : 0; + var kSub = k < 0 ? -k : 0; // rows & columns + + var rows = this._size[0]; + var columns = this._size[1]; // number diagonal values + + var n = Math.min(rows - kSub, columns - kSuper); // x is a matrix get diagonal from matrix + + var data = []; // loop rows + + for (var i = 0; i < n; i++) { + data[i] = this._data[i + kSub][i + kSuper]; + } // create DenseMatrix + + + return new DenseMatrix({ + data: data, + size: [n], + datatype: this._datatype + }); + }; + /** + * Create a diagonal matrix. + * + * @memberof DenseMatrix + * @param {Array} size The matrix size. + * @param {number | Matrix | Array } value The values for the diagonal. + * @param {number | BigNumber} [k=0] The kth diagonal where the vector will be filled in. + * @param {number} [defaultValue] The default value for non-diagonal + * @param {string} [datatype] The datatype for the diagonal + * + * @returns {DenseMatrix} + */ + + + DenseMatrix.diagonal = function (size, value, k, defaultValue) { + if (!Object(is["b" /* isArray */])(size)) { + throw new TypeError('Array expected, size parameter'); + } + + if (size.length !== 2) { + throw new Error('Only two dimensions matrix are supported'); + } // map size & validate + + + size = size.map(function (s) { + // check it is a big number + if (Object(is["e" /* isBigNumber */])(s)) { + // convert it + s = s.toNumber(); + } // validate arguments + + + if (!Object(is["y" /* isNumber */])(s) || !Object(utils_number["i" /* isInteger */])(s) || s < 1) { + throw new Error('Size values must be positive integers'); + } + + return s; + }); // validate k if any + + if (k) { + // convert BigNumber to a number + if (Object(is["e" /* isBigNumber */])(k)) { + k = k.toNumber(); + } // is must be an integer + + + if (!Object(is["y" /* isNumber */])(k) || !Object(utils_number["i" /* isInteger */])(k)) { + throw new TypeError('The parameter k must be an integer number'); + } + } else { + // default value + k = 0; + } + + var kSuper = k > 0 ? k : 0; + var kSub = k < 0 ? -k : 0; // rows and columns + + var rows = size[0]; + var columns = size[1]; // number of non-zero items + + var n = Math.min(rows - kSub, columns - kSuper); // value extraction function + + var _value; // check value + + + if (Object(is["b" /* isArray */])(value)) { + // validate array + if (value.length !== n) { + // number of values in array must be n + throw new Error('Invalid value array length'); + } // define function + + + _value = function _value(i) { + // return value @ i + return value[i]; + }; + } else if (Object(is["v" /* isMatrix */])(value)) { + // matrix size + var ms = value.size(); // validate matrix + + if (ms.length !== 1 || ms[0] !== n) { + // number of values in array must be n + throw new Error('Invalid matrix length'); + } // define function + + + _value = function _value(i) { + // return value @ i + return value.get([i]); + }; + } else { + // define function + _value = function _value() { + // return value + return value; + }; + } // discover default value if needed + + + if (!defaultValue) { + // check first value in array + defaultValue = Object(is["e" /* isBigNumber */])(_value(0)) ? _value(0).mul(0) // trick to create a BigNumber with value zero + : 0; + } // empty array + + + var data = []; // check we need to resize array + + if (size.length > 0) { + // resize array + data = Object(utils_array["o" /* resize */])(data, size, defaultValue); // fill diagonal + + for (var d = 0; d < n; d++) { + data[d + kSub][d + kSuper] = _value(d); + } + } // create DenseMatrix + + + return new DenseMatrix({ + data: data, + size: [rows, columns] + }); + }; + /** + * Generate a matrix from a JSON object + * @memberof DenseMatrix + * @param {Object} json An object structured like + * `{"mathjs": "DenseMatrix", data: [], size: []}`, + * where mathjs is optional + * @returns {DenseMatrix} + */ + + + DenseMatrix.fromJSON = function (json) { + return new DenseMatrix(json); + }; + /** + * Swap rows i and j in Matrix. + * + * @memberof DenseMatrix + * @param {number} i Matrix row index 1 + * @param {number} j Matrix row index 2 + * + * @return {Matrix} The matrix reference + */ + + + DenseMatrix.prototype.swapRows = function (i, j) { + // check index + if (!Object(is["y" /* isNumber */])(i) || !Object(utils_number["i" /* isInteger */])(i) || !Object(is["y" /* isNumber */])(j) || !Object(utils_number["i" /* isInteger */])(j)) { + throw new Error('Row index must be positive integers'); + } // check dimensions + + + if (this._size.length !== 2) { + throw new Error('Only two dimensional matrix is supported'); + } // validate index + + + Object(utils_array["s" /* validateIndex */])(i, this._size[0]); + Object(utils_array["s" /* validateIndex */])(j, this._size[0]); // swap rows + + DenseMatrix._swapRows(i, j, this._data); // return current instance + + + return this; + }; + /** + * Swap rows i and j in Dense Matrix data structure. + * + * @param {number} i Matrix row index 1 + * @param {number} j Matrix row index 2 + * @param {Array} data Matrix data + */ + + + DenseMatrix._swapRows = function (i, j, data) { + // swap values i <-> j + var vi = data[i]; + data[i] = data[j]; + data[j] = vi; + }; + /** + * Preprocess data, which can be an Array or DenseMatrix with nested Arrays and + * Matrices. Replaces all nested Matrices with Arrays + * @memberof DenseMatrix + * @param {Array} data + * @return {Array} data + */ + + + function preprocess(data) { + for (var i = 0, ii = data.length; i < ii; i++) { + var elem = data[i]; + + if (Object(is["b" /* isArray */])(elem)) { + data[i] = preprocess(elem); + } else if (elem && elem.isMatrix === true) { + data[i] = preprocess(elem.valueOf()); + } + } + + return data; + } + + return DenseMatrix; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/function/utils/clone.js + + +var clone_name = 'clone'; +var clone_dependencies = ['typed']; +var createClone = /* #__PURE__ */Object(factory["a" /* factory */])(clone_name, clone_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Clone an object. + * + * Syntax: + * + * math.clone(x) + * + * Examples: + * + * math.clone(3.5) // returns number 3.5 + * math.clone(math.complex('2-4i') // returns Complex 2 - 4i + * math.clone(math.unit(45, 'deg')) // returns Unit 45 deg + * math.clone([[1, 2], [3, 4]]) // returns Array [[1, 2], [3, 4]] + * math.clone("hello world") // returns string "hello world" + * + * @param {*} x Object to be cloned + * @return {*} A clone of object x + */ + return typed(clone_name, { + any: utils_object["a" /* clone */] + }); +}); +// EXTERNAL MODULE: ./src/error/IndexError.js +var IndexError = __webpack_require__(10); + +// CONCATENATED MODULE: ./src/utils/collection.js + + + +/** + * Test whether an array contains collections + * @param {Array} array + * @returns {boolean} Returns true when the array contains one or multiple + * collections (Arrays or Matrices). Returns false otherwise. + */ + +function containsCollections(array) { + for (var i = 0; i < array.length; i++) { + if (Object(is["i" /* isCollection */])(array[i])) { + return true; + } + } + + return false; +} +/** + * Recursively loop over all elements in a given multi dimensional array + * and invoke the callback on each of the elements. + * @param {Array | Matrix} array + * @param {Function} callback The callback method is invoked with one + * parameter: the current element in the array + */ + +function deepForEach(array, callback) { + if (Object(is["v" /* isMatrix */])(array)) { + array = array.valueOf(); + } + + for (var i = 0, ii = array.length; i < ii; i++) { + var value = array[i]; + + if (Array.isArray(value)) { + deepForEach(value, callback); + } else { + callback(value); + } + } +} +/** + * Execute the callback function element wise for each element in array and any + * nested array + * Returns an array with the results + * @param {Array | Matrix} array + * @param {Function} callback The callback is called with two parameters: + * value1 and value2, which contain the current + * element of both arrays. + * @param {boolean} [skipZeros] Invoke callback function for non-zero values only. + * + * @return {Array | Matrix} res + */ + +function deepMap(array, callback, skipZeros) { + if (array && typeof array.map === 'function') { + // TODO: replace array.map with a for loop to improve performance + return array.map(function (x) { + return deepMap(x, callback, skipZeros); + }); + } else { + return callback(array); + } +} +/** + * Reduce a given matrix or array to a new matrix or + * array with one less dimension, applying the given + * callback in the selected dimension. + * @param {Array | Matrix} mat + * @param {number} dim + * @param {Function} callback + * @return {Array | Matrix} res + */ + +function reduce(mat, dim, callback) { + var size = Array.isArray(mat) ? Object(utils_array["a" /* arraySize */])(mat) : mat.size(); + + if (dim < 0 || dim >= size.length) { + // TODO: would be more clear when throwing a DimensionError here + throw new IndexError["a" /* IndexError */](dim, size.length); + } + + if (Object(is["v" /* isMatrix */])(mat)) { + return mat.create(_reduce(mat.valueOf(), dim, callback)); + } else { + return _reduce(mat, dim, callback); + } +} +/** + * Recursively reduce a matrix + * @param {Array} mat + * @param {number} dim + * @param {Function} callback + * @returns {Array} ret + * @private + */ + +function _reduce(mat, dim, callback) { + var i, ret, val, tran; + + if (dim <= 0) { + if (!Array.isArray(mat[0])) { + val = mat[0]; + + for (i = 1; i < mat.length; i++) { + val = callback(val, mat[i]); + } + + return val; + } else { + tran = _switch(mat); + ret = []; + + for (i = 0; i < tran.length; i++) { + ret[i] = _reduce(tran[i], dim - 1, callback); + } + + return ret; + } + } else { + ret = []; + + for (i = 0; i < mat.length; i++) { + ret[i] = _reduce(mat[i], dim - 1, callback); + } + + return ret; + } +} +/** + * Transpose a matrix + * @param {Array} mat + * @returns {Array} ret + * @private + */ + + +function _switch(mat) { + var I = mat.length; + var J = mat[0].length; + var i, j; + var ret = []; + + for (j = 0; j < J; j++) { + var tmp = []; + + for (i = 0; i < I; i++) { + tmp.push(mat[i][j]); + } + + ret.push(tmp); + } + + return ret; +} // TODO: document function scatter + + +function scatter(a, j, w, x, u, mark, cindex, f, inverse, update, value) { + // a arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; // vars + + var k, k0, k1, i; // check we need to process values (pattern matrix) + + if (x) { + // values in j + for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + i = aindex[k]; // check value exists in current j + + if (w[i] !== mark) { + // i is new entry in j + w[i] = mark; // add i to pattern of C + + cindex.push(i); // x(i) = A, check we need to call function this time + + if (update) { + // copy value to workspace calling callback function + x[i] = inverse ? f(avalues[k], value) : f(value, avalues[k]); // function was called on current row + + u[i] = mark; + } else { + // copy value to workspace + x[i] = avalues[k]; + } + } else { + // i exists in C already + x[i] = inverse ? f(avalues[k], x[i]) : f(x[i], avalues[k]); // function was called on current row + + u[i] = mark; + } + } + } else { + // values in j + for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + i = aindex[k]; // check value exists in current j + + if (w[i] !== mark) { + // i is new entry in j + w[i] = mark; // add i to pattern of C + + cindex.push(i); + } else { + // indicate function was called on current row + u[i] = mark; + } + } + } +} +// CONCATENATED MODULE: ./src/function/utils/isInteger.js + + + +var isInteger_name = 'isInteger'; +var isInteger_dependencies = ['typed']; +var createIsInteger = /* #__PURE__ */Object(factory["a" /* factory */])(isInteger_name, isInteger_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is an integer number. + * The function supports `number`, `BigNumber`, and `Fraction`. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isInteger(x) + * + * Examples: + * + * math.isInteger(2) // returns true + * math.isInteger(0) // returns true + * math.isInteger(0.5) // returns false + * math.isInteger(math.bignumber(500)) // returns true + * math.isInteger(math.fraction(4)) // returns true + * math.isInteger('3') // returns true + * math.isInteger([3, 0.5, -2]) // returns [true, false, true] + * math.isInteger(math.complex('2-4i') // throws an error + * + * See also: + * + * isNumeric, isPositive, isNegative, isZero + * + * @param {number | BigNumber | Fraction | Array | Matrix} x Value to be tested + * @return {boolean} Returns true when `x` contains a numeric, integer value. + * Throws an error in case of an unknown data type. + */ + var isInteger = typed(isInteger_name, { + number: utils_number["i" /* isInteger */], + // TODO: what to do with isInteger(add(0.1, 0.2)) ? + BigNumber: function BigNumber(x) { + return x.isInt(); + }, + Fraction: function Fraction(x) { + return x.d === 1 && isFinite(x.n); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, isInteger); + } + }); + return isInteger; +}); +// CONCATENATED MODULE: ./src/plain/number/utils.js + +var utils_n1 = 'number'; +function isIntegerNumber(x) { + return Object(utils_number["i" /* isInteger */])(x); +} +isIntegerNumber.signature = utils_n1; +function isNegativeNumber(x) { + return x < 0; +} +isNegativeNumber.signature = utils_n1; +function isPositiveNumber(x) { + return x > 0; +} +isPositiveNumber.signature = utils_n1; +function isZeroNumber(x) { + return x === 0; +} +isZeroNumber.signature = utils_n1; +function isNaNNumber(x) { + return Number.isNaN(x); +} +isNaNNumber.signature = utils_n1; +// CONCATENATED MODULE: ./src/function/utils/isNegative.js + + + +var isNegative_name = 'isNegative'; +var isNegative_dependencies = ['typed']; +var createIsNegative = /* #__PURE__ */Object(factory["a" /* factory */])(isNegative_name, isNegative_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is negative: smaller than zero. + * The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isNegative(x) + * + * Examples: + * + * math.isNegative(3) // returns false + * math.isNegative(-2) // returns true + * math.isNegative(0) // returns false + * math.isNegative(-0) // returns false + * math.isNegative(math.bignumber(2)) // returns false + * math.isNegative(math.fraction(-2, 5)) // returns true + * math.isNegative('-2') // returns true + * math.isNegative([2, 0, -3]') // returns [false, false, true] + * + * See also: + * + * isNumeric, isPositive, isZero, isInteger + * + * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested + * @return {boolean} Returns true when `x` is larger than zero. + * Throws an error in case of an unknown data type. + */ + var isNegative = typed(isNegative_name, { + number: isNegativeNumber, + BigNumber: function BigNumber(x) { + return x.isNeg() && !x.isZero() && !x.isNaN(); + }, + Fraction: function Fraction(x) { + return x.s < 0; // It's enough to decide on the sign + }, + Unit: function Unit(x) { + return isNegative(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, isNegative); + } + }); + return isNegative; +}); +// CONCATENATED MODULE: ./src/function/utils/isNumeric.js + + +var isNumeric_name = 'isNumeric'; +var isNumeric_dependencies = ['typed']; +var createIsNumeric = /* #__PURE__ */Object(factory["a" /* factory */])(isNumeric_name, isNumeric_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is an numeric value. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isNumeric(x) + * + * Examples: + * + * math.isNumeric(2) // returns true + * math.isNumeric('2') // returns false + * math.hasNumericValue('2') // returns true + * math.isNumeric(0) // returns true + * math.isNumeric(math.bignumber(500)) // returns true + * math.isNumeric(math.fraction(4)) // returns true + * math.isNumeric(math.complex('2-4i') // returns false + * math.isNumeric([2.3, 'foo', false]) // returns [true, false, true] + * + * See also: + * + * isZero, isPositive, isNegative, isInteger, hasNumericValue + * + * @param {*} x Value to be tested + * @return {boolean} Returns true when `x` is a `number`, `BigNumber`, + * `Fraction`, or `boolean`. Returns false for other types. + * Throws an error in case of unknown types. + */ + var isNumeric = typed(isNumeric_name, { + 'number | BigNumber | Fraction | boolean': function numberBigNumberFractionBoolean() { + return true; + }, + 'Complex | Unit | string | null | undefined | Node': function ComplexUnitStringNullUndefinedNode() { + return false; + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, isNumeric); + } + }); + return isNumeric; +}); +// CONCATENATED MODULE: ./src/function/utils/hasNumericValue.js + +var hasNumericValue_name = 'hasNumericValue'; +var hasNumericValue_dependencies = ['typed', 'isNumeric']; +var createHasNumericValue = /* #__PURE__ */Object(factory["a" /* factory */])(hasNumericValue_name, hasNumericValue_dependencies, function (_ref) { + var typed = _ref.typed, + isNumeric = _ref.isNumeric; + + /** + * Test whether a value is an numeric value. + * + * In case of a string, true is returned if the string contains a numeric value. + * + * Syntax: + * + * math.hasNumericValue(x) + * + * Examples: + * + * math.hasNumericValue(2) // returns true + * math.hasNumericValue('2') // returns true + * math.isNumeric('2') // returns false + * math.hasNumericValue(0) // returns true + * math.hasNumericValue(math.bignumber(500)) // returns true + * math.hasNumericValue(math.fraction(4)) // returns true + * math.hasNumericValue(math.complex('2-4i') // returns false + * math.hasNumericValue([2.3, 'foo', false]) // returns [true, false, true] + * + * See also: + * + * isZero, isPositive, isNegative, isInteger, isNumeric + * + * @param {*} x Value to be tested + * @return {boolean} Returns true when `x` is a `number`, `BigNumber`, + * `Fraction`, `Boolean`, or a `String` containing number. Returns false for other types. + * Throws an error in case of unknown types. + */ + return typed(hasNumericValue_name, { + string: function string(x) { + return x.trim().length > 0 && !isNaN(Number(x)); + }, + any: function any(x) { + return isNumeric(x); + } + }); +}); +// CONCATENATED MODULE: ./src/function/utils/isPositive.js + + + +var isPositive_name = 'isPositive'; +var isPositive_dependencies = ['typed']; +var createIsPositive = /* #__PURE__ */Object(factory["a" /* factory */])(isPositive_name, isPositive_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is positive: larger than zero. + * The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isPositive(x) + * + * Examples: + * + * math.isPositive(3) // returns true + * math.isPositive(-2) // returns false + * math.isPositive(0) // returns false + * math.isPositive(-0) // returns false + * math.isPositive(0.5) // returns true + * math.isPositive(math.bignumber(2)) // returns true + * math.isPositive(math.fraction(-2, 5)) // returns false + * math.isPositive(math.fraction(1,3)) // returns false + * math.isPositive('2') // returns true + * math.isPositive([2, 0, -3]) // returns [true, false, false] + * + * See also: + * + * isNumeric, isZero, isNegative, isInteger + * + * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested + * @return {boolean} Returns true when `x` is larger than zero. + * Throws an error in case of an unknown data type. + */ + var isPositive = typed(isPositive_name, { + number: isPositiveNumber, + BigNumber: function BigNumber(x) { + return !x.isNeg() && !x.isZero() && !x.isNaN(); + }, + Fraction: function Fraction(x) { + return x.s > 0 && x.n > 0; + }, + Unit: function Unit(x) { + return isPositive(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, isPositive); + } + }); + return isPositive; +}); +// CONCATENATED MODULE: ./src/function/utils/isZero.js + + + +var isZero_name = 'isZero'; +var isZero_dependencies = ['typed']; +var createIsZero = /* #__PURE__ */Object(factory["a" /* factory */])(isZero_name, isZero_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is zero. + * The function can check for zero for types `number`, `BigNumber`, `Fraction`, + * `Complex`, and `Unit`. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isZero(x) + * + * Examples: + * + * math.isZero(0) // returns true + * math.isZero(2) // returns false + * math.isZero(0.5) // returns false + * math.isZero(math.bignumber(0)) // returns true + * math.isZero(math.fraction(0)) // returns true + * math.isZero(math.fraction(1,3)) // returns false + * math.isZero(math.complex('2 - 4i') // returns false + * math.isZero(math.complex('0i') // returns true + * math.isZero('0') // returns true + * math.isZero('2') // returns false + * math.isZero([2, 0, -3]') // returns [false, true, false] + * + * See also: + * + * isNumeric, isPositive, isNegative, isInteger + * + * @param {number | BigNumber | Complex | Fraction | Unit | Array | Matrix} x Value to be tested + * @return {boolean} Returns true when `x` is zero. + * Throws an error in case of an unknown data type. + */ + var isZero = typed(isZero_name, { + number: isZeroNumber, + BigNumber: function BigNumber(x) { + return x.isZero(); + }, + Complex: function Complex(x) { + return x.re === 0 && x.im === 0; + }, + Fraction: function Fraction(x) { + return x.d === 1 && x.n === 0; + }, + Unit: function Unit(x) { + return isZero(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, isZero); + } + }); + return isZero; +}); +// CONCATENATED MODULE: ./src/function/utils/isNaN.js + + + +var isNaN_name = 'isNaN'; +var isNaN_dependencies = ['typed']; +var createIsNaN = /* #__PURE__ */Object(factory["a" /* factory */])(isNaN_name, isNaN_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is NaN (not a number). + * The function supports types `number`, `BigNumber`, `Fraction`, `Unit` and `Complex`. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isNaN(x) + * + * Examples: + * + * math.isNaN(3) // returns false + * math.isNaN(NaN) // returns true + * math.isNaN(0) // returns false + * math.isNaN(math.bignumber(NaN)) // returns true + * math.isNaN(math.bignumber(0)) // returns false + * math.isNaN(math.fraction(-2, 5)) // returns false + * math.isNaN('-2') // returns false + * math.isNaN([2, 0, -3, NaN]') // returns [false, false, false, true] + * + * See also: + * + * isNumeric, isNegative, isPositive, isZero, isInteger + * + * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested + * @return {boolean} Returns true when `x` is NaN. + * Throws an error in case of an unknown data type. + */ + return typed(isNaN_name, { + number: isNaNNumber, + BigNumber: function BigNumber(x) { + return x.isNaN(); + }, + Fraction: function Fraction(x) { + return false; + }, + Complex: function Complex(x) { + return x.isNaN(); + }, + Unit: function Unit(x) { + return Number.isNaN(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, Number.isNaN); + } + }); +}); +// EXTERNAL MODULE: ./src/utils/log.js +var utils_log = __webpack_require__(8); + +// CONCATENATED MODULE: ./src/function/utils/typeOf.js + + + +var typeOf_name = 'typeOf'; +var typeOf_dependencies = ['typed']; +var createTypeOf = /* #__PURE__ */Object(factory["a" /* factory */])(typeOf_name, typeOf_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Determine the type of a variable. + * + * Function `typeOf` recognizes the following types of objects: + * + * Object | Returns | Example + * ---------------------- | ------------- | ------------------------------------------ + * null | `'null'` | `math.typeOf(null)` + * number | `'number'` | `math.typeOf(3.5)` + * boolean | `'boolean'` | `math.typeOf(true)` + * string | `'string'` | `math.typeOf('hello world')` + * Array | `'Array'` | `math.typeOf([1, 2, 3])` + * Date | `'Date'` | `math.typeOf(new Date())` + * Function | `'Function'` | `math.typeOf(function () {})` + * Object | `'Object'` | `math.typeOf({a: 2, b: 3})` + * RegExp | `'RegExp'` | `math.typeOf(/a regexp/)` + * undefined | `'undefined'` | `math.typeOf(undefined)` + * math.BigNumber | `'BigNumber'` | `math.typeOf(math.bignumber('2.3e500'))` + * math.Chain | `'Chain'` | `math.typeOf(math.chain(2))` + * math.Complex | `'Complex'` | `math.typeOf(math.complex(2, 3))` + * math.Fraction | `'Fraction'` | `math.typeOf(math.fraction(1, 3))` + * math.Help | `'Help'` | `math.typeOf(math.help('sqrt'))` + * math.Help | `'Help'` | `math.typeOf(math.help('sqrt'))` + * math.Index | `'Index'` | `math.typeOf(math.index(1, 3))` + * math.Matrix | `'Matrix'` | `math.typeOf(math.matrix([[1,2], [3, 4]]))` + * math.Range | `'Range'` | `math.typeOf(math.range(0, 10))` + * math.ResultSet | `'ResultSet'` | `math.typeOf(math.evaluate('a=2\nb=3'))` + * math.Unit | `'Unit'` | `math.typeOf(math.unit('45 deg'))` + * math.AccessorNode | `'AccessorNode'` | `math.typeOf(math.parse('A[2]'))` + * math.ArrayNode | `'ArrayNode'` | `math.typeOf(math.parse('[1,2,3]'))` + * math.AssignmentNode | `'AssignmentNode'` | `math.typeOf(math.parse('x=2'))` + * math.BlockNode | `'BlockNode'` | `math.typeOf(math.parse('a=2; b=3'))` + * math.ConditionalNode | `'ConditionalNode'` | `math.typeOf(math.parse('x<0 ? -x : x'))` + * math.ConstantNode | `'ConstantNode'` | `math.typeOf(math.parse('2.3'))` + * math.FunctionAssignmentNode | `'FunctionAssignmentNode'` | `math.typeOf(math.parse('f(x)=x^2'))` + * math.FunctionNode | `'FunctionNode'` | `math.typeOf(math.parse('sqrt(4)'))` + * math.IndexNode | `'IndexNode'` | `math.typeOf(math.parse('A[2]').index)` + * math.ObjectNode | `'ObjectNode'` | `math.typeOf(math.parse('{a:2}'))` + * math.ParenthesisNode | `'ParenthesisNode'` | `math.typeOf(math.parse('(2+3)'))` + * math.RangeNode | `'RangeNode'` | `math.typeOf(math.parse('1:10'))` + * math.SymbolNode | `'SymbolNode'` | `math.typeOf(math.parse('x'))` + * + * Syntax: + * + * math.typeOf(x) + * + * Examples: + * + * math.typeOf(3.5) // returns 'number' + * math.typeOf(math.complex('2-4i')) // returns 'Complex' + * math.typeOf(math.unit('45 deg')) // returns 'Unit' + * math.typeOf('hello world') // returns 'string' + * + * @param {*} x The variable for which to test the type. + * @return {string} Returns the name of the type. Primitive types are lower case, + * non-primitive types are upper-camel-case. + * For example 'number', 'string', 'Array', 'Date'. + */ + return typed(typeOf_name, { + any: is["M" /* typeOf */] + }); +}); // For backward compatibility, deprecated since version 6.0.0. Date: 2018-11-06 + +var createDeprecatedTypeof = /* #__PURE__ */Object(factory["a" /* factory */])('typeof', [], function () { + return function () { + Object(utils_log["a" /* warnOnce */])('Function "typeof" has been renamed to "typeOf" in v6.0.0, please use the new function instead.'); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return is["M" /* typeOf */].apply(is["M" /* typeOf */], args); + }; +}); +// CONCATENATED MODULE: ./src/utils/bignumber/nearlyEqual.js +/** + * Compares two BigNumbers. + * @param {BigNumber} x First value to compare + * @param {BigNumber} y Second value to compare + * @param {number} [epsilon] The maximum relative difference between x and y + * If epsilon is undefined or null, the function will + * test whether x and y are exactly equal. + * @return {boolean} whether the two numbers are nearly equal + */ +function nearlyEqual(x, y, epsilon) { + // if epsilon is null or undefined, test whether x and y are exactly equal + if (epsilon === null || epsilon === undefined) { + return x.eq(y); + } // use "==" operator, handles infinities + + + if (x.eq(y)) { + return true; + } // NaN + + + if (x.isNaN() || y.isNaN()) { + return false; + } // at this point x and y should be finite + + + if (x.isFinite() && y.isFinite()) { + // check numbers are very close, needed when comparing numbers near zero + var diff = x.minus(y).abs(); + + if (diff.isZero()) { + return true; + } else { + // use relative error + var max = x.constructor.max(x.abs(), y.abs()); + return diff.lte(max.times(epsilon)); + } + } // Infinite and Number or negative Infinite and positive Infinite cases + + + return false; +} +// CONCATENATED MODULE: ./src/utils/complex.js + +/** + * Test whether two complex values are equal provided a given epsilon. + * Does not use or change the global Complex.EPSILON setting + * @param {Complex} x + * @param {Complex} y + * @param {number} epsilon + * @returns {boolean} + */ + +function complexEquals(x, y, epsilon) { + return Object(utils_number["m" /* nearlyEqual */])(x.re, y.re, epsilon) && Object(utils_number["m" /* nearlyEqual */])(x.im, y.im, epsilon); +} +// CONCATENATED MODULE: ./src/function/relational/equalScalar.js + + + + +var equalScalar_name = 'equalScalar'; +var equalScalar_dependencies = ['typed', 'config']; +var createEqualScalar = /* #__PURE__ */Object(factory["a" /* factory */])(equalScalar_name, equalScalar_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config; + + /** + * Test whether two scalar values are nearly equal. + * + * @param {number | BigNumber | Fraction | boolean | Complex | Unit} x First value to compare + * @param {number | BigNumber | Fraction | boolean | Complex} y Second value to compare + * @return {boolean} Returns true when the compared values are equal, else returns false + * @private + */ + var equalScalar = typed(equalScalar_name, { + 'boolean, boolean': function booleanBoolean(x, y) { + return x === y; + }, + 'number, number': function numberNumber(x, y) { + return Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.eq(y) || nearlyEqual(x, y, config.epsilon); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.equals(y); + }, + 'Complex, Complex': function ComplexComplex(x, y) { + return complexEquals(x, y, config.epsilon); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (!x.equalBase(y)) { + throw new Error('Cannot compare units with different base'); + } + + return equalScalar(x.value, y.value); + } + }); + return equalScalar; +}); +var createEqualScalarNumber = Object(factory["a" /* factory */])(equalScalar_name, ['typed', 'config'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config; + return typed(equalScalar_name, { + 'number, number': function numberNumber(x, y) { + return Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + } + }); +}); +// CONCATENATED MODULE: ./src/type/matrix/SparseMatrix.js + + + + + + + +var SparseMatrix_name = 'SparseMatrix'; +var SparseMatrix_dependencies = ['typed', 'equalScalar', 'Matrix']; +var createSparseMatrixClass = /* #__PURE__ */Object(factory["a" /* factory */])(SparseMatrix_name, SparseMatrix_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar, + Matrix = _ref.Matrix; + + /** + * Sparse Matrix implementation. This type implements a Compressed Column Storage format + * for sparse matrices. + * @class SparseMatrix + */ + function SparseMatrix(data, datatype) { + if (!(this instanceof SparseMatrix)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (datatype && !Object(is["I" /* isString */])(datatype)) { + throw new Error('Invalid datatype: ' + datatype); + } + + if (Object(is["v" /* isMatrix */])(data)) { + // create from matrix + _createFromMatrix(this, data, datatype); + } else if (data && Object(is["b" /* isArray */])(data.index) && Object(is["b" /* isArray */])(data.ptr) && Object(is["b" /* isArray */])(data.size)) { + // initialize fields + this._values = data.values; + this._index = data.index; + this._ptr = data.ptr; + this._size = data.size; + this._datatype = datatype || data.datatype; + } else if (Object(is["b" /* isArray */])(data)) { + // create from array + _createFromArray(this, data, datatype); + } else if (data) { + // unsupported type + throw new TypeError('Unsupported type of data (' + Object(is["M" /* typeOf */])(data) + ')'); + } else { + // nothing provided + this._values = []; + this._index = []; + this._ptr = [0]; + this._size = [0, 0]; + this._datatype = datatype; + } + } + + function _createFromMatrix(matrix, source, datatype) { + // check matrix type + if (source.type === 'SparseMatrix') { + // clone arrays + matrix._values = source._values ? Object(utils_object["a" /* clone */])(source._values) : undefined; + matrix._index = Object(utils_object["a" /* clone */])(source._index); + matrix._ptr = Object(utils_object["a" /* clone */])(source._ptr); + matrix._size = Object(utils_object["a" /* clone */])(source._size); + matrix._datatype = datatype || source._datatype; + } else { + // build from matrix data + _createFromArray(matrix, source.valueOf(), datatype || source._datatype); + } + } + + function _createFromArray(matrix, data, datatype) { + // initialize fields + matrix._values = []; + matrix._index = []; + matrix._ptr = []; + matrix._datatype = datatype; // discover rows & columns, do not use math.size() to avoid looping array twice + + var rows = data.length; + var columns = 0; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; + + if (Object(is["I" /* isString */])(datatype)) { + // find signature that matches (datatype, datatype) + eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar; // convert 0 to the same datatype + + zero = typed.convert(0, datatype); + } // check we have rows (empty array) + + + if (rows > 0) { + // column index + var j = 0; + + do { + // store pointer to values index + matrix._ptr.push(matrix._index.length); // loop rows + + + for (var i = 0; i < rows; i++) { + // current row + var row = data[i]; // check row is an array + + if (Object(is["b" /* isArray */])(row)) { + // update columns if needed (only on first column) + if (j === 0 && columns < row.length) { + columns = row.length; + } // check row has column + + + if (j < row.length) { + // value + var v = row[j]; // check value != 0 + + if (!eq(v, zero)) { + // store value + matrix._values.push(v); // index + + + matrix._index.push(i); + } + } + } else { + // update columns if needed (only on first column) + if (j === 0 && columns < 1) { + columns = 1; + } // check value != 0 (row is a scalar) + + + if (!eq(row, zero)) { + // store value + matrix._values.push(row); // index + + + matrix._index.push(i); + } + } + } // increment index + + + j++; + } while (j < columns); + } // store number of values in ptr + + + matrix._ptr.push(matrix._index.length); // size + + + matrix._size = [rows, columns]; + } + + SparseMatrix.prototype = new Matrix(); + /** + * Create a new SparseMatrix + */ + + SparseMatrix.prototype.createSparseMatrix = function (data, datatype) { + return new SparseMatrix(data, datatype); + }; + /** + * Attach type information + */ + + + SparseMatrix.prototype.type = 'SparseMatrix'; + SparseMatrix.prototype.isSparseMatrix = true; + /** + * Get the matrix type + * + * Usage: + * const matrixType = matrix.getDataType() // retrieves the matrix type + * + * @memberOf SparseMatrix + * @return {string} type information; if multiple types are found from the Matrix, it will return "mixed" + */ + + SparseMatrix.prototype.getDataType = function () { + return Object(utils_array["h" /* getArrayDataType */])(this._values, is["M" /* typeOf */]); + }; + /** + * Get the storage format used by the matrix. + * + * Usage: + * const format = matrix.storage() // retrieve storage format + * + * @memberof SparseMatrix + * @return {string} The storage format. + */ + + + SparseMatrix.prototype.storage = function () { + return 'sparse'; + }; + /** + * Get the datatype of the data stored in the matrix. + * + * Usage: + * const format = matrix.datatype() // retrieve matrix datatype + * + * @memberof SparseMatrix + * @return {string} The datatype. + */ + + + SparseMatrix.prototype.datatype = function () { + return this._datatype; + }; + /** + * Create a new SparseMatrix + * @memberof SparseMatrix + * @param {Array} data + * @param {string} [datatype] + */ + + + SparseMatrix.prototype.create = function (data, datatype) { + return new SparseMatrix(data, datatype); + }; + /** + * Get the matrix density. + * + * Usage: + * const density = matrix.density() // retrieve matrix density + * + * @memberof SparseMatrix + * @return {number} The matrix density. + */ + + + SparseMatrix.prototype.density = function () { + // rows & columns + var rows = this._size[0]; + var columns = this._size[1]; // calculate density + + return rows !== 0 && columns !== 0 ? this._index.length / (rows * columns) : 0; + }; + /** + * Get a subset of the matrix, or replace a subset of the matrix. + * + * Usage: + * const subset = matrix.subset(index) // retrieve subset + * const value = matrix.subset(index, replacement) // replace subset + * + * @memberof SparseMatrix + * @param {Index} index + * @param {Array | Matrix | *} [replacement] + * @param {*} [defaultValue=0] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be filled with zeros. + */ + + + SparseMatrix.prototype.subset = function (index, replacement, defaultValue) { + // check it is a pattern matrix + if (!this._values) { + throw new Error('Cannot invoke subset on a Pattern only matrix'); + } // check arguments + + + switch (arguments.length) { + case 1: + return _getsubset(this, index); + // intentional fall through + + case 2: + case 3: + return _setsubset(this, index, replacement, defaultValue); + + default: + throw new SyntaxError('Wrong number of arguments'); + } + }; + + function _getsubset(matrix, idx) { + // check idx + if (!Object(is["t" /* isIndex */])(idx)) { + throw new TypeError('Invalid index'); + } + + var isScalar = idx.isScalar(); + + if (isScalar) { + // return a scalar + return matrix.get(idx.min()); + } // validate dimensions + + + var size = idx.size(); + + if (size.length !== matrix._size.length) { + throw new DimensionError["a" /* DimensionError */](size.length, matrix._size.length); + } // vars + + + var i, ii, k, kk; // validate if any of the ranges in the index is out of range + + var min = idx.min(); + var max = idx.max(); + + for (i = 0, ii = matrix._size.length; i < ii; i++) { + Object(utils_array["s" /* validateIndex */])(min[i], matrix._size[i]); + Object(utils_array["s" /* validateIndex */])(max[i], matrix._size[i]); + } // matrix arrays + + + var mvalues = matrix._values; + var mindex = matrix._index; + var mptr = matrix._ptr; // rows & columns dimensions for result matrix + + var rows = idx.dimension(0); + var columns = idx.dimension(1); // workspace & permutation vector + + var w = []; + var pv = []; // loop rows in resulting matrix + + rows.forEach(function (i, r) { + // update permutation vector + pv[i] = r[0]; // mark i in workspace + + w[i] = true; + }); // result matrix arrays + + var values = mvalues ? [] : undefined; + var index = []; + var ptr = []; // loop columns in result matrix + + columns.forEach(function (j) { + // update ptr + ptr.push(index.length); // loop values in column j + + for (k = mptr[j], kk = mptr[j + 1]; k < kk; k++) { + // row + i = mindex[k]; // check row is in result matrix + + if (w[i] === true) { + // push index + index.push(pv[i]); // check we need to process values + + if (values) { + values.push(mvalues[k]); + } + } + } + }); // update ptr + + ptr.push(index.length); // return matrix + + return new SparseMatrix({ + values: values, + index: index, + ptr: ptr, + size: size, + datatype: matrix._datatype + }); + } + + function _setsubset(matrix, index, submatrix, defaultValue) { + // check index + if (!index || index.isIndex !== true) { + throw new TypeError('Invalid index'); + } // get index size and check whether the index contains a single value + + + var iSize = index.size(); + var isScalar = index.isScalar(); // calculate the size of the submatrix, and convert it into an Array if needed + + var sSize; + + if (Object(is["v" /* isMatrix */])(submatrix)) { + // submatrix size + sSize = submatrix.size(); // use array representation + + submatrix = submatrix.toArray(); + } else { + // get submatrix size (array, scalar) + sSize = Object(utils_array["a" /* arraySize */])(submatrix); + } // check index is a scalar + + + if (isScalar) { + // verify submatrix is a scalar + if (sSize.length !== 0) { + throw new TypeError('Scalar expected'); + } // set value + + + matrix.set(index.min(), submatrix, defaultValue); + } else { + // validate dimensions, index size must be one or two dimensions + if (iSize.length !== 1 && iSize.length !== 2) { + throw new DimensionError["a" /* DimensionError */](iSize.length, matrix._size.length, '<'); + } // check submatrix and index have the same dimensions + + + if (sSize.length < iSize.length) { + // calculate number of missing outer dimensions + var i = 0; + var outer = 0; + + while (iSize[i] === 1 && sSize[i] === 1) { + i++; + } + + while (iSize[i] === 1) { + outer++; + i++; + } // unsqueeze both outer and inner dimensions + + + submatrix = Object(utils_array["q" /* unsqueeze */])(submatrix, iSize.length, outer, sSize); + } // check whether the size of the submatrix matches the index size + + + if (!Object(utils_object["d" /* deepStrictEqual */])(iSize, sSize)) { + throw new DimensionError["a" /* DimensionError */](iSize, sSize, '>'); + } // offsets + + + var x0 = index.min()[0]; + var y0 = index.min()[1]; // submatrix rows and columns + + var m = sSize[0]; + var n = sSize[1]; // loop submatrix + + for (var x = 0; x < m; x++) { + // loop columns + for (var y = 0; y < n; y++) { + // value at i, j + var v = submatrix[x][y]; // invoke set (zero value will remove entry from matrix) + + matrix.set([x + x0, y + y0], v, defaultValue); + } + } + } + + return matrix; + } + /** + * Get a single element from the matrix. + * @memberof SparseMatrix + * @param {number[]} index Zero-based index + * @return {*} value + */ + + + SparseMatrix.prototype.get = function (index) { + if (!Object(is["b" /* isArray */])(index)) { + throw new TypeError('Array expected'); + } + + if (index.length !== this._size.length) { + throw new DimensionError["a" /* DimensionError */](index.length, this._size.length); + } // check it is a pattern matrix + + + if (!this._values) { + throw new Error('Cannot invoke get on a Pattern only matrix'); + } // row and column + + + var i = index[0]; + var j = index[1]; // check i, j are valid + + Object(utils_array["s" /* validateIndex */])(i, this._size[0]); + Object(utils_array["s" /* validateIndex */])(j, this._size[1]); // find value index + + var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index); // check k is prior to next column k and it is in the correct row + + + if (k < this._ptr[j + 1] && this._index[k] === i) { + return this._values[k]; + } + + return 0; + }; + /** + * Replace a single element in the matrix. + * @memberof SparseMatrix + * @param {number[]} index Zero-based index + * @param {*} v + * @param {*} [defaultValue] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be set to zero. + * @return {SparseMatrix} self + */ + + + SparseMatrix.prototype.set = function (index, v, defaultValue) { + if (!Object(is["b" /* isArray */])(index)) { + throw new TypeError('Array expected'); + } + + if (index.length !== this._size.length) { + throw new DimensionError["a" /* DimensionError */](index.length, this._size.length); + } // check it is a pattern matrix + + + if (!this._values) { + throw new Error('Cannot invoke set on a Pattern only matrix'); + } // row and column + + + var i = index[0]; + var j = index[1]; // rows & columns + + var rows = this._size[0]; + var columns = this._size[1]; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; + + if (Object(is["I" /* isString */])(this._datatype)) { + // find signature that matches (datatype, datatype) + eq = typed.find(equalScalar, [this._datatype, this._datatype]) || equalScalar; // convert 0 to the same datatype + + zero = typed.convert(0, this._datatype); + } // check we need to resize matrix + + + if (i > rows - 1 || j > columns - 1) { + // resize matrix + _resize(this, Math.max(i + 1, rows), Math.max(j + 1, columns), defaultValue); // update rows & columns + + + rows = this._size[0]; + columns = this._size[1]; + } // check i, j are valid + + + Object(utils_array["s" /* validateIndex */])(i, rows); + Object(utils_array["s" /* validateIndex */])(j, columns); // find value index + + var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index); // check k is prior to next column k and it is in the correct row + + + if (k < this._ptr[j + 1] && this._index[k] === i) { + // check value != 0 + if (!eq(v, zero)) { + // update value + this._values[k] = v; + } else { + // remove value from matrix + _remove(k, j, this._values, this._index, this._ptr); + } + } else { + // insert value @ (i, j) + _insert(k, i, j, v, this._values, this._index, this._ptr); + } + + return this; + }; + + function _getValueIndex(i, top, bottom, index) { + // check row is on the bottom side + if (bottom - top === 0) { + return bottom; + } // loop rows [top, bottom[ + + + for (var r = top; r < bottom; r++) { + // check we found value index + if (index[r] === i) { + return r; + } + } // we did not find row + + + return top; + } + + function _remove(k, j, values, index, ptr) { + // remove value @ k + values.splice(k, 1); + index.splice(k, 1); // update pointers + + for (var x = j + 1; x < ptr.length; x++) { + ptr[x]--; + } + } + + function _insert(k, i, j, v, values, index, ptr) { + // insert value + values.splice(k, 0, v); // update row for k + + index.splice(k, 0, i); // update column pointers + + for (var x = j + 1; x < ptr.length; x++) { + ptr[x]++; + } + } + /** + * Resize the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (resize in place). + * + * @memberof SparseMatrix + * @param {number[]} size The new size the matrix should have. + * @param {*} [defaultValue=0] Default value, filled in on new entries. + * If not provided, the matrix elements will + * be filled with zeros. + * @param {boolean} [copy] Return a resized copy of the matrix + * + * @return {Matrix} The resized matrix + */ + + + SparseMatrix.prototype.resize = function (size, defaultValue, copy) { + // validate arguments + if (!Object(is["b" /* isArray */])(size)) { + throw new TypeError('Array expected'); + } + + if (size.length !== 2) { + throw new Error('Only two dimensions matrix are supported'); + } // check sizes + + + size.forEach(function (value) { + if (!Object(is["y" /* isNumber */])(value) || !Object(utils_number["i" /* isInteger */])(value) || value < 0) { + throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + }); // matrix to resize + + var m = copy ? this.clone() : this; // resize matrix + + return _resize(m, size[0], size[1], defaultValue); + }; + + function _resize(matrix, rows, columns, defaultValue) { + // value to insert at the time of growing matrix + var value = defaultValue || 0; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; + + if (Object(is["I" /* isString */])(matrix._datatype)) { + // find signature that matches (datatype, datatype) + eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar; // convert 0 to the same datatype + + zero = typed.convert(0, matrix._datatype); // convert value to the same datatype + + value = typed.convert(value, matrix._datatype); + } // should we insert the value? + + + var ins = !eq(value, zero); // old columns and rows + + var r = matrix._size[0]; + var c = matrix._size[1]; + var i, j, k; // check we need to increase columns + + if (columns > c) { + // loop new columns + for (j = c; j < columns; j++) { + // update matrix._ptr for current column + matrix._ptr[j] = matrix._values.length; // check we need to insert matrix._values + + if (ins) { + // loop rows + for (i = 0; i < r; i++) { + // add new matrix._values + matrix._values.push(value); // update matrix._index + + + matrix._index.push(i); + } + } + } // store number of matrix._values in matrix._ptr + + + matrix._ptr[columns] = matrix._values.length; + } else if (columns < c) { + // truncate matrix._ptr + matrix._ptr.splice(columns + 1, c - columns); // truncate matrix._values and matrix._index + + + matrix._values.splice(matrix._ptr[columns], matrix._values.length); + + matrix._index.splice(matrix._ptr[columns], matrix._index.length); + } // update columns + + + c = columns; // check we need to increase rows + + if (rows > r) { + // check we have to insert values + if (ins) { + // inserts + var n = 0; // loop columns + + for (j = 0; j < c; j++) { + // update matrix._ptr for current column + matrix._ptr[j] = matrix._ptr[j] + n; // where to insert matrix._values + + k = matrix._ptr[j + 1] + n; // pointer + + var p = 0; // loop new rows, initialize pointer + + for (i = r; i < rows; i++, p++) { + // add value + matrix._values.splice(k + p, 0, value); // update matrix._index + + + matrix._index.splice(k + p, 0, i); // increment inserts + + + n++; + } + } // store number of matrix._values in matrix._ptr + + + matrix._ptr[c] = matrix._values.length; + } + } else if (rows < r) { + // deletes + var d = 0; // loop columns + + for (j = 0; j < c; j++) { + // update matrix._ptr for current column + matrix._ptr[j] = matrix._ptr[j] - d; // where matrix._values start for next column + + var k0 = matrix._ptr[j]; + var k1 = matrix._ptr[j + 1] - d; // loop matrix._index + + for (k = k0; k < k1; k++) { + // row + i = matrix._index[k]; // check we need to delete value and matrix._index + + if (i > rows - 1) { + // remove value + matrix._values.splice(k, 1); // remove item from matrix._index + + + matrix._index.splice(k, 1); // increase deletes + + + d++; + } + } + } // update matrix._ptr for current column + + + matrix._ptr[j] = matrix._values.length; + } // update matrix._size + + + matrix._size[0] = rows; + matrix._size[1] = columns; // return matrix + + return matrix; + } + /** + * Reshape the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (reshape in place). + * + * NOTE: This might be better suited to copy by default, instead of modifying + * in place. For now, it operates in place to remain consistent with + * resize(). + * + * @memberof SparseMatrix + * @param {number[]} size The new size the matrix should have. + * @param {boolean} [copy] Return a reshaped copy of the matrix + * + * @return {Matrix} The reshaped matrix + */ + + + SparseMatrix.prototype.reshape = function (size, copy) { + // validate arguments + if (!Object(is["b" /* isArray */])(size)) { + throw new TypeError('Array expected'); + } + + if (size.length !== 2) { + throw new Error('Sparse matrices can only be reshaped in two dimensions'); + } // check sizes + + + size.forEach(function (value) { + if (!Object(is["y" /* isNumber */])(value) || !Object(utils_number["i" /* isInteger */])(value) || value < 0) { + throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + }); // m * n must not change + + if (this._size[0] * this._size[1] !== size[0] * size[1]) { + throw new Error('Reshaping sparse matrix will result in the wrong number of elements'); + } // matrix to reshape + + + var m = copy ? this.clone() : this; // return unchanged if the same shape + + if (this._size[0] === size[0] && this._size[1] === size[1]) { + return m; + } // Convert to COO format (generate a column index) + + + var colIndex = []; + + for (var i = 0; i < m._ptr.length; i++) { + for (var j = 0; j < m._ptr[i + 1] - m._ptr[i]; j++) { + colIndex.push(i); + } + } // Clone the values array + + + var values = m._values.slice(); // Clone the row index array + + + var rowIndex = m._index.slice(); // Transform the (row, column) indices + + + for (var _i = 0; _i < m._index.length; _i++) { + var r1 = rowIndex[_i]; + var c1 = colIndex[_i]; + var flat = r1 * m._size[1] + c1; + colIndex[_i] = flat % size[1]; + rowIndex[_i] = Math.floor(flat / size[1]); + } // Now reshaping is supposed to preserve the row-major order, BUT these sparse matrices are stored + // in column-major order, so we have to reorder the value array now. One option is to use a multisort, + // sorting several arrays based on some other array. + // OR, we could easily just: + // 1. Remove all values from the matrix + + + m._values.length = 0; + m._index.length = 0; + m._ptr.length = size[1] + 1; + m._size = size.slice(); + + for (var _i2 = 0; _i2 < m._ptr.length; _i2++) { + m._ptr[_i2] = 0; + } // 2. Re-insert all elements in the proper order (simplified code from SparseMatrix.prototype.set) + // This step is probably the most time-consuming + + + for (var h = 0; h < values.length; h++) { + var _i3 = rowIndex[h]; + var _j = colIndex[h]; + var v = values[h]; + + var k = _getValueIndex(_i3, m._ptr[_j], m._ptr[_j + 1], m._index); + + _insert(k, _i3, _j, v, m._values, m._index, m._ptr); + } // The value indices are inserted out of order, but apparently that's... still OK? + + + return m; + }; + /** + * Create a clone of the matrix + * @memberof SparseMatrix + * @return {SparseMatrix} clone + */ + + + SparseMatrix.prototype.clone = function () { + var m = new SparseMatrix({ + values: this._values ? Object(utils_object["a" /* clone */])(this._values) : undefined, + index: Object(utils_object["a" /* clone */])(this._index), + ptr: Object(utils_object["a" /* clone */])(this._ptr), + size: Object(utils_object["a" /* clone */])(this._size), + datatype: this._datatype + }); + return m; + }; + /** + * Retrieve the size of the matrix. + * @memberof SparseMatrix + * @returns {number[]} size + */ + + + SparseMatrix.prototype.size = function () { + return this._size.slice(0); // copy the Array + }; + /** + * Create a new matrix with the results of the callback function executed on + * each entry of the matrix. + * @memberof SparseMatrix + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + * @param {boolean} [skipZeros] Invoke callback function for non-zero values only. + * + * @return {SparseMatrix} matrix + */ + + + SparseMatrix.prototype.map = function (callback, skipZeros) { + // check it is a pattern matrix + if (!this._values) { + throw new Error('Cannot invoke map on a Pattern only matrix'); + } // matrix instance + + + var me = this; // rows and columns + + var rows = this._size[0]; + var columns = this._size[1]; // invoke callback + + var invoke = function invoke(v, i, j) { + // invoke callback + return callback(v, [i, j], me); + }; // invoke _map + + + return _map(this, 0, rows - 1, 0, columns - 1, invoke, skipZeros); + }; + /** + * Create a new matrix with the results of the callback function executed on the interval + * [minRow..maxRow, minColumn..maxColumn]. + */ + + + function _map(matrix, minRow, maxRow, minColumn, maxColumn, callback, skipZeros) { + // result arrays + var values = []; + var index = []; + var ptr = []; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; + + if (Object(is["I" /* isString */])(matrix._datatype)) { + // find signature that matches (datatype, datatype) + eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar; // convert 0 to the same datatype + + zero = typed.convert(0, matrix._datatype); + } // invoke callback + + + var invoke = function invoke(v, x, y) { + // invoke callback + v = callback(v, x, y); // check value != 0 + + if (!eq(v, zero)) { + // store value + values.push(v); // index + + index.push(x); + } + }; // loop columns + + + for (var j = minColumn; j <= maxColumn; j++) { + // store pointer to values index + ptr.push(values.length); // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + + var k0 = matrix._ptr[j]; + var k1 = matrix._ptr[j + 1]; + + if (skipZeros) { + // loop k within [k0, k1[ + for (var k = k0; k < k1; k++) { + // row index + var i = matrix._index[k]; // check i is in range + + if (i >= minRow && i <= maxRow) { + // value @ k + invoke(matrix._values[k], i - minRow, j - minColumn); + } + } + } else { + // create a cache holding all defined values + var _values = {}; + + for (var _k = k0; _k < k1; _k++) { + var _i4 = matrix._index[_k]; + _values[_i4] = matrix._values[_k]; + } // loop over all rows (indexes can be unordered so we can't use that), + // and either read the value or zero + + + for (var _i5 = minRow; _i5 <= maxRow; _i5++) { + var value = _i5 in _values ? _values[_i5] : 0; + invoke(value, _i5 - minRow, j - minColumn); + } + } + } // store number of values in ptr + + + ptr.push(values.length); // return sparse matrix + + return new SparseMatrix({ + values: values, + index: index, + ptr: ptr, + size: [maxRow - minRow + 1, maxColumn - minColumn + 1] + }); + } + /** + * Execute a callback function on each entry of the matrix. + * @memberof SparseMatrix + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + * @param {boolean} [skipZeros] Invoke callback function for non-zero values only. + */ + + + SparseMatrix.prototype.forEach = function (callback, skipZeros) { + // check it is a pattern matrix + if (!this._values) { + throw new Error('Cannot invoke forEach on a Pattern only matrix'); + } // matrix instance + + + var me = this; // rows and columns + + var rows = this._size[0]; + var columns = this._size[1]; // loop columns + + for (var j = 0; j < columns; j++) { + // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + var k0 = this._ptr[j]; + var k1 = this._ptr[j + 1]; + + if (skipZeros) { + // loop k within [k0, k1[ + for (var k = k0; k < k1; k++) { + // row index + var i = this._index[k]; // value @ k + + callback(this._values[k], [i, j], me); + } + } else { + // create a cache holding all defined values + var values = {}; + + for (var _k2 = k0; _k2 < k1; _k2++) { + var _i6 = this._index[_k2]; + values[_i6] = this._values[_k2]; + } // loop over all rows (indexes can be unordered so we can't use that), + // and either read the value or zero + + + for (var _i7 = 0; _i7 < rows; _i7++) { + var value = _i7 in values ? values[_i7] : 0; + callback(value, [_i7, j], me); + } + } + } + }; + /** + * Create an Array with a copy of the data of the SparseMatrix + * @memberof SparseMatrix + * @returns {Array} array + */ + + + SparseMatrix.prototype.toArray = function () { + return _toArray(this._values, this._index, this._ptr, this._size, true); + }; + /** + * Get the primitive value of the SparseMatrix: a two dimensions array + * @memberof SparseMatrix + * @returns {Array} array + */ + + + SparseMatrix.prototype.valueOf = function () { + return _toArray(this._values, this._index, this._ptr, this._size, false); + }; + + function _toArray(values, index, ptr, size, copy) { + // rows and columns + var rows = size[0]; + var columns = size[1]; // result + + var a = []; // vars + + var i, j; // initialize array + + for (i = 0; i < rows; i++) { + a[i] = []; + + for (j = 0; j < columns; j++) { + a[i][j] = 0; + } + } // loop columns + + + for (j = 0; j < columns; j++) { + // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + var k0 = ptr[j]; + var k1 = ptr[j + 1]; // loop k within [k0, k1[ + + for (var k = k0; k < k1; k++) { + // row index + i = index[k]; // set value (use one for pattern matrix) + + a[i][j] = values ? copy ? Object(utils_object["a" /* clone */])(values[k]) : values[k] : 1; + } + } + + return a; + } + /** + * Get a string representation of the matrix, with optional formatting options. + * @memberof SparseMatrix + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @returns {string} str + */ + + + SparseMatrix.prototype.format = function (options) { + // rows and columns + var rows = this._size[0]; + var columns = this._size[1]; // density + + var density = this.density(); // rows & columns + + var str = 'Sparse Matrix [' + Object(utils_string["d" /* format */])(rows, options) + ' x ' + Object(utils_string["d" /* format */])(columns, options) + '] density: ' + Object(utils_string["d" /* format */])(density, options) + '\n'; // loop columns + + for (var j = 0; j < columns; j++) { + // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + var k0 = this._ptr[j]; + var k1 = this._ptr[j + 1]; // loop k within [k0, k1[ + + for (var k = k0; k < k1; k++) { + // row index + var i = this._index[k]; // append value + + str += '\n (' + Object(utils_string["d" /* format */])(i, options) + ', ' + Object(utils_string["d" /* format */])(j, options) + ') ==> ' + (this._values ? Object(utils_string["d" /* format */])(this._values[k], options) : 'X'); + } + } + + return str; + }; + /** + * Get a string representation of the matrix + * @memberof SparseMatrix + * @returns {string} str + */ + + + SparseMatrix.prototype.toString = function () { + return Object(utils_string["d" /* format */])(this.toArray()); + }; + /** + * Get a JSON representation of the matrix + * @memberof SparseMatrix + * @returns {Object} + */ + + + SparseMatrix.prototype.toJSON = function () { + return { + mathjs: 'SparseMatrix', + values: this._values, + index: this._index, + ptr: this._ptr, + size: this._size, + datatype: this._datatype + }; + }; + /** + * Get the kth Matrix diagonal. + * + * @memberof SparseMatrix + * @param {number | BigNumber} [k=0] The kth diagonal where the vector will retrieved. + * + * @returns {Matrix} The matrix vector with the diagonal values. + */ + + + SparseMatrix.prototype.diagonal = function (k) { + // validate k if any + if (k) { + // convert BigNumber to a number + if (Object(is["e" /* isBigNumber */])(k)) { + k = k.toNumber(); + } // is must be an integer + + + if (!Object(is["y" /* isNumber */])(k) || !Object(utils_number["i" /* isInteger */])(k)) { + throw new TypeError('The parameter k must be an integer number'); + } + } else { + // default value + k = 0; + } + + var kSuper = k > 0 ? k : 0; + var kSub = k < 0 ? -k : 0; // rows & columns + + var rows = this._size[0]; + var columns = this._size[1]; // number diagonal values + + var n = Math.min(rows - kSub, columns - kSuper); // diagonal arrays + + var values = []; + var index = []; + var ptr = []; // initial ptr value + + ptr[0] = 0; // loop columns + + for (var j = kSuper; j < columns && values.length < n; j++) { + // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + var k0 = this._ptr[j]; + var k1 = this._ptr[j + 1]; // loop x within [k0, k1[ + + for (var x = k0; x < k1; x++) { + // row index + var i = this._index[x]; // check row + + if (i === j - kSuper + kSub) { + // value on this column + values.push(this._values[x]); // store row + + index[values.length - 1] = i - kSub; // exit loop + + break; + } + } + } // close ptr + + + ptr.push(values.length); // return matrix + + return new SparseMatrix({ + values: values, + index: index, + ptr: ptr, + size: [n, 1] + }); + }; + /** + * Generate a matrix from a JSON object + * @memberof SparseMatrix + * @param {Object} json An object structured like + * `{"mathjs": "SparseMatrix", "values": [], "index": [], "ptr": [], "size": []}`, + * where mathjs is optional + * @returns {SparseMatrix} + */ + + + SparseMatrix.fromJSON = function (json) { + return new SparseMatrix(json); + }; + /** + * Create a diagonal matrix. + * + * @memberof SparseMatrix + * @param {Array} size The matrix size. + * @param {number | Array | Matrix } value The values for the diagonal. + * @param {number | BigNumber} [k=0] The kth diagonal where the vector will be filled in. + * @param {number} [defaultValue] The default value for non-diagonal + * @param {string} [datatype] The Matrix datatype, values must be of this datatype. + * + * @returns {SparseMatrix} + */ + + + SparseMatrix.diagonal = function (size, value, k, defaultValue, datatype) { + if (!Object(is["b" /* isArray */])(size)) { + throw new TypeError('Array expected, size parameter'); + } + + if (size.length !== 2) { + throw new Error('Only two dimensions matrix are supported'); + } // map size & validate + + + size = size.map(function (s) { + // check it is a big number + if (Object(is["e" /* isBigNumber */])(s)) { + // convert it + s = s.toNumber(); + } // validate arguments + + + if (!Object(is["y" /* isNumber */])(s) || !Object(utils_number["i" /* isInteger */])(s) || s < 1) { + throw new Error('Size values must be positive integers'); + } + + return s; + }); // validate k if any + + if (k) { + // convert BigNumber to a number + if (Object(is["e" /* isBigNumber */])(k)) { + k = k.toNumber(); + } // is must be an integer + + + if (!Object(is["y" /* isNumber */])(k) || !Object(utils_number["i" /* isInteger */])(k)) { + throw new TypeError('The parameter k must be an integer number'); + } + } else { + // default value + k = 0; + } // equal signature to use + + + var eq = equalScalar; // zero value + + var zero = 0; + + if (Object(is["I" /* isString */])(datatype)) { + // find signature that matches (datatype, datatype) + eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar; // convert 0 to the same datatype + + zero = typed.convert(0, datatype); + } + + var kSuper = k > 0 ? k : 0; + var kSub = k < 0 ? -k : 0; // rows and columns + + var rows = size[0]; + var columns = size[1]; // number of non-zero items + + var n = Math.min(rows - kSub, columns - kSuper); // value extraction function + + var _value; // check value + + + if (Object(is["b" /* isArray */])(value)) { + // validate array + if (value.length !== n) { + // number of values in array must be n + throw new Error('Invalid value array length'); + } // define function + + + _value = function _value(i) { + // return value @ i + return value[i]; + }; + } else if (Object(is["v" /* isMatrix */])(value)) { + // matrix size + var ms = value.size(); // validate matrix + + if (ms.length !== 1 || ms[0] !== n) { + // number of values in array must be n + throw new Error('Invalid matrix length'); + } // define function + + + _value = function _value(i) { + // return value @ i + return value.get([i]); + }; + } else { + // define function + _value = function _value() { + // return value + return value; + }; + } // create arrays + + + var values = []; + var index = []; + var ptr = []; // loop items + + for (var j = 0; j < columns; j++) { + // number of rows with value + ptr.push(values.length); // diagonal index + + var i = j - kSuper; // check we need to set diagonal value + + if (i >= 0 && i < n) { + // get value @ i + var v = _value(i); // check for zero + + + if (!eq(v, zero)) { + // column + index.push(i + kSub); // add value + + values.push(v); + } + } + } // last value should be number of values + + + ptr.push(values.length); // create SparseMatrix + + return new SparseMatrix({ + values: values, + index: index, + ptr: ptr, + size: [rows, columns] + }); + }; + /** + * Swap rows i and j in Matrix. + * + * @memberof SparseMatrix + * @param {number} i Matrix row index 1 + * @param {number} j Matrix row index 2 + * + * @return {Matrix} The matrix reference + */ + + + SparseMatrix.prototype.swapRows = function (i, j) { + // check index + if (!Object(is["y" /* isNumber */])(i) || !Object(utils_number["i" /* isInteger */])(i) || !Object(is["y" /* isNumber */])(j) || !Object(utils_number["i" /* isInteger */])(j)) { + throw new Error('Row index must be positive integers'); + } // check dimensions + + + if (this._size.length !== 2) { + throw new Error('Only two dimensional matrix is supported'); + } // validate index + + + Object(utils_array["s" /* validateIndex */])(i, this._size[0]); + Object(utils_array["s" /* validateIndex */])(j, this._size[0]); // swap rows + + SparseMatrix._swapRows(i, j, this._size[1], this._values, this._index, this._ptr); // return current instance + + + return this; + }; + /** + * Loop rows with data in column j. + * + * @param {number} j Column + * @param {Array} values Matrix values + * @param {Array} index Matrix row indeces + * @param {Array} ptr Matrix column pointers + * @param {Function} callback Callback function invoked for every row in column j + */ + + + SparseMatrix._forEachRow = function (j, values, index, ptr, callback) { + // indeces for column j + var k0 = ptr[j]; + var k1 = ptr[j + 1]; // loop + + for (var k = k0; k < k1; k++) { + // invoke callback + callback(index[k], values[k]); + } + }; + /** + * Swap rows x and y in Sparse Matrix data structures. + * + * @param {number} x Matrix row index 1 + * @param {number} y Matrix row index 2 + * @param {number} columns Number of columns in matrix + * @param {Array} values Matrix values + * @param {Array} index Matrix row indeces + * @param {Array} ptr Matrix column pointers + */ + + + SparseMatrix._swapRows = function (x, y, columns, values, index, ptr) { + // loop columns + for (var j = 0; j < columns; j++) { + // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + var k0 = ptr[j]; + var k1 = ptr[j + 1]; // find value index @ x + + var kx = _getValueIndex(x, k0, k1, index); // find value index @ x + + + var ky = _getValueIndex(y, k0, k1, index); // check both rows exist in matrix + + + if (kx < k1 && ky < k1 && index[kx] === x && index[ky] === y) { + // swap values (check for pattern matrix) + if (values) { + var v = values[kx]; + values[kx] = values[ky]; + values[ky] = v; + } // next column + + + continue; + } // check x row exist & no y row + + + if (kx < k1 && index[kx] === x && (ky >= k1 || index[ky] !== y)) { + // value @ x (check for pattern matrix) + var vx = values ? values[kx] : undefined; // insert value @ y + + index.splice(ky, 0, y); + + if (values) { + values.splice(ky, 0, vx); + } // remove value @ x (adjust array index if needed) + + + index.splice(ky <= kx ? kx + 1 : kx, 1); + + if (values) { + values.splice(ky <= kx ? kx + 1 : kx, 1); + } // next column + + + continue; + } // check y row exist & no x row + + + if (ky < k1 && index[ky] === y && (kx >= k1 || index[kx] !== x)) { + // value @ y (check for pattern matrix) + var vy = values ? values[ky] : undefined; // insert value @ x + + index.splice(kx, 0, x); + + if (values) { + values.splice(kx, 0, vy); + } // remove value @ y (adjust array index if needed) + + + index.splice(kx <= ky ? ky + 1 : ky, 1); + + if (values) { + values.splice(kx <= ky ? ky + 1 : ky, 1); + } + } + } + }; + + return SparseMatrix; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/number.js + + +var number_name = 'number'; +var number_dependencies = ['typed']; +var createNumber = /* #__PURE__ */Object(factory["a" /* factory */])(number_name, number_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Create a number or convert a string, boolean, or unit to a number. + * When value is a matrix, all elements will be converted to number. + * + * Syntax: + * + * math.number(value) + * math.number(unit, valuelessUnit) + * + * Examples: + * + * math.number(2) // returns number 2 + * math.number('7.2') // returns number 7.2 + * math.number(true) // returns number 1 + * math.number([true, false, true, true]) // returns [1, 0, 1, 1] + * math.number(math.unit('52cm'), 'm') // returns 0.52 + * + * See also: + * + * bignumber, boolean, complex, index, matrix, string, unit + * + * @param {string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null} [value] Value to be converted + * @param {Unit | string} [valuelessUnit] A valueless unit, used to convert a unit to a number + * @return {number | Array | Matrix} The created number + */ + var number = typed('number', { + '': function _() { + return 0; + }, + number: function number(x) { + return x; + }, + string: function string(x) { + if (x === 'NaN') return NaN; + var num = Number(x); + + if (isNaN(num)) { + throw new SyntaxError('String "' + x + '" is no valid number'); + } + + return num; + }, + BigNumber: function BigNumber(x) { + return x.toNumber(); + }, + Fraction: function Fraction(x) { + return x.valueOf(); + }, + Unit: function Unit(x) { + throw new Error('Second argument with valueless unit expected'); + }, + "null": function _null(x) { + return 0; + }, + 'Unit, string | Unit': function UnitStringUnit(unit, valuelessUnit) { + return unit.toNumber(valuelessUnit); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, number); + } + }); // reviver function to parse a JSON object like: + // + // {"mathjs":"number","value":"2.3"} + // + // into a number 2.3 + + number.fromJSON = function (json) { + return parseFloat(json.value); + }; + + return number; +}); +// CONCATENATED MODULE: ./src/type/string.js + + + +var string_name = 'string'; +var string_dependencies = ['typed']; +var createString = /* #__PURE__ */Object(factory["a" /* factory */])(string_name, string_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Create a string or convert any object into a string. + * Elements of Arrays and Matrices are processed element wise. + * + * Syntax: + * + * math.string(value) + * + * Examples: + * + * math.string(4.2) // returns string '4.2' + * math.string(math.complex(3, 2) // returns string '3 + 2i' + * + * const u = math.unit(5, 'km') + * math.string(u.to('m')) // returns string '5000 m' + * + * math.string([true, false]) // returns ['true', 'false'] + * + * See also: + * + * bignumber, boolean, complex, index, matrix, number, unit + * + * @param {* | Array | Matrix | null} [value] A value to convert to a string + * @return {string | Array | Matrix} The created string + */ + var string = typed(string_name, { + '': function _() { + return ''; + }, + number: utils_number["h" /* format */], + "null": function _null(x) { + return 'null'; + }, + "boolean": function boolean(x) { + return x + ''; + }, + string: function string(x) { + return x; + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, string); + }, + any: function any(x) { + return String(x); + } + }); + return string; +}); +// CONCATENATED MODULE: ./src/type/boolean.js + + +var boolean_name = 'boolean'; +var boolean_dependencies = ['typed']; +var createBoolean = /* #__PURE__ */Object(factory["a" /* factory */])(boolean_name, boolean_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Create a boolean or convert a string or number to a boolean. + * In case of a number, `true` is returned for non-zero numbers, and `false` in + * case of zero. + * Strings can be `'true'` or `'false'`, or can contain a number. + * When value is a matrix, all elements will be converted to boolean. + * + * Syntax: + * + * math.boolean(x) + * + * Examples: + * + * math.boolean(0) // returns false + * math.boolean(1) // returns true + * math.boolean(-3) // returns true + * math.boolean('true') // returns true + * math.boolean('false') // returns false + * math.boolean([1, 0, 1, 1]) // returns [true, false, true, true] + * + * See also: + * + * bignumber, complex, index, matrix, string, unit + * + * @param {string | number | boolean | Array | Matrix | null} value A value of any type + * @return {boolean | Array | Matrix} The boolean value + */ + var bool = typed(boolean_name, { + '': function _() { + return false; + }, + "boolean": function boolean(x) { + return x; + }, + number: function number(x) { + return !!x; + }, + "null": function _null(x) { + return false; + }, + BigNumber: function BigNumber(x) { + return !x.isZero(); + }, + string: function string(x) { + // try case insensitive + var lcase = x.toLowerCase(); + + if (lcase === 'true') { + return true; + } else if (lcase === 'false') { + return false; + } // test whether value is a valid number + + + var num = Number(x); + + if (x !== '' && !isNaN(num)) { + return !!num; + } + + throw new Error('Cannot convert "' + x + '" to a boolean'); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, bool); + } + }); + return bool; +}); +// CONCATENATED MODULE: ./src/type/bignumber/function/bignumber.js + + +var bignumber_name = 'bignumber'; +var bignumber_dependencies = ['typed', 'BigNumber']; +var createBignumber = /* #__PURE__ */Object(factory["a" /* factory */])(bignumber_name, bignumber_dependencies, function (_ref) { + var typed = _ref.typed, + BigNumber = _ref.BigNumber; + + /** + * Create a BigNumber, which can store numbers with arbitrary precision. + * When a matrix is provided, all elements will be converted to BigNumber. + * + * Syntax: + * + * math.bignumber(x) + * + * Examples: + * + * 0.1 + 0.2 // returns number 0.30000000000000004 + * math.bignumber(0.1) + math.bignumber(0.2) // returns BigNumber 0.3 + * + * + * 7.2e500 // returns number Infinity + * math.bignumber('7.2e500') // returns BigNumber 7.2e500 + * + * See also: + * + * boolean, complex, index, matrix, string, unit + * + * @param {number | string | Fraction | BigNumber | Array | Matrix | boolean | null} [value] Value for the big number, + * 0 by default. + * @returns {BigNumber} The created bignumber + */ + var bignumber = typed('bignumber', { + '': function _() { + return new BigNumber(0); + }, + number: function number(x) { + // convert to string to prevent errors in case of >15 digits + return new BigNumber(x + ''); + }, + string: function string(x) { + return new BigNumber(x); + }, + BigNumber: function BigNumber(x) { + // we assume a BigNumber is immutable + return x; + }, + Fraction: function Fraction(x) { + return new BigNumber(x.n).div(x.d).times(x.s); + }, + "null": function _null(x) { + return new BigNumber(0); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, bignumber); + } + }); + return bignumber; +}); +// CONCATENATED MODULE: ./src/type/complex/function/complex.js + + +var complex_name = 'complex'; +var complex_dependencies = ['typed', 'Complex']; +var createComplex = /* #__PURE__ */Object(factory["a" /* factory */])(complex_name, complex_dependencies, function (_ref) { + var typed = _ref.typed, + Complex = _ref.Complex; + + /** + * Create a complex value or convert a value to a complex value. + * + * Syntax: + * + * math.complex() // creates a complex value with zero + * // as real and imaginary part. + * math.complex(re : number, im : string) // creates a complex value with provided + * // values for real and imaginary part. + * math.complex(re : number) // creates a complex value with provided + * // real value and zero imaginary part. + * math.complex(complex : Complex) // clones the provided complex value. + * math.complex(arg : string) // parses a string into a complex value. + * math.complex(array : Array) // converts the elements of the array + * // or matrix element wise into a + * // complex value. + * math.complex({re: number, im: number}) // creates a complex value with provided + * // values for real an imaginary part. + * math.complex({r: number, phi: number}) // creates a complex value with provided + * // polar coordinates + * + * Examples: + * + * const a = math.complex(3, -4) // a = Complex 3 - 4i + * a.re = 5 // a = Complex 5 - 4i + * const i = a.im // Number -4 + * const b = math.complex('2 + 6i') // Complex 2 + 6i + * const c = math.complex() // Complex 0 + 0i + * const d = math.add(a, b) // Complex 5 + 2i + * + * See also: + * + * bignumber, boolean, index, matrix, number, string, unit + * + * @param {* | Array | Matrix} [args] + * Arguments specifying the real and imaginary part of the complex number + * @return {Complex | Array | Matrix} Returns a complex value + */ + var complex = typed('complex', { + '': function _() { + return Complex.ZERO; + }, + number: function number(x) { + return new Complex(x, 0); + }, + 'number, number': function numberNumber(re, im) { + return new Complex(re, im); + }, + // TODO: this signature should be redundant + 'BigNumber, BigNumber': function BigNumberBigNumber(re, im) { + return new Complex(re.toNumber(), im.toNumber()); + }, + Fraction: function Fraction(x) { + return new Complex(x.valueOf(), 0); + }, + Complex: function Complex(x) { + return x.clone(); + }, + string: function string(x) { + return Complex(x); // for example '2 + 3i' + }, + "null": function _null(x) { + return Complex(0); + }, + Object: function Object(x) { + if ('re' in x && 'im' in x) { + return new Complex(x.re, x.im); + } + + if ('r' in x && 'phi' in x || 'abs' in x && 'arg' in x) { + return new Complex(x); + } + + throw new Error('Expected object with properties (re and im) or (r and phi) or (abs and arg)'); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, complex); + } + }); + return complex; +}); +// CONCATENATED MODULE: ./src/type/fraction/function/fraction.js + + +var fraction_name = 'fraction'; +var fraction_dependencies = ['typed', 'Fraction']; +var createFraction = /* #__PURE__ */Object(factory["a" /* factory */])(fraction_name, fraction_dependencies, function (_ref) { + var typed = _ref.typed, + Fraction = _ref.Fraction; + + /** + * Create a fraction convert a value to a fraction. + * + * Syntax: + * math.fraction(numerator, denominator) + * math.fraction({n: numerator, d: denominator}) + * math.fraction(matrix: Array | Matrix) Turn all matrix entries + * into fractions + * + * Examples: + * + * math.fraction(1, 3) + * math.fraction('2/3') + * math.fraction({n: 2, d: 3}) + * math.fraction([0.2, 0.25, 1.25]) + * + * See also: + * + * bignumber, number, string, unit + * + * @param {number | string | Fraction | BigNumber | Array | Matrix} [args] + * Arguments specifying the numerator and denominator of + * the fraction + * @return {Fraction | Array | Matrix} Returns a fraction + */ + var fraction = typed('fraction', { + number: function number(x) { + if (!isFinite(x) || isNaN(x)) { + throw new Error(x + ' cannot be represented as a fraction'); + } + + return new Fraction(x); + }, + string: function string(x) { + return new Fraction(x); + }, + 'number, number': function numberNumber(numerator, denominator) { + return new Fraction(numerator, denominator); + }, + "null": function _null(x) { + return new Fraction(0); + }, + BigNumber: function BigNumber(x) { + return new Fraction(x.toString()); + }, + Fraction: function Fraction(x) { + return x; // fractions are immutable + }, + Object: function Object(x) { + return new Fraction(x); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, fraction); + } + }); + return fraction; +}); +// CONCATENATED MODULE: ./src/type/matrix/function/matrix.js + +var matrix_name = 'matrix'; +var matrix_dependencies = ['typed', 'Matrix', 'DenseMatrix', 'SparseMatrix']; +var createMatrix = /* #__PURE__ */Object(factory["a" /* factory */])(matrix_name, matrix_dependencies, function (_ref) { + var typed = _ref.typed, + Matrix = _ref.Matrix, + DenseMatrix = _ref.DenseMatrix, + SparseMatrix = _ref.SparseMatrix; + + /** + * Create a Matrix. The function creates a new `math.Matrix` object from + * an `Array`. A Matrix has utility functions to manipulate the data in the + * matrix, like getting the size and getting or setting values in the matrix. + * Supported storage formats are 'dense' and 'sparse'. + * + * Syntax: + * + * math.matrix() // creates an empty matrix using default storage format (dense). + * math.matrix(data) // creates a matrix with initial data using default storage format (dense). + * math.matrix('dense') // creates an empty matrix using the given storage format. + * math.matrix(data, 'dense') // creates a matrix with initial data using the given storage format. + * math.matrix(data, 'sparse') // creates a sparse matrix with initial data. + * math.matrix(data, 'sparse', 'number') // creates a sparse matrix with initial data, number data type. + * + * Examples: + * + * let m = math.matrix([[1, 2], [3, 4]]) + * m.size() // Array [2, 2] + * m.resize([3, 2], 5) + * m.valueOf() // Array [[1, 2], [3, 4], [5, 5]] + * m.get([1, 0]) // number 3 + * + * See also: + * + * bignumber, boolean, complex, index, number, string, unit, sparse + * + * @param {Array | Matrix} [data] A multi dimensional array + * @param {string} [format] The Matrix storage format + * + * @return {Matrix} The created matrix + */ + return typed(matrix_name, { + '': function _() { + return _create([]); + }, + string: function string(format) { + return _create([], format); + }, + 'string, string': function stringString(format, datatype) { + return _create([], format, datatype); + }, + Array: function Array(data) { + return _create(data); + }, + Matrix: function Matrix(data) { + return _create(data, data.storage()); + }, + 'Array | Matrix, string': _create, + 'Array | Matrix, string, string': _create + }); + /** + * Create a new Matrix with given storage format + * @param {Array} data + * @param {string} [format] + * @param {string} [datatype] + * @returns {Matrix} Returns a new Matrix + * @private + */ + + function _create(data, format, datatype) { + // get storage format constructor + if (format === 'dense' || format === 'default' || format === undefined) { + return new DenseMatrix(data, datatype); + } + + if (format === 'sparse') { + return new SparseMatrix(data, datatype); + } + + throw new TypeError('Unknown matrix type ' + JSON.stringify(format) + '.'); + } +}); +// CONCATENATED MODULE: ./src/type/unit/function/splitUnit.js + +var splitUnit_name = 'splitUnit'; +var splitUnit_dependencies = ['typed']; +var createSplitUnit = /* #__PURE__ */Object(factory["a" /* factory */])(splitUnit_name, splitUnit_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Split a unit in an array of units whose sum is equal to the original unit. + * + * Syntax: + * + * splitUnit(unit: Unit, parts: Array.) + * + * Example: + * + * math.splitUnit(new Unit(1, 'm'), ['feet', 'inch']) + * // [ 3 feet, 3.3700787401575 inch ] + * + * See also: + * + * unit + * + * @param {Array} [parts] An array of strings or valueless units. + * @return {Array} An array of units. + */ + return typed(splitUnit_name, { + 'Unit, Array': function UnitArray(unit, parts) { + return unit.splitUnit(parts); + } + }); +}); +// CONCATENATED MODULE: ./src/plain/number/arithmetic.js + +var arithmetic_n1 = 'number'; +var arithmetic_n2 = 'number, number'; +function absNumber(a) { + return Math.abs(a); +} +absNumber.signature = arithmetic_n1; +function addNumber(a, b) { + return a + b; +} +addNumber.signature = arithmetic_n2; +function subtractNumber(a, b) { + return a - b; +} +subtractNumber.signature = arithmetic_n2; +function multiplyNumber(a, b) { + return a * b; +} +multiplyNumber.signature = arithmetic_n2; +function divideNumber(a, b) { + return a / b; +} +divideNumber.signature = arithmetic_n2; +function unaryMinusNumber(x) { + return -x; +} +unaryMinusNumber.signature = arithmetic_n1; +function unaryPlusNumber(x) { + return x; +} +unaryPlusNumber.signature = arithmetic_n1; +function cbrtNumber(x) { + return Object(utils_number["d" /* cbrt */])(x); +} +cbrtNumber.signature = arithmetic_n1; +function ceilNumber(x) { + return Math.ceil(x); +} +ceilNumber.signature = arithmetic_n1; +function cubeNumber(x) { + return x * x * x; +} +cubeNumber.signature = arithmetic_n1; +function expNumber(x) { + return Math.exp(x); +} +expNumber.signature = arithmetic_n1; +function expm1Number(x) { + return Object(utils_number["g" /* expm1 */])(x); +} +expm1Number.signature = arithmetic_n1; +function fixNumber(x) { + return x > 0 ? Math.floor(x) : Math.ceil(x); +} +fixNumber.signature = arithmetic_n1; +function floorNumber(x) { + return Math.floor(x); +} +floorNumber.signature = arithmetic_n1; +/** + * Calculate gcd for numbers + * @param {number} a + * @param {number} b + * @returns {number} Returns the greatest common denominator of a and b + */ + +function gcdNumber(a, b) { + if (!Object(utils_number["i" /* isInteger */])(a) || !Object(utils_number["i" /* isInteger */])(b)) { + throw new Error('Parameters in function gcd must be integer numbers'); + } // https://en.wikipedia.org/wiki/Euclidean_algorithm + + + var r; + + while (b !== 0) { + r = a % b; + a = b; + b = r; + } + + return a < 0 ? -a : a; +} +gcdNumber.signature = arithmetic_n2; +/** + * Calculate lcm for two numbers + * @param {number} a + * @param {number} b + * @returns {number} Returns the least common multiple of a and b + */ + +function lcmNumber(a, b) { + if (!Object(utils_number["i" /* isInteger */])(a) || !Object(utils_number["i" /* isInteger */])(b)) { + throw new Error('Parameters in function lcm must be integer numbers'); + } + + if (a === 0 || b === 0) { + return 0; + } // https://en.wikipedia.org/wiki/Euclidean_algorithm + // evaluate lcm here inline to reduce overhead + + + var t; + var prod = a * b; + + while (b !== 0) { + t = b; + b = a % t; + a = t; + } + + return Math.abs(prod / a); +} +lcmNumber.signature = arithmetic_n2; +/** + * Calculate the logarithm of a value. + * @param {number} x + * @return {number} + */ + +function logNumber(x) { + return Math.log(x); +} +logNumber.signature = arithmetic_n1; +/** + * Calculate the 10-base logarithm of a number + * @param {number} x + * @return {number} + */ + +function log10Number(x) { + return Object(utils_number["j" /* log10 */])(x); +} +log10Number.signature = arithmetic_n1; +/** + * Calculate the 2-base logarithm of a number + * @param {number} x + * @return {number} + */ + +function log2Number(x) { + return Object(utils_number["l" /* log2 */])(x); +} +log2Number.signature = arithmetic_n1; +/** + * Calculate the natural logarithm of a `number+1` + * @param {number} x + * @returns {number} + */ + +function log1pNumber(x) { + return Object(utils_number["k" /* log1p */])(x); +} +log1pNumber.signature = arithmetic_n1; +/** + * Calculate the modulus of two numbers + * @param {number} x + * @param {number} y + * @returns {number} res + * @private + */ + +function modNumber(x, y) { + if (y > 0) { + // We don't use JavaScript's % operator here as this doesn't work + // correctly for x < 0 and x === 0 + // see https://en.wikipedia.org/wiki/Modulo_operation + return x - y * Math.floor(x / y); + } else if (y === 0) { + return x; + } else { + // y < 0 + // TODO: implement mod for a negative divisor + throw new Error('Cannot calculate mod for a negative divisor'); + } +} +modNumber.signature = arithmetic_n2; +/** + * Calculate the nth root of a, solve x^root == a + * http://rosettacode.org/wiki/Nth_root#JavaScript + * @param {number} a + * @param {number} root + * @private + */ + +function nthRootNumber(a, root) { + var inv = root < 0; + + if (inv) { + root = -root; + } + + if (root === 0) { + throw new Error('Root must be non-zero'); + } + + if (a < 0 && Math.abs(root) % 2 !== 1) { + throw new Error('Root must be odd when a is negative.'); + } // edge cases zero and infinity + + + if (a === 0) { + return inv ? Infinity : 0; + } + + if (!isFinite(a)) { + return inv ? 0 : a; + } + + var x = Math.pow(Math.abs(a), 1 / root); // If a < 0, we require that root is an odd integer, + // so (-1) ^ (1/root) = -1 + + x = a < 0 ? -x : x; + return inv ? 1 / x : x; // Very nice algorithm, but fails with nthRoot(-2, 3). + // Newton's method has some well-known problems at times: + // https://en.wikipedia.org/wiki/Newton%27s_method#Failure_analysis + + /* + let x = 1 // Initial guess + let xPrev = 1 + let i = 0 + const iMax = 10000 + do { + const delta = (a / Math.pow(x, root - 1) - x) / root + xPrev = x + x = x + delta + i++ + } + while (xPrev !== x && i < iMax) + if (xPrev !== x) { + throw new Error('Function nthRoot failed to converge') + } + return inv ? 1 / x : x + */ +} +nthRootNumber.signature = arithmetic_n2; +function signNumber(x) { + return Object(utils_number["n" /* sign */])(x); +} +signNumber.signature = arithmetic_n1; +function sqrtNumber(x) { + return Math.sqrt(x); +} +sqrtNumber.signature = arithmetic_n1; +function squareNumber(x) { + return x * x; +} +squareNumber.signature = arithmetic_n1; +/** + * Calculate xgcd for two numbers + * @param {number} a + * @param {number} b + * @return {number} result + * @private + */ + +function xgcdNumber(a, b) { + // source: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm + var t; // used to swap two variables + + var q; // quotient + + var r; // remainder + + var x = 0; + var lastx = 1; + var y = 1; + var lasty = 0; + + if (!Object(utils_number["i" /* isInteger */])(a) || !Object(utils_number["i" /* isInteger */])(b)) { + throw new Error('Parameters in function xgcd must be integer numbers'); + } + + while (b) { + q = Math.floor(a / b); + r = a - q * b; + t = x; + x = lastx - q * x; + lastx = t; + t = y; + y = lasty - q * y; + lasty = t; + a = b; + b = r; + } + + var res; + + if (a < 0) { + res = [-a, -lastx, -lasty]; + } else { + res = [a, a ? lastx : 0, lasty]; + } + + return res; +} +xgcdNumber.signature = arithmetic_n2; +/** + * Calculates the power of x to y, x^y, for two numbers. + * @param {number} x + * @param {number} y + * @return {number} res + */ + +function powNumber(x, y) { + // x^Infinity === 0 if -1 < x < 1 + // A real number 0 is returned instead of complex(0) + if (x * x < 1 && y === Infinity || x * x > 1 && y === -Infinity) { + return 0; + } + + return Math.pow(x, y); +} +powNumber.signature = arithmetic_n2; +/** + * round a number to the given number of decimals, or to zero if decimals is + * not provided + * @param {number} value + * @param {number} decimals number of decimals, between 0 and 15 (0 by default) + * @return {number} roundedValue + */ + +function roundNumber(value) { + var decimals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + return parseFloat(Object(utils_number["q" /* toFixed */])(value, decimals)); +} +roundNumber.signature = arithmetic_n2; +/** + * Calculate the norm of a number, the absolute value. + * @param {number} x + * @return {number} + */ + +function normNumber(x) { + return Math.abs(x); +} +normNumber.signature = arithmetic_n1; +// CONCATENATED MODULE: ./src/function/arithmetic/unaryMinus.js + + + +var unaryMinus_name = 'unaryMinus'; +var unaryMinus_dependencies = ['typed']; +var createUnaryMinus = /* #__PURE__ */Object(factory["a" /* factory */])(unaryMinus_name, unaryMinus_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Inverse the sign of a value, apply a unary minus operation. + * + * For matrices, the function is evaluated element wise. Boolean values and + * strings will be converted to a number. For complex numbers, both real and + * complex value are inverted. + * + * Syntax: + * + * math.unaryMinus(x) + * + * Examples: + * + * math.unaryMinus(3.5) // returns -3.5 + * math.unaryMinus(-4.2) // returns 4.2 + * + * See also: + * + * add, subtract, unaryPlus + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Number to be inverted. + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Returns the value with inverted sign. + */ + var unaryMinus = typed(unaryMinus_name, { + number: unaryMinusNumber, + Complex: function Complex(x) { + return x.neg(); + }, + BigNumber: function BigNumber(x) { + return x.neg(); + }, + Fraction: function Fraction(x) { + return x.neg(); + }, + Unit: function Unit(x) { + var res = x.clone(); + res.value = unaryMinus(x.value); + return res; + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since unaryMinus(0) = 0 + return deepMap(x, unaryMinus, true); + } // TODO: add support for string + + }); + return unaryMinus; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/unaryPlus.js + + + +var unaryPlus_name = 'unaryPlus'; +var unaryPlus_dependencies = ['typed', 'config', 'BigNumber']; +var createUnaryPlus = /* #__PURE__ */Object(factory["a" /* factory */])(unaryPlus_name, unaryPlus_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + BigNumber = _ref.BigNumber; + + /** + * Unary plus operation. + * Boolean values and strings will be converted to a number, numeric values will be returned as is. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.unaryPlus(x) + * + * Examples: + * + * math.unaryPlus(3.5) // returns 3.5 + * math.unaryPlus(1) // returns 1 + * + * See also: + * + * unaryMinus, add, subtract + * + * @param {number | BigNumber | Fraction | string | Complex | Unit | Array | Matrix} x + * Input value + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} + * Returns the input value when numeric, converts to a number when input is non-numeric. + */ + var unaryPlus = typed(unaryPlus_name, { + number: unaryPlusNumber, + Complex: function Complex(x) { + return x; // complex numbers are immutable + }, + BigNumber: function BigNumber(x) { + return x; // bignumbers are immutable + }, + Fraction: function Fraction(x) { + return x; // fractions are immutable + }, + Unit: function Unit(x) { + return x.clone(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since unaryPlus(0) = 0 + return deepMap(x, unaryPlus, true); + }, + 'boolean | string': function booleanString(x) { + // convert to a number or bignumber + return config.number === 'BigNumber' ? new BigNumber(+x) : +x; + } + }); + return unaryPlus; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/abs.js + + + +var abs_name = 'abs'; +var abs_dependencies = ['typed']; +var createAbs = /* #__PURE__ */Object(factory["a" /* factory */])(abs_name, abs_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the absolute value of a number. For matrices, the function is + * evaluated element wise. + * + * Syntax: + * + * math.abs(x) + * + * Examples: + * + * math.abs(3.5) // returns number 3.5 + * math.abs(-4.2) // returns number 4.2 + * + * math.abs([3, -5, -1, 0, 2]) // returns Array [3, 5, 1, 0, 2] + * + * See also: + * + * sign + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x + * A number or matrix for which to get the absolute value + * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} + * Absolute value of `x` + */ + var abs = typed(abs_name, { + number: absNumber, + Complex: function Complex(x) { + return x.abs(); + }, + BigNumber: function BigNumber(x) { + return x.abs(); + }, + Fraction: function Fraction(x) { + return x.abs(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since abs(0) = 0 + return deepMap(x, abs, true); + }, + Unit: function Unit(x) { + return x.abs(); + } + }); + return abs; +}); +// CONCATENATED MODULE: ./src/function/matrix/apply.js + + + + +var apply_name = 'apply'; +var apply_dependencies = ['typed', 'isInteger']; +var createApply = /* #__PURE__ */Object(factory["a" /* factory */])(apply_name, apply_dependencies, function (_ref) { + var typed = _ref.typed, + isInteger = _ref.isInteger; + + /** + * Apply a function that maps an array to a scalar + * along a given axis of a matrix or array. + * Returns a new matrix or array with one less dimension than the input. + * + * Syntax: + * + * math.apply(A, dim, callback) + * + * Where: + * + * - `dim: number` is a zero-based dimension over which to concatenate the matrices. + * + * Examples: + * + * const A = [[1, 2], [3, 4]] + * const sum = math.sum + * + * math.apply(A, 0, sum) // returns [4, 6] + * math.apply(A, 1, sum) // returns [3, 7] + * + * See also: + * + * map, filter, forEach + * + * @param {Array | Matrix} array The input Matrix + * @param {number} dim The dimension along which the callback is applied + * @param {Function} callback The callback function that is applied. This Function + * should take an array or 1-d matrix as an input and + * return a number. + * @return {Array | Matrix} res The residual matrix with the function applied over some dimension. + */ + var apply = typed(apply_name, { + 'Array | Matrix, number | BigNumber, function': function ArrayMatrixNumberBigNumberFunction(mat, dim, callback) { + if (!isInteger(dim)) { + throw new TypeError('Integer number expected for dimension'); + } + + var size = Array.isArray(mat) ? Object(utils_array["a" /* arraySize */])(mat) : mat.size(); + + if (dim < 0 || dim >= size.length) { + throw new IndexError["a" /* IndexError */](dim, size.length); + } + + if (Object(is["v" /* isMatrix */])(mat)) { + return mat.create(_apply(mat.valueOf(), dim, callback)); + } else { + return _apply(mat, dim, callback); + } + } + }); + return apply; +}); +/** + * Recursively reduce a matrix + * @param {Array} mat + * @param {number} dim + * @param {Function} callback + * @returns {Array} ret + * @private + */ + +function _apply(mat, dim, callback) { + var i, ret, tran; + + if (dim <= 0) { + if (!Array.isArray(mat[0])) { + return callback(mat); + } else { + tran = apply_switch(mat); + ret = []; + + for (i = 0; i < tran.length; i++) { + ret[i] = _apply(tran[i], dim - 1, callback); + } + + return ret; + } + } else { + ret = []; + + for (i = 0; i < mat.length; i++) { + ret[i] = _apply(mat[i], dim - 1, callback); + } + + return ret; + } +} +/** + * Transpose a matrix + * @param {Array} mat + * @returns {Array} ret + * @private + */ + + +function apply_switch(mat) { + var I = mat.length; + var J = mat[0].length; + var i, j; + var ret = []; + + for (j = 0; j < J; j++) { + var tmp = []; + + for (i = 0; i < I; i++) { + tmp.push(mat[i][j]); + } + + ret.push(tmp); + } + + return ret; +} +// CONCATENATED MODULE: ./src/function/arithmetic/addScalar.js + + +var addScalar_name = 'addScalar'; +var addScalar_dependencies = ['typed']; +var createAddScalar = /* #__PURE__ */Object(factory["a" /* factory */])(addScalar_name, addScalar_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Add two scalar values, `x + y`. + * This function is meant for internal use: it is used by the public function + * `add` + * + * This function does not support collections (Array or Matrix). + * + * @param {number | BigNumber | Fraction | Complex | Unit} x First value to add + * @param {number | BigNumber | Fraction | Complex} y Second value to add + * @return {number | BigNumber | Fraction | Complex | Unit} Sum of `x` and `y` + * @private + */ + var addScalar = typed(addScalar_name, { + 'number, number': addNumber, + 'Complex, Complex': function ComplexComplex(x, y) { + return x.add(y); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.plus(y); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.add(y); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (x.value === null || x.value === undefined) throw new Error('Parameter x contains a unit with undefined value'); + if (y.value === null || y.value === undefined) throw new Error('Parameter y contains a unit with undefined value'); + if (!x.equalBase(y)) throw new Error('Units do not match'); + var res = x.clone(); + res.value = addScalar(res.value, y.value); + res.fixPrefix = false; + return res; + } + }); + return addScalar; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/cbrt.js + + + + +var cbrt_name = 'cbrt'; +var cbrt_dependencies = ['config', 'typed', 'isNegative', 'unaryMinus', 'matrix', 'Complex', 'BigNumber', 'Fraction']; +var createCbrt = /* #__PURE__ */Object(factory["a" /* factory */])(cbrt_name, cbrt_dependencies, function (_ref) { + var config = _ref.config, + typed = _ref.typed, + isNegative = _ref.isNegative, + unaryMinus = _ref.unaryMinus, + matrix = _ref.matrix, + Complex = _ref.Complex, + BigNumber = _ref.BigNumber, + Fraction = _ref.Fraction; + + /** + * Calculate the cubic root of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.cbrt(x) + * math.cbrt(x, allRoots) + * + * Examples: + * + * math.cbrt(27) // returns 3 + * math.cube(3) // returns 27 + * math.cbrt(-64) // returns -4 + * math.cbrt(math.unit('27 m^3')) // returns Unit 3 m + * math.cbrt([27, 64, 125]) // returns [3, 4, 5] + * + * const x = math.complex('8i') + * math.cbrt(x) // returns Complex 1.7320508075689 + i + * math.cbrt(x, true) // returns Matrix [ + * // 1.7320508075689 + i + * // -1.7320508075689 + i + * // -2i + * // ] + * + * See also: + * + * square, sqrt, cube + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x + * Value for which to calculate the cubic root. + * @param {boolean} [allRoots] Optional, false by default. Only applicable + * when `x` is a number or complex number. If true, all complex + * roots are returned, if false (default) the principal root is + * returned. + * @return {number | BigNumber | Complex | Unit | Array | Matrix} + * Returns the cubic root of `x` + */ + var cbrt = typed(cbrt_name, { + number: cbrtNumber, + // note: signature 'number, boolean' is also supported, + // created by typed as it knows how to convert number to Complex + Complex: _cbrtComplex, + 'Complex, boolean': _cbrtComplex, + BigNumber: function BigNumber(x) { + return x.cbrt(); + }, + Unit: _cbrtUnit, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since cbrt(0) = 0 + return deepMap(x, cbrt, true); + } + }); + /** + * Calculate the cubic root for a complex number + * @param {Complex} x + * @param {boolean} [allRoots] If true, the function will return an array + * with all three roots. If false or undefined, + * the principal root is returned. + * @returns {Complex | Array. | Matrix.} Returns the cubic root(s) of x + * @private + */ + + function _cbrtComplex(x, allRoots) { + // https://www.wikiwand.com/en/Cube_root#/Complex_numbers + var arg3 = x.arg() / 3; + var abs = x.abs(); // principal root: + + var principal = new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3).exp()); + + if (allRoots) { + var all = [principal, new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3 + Math.PI * 2 / 3).exp()), new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3 - Math.PI * 2 / 3).exp())]; + return config.matrix === 'Array' ? all : matrix(all); + } else { + return principal; + } + } + /** + * Calculate the cubic root for a Unit + * @param {Unit} x + * @return {Unit} Returns the cubic root of x + * @private + */ + + + function _cbrtUnit(x) { + if (x.value && Object(is["j" /* isComplex */])(x.value)) { + var result = x.clone(); + result.value = 1.0; + result = result.pow(1.0 / 3); // Compute the units + + result.value = _cbrtComplex(x.value); // Compute the value + + return result; + } else { + var negate = isNegative(x.value); + + if (negate) { + x.value = unaryMinus(x.value); + } // TODO: create a helper function for this + + + var third; + + if (Object(is["e" /* isBigNumber */])(x.value)) { + third = new BigNumber(1).div(3); + } else if (Object(is["o" /* isFraction */])(x.value)) { + third = new Fraction(1, 3); + } else { + third = 1 / 3; + } + + var _result = x.pow(third); + + if (negate) { + _result.value = unaryMinus(_result.value); + } + + return _result; + } + } + + return cbrt; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/ceil.js + + + + + +var ceil_name = 'ceil'; +var ceil_dependencies = ['typed', 'config', 'round']; +var createCeil = /* #__PURE__ */Object(factory["a" /* factory */])(ceil_name, ceil_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + round = _ref.round; + + /** + * Round a value towards plus infinity + * If `x` is complex, both real and imaginary part are rounded towards plus infinity. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.ceil(x) + * + * Examples: + * + * math.ceil(3.2) // returns number 4 + * math.ceil(3.8) // returns number 4 + * math.ceil(-4.2) // returns number -4 + * math.ceil(-4.7) // returns number -4 + * + * const c = math.complex(3.2, -2.7) + * math.ceil(c) // returns Complex 4 - 2i + * + * math.ceil([3.2, 3.8, -4.7]) // returns Array [4, 4, -4] + * + * See also: + * + * floor, fix, round + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded + * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value + */ + var ceil = typed('ceil', { + number: function number(x) { + if (Object(utils_number["m" /* nearlyEqual */])(x, round(x), config.epsilon)) { + return round(x); + } else { + return ceilNumber(x); + } + }, + Complex: function Complex(x) { + return x.ceil(); + }, + BigNumber: function BigNumber(x) { + if (nearlyEqual(x, round(x), config.epsilon)) { + return round(x); + } else { + return x.ceil(); + } + }, + Fraction: function Fraction(x) { + return x.ceil(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since ceil(0) = 0 + return deepMap(x, ceil, true); + } + }); + return ceil; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/cube.js + + + +var cube_name = 'cube'; +var cube_dependencies = ['typed']; +var createCube = /* #__PURE__ */Object(factory["a" /* factory */])(cube_name, cube_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the cube of a value, `x * x * x`. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.cube(x) + * + * Examples: + * + * math.cube(2) // returns number 8 + * math.pow(2, 3) // returns number 8 + * math.cube(4) // returns number 64 + * 4 * 4 * 4 // returns number 64 + * + * math.cube([1, 2, 3, 4]) // returns Array [1, 8, 27, 64] + * + * See also: + * + * multiply, square, pow, cbrt + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x Number for which to calculate the cube + * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} Cube of x + */ + var cube = typed(cube_name, { + number: cubeNumber, + Complex: function Complex(x) { + return x.mul(x).mul(x); // Is faster than pow(x, 3) + }, + BigNumber: function BigNumber(x) { + return x.times(x).times(x); + }, + Fraction: function Fraction(x) { + return x.pow(3); // Is faster than mul()mul()mul() + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since cube(0) = 0 + return deepMap(x, cube, true); + }, + Unit: function Unit(x) { + return x.pow(3); + } + }); + return cube; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/exp.js + + + +var exp_name = 'exp'; +var exp_dependencies = ['typed']; +var createExp = /* #__PURE__ */Object(factory["a" /* factory */])(exp_name, exp_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the exponent of a value. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.exp(x) + * + * Examples: + * + * math.exp(2) // returns number 7.3890560989306495 + * math.pow(math.e, 2) // returns number 7.3890560989306495 + * math.log(math.exp(2)) // returns number 2 + * + * math.exp([1, 2, 3]) + * // returns Array [ + * // 2.718281828459045, + * // 7.3890560989306495, + * // 20.085536923187668 + * // ] + * + * See also: + * + * expm1, log, pow + * + * @param {number | BigNumber | Complex | Array | Matrix} x A number or matrix to exponentiate + * @return {number | BigNumber | Complex | Array | Matrix} Exponent of `x` + */ + var exp = typed(exp_name, { + number: expNumber, + Complex: function Complex(x) { + return x.exp(); + }, + BigNumber: function BigNumber(x) { + return x.exp(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // TODO: exp(sparse) should return a dense matrix since exp(0)==1 + return deepMap(x, exp); + } + }); + return exp; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/expm1.js + + + +var expm1_name = 'expm1'; +var expm1_dependencies = ['typed', 'Complex']; +var createExpm1 = /* #__PURE__ */Object(factory["a" /* factory */])(expm1_name, expm1_dependencies, function (_ref) { + var typed = _ref.typed, + _Complex = _ref.Complex; + + /** + * Calculate the value of subtracting 1 from the exponential value. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.expm1(x) + * + * Examples: + * + * math.expm1(2) // returns number 6.38905609893065 + * math.pow(math.e, 2) - 1 // returns number 6.3890560989306495 + * math.log(math.expm1(2) + 1) // returns number 2 + * + * math.expm1([1, 2, 3]) + * // returns Array [ + * // 1.718281828459045, + * // 6.3890560989306495, + * // 19.085536923187668 + * // ] + * + * See also: + * + * exp, log, pow + * + * @param {number | BigNumber | Complex | Array | Matrix} x A number or matrix to apply expm1 + * @return {number | BigNumber | Complex | Array | Matrix} Exponent of `x` + */ + var expm1 = typed(expm1_name, { + number: expm1Number, + Complex: function Complex(x) { + var r = Math.exp(x.re); + return new _Complex(r * Math.cos(x.im) - 1, r * Math.sin(x.im)); + }, + BigNumber: function BigNumber(x) { + return x.exp().minus(1); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, expm1); + } + }); + return expm1; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/fix.js + + +var fix_name = 'fix'; +var fix_dependencies = ['typed', 'Complex', 'ceil', 'floor']; +var createFix = /* #__PURE__ */Object(factory["a" /* factory */])(fix_name, fix_dependencies, function (_ref) { + var typed = _ref.typed, + _Complex = _ref.Complex, + ceil = _ref.ceil, + floor = _ref.floor; + + /** + * Round a value towards zero. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.fix(x) + * + * Examples: + * + * math.fix(3.2) // returns number 3 + * math.fix(3.8) // returns number 3 + * math.fix(-4.2) // returns number -4 + * math.fix(-4.7) // returns number -4 + * + * const c = math.complex(3.2, -2.7) + * math.fix(c) // returns Complex 3 - 2i + * + * math.fix([3.2, 3.8, -4.7]) // returns Array [3, 3, -4] + * + * See also: + * + * ceil, floor, round + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded + * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value + */ + var fix = typed('fix', { + number: function number(x) { + return x > 0 ? floor(x) : ceil(x); + }, + Complex: function Complex(x) { + return new _Complex(x.re > 0 ? Math.floor(x.re) : Math.ceil(x.re), x.im > 0 ? Math.floor(x.im) : Math.ceil(x.im)); + }, + BigNumber: function BigNumber(x) { + return x.isNegative() ? ceil(x) : floor(x); + }, + Fraction: function Fraction(x) { + return x.s < 0 ? x.ceil() : x.floor(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since fix(0) = 0 + return deepMap(x, fix, true); + } + }); + return fix; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/floor.js + + + + +var floor_name = 'floor'; +var floor_dependencies = ['typed', 'config', 'round']; +var createFloor = /* #__PURE__ */Object(factory["a" /* factory */])(floor_name, floor_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + round = _ref.round; + + /** + * Round a value towards minus infinity. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.floor(x) + * + * Examples: + * + * math.floor(3.2) // returns number 3 + * math.floor(3.8) // returns number 3 + * math.floor(-4.2) // returns number -5 + * math.floor(-4.7) // returns number -5 + * + * const c = math.complex(3.2, -2.7) + * math.floor(c) // returns Complex 3 - 3i + * + * math.floor([3.2, 3.8, -4.7]) // returns Array [3, 3, -5] + * + * See also: + * + * ceil, fix, round + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded + * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value + */ + var floor = typed('floor', { + number: function number(x) { + if (Object(utils_number["m" /* nearlyEqual */])(x, round(x), config.epsilon)) { + return round(x); + } else { + return Math.floor(x); + } + }, + Complex: function Complex(x) { + return x.floor(); + }, + BigNumber: function BigNumber(x) { + if (nearlyEqual(x, round(x), config.epsilon)) { + return round(x); + } else { + return x.floor(); + } + }, + Fraction: function Fraction(x) { + return x.floor(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since floor(0) = 0 + return deepMap(x, floor, true); + } + }); + return floor; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm01.js + + +var algorithm01_name = 'algorithm01'; +var algorithm01_dependencies = ['typed']; +var createAlgorithm01 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm01_name, algorithm01_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Iterates over SparseMatrix nonzero items and invokes the callback function f(Dij, Sij). + * Callback function invoked NNZ times (number of nonzero items in SparseMatrix). + * + * + * ┌ f(Dij, Sij) ; S(i,j) !== 0 + * C(i,j) = ┤ + * └ Dij ; otherwise + * + * + * @param {Matrix} denseMatrix The DenseMatrix instance (D) + * @param {Matrix} sparseMatrix The SparseMatrix instance (S) + * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j) + * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij) + * + * @return {Matrix} DenseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571 + */ + return function algorithm1(denseMatrix, sparseMatrix, callback, inverse) { + // dense matrix arrays + var adata = denseMatrix._data; + var asize = denseMatrix._size; + var adt = denseMatrix._datatype; // sparse matrix arrays + + var bvalues = sparseMatrix._values; + var bindex = sparseMatrix._index; + var bptr = sparseMatrix._ptr; + var bsize = sparseMatrix._size; + var bdt = sparseMatrix._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // sparse matrix cannot be a Pattern matrix + + + if (!bvalues) { + throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // process data types + + var dt = typeof adt === 'string' && adt === bdt ? adt : undefined; // callback function + + var cf = dt ? typed.find(callback, [dt, dt]) : callback; // vars + + var i, j; // result (DenseMatrix) + + var cdata = []; // initialize c + + for (i = 0; i < rows; i++) { + cdata[i] = []; + } // workspace + + + var x = []; // marks indicating we have a value in x for a given column + + var w = []; // loop columns in b + + for (j = 0; j < columns; j++) { + // column mark + var mark = j + 1; // values in column j + + for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) { + // row + i = bindex[k]; // update workspace + + x[i] = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]); // mark i as updated + + w[i] = mark; + } // loop rows + + + for (i = 0; i < rows; i++) { + // check row is in workspace + if (w[i] === mark) { + // c[i][j] was already calculated + cdata[i][j] = x[i]; + } else { + // item does not exist in S + cdata[i][j] = adata[i][j]; + } + } + } // return dense matrix + + + return denseMatrix.createDenseMatrix({ + data: cdata, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm04.js + + +var algorithm04_name = 'algorithm04'; +var algorithm04_dependencies = ['typed', 'equalScalar']; +var createAlgorithm04 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm04_name, algorithm04_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij). + * Callback function invoked MAX(NNZA, NNZB) times + * + * + * ┌ f(Aij, Bij) ; A(i,j) !== 0 && B(i,j) !== 0 + * C(i,j) = ┤ A(i,j) ; A(i,j) !== 0 + * └ B(i,j) ; B(i,j) !== 0 + * + * + * @param {Matrix} a The SparseMatrix instance (A) + * @param {Matrix} b The SparseMatrix instance (B) + * @param {Function} callback The f(Aij,Bij) operation to invoke + * + * @return {Matrix} SparseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294 + */ + return function algorithm04(a, b, callback) { + // sparse matrix arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; + var adt = a._datatype; // sparse matrix arrays + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; + var bsize = b._size; + var bdt = b._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cvalues = avalues && bvalues ? [] : undefined; + var cindex = []; + var cptr = []; // workspace + + var xa = avalues && bvalues ? [] : undefined; + var xb = avalues && bvalues ? [] : undefined; // marks indicating we have a value in x for a given column + + var wa = []; + var wb = []; // vars + + var i, j, k, k0, k1; // loop columns + + for (j = 0; j < columns; j++) { + // update cptr + cptr[j] = cindex.length; // columns mark + + var mark = j + 1; // loop A(:,j) + + for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + i = aindex[k]; // update c + + cindex.push(i); // update workspace + + wa[i] = mark; // check we need to process values + + if (xa) { + xa[i] = avalues[k]; + } + } // loop B(:,j) + + + for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) { + // row + i = bindex[k]; // check row exists in A + + if (wa[i] === mark) { + // update record in xa @ i + if (xa) { + // invoke callback + var v = cf(xa[i], bvalues[k]); // check for zero + + if (!eq(v, zero)) { + // update workspace + xa[i] = v; + } else { + // remove mark (index will be removed later) + wa[i] = null; + } + } + } else { + // update c + cindex.push(i); // update workspace + + wb[i] = mark; // check we need to process values + + if (xb) { + xb[i] = bvalues[k]; + } + } + } // check we need to process values (non pattern matrix) + + + if (xa && xb) { + // initialize first index in j + k = cptr[j]; // loop index in j + + while (k < cindex.length) { + // row + i = cindex[k]; // check workspace has value @ i + + if (wa[i] === mark) { + // push value (Aij != 0 || (Aij != 0 && Bij != 0)) + cvalues[k] = xa[i]; // increment pointer + + k++; + } else if (wb[i] === mark) { + // push value (bij != 0) + cvalues[k] = xb[i]; // increment pointer + + k++; + } else { + // remove index @ k + cindex.splice(k, 1); + } + } + } + } // update cptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm10.js + +var algorithm10_name = 'algorithm10'; +var algorithm10_dependencies = ['typed', 'DenseMatrix']; +var createAlgorithm10 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm10_name, algorithm10_dependencies, function (_ref) { + var typed = _ref.typed, + DenseMatrix = _ref.DenseMatrix; + + /** + * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b). + * Callback function invoked NZ times (number of nonzero items in S). + * + * + * ┌ f(Sij, b) ; S(i,j) !== 0 + * C(i,j) = ┤ + * └ b ; otherwise + * + * + * @param {Matrix} s The SparseMatrix instance (S) + * @param {Scalar} b The Scalar value + * @param {Function} callback The f(Aij,b) operation to invoke + * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij) + * + * @return {Matrix} DenseMatrix (C) + * + * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813 + */ + return function algorithm10(s, b, callback, inverse) { + // sparse matrix arrays + var avalues = s._values; + var aindex = s._index; + var aptr = s._ptr; + var asize = s._size; + var adt = s._datatype; // sparse matrix cannot be a Pattern matrix + + if (!avalues) { + throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string') { + // datatype + dt = adt; // convert b to the same datatype + + b = typed.convert(b, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cdata = []; // workspaces + + var x = []; // marks indicating we have a value in x for a given column + + var w = []; // loop columns + + for (var j = 0; j < columns; j++) { + // columns mark + var mark = j + 1; // values in j + + for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + var r = aindex[k]; // update workspace + + x[r] = avalues[k]; + w[r] = mark; + } // loop rows + + + for (var i = 0; i < rows; i++) { + // initialize C on first column + if (j === 0) { + // create row array + cdata[i] = []; + } // check sparse matrix has a value @ i,j + + + if (w[i] === mark) { + // invoke callback, update C + cdata[i][j] = inverse ? cf(b, x[i]) : cf(x[i], b); + } else { + // dense matrix value @ i, j + cdata[i][j] = b; + } + } + } // return dense matrix + + + return new DenseMatrix({ + data: cdata, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm13.js + + +var algorithm13_name = 'algorithm13'; +var algorithm13_dependencies = ['typed']; +var createAlgorithm13 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm13_name, algorithm13_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, Bij..z). + * Callback function invoked MxN times. + * + * C(i,j,...z) = f(Aij..z, Bij..z) + * + * @param {Matrix} a The DenseMatrix instance (A) + * @param {Matrix} b The DenseMatrix instance (B) + * @param {Function} callback The f(Aij..z,Bij..z) operation to invoke + * + * @return {Matrix} DenseMatrix (C) + * + * https://github.com/josdejong/mathjs/pull/346#issuecomment-97658658 + */ + return function algorithm13(a, b, callback) { + // a arrays + var adata = a._data; + var asize = a._size; + var adt = a._datatype; // b arrays + + var bdata = b._data; + var bsize = b._size; + var bdt = b._datatype; // c arrays + + var csize = []; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // validate each one of the dimension sizes + + + for (var s = 0; s < asize.length; s++) { + // must match + if (asize[s] !== bsize[s]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // update dimension in c + + + csize[s] = asize[s]; + } // datatype + + + var dt; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // callback + + cf = typed.find(callback, [dt, dt]); + } // populate cdata, iterate through dimensions + + + var cdata = csize.length > 0 ? _iterate(cf, 0, csize, csize[0], adata, bdata) : []; // c matrix + + return a.createDenseMatrix({ + data: cdata, + size: csize, + datatype: dt + }); + }; // recursive function + + function _iterate(f, level, s, n, av, bv) { + // initialize array for this level + var cv = []; // check we reach the last level + + if (level === s.length - 1) { + // loop arrays in last level + for (var i = 0; i < n; i++) { + // invoke callback and store value + cv[i] = f(av[i], bv[i]); + } + } else { + // iterate current level + for (var j = 0; j < n; j++) { + // iterate next level + cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv[j]); + } + } + + return cv; + } +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm14.js + + +var algorithm14_name = 'algorithm14'; +var algorithm14_dependencies = ['typed']; +var createAlgorithm14 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm14_name, algorithm14_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, b). + * Callback function invoked MxN times. + * + * C(i,j,...z) = f(Aij..z, b) + * + * @param {Matrix} a The DenseMatrix instance (A) + * @param {Scalar} b The Scalar value + * @param {Function} callback The f(Aij..z,b) operation to invoke + * @param {boolean} inverse A true value indicates callback should be invoked f(b,Aij..z) + * + * @return {Matrix} DenseMatrix (C) + * + * https://github.com/josdejong/mathjs/pull/346#issuecomment-97659042 + */ + return function algorithm14(a, b, callback, inverse) { + // a arrays + var adata = a._data; + var asize = a._size; + var adt = a._datatype; // datatype + + var dt; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string') { + // datatype + dt = adt; // convert b to the same datatype + + b = typed.convert(b, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // populate cdata, iterate through dimensions + + + var cdata = asize.length > 0 ? _iterate(cf, 0, asize, asize[0], adata, b, inverse) : []; // c matrix + + return a.createDenseMatrix({ + data: cdata, + size: Object(utils_object["a" /* clone */])(asize), + datatype: dt + }); + }; // recursive function + + function _iterate(f, level, s, n, av, bv, inverse) { + // initialize array for this level + var cv = []; // check we reach the last level + + if (level === s.length - 1) { + // loop arrays in last level + for (var i = 0; i < n; i++) { + // invoke callback and store value + cv[i] = inverse ? f(bv, av[i]) : f(av[i], bv); + } + } else { + // iterate current level + for (var j = 0; j < n; j++) { + // iterate next level + cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv, inverse); + } + } + + return cv; + } +}); +// CONCATENATED MODULE: ./src/function/arithmetic/gcd.js + + + + + + + +var gcd_name = 'gcd'; +var gcd_dependencies = ['typed', 'matrix', 'equalScalar', 'BigNumber', 'DenseMatrix']; +var createGcd = /* #__PURE__ */Object(factory["a" /* factory */])(gcd_name, gcd_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + BigNumber = _ref.BigNumber, + DenseMatrix = _ref.DenseMatrix; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm04 = createAlgorithm04({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Calculate the greatest common divisor for two or more values or arrays. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.gcd(a, b) + * math.gcd(a, b, c, ...) + * + * Examples: + * + * math.gcd(8, 12) // returns 4 + * math.gcd(-4, 6) // returns 2 + * math.gcd(25, 15, -10) // returns 5 + * + * math.gcd([8, -4], [12, 6]) // returns [4, 2] + * + * See also: + * + * lcm, xgcd + * + * @param {... number | BigNumber | Fraction | Array | Matrix} args Two or more integer numbers + * @return {number | BigNumber | Fraction | Array | Matrix} The greatest common divisor + */ + + var gcd = typed(gcd_name, { + 'number, number': gcdNumber, + 'BigNumber, BigNumber': _gcdBigNumber, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.gcd(y); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm04(x, y, gcd); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm01(y, x, gcd, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm01(x, y, gcd, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, gcd); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return gcd(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return gcd(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return gcd(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + return algorithm10(x, y, gcd, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + return algorithm14(x, y, gcd, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + return algorithm10(y, x, gcd, true); + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + return algorithm14(y, x, gcd, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, gcd, false).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, gcd, true).valueOf(); + }, + // TODO: need a smarter notation here + 'Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber': function ArrayMatrixNumberBigNumberArrayMatrixNumberBigNumberArrayMatrixNumberBigNumber(a, b, args) { + var res = gcd(a, b); + + for (var i = 0; i < args.length; i++) { + res = gcd(res, args[i]); + } + + return res; + } + }); + return gcd; + /** + * Calculate gcd for BigNumbers + * @param {BigNumber} a + * @param {BigNumber} b + * @returns {BigNumber} Returns greatest common denominator of a and b + * @private + */ + + function _gcdBigNumber(a, b) { + if (!a.isInt() || !b.isInt()) { + throw new Error('Parameters in function gcd must be integer numbers'); + } // https://en.wikipedia.org/wiki/Euclidean_algorithm + + + var zero = new BigNumber(0); + + while (!b.isZero()) { + var r = a.mod(b); + a = b; + b = r; + } + + return a.lt(zero) ? a.neg() : a; + } +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm02.js + + +var algorithm02_name = 'algorithm02'; +var algorithm02_dependencies = ['typed', 'equalScalar']; +var createAlgorithm02 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm02_name, algorithm02_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix nonzero items and invokes the callback function f(Dij, Sij). + * Callback function invoked NNZ times (number of nonzero items in SparseMatrix). + * + * + * ┌ f(Dij, Sij) ; S(i,j) !== 0 + * C(i,j) = ┤ + * └ 0 ; otherwise + * + * + * @param {Matrix} denseMatrix The DenseMatrix instance (D) + * @param {Matrix} sparseMatrix The SparseMatrix instance (S) + * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j) + * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij) + * + * @return {Matrix} SparseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571 + */ + return function algorithm02(denseMatrix, sparseMatrix, callback, inverse) { + // dense matrix arrays + var adata = denseMatrix._data; + var asize = denseMatrix._size; + var adt = denseMatrix._datatype; // sparse matrix arrays + + var bvalues = sparseMatrix._values; + var bindex = sparseMatrix._index; + var bptr = sparseMatrix._ptr; + var bsize = sparseMatrix._size; + var bdt = sparseMatrix._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // sparse matrix cannot be a Pattern matrix + + + if (!bvalues) { + throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result (SparseMatrix) + + + var cvalues = []; + var cindex = []; + var cptr = []; // loop columns in b + + for (var j = 0; j < columns; j++) { + // update cptr + cptr[j] = cindex.length; // values in column j + + for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) { + // row + var i = bindex[k]; // update C(i,j) + + var cij = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]); // check for nonzero + + if (!eq(cij, zero)) { + // push i & v + cindex.push(i); + cvalues.push(cij); + } + } + } // update cptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return sparseMatrix.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm06.js + + + +var algorithm06_name = 'algorithm06'; +var algorithm06_dependencies = ['typed', 'equalScalar']; +var createAlgorithm06 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm06_name, algorithm06_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij). + * Callback function invoked (Anz U Bnz) times, where Anz and Bnz are the nonzero elements in both matrices. + * + * + * ┌ f(Aij, Bij) ; A(i,j) !== 0 && B(i,j) !== 0 + * C(i,j) = ┤ + * └ 0 ; otherwise + * + * + * @param {Matrix} a The SparseMatrix instance (A) + * @param {Matrix} b The SparseMatrix instance (B) + * @param {Function} callback The f(Aij,Bij) operation to invoke + * + * @return {Matrix} SparseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294 + */ + return function algorithm06(a, b, callback) { + // sparse matrix arrays + var avalues = a._values; + var asize = a._size; + var adt = a._datatype; // sparse matrix arrays + + var bvalues = b._values; + var bsize = b._size; + var bdt = b._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cvalues = avalues && bvalues ? [] : undefined; + var cindex = []; + var cptr = []; // workspaces + + var x = cvalues ? [] : undefined; // marks indicating we have a value in x for a given column + + var w = []; // marks indicating value in a given row has been updated + + var u = []; // loop columns + + for (var j = 0; j < columns; j++) { + // update cptr + cptr[j] = cindex.length; // columns mark + + var mark = j + 1; // scatter the values of A(:,j) into workspace + + scatter(a, j, w, x, u, mark, cindex, cf); // scatter the values of B(:,j) into workspace + + scatter(b, j, w, x, u, mark, cindex, cf); // check we need to process values (non pattern matrix) + + if (x) { + // initialize first index in j + var k = cptr[j]; // loop index in j + + while (k < cindex.length) { + // row + var i = cindex[k]; // check function was invoked on current row (Aij !=0 && Bij != 0) + + if (u[i] === mark) { + // value @ i + var v = x[i]; // check for zero value + + if (!eq(v, zero)) { + // push value + cvalues.push(v); // increment pointer + + k++; + } else { + // remove value @ i, do not increment pointer + cindex.splice(k, 1); + } + } else { + // remove value @ i, do not increment pointer + cindex.splice(k, 1); + } + } + } else { + // initialize first index in j + var p = cptr[j]; // loop index in j + + while (p < cindex.length) { + // row + var r = cindex[p]; // check function was invoked on current row (Aij !=0 && Bij != 0) + + if (u[r] !== mark) { + // remove value @ i, do not increment pointer + cindex.splice(p, 1); + } else { + // increment pointer + p++; + } + } + } + } // update cptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm11.js + +var algorithm11_name = 'algorithm11'; +var algorithm11_dependencies = ['typed', 'equalScalar']; +var createAlgorithm11 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm11_name, algorithm11_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b). + * Callback function invoked NZ times (number of nonzero items in S). + * + * + * ┌ f(Sij, b) ; S(i,j) !== 0 + * C(i,j) = ┤ + * └ 0 ; otherwise + * + * + * @param {Matrix} s The SparseMatrix instance (S) + * @param {Scalar} b The Scalar value + * @param {Function} callback The f(Aij,b) operation to invoke + * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij) + * + * @return {Matrix} SparseMatrix (C) + * + * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813 + */ + return function algorithm11(s, b, callback, inverse) { + // sparse matrix arrays + var avalues = s._values; + var aindex = s._index; + var aptr = s._ptr; + var asize = s._size; + var adt = s._datatype; // sparse matrix cannot be a Pattern matrix + + if (!avalues) { + throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string') { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // convert b to the same datatype + + b = typed.convert(b, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cvalues = []; + var cindex = []; + var cptr = []; // loop columns + + for (var j = 0; j < columns; j++) { + // initialize ptr + cptr[j] = cindex.length; // values in j + + for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + var i = aindex[k]; // invoke callback + + var v = inverse ? cf(b, avalues[k]) : cf(avalues[k], b); // check value is zero + + if (!eq(v, zero)) { + // push index & value + cindex.push(i); + cvalues.push(v); + } + } + } // update ptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return s.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/lcm.js + + + + + + + +var lcm_name = 'lcm'; +var lcm_dependencies = ['typed', 'matrix', 'equalScalar']; +var createLcm = /* #__PURE__ */Object(factory["a" /* factory */])(lcm_name, lcm_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm06 = createAlgorithm06({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Calculate the least common multiple for two or more values or arrays. + * + * lcm is defined as: + * + * lcm(a, b) = abs(a * b) / gcd(a, b) + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.lcm(a, b) + * math.lcm(a, b, c, ...) + * + * Examples: + * + * math.lcm(4, 6) // returns 12 + * math.lcm(6, 21) // returns 42 + * math.lcm(6, 21, 5) // returns 210 + * + * math.lcm([4, 6], [6, 21]) // returns [12, 42] + * + * See also: + * + * gcd, xgcd + * + * @param {... number | BigNumber | Array | Matrix} args Two or more integer numbers + * @return {number | BigNumber | Array | Matrix} The least common multiple + */ + + var lcm = typed(lcm_name, { + 'number, number': lcmNumber, + 'BigNumber, BigNumber': _lcmBigNumber, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.lcm(y); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm06(x, y, lcm); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, lcm, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm02(x, y, lcm, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, lcm); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return lcm(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return lcm(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return lcm(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + return algorithm11(x, y, lcm, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + return algorithm14(x, y, lcm, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + return algorithm11(y, x, lcm, true); + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + return algorithm14(y, x, lcm, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, lcm, false).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, lcm, true).valueOf(); + }, + // TODO: need a smarter notation here + 'Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber': function ArrayMatrixNumberBigNumberArrayMatrixNumberBigNumberArrayMatrixNumberBigNumber(a, b, args) { + var res = lcm(a, b); + + for (var i = 0; i < args.length; i++) { + res = lcm(res, args[i]); + } + + return res; + } + }); + return lcm; + /** + * Calculate lcm for two BigNumbers + * @param {BigNumber} a + * @param {BigNumber} b + * @returns {BigNumber} Returns the least common multiple of a and b + * @private + */ + + function _lcmBigNumber(a, b) { + if (!a.isInt() || !b.isInt()) { + throw new Error('Parameters in function lcm must be integer numbers'); + } + + if (a.isZero()) { + return a; + } + + if (b.isZero()) { + return b; + } // https://en.wikipedia.org/wiki/Euclidean_algorithm + // evaluate lcm here inline to reduce overhead + + + var prod = a.times(b); + + while (!b.isZero()) { + var t = b; + b = a.mod(t); + a = t; + } + + return prod.div(a).abs(); + } +}); +// CONCATENATED MODULE: ./src/function/arithmetic/log10.js + + + +var log10_name = 'log10'; +var log10_dependencies = ['typed', 'config', 'Complex']; +var createLog10 = /* #__PURE__ */Object(factory["a" /* factory */])(log10_name, log10_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + _Complex = _ref.Complex; + + /** + * Calculate the 10-base logarithm of a value. This is the same as calculating `log(x, 10)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.log10(x) + * + * Examples: + * + * math.log10(0.00001) // returns -5 + * math.log10(10000) // returns 4 + * math.log(10000) / math.log(10) // returns 4 + * math.pow(10, 4) // returns 10000 + * + * See also: + * + * exp, log, log1p, log2 + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * Value for which to calculate the logarithm. + * @return {number | BigNumber | Complex | Array | Matrix} + * Returns the 10-base logarithm of `x` + */ + var log10 = typed(log10_name, { + number: function number(x) { + if (x >= 0 || config.predictable) { + return log10Number(x); + } else { + // negative value -> complex value computation + return new _Complex(x, 0).log().div(Math.LN10); + } + }, + Complex: function Complex(x) { + return new _Complex(x).log().div(Math.LN10); + }, + BigNumber: function BigNumber(x) { + if (!x.isNegative() || config.predictable) { + return x.log(); + } else { + // downgrade to number, return Complex valued result + return new _Complex(x.toNumber(), 0).log().div(Math.LN10); + } + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, log10); + } + }); + return log10; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/log2.js + + + +var log2_name = 'log2'; +var log2_dependencies = ['typed', 'config', 'Complex']; +var createLog2 = /* #__PURE__ */Object(factory["a" /* factory */])(log2_name, log2_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex; + + /** + * Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.log2(x) + * + * Examples: + * + * math.log2(0.03125) // returns -5 + * math.log2(16) // returns 4 + * math.log2(16) / math.log2(2) // returns 4 + * math.pow(2, 4) // returns 16 + * + * See also: + * + * exp, log, log1p, log10 + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * Value for which to calculate the logarithm. + * @return {number | BigNumber | Complex | Array | Matrix} + * Returns the 2-base logarithm of `x` + */ + var log2 = typed(log2_name, { + number: function number(x) { + if (x >= 0 || config.predictable) { + return log2Number(x); + } else { + // negative value -> complex value computation + return _log2Complex(new Complex(x, 0)); + } + }, + Complex: _log2Complex, + BigNumber: function BigNumber(x) { + if (!x.isNegative() || config.predictable) { + return x.log(2); + } else { + // downgrade to number, return Complex valued result + return _log2Complex(new Complex(x.toNumber(), 0)); + } + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, log2); + } + }); + /** + * Calculate log2 for a complex value + * @param {Complex} x + * @returns {Complex} + * @private + */ + + function _log2Complex(x) { + var newX = Math.sqrt(x.re * x.re + x.im * x.im); + return new Complex(Math.log2 ? Math.log2(newX) : Math.log(newX) / Math.LN2, Math.atan2(x.im, x.re) / Math.LN2); + } + + return log2; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm03.js + + +var algorithm03_name = 'algorithm03'; +var algorithm03_dependencies = ['typed']; +var createAlgorithm03 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm03_name, algorithm03_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Iterates over SparseMatrix items and invokes the callback function f(Dij, Sij). + * Callback function invoked M*N times. + * + * + * ┌ f(Dij, Sij) ; S(i,j) !== 0 + * C(i,j) = ┤ + * └ f(Dij, 0) ; otherwise + * + * + * @param {Matrix} denseMatrix The DenseMatrix instance (D) + * @param {Matrix} sparseMatrix The SparseMatrix instance (C) + * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j) + * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij) + * + * @return {Matrix} DenseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571 + */ + return function algorithm03(denseMatrix, sparseMatrix, callback, inverse) { + // dense matrix arrays + var adata = denseMatrix._data; + var asize = denseMatrix._size; + var adt = denseMatrix._datatype; // sparse matrix arrays + + var bvalues = sparseMatrix._values; + var bindex = sparseMatrix._index; + var bptr = sparseMatrix._ptr; + var bsize = sparseMatrix._size; + var bdt = sparseMatrix._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // sparse matrix cannot be a Pattern matrix + + + if (!bvalues) { + throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result (DenseMatrix) + + + var cdata = []; // initialize dense matrix + + for (var z = 0; z < rows; z++) { + // initialize row + cdata[z] = []; + } // workspace + + + var x = []; // marks indicating we have a value in x for a given column + + var w = []; // loop columns in b + + for (var j = 0; j < columns; j++) { + // column mark + var mark = j + 1; // values in column j + + for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) { + // row + var i = bindex[k]; // update workspace + + x[i] = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]); + w[i] = mark; + } // process workspace + + + for (var y = 0; y < rows; y++) { + // check we have a calculated value for current row + if (w[y] === mark) { + // use calculated value + cdata[y][j] = x[y]; + } else { + // calculate value + cdata[y][j] = inverse ? cf(zero, adata[y][j]) : cf(adata[y][j], zero); + } + } + } // return dense matrix + + + return denseMatrix.createDenseMatrix({ + data: cdata, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm05.js + + +var algorithm05_name = 'algorithm05'; +var algorithm05_dependencies = ['typed', 'equalScalar']; +var createAlgorithm05 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm05_name, algorithm05_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij). + * Callback function invoked MAX(NNZA, NNZB) times + * + * + * ┌ f(Aij, Bij) ; A(i,j) !== 0 || B(i,j) !== 0 + * C(i,j) = ┤ + * └ 0 ; otherwise + * + * + * @param {Matrix} a The SparseMatrix instance (A) + * @param {Matrix} b The SparseMatrix instance (B) + * @param {Function} callback The f(Aij,Bij) operation to invoke + * + * @return {Matrix} SparseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294 + */ + return function algorithm05(a, b, callback) { + // sparse matrix arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; + var adt = a._datatype; // sparse matrix arrays + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; + var bsize = b._size; + var bdt = b._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cvalues = avalues && bvalues ? [] : undefined; + var cindex = []; + var cptr = []; // workspaces + + var xa = cvalues ? [] : undefined; + var xb = cvalues ? [] : undefined; // marks indicating we have a value in x for a given column + + var wa = []; + var wb = []; // vars + + var i, j, k, k1; // loop columns + + for (j = 0; j < columns; j++) { + // update cptr + cptr[j] = cindex.length; // columns mark + + var mark = j + 1; // loop values A(:,j) + + for (k = aptr[j], k1 = aptr[j + 1]; k < k1; k++) { + // row + i = aindex[k]; // push index + + cindex.push(i); // update workspace + + wa[i] = mark; // check we need to process values + + if (xa) { + xa[i] = avalues[k]; + } + } // loop values B(:,j) + + + for (k = bptr[j], k1 = bptr[j + 1]; k < k1; k++) { + // row + i = bindex[k]; // check row existed in A + + if (wa[i] !== mark) { + // push index + cindex.push(i); + } // update workspace + + + wb[i] = mark; // check we need to process values + + if (xb) { + xb[i] = bvalues[k]; + } + } // check we need to process values (non pattern matrix) + + + if (cvalues) { + // initialize first index in j + k = cptr[j]; // loop index in j + + while (k < cindex.length) { + // row + i = cindex[k]; // marks + + var wai = wa[i]; + var wbi = wb[i]; // check Aij or Bij are nonzero + + if (wai === mark || wbi === mark) { + // matrix values @ i,j + var va = wai === mark ? xa[i] : zero; + var vb = wbi === mark ? xb[i] : zero; // Cij + + var vc = cf(va, vb); // check for zero + + if (!eq(vc, zero)) { + // push value + cvalues.push(vc); // increment pointer + + k++; + } else { + // remove value @ i, do not increment pointer + cindex.splice(k, 1); + } + } + } + } + } // update cptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm12.js + +var algorithm12_name = 'algorithm12'; +var algorithm12_dependencies = ['typed', 'DenseMatrix']; +var createAlgorithm12 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm12_name, algorithm12_dependencies, function (_ref) { + var typed = _ref.typed, + DenseMatrix = _ref.DenseMatrix; + + /** + * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b). + * Callback function invoked MxN times. + * + * + * ┌ f(Sij, b) ; S(i,j) !== 0 + * C(i,j) = ┤ + * └ f(0, b) ; otherwise + * + * + * @param {Matrix} s The SparseMatrix instance (S) + * @param {Scalar} b The Scalar value + * @param {Function} callback The f(Aij,b) operation to invoke + * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij) + * + * @return {Matrix} DenseMatrix (C) + * + * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813 + */ + return function algorithm12(s, b, callback, inverse) { + // sparse matrix arrays + var avalues = s._values; + var aindex = s._index; + var aptr = s._ptr; + var asize = s._size; + var adt = s._datatype; // sparse matrix cannot be a Pattern matrix + + if (!avalues) { + throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string') { + // datatype + dt = adt; // convert b to the same datatype + + b = typed.convert(b, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cdata = []; // workspaces + + var x = []; // marks indicating we have a value in x for a given column + + var w = []; // loop columns + + for (var j = 0; j < columns; j++) { + // columns mark + var mark = j + 1; // values in j + + for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + var r = aindex[k]; // update workspace + + x[r] = avalues[k]; + w[r] = mark; + } // loop rows + + + for (var i = 0; i < rows; i++) { + // initialize C on first column + if (j === 0) { + // create row array + cdata[i] = []; + } // check sparse matrix has a value @ i,j + + + if (w[i] === mark) { + // invoke callback, update C + cdata[i][j] = inverse ? cf(b, x[i]) : cf(x[i], b); + } else { + // dense matrix value @ i, j + cdata[i][j] = inverse ? cf(b, 0) : cf(0, b); + } + } + } // return dense matrix + + + return new DenseMatrix({ + data: cdata, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/mod.js + + + + + + + + + +var mod_name = 'mod'; +var mod_dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix']; +var createMod = /* #__PURE__ */Object(factory["a" /* factory */])(mod_name, mod_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm05 = createAlgorithm05({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Calculates the modulus, the remainder of an integer division. + * + * For matrices, the function is evaluated element wise. + * + * The modulus is defined as: + * + * x - y * floor(x / y) + * + * See https://en.wikipedia.org/wiki/Modulo_operation. + * + * Syntax: + * + * math.mod(x, y) + * + * Examples: + * + * math.mod(8, 3) // returns 2 + * math.mod(11, 2) // returns 1 + * + * function isOdd(x) { + * return math.mod(x, 2) != 0 + * } + * + * isOdd(2) // returns false + * isOdd(3) // returns true + * + * See also: + * + * divide + * + * @param {number | BigNumber | Fraction | Array | Matrix} x Dividend + * @param {number | BigNumber | Fraction | Array | Matrix} y Divisor + * @return {number | BigNumber | Fraction | Array | Matrix} Returns the remainder of `x` divided by `y`. + */ + + var mod = typed(mod_name, { + 'number, number': modNumber, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return y.isZero() ? x : x.mod(y); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.mod(y); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm05(x, y, mod, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, mod, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, mod, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, mod); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return mod(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return mod(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return mod(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, mod, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, mod, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, mod, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, mod, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, mod, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, mod, true).valueOf(); + } + }); + return mod; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/multiplyScalar.js + + +var multiplyScalar_name = 'multiplyScalar'; +var multiplyScalar_dependencies = ['typed']; +var createMultiplyScalar = /* #__PURE__ */Object(factory["a" /* factory */])(multiplyScalar_name, multiplyScalar_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Multiply two scalar values, `x * y`. + * This function is meant for internal use: it is used by the public function + * `multiply` + * + * This function does not support collections (Array or Matrix). + * + * @param {number | BigNumber | Fraction | Complex | Unit} x First value to multiply + * @param {number | BigNumber | Fraction | Complex} y Second value to multiply + * @return {number | BigNumber | Fraction | Complex | Unit} Multiplication of `x` and `y` + * @private + */ + var multiplyScalar = typed('multiplyScalar', { + 'number, number': multiplyNumber, + 'Complex, Complex': function ComplexComplex(x, y) { + return x.mul(y); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.times(y); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.mul(y); + }, + 'number | Fraction | BigNumber | Complex, Unit': function numberFractionBigNumberComplexUnit(x, y) { + var res = y.clone(); + res.value = res.value === null ? res._normalize(x) : multiplyScalar(res.value, x); + return res; + }, + 'Unit, number | Fraction | BigNumber | Complex': function UnitNumberFractionBigNumberComplex(x, y) { + var res = x.clone(); + res.value = res.value === null ? res._normalize(y) : multiplyScalar(res.value, y); + return res; + }, + 'Unit, Unit': function UnitUnit(x, y) { + return x.multiply(y); + } + }); + return multiplyScalar; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/multiply.js + + + + + + +var multiply_name = 'multiply'; +var multiply_dependencies = ['typed', 'matrix', 'addScalar', 'multiplyScalar', 'equalScalar']; +var createMultiply = /* #__PURE__ */Object(factory["a" /* factory */])(multiply_name, multiply_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + addScalar = _ref.addScalar, + multiplyScalar = _ref.multiplyScalar, + equalScalar = _ref.equalScalar; + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Multiply two or more values, `x * y`. + * For matrices, the matrix product is calculated. + * + * Syntax: + * + * math.multiply(x, y) + * math.multiply(x, y, z, ...) + * + * Examples: + * + * math.multiply(4, 5.2) // returns number 20.8 + * math.multiply(2, 3, 4) // returns number 24 + * + * const a = math.complex(2, 3) + * const b = math.complex(4, 1) + * math.multiply(a, b) // returns Complex 5 + 14i + * + * const c = [[1, 2], [4, 3]] + * const d = [[1, 2, 3], [3, -4, 7]] + * math.multiply(c, d) // returns Array [[7, -6, 17], [13, -4, 33]] + * + * const e = math.unit('2.1 km') + * math.multiply(3, e) // returns Unit 6.3 km + * + * See also: + * + * divide, prod, cross, dot + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First value to multiply + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second value to multiply + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y` + */ + + var multiply = typed(multiply_name, Object(utils_object["e" /* extend */])({ + // we extend the signatures of multiplyScalar with signatures dealing with matrices + 'Array, Array': function ArrayArray(x, y) { + // check dimensions + _validateMatrixDimensions(Object(utils_array["a" /* arraySize */])(x), Object(utils_array["a" /* arraySize */])(y)); // use dense matrix implementation + + + var m = multiply(matrix(x), matrix(y)); // return array or scalar + + return Object(is["v" /* isMatrix */])(m) ? m.valueOf() : m; + }, + 'Matrix, Matrix': function MatrixMatrix(x, y) { + // dimensions + var xsize = x.size(); + var ysize = y.size(); // check dimensions + + _validateMatrixDimensions(xsize, ysize); // process dimensions + + + if (xsize.length === 1) { + // process y dimensions + if (ysize.length === 1) { + // Vector * Vector + return _multiplyVectorVector(x, y, xsize[0]); + } // Vector * Matrix + + + return _multiplyVectorMatrix(x, y); + } // process y dimensions + + + if (ysize.length === 1) { + // Matrix * Vector + return _multiplyMatrixVector(x, y); + } // Matrix * Matrix + + + return _multiplyMatrixMatrix(x, y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use Matrix * Matrix implementation + return multiply(x, matrix(y)); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use Matrix * Matrix implementation + return multiply(matrix(x, y.storage()), y); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, multiplyScalar, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, multiplyScalar, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm11(y, x, multiplyScalar, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, multiplyScalar, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, multiplyScalar, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, multiplyScalar, true).valueOf(); + }, + 'any, any': multiplyScalar, + 'any, any, ...any': function anyAnyAny(x, y, rest) { + var result = multiply(x, y); + + for (var i = 0; i < rest.length; i++) { + result = multiply(result, rest[i]); + } + + return result; + } + }, multiplyScalar.signatures)); + + function _validateMatrixDimensions(size1, size2) { + // check left operand dimensions + switch (size1.length) { + case 1: + // check size2 + switch (size2.length) { + case 1: + // Vector x Vector + if (size1[0] !== size2[0]) { + // throw error + throw new RangeError('Dimension mismatch in multiplication. Vectors must have the same length'); + } + + break; + + case 2: + // Vector x Matrix + if (size1[0] !== size2[0]) { + // throw error + throw new RangeError('Dimension mismatch in multiplication. Vector length (' + size1[0] + ') must match Matrix rows (' + size2[0] + ')'); + } + + break; + + default: + throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)'); + } + + break; + + case 2: + // check size2 + switch (size2.length) { + case 1: + // Matrix x Vector + if (size1[1] !== size2[0]) { + // throw error + throw new RangeError('Dimension mismatch in multiplication. Matrix columns (' + size1[1] + ') must match Vector length (' + size2[0] + ')'); + } + + break; + + case 2: + // Matrix x Matrix + if (size1[1] !== size2[0]) { + // throw error + throw new RangeError('Dimension mismatch in multiplication. Matrix A columns (' + size1[1] + ') must match Matrix B rows (' + size2[0] + ')'); + } + + break; + + default: + throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)'); + } + + break; + + default: + throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix A has ' + size1.length + ' dimensions)'); + } + } + /** + * C = A * B + * + * @param {Matrix} a Dense Vector (N) + * @param {Matrix} b Dense Vector (N) + * + * @return {number} Scalar value + */ + + + function _multiplyVectorVector(a, b, n) { + // check empty vector + if (n === 0) { + throw new Error('Cannot multiply two empty vectors'); + } // a dense + + + var adata = a._data; + var adt = a._datatype; // b dense + + var bdata = b._data; + var bdt = b._datatype; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + } // result (do not initialize it with zero) + + + var c = mf(adata[0], bdata[0]); // loop data + + for (var i = 1; i < n; i++) { + // multiply and accumulate + c = af(c, mf(adata[i], bdata[i])); + } + + return c; + } + /** + * C = A * B + * + * @param {Matrix} a Dense Vector (M) + * @param {Matrix} b Matrix (MxN) + * + * @return {Matrix} Dense Vector (N) + */ + + + function _multiplyVectorMatrix(a, b) { + // process storage + if (b.storage() !== 'dense') { + throw new Error('Support for SparseMatrix not implemented'); + } + + return _multiplyVectorDenseMatrix(a, b); + } + /** + * C = A * B + * + * @param {Matrix} a Dense Vector (M) + * @param {Matrix} b Dense Matrix (MxN) + * + * @return {Matrix} Dense Vector (N) + */ + + + function _multiplyVectorDenseMatrix(a, b) { + // a dense + var adata = a._data; + var asize = a._size; + var adt = a._datatype; // b dense + + var bdata = b._data; + var bsize = b._size; + var bdt = b._datatype; // rows & columns + + var alength = asize[0]; + var bcolumns = bsize[1]; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + } // result + + + var c = []; // loop matrix columns + + for (var j = 0; j < bcolumns; j++) { + // sum (do not initialize it with zero) + var sum = mf(adata[0], bdata[0][j]); // loop vector + + for (var i = 1; i < alength; i++) { + // multiply & accumulate + sum = af(sum, mf(adata[i], bdata[i][j])); + } + + c[j] = sum; + } // return matrix + + + return a.createDenseMatrix({ + data: c, + size: [bcolumns], + datatype: dt + }); + } + /** + * C = A * B + * + * @param {Matrix} a Matrix (MxN) + * @param {Matrix} b Dense Vector (N) + * + * @return {Matrix} Dense Vector (M) + */ + + + var _multiplyMatrixVector = typed('_multiplyMatrixVector', { + 'DenseMatrix, any': _multiplyDenseMatrixVector, + 'SparseMatrix, any': _multiplySparseMatrixVector + }); + /** + * C = A * B + * + * @param {Matrix} a Matrix (MxN) + * @param {Matrix} b Matrix (NxC) + * + * @return {Matrix} Matrix (MxC) + */ + + + var _multiplyMatrixMatrix = typed('_multiplyMatrixMatrix', { + 'DenseMatrix, DenseMatrix': _multiplyDenseMatrixDenseMatrix, + 'DenseMatrix, SparseMatrix': _multiplyDenseMatrixSparseMatrix, + 'SparseMatrix, DenseMatrix': _multiplySparseMatrixDenseMatrix, + 'SparseMatrix, SparseMatrix': _multiplySparseMatrixSparseMatrix + }); + /** + * C = A * B + * + * @param {Matrix} a DenseMatrix (MxN) + * @param {Matrix} b Dense Vector (N) + * + * @return {Matrix} Dense Vector (M) + */ + + + function _multiplyDenseMatrixVector(a, b) { + // a dense + var adata = a._data; + var asize = a._size; + var adt = a._datatype; // b dense + + var bdata = b._data; + var bdt = b._datatype; // rows & columns + + var arows = asize[0]; + var acolumns = asize[1]; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + } // result + + + var c = []; // loop matrix a rows + + for (var i = 0; i < arows; i++) { + // current row + var row = adata[i]; // sum (do not initialize it with zero) + + var sum = mf(row[0], bdata[0]); // loop matrix a columns + + for (var j = 1; j < acolumns; j++) { + // multiply & accumulate + sum = af(sum, mf(row[j], bdata[j])); + } + + c[i] = sum; + } // return matrix + + + return a.createDenseMatrix({ + data: c, + size: [arows], + datatype: dt + }); + } + /** + * C = A * B + * + * @param {Matrix} a DenseMatrix (MxN) + * @param {Matrix} b DenseMatrix (NxC) + * + * @return {Matrix} DenseMatrix (MxC) + */ + + + function _multiplyDenseMatrixDenseMatrix(a, b) { + // a dense + var adata = a._data; + var asize = a._size; + var adt = a._datatype; // b dense + + var bdata = b._data; + var bsize = b._size; + var bdt = b._datatype; // rows & columns + + var arows = asize[0]; + var acolumns = asize[1]; + var bcolumns = bsize[1]; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + } // result + + + var c = []; // loop matrix a rows + + for (var i = 0; i < arows; i++) { + // current row + var row = adata[i]; // initialize row array + + c[i] = []; // loop matrix b columns + + for (var j = 0; j < bcolumns; j++) { + // sum (avoid initializing sum to zero) + var sum = mf(row[0], bdata[0][j]); // loop matrix a columns + + for (var x = 1; x < acolumns; x++) { + // multiply & accumulate + sum = af(sum, mf(row[x], bdata[x][j])); + } + + c[i][j] = sum; + } + } // return matrix + + + return a.createDenseMatrix({ + data: c, + size: [arows, bcolumns], + datatype: dt + }); + } + /** + * C = A * B + * + * @param {Matrix} a DenseMatrix (MxN) + * @param {Matrix} b SparseMatrix (NxC) + * + * @return {Matrix} SparseMatrix (MxC) + */ + + + function _multiplyDenseMatrixSparseMatrix(a, b) { + // a dense + var adata = a._data; + var asize = a._size; + var adt = a._datatype; // b sparse + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; + var bsize = b._size; + var bdt = b._datatype; // validate b matrix + + if (!bvalues) { + throw new Error('Cannot multiply Dense Matrix times Pattern only Matrix'); + } // rows & columns + + + var arows = asize[0]; + var bcolumns = bsize[1]; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // equalScalar signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); + } // result + + + var cvalues = []; + var cindex = []; + var cptr = []; // c matrix + + var c = b.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [arows, bcolumns], + datatype: dt + }); // loop b columns + + for (var jb = 0; jb < bcolumns; jb++) { + // update ptr + cptr[jb] = cindex.length; // indeces in column jb + + var kb0 = bptr[jb]; + var kb1 = bptr[jb + 1]; // do not process column jb if no data exists + + if (kb1 > kb0) { + // last row mark processed + var last = 0; // loop a rows + + for (var i = 0; i < arows; i++) { + // column mark + var mark = i + 1; // C[i, jb] + + var cij = void 0; // values in b column j + + for (var kb = kb0; kb < kb1; kb++) { + // row + var ib = bindex[kb]; // check value has been initialized + + if (last !== mark) { + // first value in column jb + cij = mf(adata[i][ib], bvalues[kb]); // update mark + + last = mark; + } else { + // accumulate value + cij = af(cij, mf(adata[i][ib], bvalues[kb])); + } + } // check column has been processed and value != 0 + + + if (last === mark && !eq(cij, zero)) { + // push row & value + cindex.push(i); + cvalues.push(cij); + } + } + } + } // update ptr + + + cptr[bcolumns] = cindex.length; // return sparse matrix + + return c; + } + /** + * C = A * B + * + * @param {Matrix} a SparseMatrix (MxN) + * @param {Matrix} b Dense Vector (N) + * + * @return {Matrix} SparseMatrix (M, 1) + */ + + + function _multiplySparseMatrixVector(a, b) { + // a sparse + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var adt = a._datatype; // validate a matrix + + if (!avalues) { + throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix'); + } // b dense + + + var bdata = b._data; + var bdt = b._datatype; // rows & columns + + var arows = a._size[0]; + var brows = b._size[0]; // result + + var cvalues = []; + var cindex = []; + var cptr = []; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // equalScalar signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); + } // workspace + + + var x = []; // vector with marks indicating a value x[i] exists in a given column + + var w = []; // update ptr + + cptr[0] = 0; // rows in b + + for (var ib = 0; ib < brows; ib++) { + // b[ib] + var vbi = bdata[ib]; // check b[ib] != 0, avoid loops + + if (!eq(vbi, zero)) { + // A values & index in ib column + for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) { + // a row + var ia = aindex[ka]; // check value exists in current j + + if (!w[ia]) { + // ia is new entry in j + w[ia] = true; // add i to pattern of C + + cindex.push(ia); // x(ia) = A + + x[ia] = mf(vbi, avalues[ka]); + } else { + // i exists in C already + x[ia] = af(x[ia], mf(vbi, avalues[ka])); + } + } + } + } // copy values from x to column jb of c + + + for (var p1 = cindex.length, p = 0; p < p1; p++) { + // row + var ic = cindex[p]; // copy value + + cvalues[p] = x[ic]; + } // update ptr + + + cptr[1] = cindex.length; // return sparse matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [arows, 1], + datatype: dt + }); + } + /** + * C = A * B + * + * @param {Matrix} a SparseMatrix (MxN) + * @param {Matrix} b DenseMatrix (NxC) + * + * @return {Matrix} SparseMatrix (MxC) + */ + + + function _multiplySparseMatrixDenseMatrix(a, b) { + // a sparse + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var adt = a._datatype; // validate a matrix + + if (!avalues) { + throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix'); + } // b dense + + + var bdata = b._data; + var bdt = b._datatype; // rows & columns + + var arows = a._size[0]; + var brows = b._size[0]; + var bcolumns = b._size[1]; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // equalScalar signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); + } // result + + + var cvalues = []; + var cindex = []; + var cptr = []; // c matrix + + var c = a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [arows, bcolumns], + datatype: dt + }); // workspace + + var x = []; // vector with marks indicating a value x[i] exists in a given column + + var w = []; // loop b columns + + for (var jb = 0; jb < bcolumns; jb++) { + // update ptr + cptr[jb] = cindex.length; // mark in workspace for current column + + var mark = jb + 1; // rows in jb + + for (var ib = 0; ib < brows; ib++) { + // b[ib, jb] + var vbij = bdata[ib][jb]; // check b[ib, jb] != 0, avoid loops + + if (!eq(vbij, zero)) { + // A values & index in ib column + for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) { + // a row + var ia = aindex[ka]; // check value exists in current j + + if (w[ia] !== mark) { + // ia is new entry in j + w[ia] = mark; // add i to pattern of C + + cindex.push(ia); // x(ia) = A + + x[ia] = mf(vbij, avalues[ka]); + } else { + // i exists in C already + x[ia] = af(x[ia], mf(vbij, avalues[ka])); + } + } + } + } // copy values from x to column jb of c + + + for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) { + // row + var ic = cindex[p]; // copy value + + cvalues[p] = x[ic]; + } + } // update ptr + + + cptr[bcolumns] = cindex.length; // return sparse matrix + + return c; + } + /** + * C = A * B + * + * @param {Matrix} a SparseMatrix (MxN) + * @param {Matrix} b SparseMatrix (NxC) + * + * @return {Matrix} SparseMatrix (MxC) + */ + + + function _multiplySparseMatrixSparseMatrix(a, b) { + // a sparse + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var adt = a._datatype; // b sparse + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; + var bdt = b._datatype; // rows & columns + + var arows = a._size[0]; + var bcolumns = b._size[1]; // flag indicating both matrices (a & b) contain data + + var values = avalues && bvalues; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + } // result + + + var cvalues = values ? [] : undefined; + var cindex = []; + var cptr = []; // c matrix + + var c = a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [arows, bcolumns], + datatype: dt + }); // workspace + + var x = values ? [] : undefined; // vector with marks indicating a value x[i] exists in a given column + + var w = []; // variables + + var ka, ka0, ka1, kb, kb0, kb1, ia, ib; // loop b columns + + for (var jb = 0; jb < bcolumns; jb++) { + // update ptr + cptr[jb] = cindex.length; // mark in workspace for current column + + var mark = jb + 1; // B values & index in j + + for (kb0 = bptr[jb], kb1 = bptr[jb + 1], kb = kb0; kb < kb1; kb++) { + // b row + ib = bindex[kb]; // check we need to process values + + if (values) { + // loop values in a[:,ib] + for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) { + // row + ia = aindex[ka]; // check value exists in current j + + if (w[ia] !== mark) { + // ia is new entry in j + w[ia] = mark; // add i to pattern of C + + cindex.push(ia); // x(ia) = A + + x[ia] = mf(bvalues[kb], avalues[ka]); + } else { + // i exists in C already + x[ia] = af(x[ia], mf(bvalues[kb], avalues[ka])); + } + } + } else { + // loop values in a[:,ib] + for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) { + // row + ia = aindex[ka]; // check value exists in current j + + if (w[ia] !== mark) { + // ia is new entry in j + w[ia] = mark; // add i to pattern of C + + cindex.push(ia); + } + } + } + } // check we need to process matrix values (pattern matrix) + + + if (values) { + // copy values from x to column jb of c + for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) { + // row + var ic = cindex[p]; // copy value + + cvalues[p] = x[ic]; + } + } + } // update ptr + + + cptr[bcolumns] = cindex.length; // return sparse matrix + + return c; + } + + return multiply; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/nthRoot.js + + + + + + + + +var nthRoot_name = 'nthRoot'; +var nthRoot_dependencies = ['typed', 'matrix', 'equalScalar', 'BigNumber']; +var createNthRoot = /* #__PURE__ */Object(factory["a" /* factory */])(nthRoot_name, nthRoot_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + _BigNumber = _ref.BigNumber; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm06 = createAlgorithm06({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Calculate the nth root of a value. + * The principal nth root of a positive real number A, is the positive real + * solution of the equation + * + * x^root = A + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.nthRoot(a) + * math.nthRoot(a, root) + * + * Examples: + * + * math.nthRoot(9, 2) // returns 3, as 3^2 == 9 + * math.sqrt(9) // returns 3, as 3^2 == 9 + * math.nthRoot(64, 3) // returns 4, as 4^3 == 64 + * + * See also: + * + * sqrt, pow + * + * @param {number | BigNumber | Array | Matrix | Complex} a + * Value for which to calculate the nth root + * @param {number | BigNumber} [root=2] The root. + * @return {number | Complex | Array | Matrix} Returns the nth root of `a` + */ + + var complexErr = '' + 'Complex number not supported in function nthRoot. ' + 'Use nthRoots instead.'; + var nthRoot = typed(nthRoot_name, { + number: function number(x) { + return nthRootNumber(x, 2); + }, + 'number, number': nthRootNumber, + BigNumber: function BigNumber(x) { + return _bigNthRoot(x, new _BigNumber(2)); + }, + Complex: function Complex(x) { + throw new Error(complexErr); + }, + 'Complex, number': function ComplexNumber(x, y) { + throw new Error(complexErr); + }, + 'BigNumber, BigNumber': _bigNthRoot, + 'Array | Matrix': function ArrayMatrix(x) { + return nthRoot(x, 2); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + // density must be one (no zeros in matrix) + if (y.density() === 1) { + // sparse + sparse + return algorithm06(x, y, nthRoot); + } else { + // throw exception + throw new Error('Root must be non-zero'); + } + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, nthRoot, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + // density must be one (no zeros in matrix) + if (y.density() === 1) { + // dense + sparse + return algorithm01(x, y, nthRoot, false); + } else { + // throw exception + throw new Error('Root must be non-zero'); + } + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, nthRoot); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return nthRoot(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return nthRoot(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return nthRoot(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + return algorithm11(x, y, nthRoot, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + return algorithm14(x, y, nthRoot, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + // density must be one (no zeros in matrix) + if (y.density() === 1) { + // sparse - scalar + return algorithm11(y, x, nthRoot, true); + } else { + // throw exception + throw new Error('Root must be non-zero'); + } + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + return algorithm14(y, x, nthRoot, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return nthRoot(matrix(x), y).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + // use matrix implementation + return nthRoot(x, matrix(y)).valueOf(); + } + }); + return nthRoot; + /** + * Calculate the nth root of a for BigNumbers, solve x^root == a + * https://rosettacode.org/wiki/Nth_root#JavaScript + * @param {BigNumber} a + * @param {BigNumber} root + * @private + */ + + function _bigNthRoot(a, root) { + var precision = _BigNumber.precision; + + var Big = _BigNumber.clone({ + precision: precision + 2 + }); + + var zero = new _BigNumber(0); + var one = new Big(1); + var inv = root.isNegative(); + + if (inv) { + root = root.neg(); + } + + if (root.isZero()) { + throw new Error('Root must be non-zero'); + } + + if (a.isNegative() && !root.abs().mod(2).equals(1)) { + throw new Error('Root must be odd when a is negative.'); + } // edge cases zero and infinity + + + if (a.isZero()) { + return inv ? new Big(Infinity) : 0; + } + + if (!a.isFinite()) { + return inv ? zero : a; + } + + var x = a.abs().pow(one.div(root)); // If a < 0, we require that root is an odd integer, + // so (-1) ^ (1/root) = -1 + + x = a.isNeg() ? x.neg() : x; + return new _BigNumber((inv ? one.div(x) : x).toPrecision(precision)); + } +}); +var createNthRootNumber = /* #__PURE__ */Object(factory["a" /* factory */])(nthRoot_name, ['typed'], function (_ref2) { + var typed = _ref2.typed; + return typed(nthRoot_name, { + number: nthRootNumber, + 'number, number': nthRootNumber + }); +}); +// CONCATENATED MODULE: ./src/function/arithmetic/sign.js + + + +var sign_name = 'sign'; +var sign_dependencies = ['typed', 'BigNumber', 'Fraction', 'complex']; +var createSign = /* #__PURE__ */Object(factory["a" /* factory */])(sign_name, sign_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber, + complex = _ref.complex, + _Fraction = _ref.Fraction; + + /** + * Compute the sign of a value. The sign of a value x is: + * + * - 1 when x > 0 + * - -1 when x < 0 + * - 0 when x == 0 + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.sign(x) + * + * Examples: + * + * math.sign(3.5) // returns 1 + * math.sign(-4.2) // returns -1 + * math.sign(0) // returns 0 + * + * math.sign([3, 5, -2, 0, 2]) // returns [1, 1, -1, 0, 1] + * + * See also: + * + * abs + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x + * The number for which to determine the sign + * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit}e + * The sign of `x` + */ + var sign = typed(sign_name, { + number: signNumber, + Complex: function Complex(x) { + return x.im === 0 ? complex(signNumber(x.re)) : x.sign(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(x.cmp(0)); + }, + Fraction: function Fraction(x) { + return new _Fraction(x.s, 1); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since sign(0) = 0 + return deepMap(x, sign, true); + }, + Unit: function Unit(x) { + return sign(x.value); + } + }); + return sign; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/sqrt.js + + +var sqrt_name = 'sqrt'; +var sqrt_dependencies = ['config', 'typed', 'Complex']; +var createSqrt = /* #__PURE__ */Object(factory["a" /* factory */])(sqrt_name, sqrt_dependencies, function (_ref) { + var config = _ref.config, + typed = _ref.typed, + Complex = _ref.Complex; + + /** + * Calculate the square root of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.sqrt(x) + * + * Examples: + * + * math.sqrt(25) // returns 5 + * math.square(5) // returns 25 + * math.sqrt(-4) // returns Complex 2i + * + * See also: + * + * square, multiply, cube, cbrt, sqrtm + * + * @param {number | BigNumber | Complex | Array | Matrix | Unit} x + * Value for which to calculate the square root. + * @return {number | BigNumber | Complex | Array | Matrix | Unit} + * Returns the square root of `x` + */ + var sqrt = typed('sqrt', { + number: _sqrtNumber, + Complex: function Complex(x) { + return x.sqrt(); + }, + BigNumber: function BigNumber(x) { + if (!x.isNegative() || config.predictable) { + return x.sqrt(); + } else { + // negative value -> downgrade to number to do complex value computation + return _sqrtNumber(x.toNumber()); + } + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since sqrt(0) = 0 + return deepMap(x, sqrt, true); + }, + Unit: function Unit(x) { + // Someday will work for complex units when they are implemented + return x.pow(0.5); + } + }); + /** + * Calculate sqrt for a number + * @param {number} x + * @returns {number | Complex} Returns the square root of x + * @private + */ + + function _sqrtNumber(x) { + if (isNaN(x)) { + return NaN; + } else if (x >= 0 || config.predictable) { + return Math.sqrt(x); + } else { + return new Complex(x, 0).sqrt(); + } + } + + return sqrt; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/square.js + + + +var square_name = 'square'; +var square_dependencies = ['typed']; +var createSquare = /* #__PURE__ */Object(factory["a" /* factory */])(square_name, square_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the square of a value, `x * x`. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.square(x) + * + * Examples: + * + * math.square(2) // returns number 4 + * math.square(3) // returns number 9 + * math.pow(3, 2) // returns number 9 + * math.multiply(3, 3) // returns number 9 + * + * math.square([1, 2, 3, 4]) // returns Array [1, 4, 9, 16] + * + * See also: + * + * multiply, cube, sqrt, pow + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x + * Number for which to calculate the square + * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} + * Squared value + */ + var square = typed(square_name, { + number: squareNumber, + Complex: function Complex(x) { + return x.mul(x); + }, + BigNumber: function BigNumber(x) { + return x.times(x); + }, + Fraction: function Fraction(x) { + return x.mul(x); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since square(0) = 0 + return deepMap(x, square, true); + }, + Unit: function Unit(x) { + return x.pow(2); + } + }); + return square; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/subtract.js + + + + + + + + +var subtract_name = 'subtract'; +var subtract_dependencies = ['typed', 'matrix', 'equalScalar', 'addScalar', 'unaryMinus', 'DenseMatrix']; +var createSubtract = /* #__PURE__ */Object(factory["a" /* factory */])(subtract_name, subtract_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + addScalar = _ref.addScalar, + unaryMinus = _ref.unaryMinus, + DenseMatrix = _ref.DenseMatrix; + // TODO: split function subtract in two: subtract and subtractScalar + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm05 = createAlgorithm05({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Subtract two values, `x - y`. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.subtract(x, y) + * + * Examples: + * + * math.subtract(5.3, 2) // returns number 3.3 + * + * const a = math.complex(2, 3) + * const b = math.complex(4, 1) + * math.subtract(a, b) // returns Complex -2 + 2i + * + * math.subtract([5, 7, 4], 4) // returns Array [1, 3, 0] + * + * const c = math.unit('2.1 km') + * const d = math.unit('500m') + * math.subtract(c, d) // returns Unit 1.6 km + * + * See also: + * + * add + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x + * Initial value + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y + * Value to subtract from `x` + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} + * Subtraction of `x` and `y` + */ + + var subtract = typed(subtract_name, { + 'number, number': function numberNumber(x, y) { + return x - y; + }, + 'Complex, Complex': function ComplexComplex(x, y) { + return x.sub(y); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.minus(y); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.sub(y); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (x.value === null) { + throw new Error('Parameter x contains a unit with undefined value'); + } + + if (y.value === null) { + throw new Error('Parameter y contains a unit with undefined value'); + } + + if (!x.equalBase(y)) { + throw new Error('Units do not match'); + } + + var res = x.clone(); + res.value = subtract(res.value, y.value); + res.fixPrefix = false; + return res; + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + checkEqualDimensions(x, y); + return algorithm05(x, y, subtract); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + checkEqualDimensions(x, y); + return algorithm03(y, x, subtract, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + checkEqualDimensions(x, y); + return algorithm01(x, y, subtract, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + checkEqualDimensions(x, y); + return algorithm13(x, y, subtract); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return subtract(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return subtract(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return subtract(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm10(x, unaryMinus(y), addScalar); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, subtract); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm10(y, x, subtract, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, subtract, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, subtract, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, subtract, true).valueOf(); + } + }); + return subtract; +}); +/** + * Check whether matrix x and y have the same number of dimensions. + * Throws a DimensionError when dimensions are not equal + * @param {Matrix} x + * @param {Matrix} y + */ + +function checkEqualDimensions(x, y) { + var xsize = x.size(); + var ysize = y.size(); + + if (xsize.length !== ysize.length) { + throw new DimensionError["a" /* DimensionError */](xsize.length, ysize.length); + } +} +// CONCATENATED MODULE: ./src/function/arithmetic/xgcd.js + + +var xgcd_name = 'xgcd'; +var xgcd_dependencies = ['typed', 'config', 'matrix', 'BigNumber']; +var createXgcd = /* #__PURE__ */Object(factory["a" /* factory */])(xgcd_name, xgcd_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + BigNumber = _ref.BigNumber; + + /** + * Calculate the extended greatest common divisor for two values. + * See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm. + * + * Syntax: + * + * math.xgcd(a, b) + * + * Examples: + * + * math.xgcd(8, 12) // returns [4, -1, 1] + * math.gcd(8, 12) // returns 4 + * math.xgcd(36163, 21199) // returns [1247, -7, 12] + * + * See also: + * + * gcd, lcm + * + * @param {number | BigNumber} a An integer number + * @param {number | BigNumber} b An integer number + * @return {Array} Returns an array containing 3 integers `[div, m, n]` + * where `div = gcd(a, b)` and `a*m + b*n = div` + */ + return typed(xgcd_name, { + 'number, number': function numberNumber(a, b) { + var res = xgcdNumber(a, b); + return config.matrix === 'Array' ? res : matrix(res); + }, + 'BigNumber, BigNumber': _xgcdBigNumber // TODO: implement support for Fraction + + }); + /** + * Calculate xgcd for two BigNumbers + * @param {BigNumber} a + * @param {BigNumber} b + * @return {BigNumber[]} result + * @private + */ + + function _xgcdBigNumber(a, b) { + // source: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm + var // used to swap two variables + t; + var // quotient + q; + var // remainder + r; + var zero = new BigNumber(0); + var one = new BigNumber(1); + var x = zero; + var lastx = one; + var y = one; + var lasty = zero; + + if (!a.isInt() || !b.isInt()) { + throw new Error('Parameters in function xgcd must be integer numbers'); + } + + while (!b.isZero()) { + q = a.div(b).floor(); + r = a.mod(b); + t = x; + x = lastx.minus(q.times(x)); + lastx = t; + t = y; + y = lasty.minus(q.times(y)); + lasty = t; + a = b; + b = r; + } + + var res; + + if (a.lt(zero)) { + res = [a.neg(), lastx.neg(), lasty.neg()]; + } else { + res = [a, !a.isZero() ? lastx : 0, lasty]; + } + + return config.matrix === 'Array' ? res : matrix(res); + } +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm09.js + + +var algorithm09_name = 'algorithm09'; +var algorithm09_dependencies = ['typed', 'equalScalar']; +var createAlgorithm09 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm09_name, algorithm09_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix A and invokes the callback function f(Aij, Bij). + * Callback function invoked NZA times, number of nonzero elements in A. + * + * + * ┌ f(Aij, Bij) ; A(i,j) !== 0 + * C(i,j) = ┤ + * └ 0 ; otherwise + * + * + * @param {Matrix} a The SparseMatrix instance (A) + * @param {Matrix} b The SparseMatrix instance (B) + * @param {Function} callback The f(Aij,Bij) operation to invoke + * + * @return {Matrix} SparseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294 + */ + return function algorithm09(a, b, callback) { + // sparse matrix arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; + var adt = a._datatype; // sparse matrix arrays + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; + var bsize = b._size; + var bdt = b._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cvalues = avalues && bvalues ? [] : undefined; + var cindex = []; + var cptr = []; // workspaces + + var x = cvalues ? [] : undefined; // marks indicating we have a value in x for a given column + + var w = []; // vars + + var i, j, k, k0, k1; // loop columns + + for (j = 0; j < columns; j++) { + // update cptr + cptr[j] = cindex.length; // column mark + + var mark = j + 1; // check we need to process values + + if (x) { + // loop B(:,j) + for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) { + // row + i = bindex[k]; // update workspace + + w[i] = mark; + x[i] = bvalues[k]; + } + } // loop A(:,j) + + + for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + i = aindex[k]; // check we need to process values + + if (x) { + // b value @ i,j + var vb = w[i] === mark ? x[i] : zero; // invoke f + + var vc = cf(avalues[k], vb); // check zero value + + if (!eq(vc, zero)) { + // push index + cindex.push(i); // push value + + cvalues.push(vc); + } + } else { + // push index + cindex.push(i); + } + } + } // update cptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/dotMultiply.js + + + + + + +var dotMultiply_name = 'dotMultiply'; +var dotMultiply_dependencies = ['typed', 'matrix', 'equalScalar', 'multiplyScalar']; +var createDotMultiply = /* #__PURE__ */Object(factory["a" /* factory */])(dotMultiply_name, dotMultiply_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + multiplyScalar = _ref.multiplyScalar; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm09 = createAlgorithm09({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Multiply two matrices element wise. The function accepts both matrices and + * scalar values. + * + * Syntax: + * + * math.dotMultiply(x, y) + * + * Examples: + * + * math.dotMultiply(2, 4) // returns 8 + * + * a = [[9, 5], [6, 1]] + * b = [[3, 2], [5, 2]] + * + * math.dotMultiply(a, b) // returns [[27, 10], [30, 2]] + * math.multiply(a, b) // returns [[52, 28], [23, 14]] + * + * See also: + * + * multiply, divide, dotDivide + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Left hand value + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Right hand value + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y` + */ + + var dotMultiply = typed(dotMultiply_name, { + 'any, any': multiplyScalar, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm09(x, y, multiplyScalar, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, multiplyScalar, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm02(x, y, multiplyScalar, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, multiplyScalar); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return dotMultiply(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return dotMultiply(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return dotMultiply(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, multiplyScalar, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, multiplyScalar, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm11(y, x, multiplyScalar, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, multiplyScalar, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, multiplyScalar, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, multiplyScalar, true).valueOf(); + } + }); + return dotMultiply; +}); +// CONCATENATED MODULE: ./src/utils/bignumber/bitwise.js +/** + * Bitwise and for Bignumbers + * + * Special Cases: + * N & n = N + * n & 0 = 0 + * n & -1 = n + * n & n = n + * I & I = I + * -I & -I = -I + * I & -I = 0 + * I & n = n + * I & -n = I + * -I & n = 0 + * -I & -n = -I + * + * @param {BigNumber} x + * @param {BigNumber} y + * @return {BigNumber} Result of `x` & `y`, is fully precise + * @private + */ +function bitAndBigNumber(x, y) { + if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) { + throw new Error('Integers expected in function bitAnd'); + } + + var BigNumber = x.constructor; + + if (x.isNaN() || y.isNaN()) { + return new BigNumber(NaN); + } + + if (x.isZero() || y.eq(-1) || x.eq(y)) { + return x; + } + + if (y.isZero() || x.eq(-1)) { + return y; + } + + if (!x.isFinite() || !y.isFinite()) { + if (!x.isFinite() && !y.isFinite()) { + if (x.isNegative() === y.isNegative()) { + return x; + } + + return new BigNumber(0); + } + + if (!x.isFinite()) { + if (y.isNegative()) { + return x; + } + + if (x.isNegative()) { + return new BigNumber(0); + } + + return y; + } + + if (!y.isFinite()) { + if (x.isNegative()) { + return y; + } + + if (y.isNegative()) { + return new BigNumber(0); + } + + return x; + } + } + + return bitwise(x, y, function (a, b) { + return a & b; + }); +} +/** + * Bitwise not + * @param {BigNumber} x + * @return {BigNumber} Result of ~`x`, fully precise + * + */ + +function bitNotBigNumber(x) { + if (x.isFinite() && !x.isInteger()) { + throw new Error('Integer expected in function bitNot'); + } + + var BigNumber = x.constructor; + var prevPrec = BigNumber.precision; + BigNumber.config({ + precision: 1E9 + }); + var result = x.plus(new BigNumber(1)); + result.s = -result.s || null; + BigNumber.config({ + precision: prevPrec + }); + return result; +} +/** + * Bitwise OR for BigNumbers + * + * Special Cases: + * N | n = N + * n | 0 = n + * n | -1 = -1 + * n | n = n + * I | I = I + * -I | -I = -I + * I | -n = -1 + * I | -I = -1 + * I | n = I + * -I | n = -I + * -I | -n = -n + * + * @param {BigNumber} x + * @param {BigNumber} y + * @return {BigNumber} Result of `x` | `y`, fully precise + */ + +function bitOrBigNumber(x, y) { + if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) { + throw new Error('Integers expected in function bitOr'); + } + + var BigNumber = x.constructor; + + if (x.isNaN() || y.isNaN()) { + return new BigNumber(NaN); + } + + var negOne = new BigNumber(-1); + + if (x.isZero() || y.eq(negOne) || x.eq(y)) { + return y; + } + + if (y.isZero() || x.eq(negOne)) { + return x; + } + + if (!x.isFinite() || !y.isFinite()) { + if (!x.isFinite() && !x.isNegative() && y.isNegative() || x.isNegative() && !y.isNegative() && !y.isFinite()) { + return negOne; + } + + if (x.isNegative() && y.isNegative()) { + return x.isFinite() ? x : y; + } + + return x.isFinite() ? y : x; + } + + return bitwise(x, y, function (a, b) { + return a | b; + }); +} +/** + * Applies bitwise function to numbers + * @param {BigNumber} x + * @param {BigNumber} y + * @param {function (a, b)} func + * @return {BigNumber} + */ + +function bitwise(x, y, func) { + var BigNumber = x.constructor; + var xBits, yBits; + var xSign = +(x.s < 0); + var ySign = +(y.s < 0); + + if (xSign) { + xBits = decCoefficientToBinaryString(bitNotBigNumber(x)); + + for (var i = 0; i < xBits.length; ++i) { + xBits[i] ^= 1; + } + } else { + xBits = decCoefficientToBinaryString(x); + } + + if (ySign) { + yBits = decCoefficientToBinaryString(bitNotBigNumber(y)); + + for (var _i = 0; _i < yBits.length; ++_i) { + yBits[_i] ^= 1; + } + } else { + yBits = decCoefficientToBinaryString(y); + } + + var minBits, maxBits, minSign; + + if (xBits.length <= yBits.length) { + minBits = xBits; + maxBits = yBits; + minSign = xSign; + } else { + minBits = yBits; + maxBits = xBits; + minSign = ySign; + } + + var shortLen = minBits.length; + var longLen = maxBits.length; + var expFuncVal = func(xSign, ySign) ^ 1; + var outVal = new BigNumber(expFuncVal ^ 1); + var twoPower = new BigNumber(1); + var two = new BigNumber(2); + var prevPrec = BigNumber.precision; + BigNumber.config({ + precision: 1E9 + }); + + while (shortLen > 0) { + if (func(minBits[--shortLen], maxBits[--longLen]) === expFuncVal) { + outVal = outVal.plus(twoPower); + } + + twoPower = twoPower.times(two); + } + + while (longLen > 0) { + if (func(minSign, maxBits[--longLen]) === expFuncVal) { + outVal = outVal.plus(twoPower); + } + + twoPower = twoPower.times(two); + } + + BigNumber.config({ + precision: prevPrec + }); + + if (expFuncVal === 0) { + outVal.s = -outVal.s; + } + + return outVal; +} +/* Extracted from decimal.js, and edited to specialize. */ + +function decCoefficientToBinaryString(x) { + // Convert to string + var a = x.d; // array with digits + + var r = a[0] + ''; + + for (var i = 1; i < a.length; ++i) { + var s = a[i] + ''; + + for (var z = 7 - s.length; z--;) { + s = '0' + s; + } + + r += s; + } + + var j = r.length; + + while (r.charAt(j) === '0') { + j--; + } + + var xe = x.e; + var str = r.slice(0, j + 1 || 1); + var strL = str.length; + + if (xe > 0) { + if (++xe > strL) { + // Append zeros. + xe -= strL; + + while (xe--) { + str += '0'; + } + } else if (xe < strL) { + str = str.slice(0, xe) + '.' + str.slice(xe); + } + } // Convert from base 10 (decimal) to base 2 + + + var arr = [0]; + + for (var _i2 = 0; _i2 < str.length;) { + var arrL = arr.length; + + while (arrL--) { + arr[arrL] *= 10; + } + + arr[0] += parseInt(str.charAt(_i2++)); // convert to int + + for (var _j = 0; _j < arr.length; ++_j) { + if (arr[_j] > 1) { + if (arr[_j + 1] === null || arr[_j + 1] === undefined) { + arr[_j + 1] = 0; + } + + arr[_j + 1] += arr[_j] >> 1; + arr[_j] &= 1; + } + } + } + + return arr.reverse(); +} +/** + * Bitwise XOR for BigNumbers + * + * Special Cases: + * N ^ n = N + * n ^ 0 = n + * n ^ n = 0 + * n ^ -1 = ~n + * I ^ n = I + * I ^ -n = -I + * I ^ -I = -1 + * -I ^ n = -I + * -I ^ -n = I + * + * @param {BigNumber} x + * @param {BigNumber} y + * @return {BigNumber} Result of `x` ^ `y`, fully precise + * + */ + + +function bitwise_bitXor(x, y) { + if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) { + throw new Error('Integers expected in function bitXor'); + } + + var BigNumber = x.constructor; + + if (x.isNaN() || y.isNaN()) { + return new BigNumber(NaN); + } + + if (x.isZero()) { + return y; + } + + if (y.isZero()) { + return x; + } + + if (x.eq(y)) { + return new BigNumber(0); + } + + var negOne = new BigNumber(-1); + + if (x.eq(negOne)) { + return bitNotBigNumber(y); + } + + if (y.eq(negOne)) { + return bitNotBigNumber(x); + } + + if (!x.isFinite() || !y.isFinite()) { + if (!x.isFinite() && !y.isFinite()) { + return negOne; + } + + return new BigNumber(x.isNegative() === y.isNegative() ? Infinity : -Infinity); + } + + return bitwise(x, y, function (a, b) { + return a ^ b; + }); +} +/** + * Bitwise left shift + * + * Special Cases: + * n << -n = N + * n << N = N + * N << n = N + * n << 0 = n + * 0 << n = 0 + * I << I = N + * I << n = I + * n << I = I + * + * @param {BigNumber} x + * @param {BigNumber} y + * @return {BigNumber} Result of `x` << `y` + * + */ + +function leftShiftBigNumber(x, y) { + if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) { + throw new Error('Integers expected in function leftShift'); + } + + var BigNumber = x.constructor; + + if (x.isNaN() || y.isNaN() || y.isNegative() && !y.isZero()) { + return new BigNumber(NaN); + } + + if (x.isZero() || y.isZero()) { + return x; + } + + if (!x.isFinite() && !y.isFinite()) { + return new BigNumber(NaN); + } // Math.pow(2, y) is fully precise for y < 55, and fast + + + if (y.lt(55)) { + return x.times(Math.pow(2, y.toNumber()) + ''); + } + + return x.times(new BigNumber(2).pow(y)); +} +/* + * Special Cases: + * n >> -n = N + * n >> N = N + * N >> n = N + * I >> I = N + * n >> 0 = n + * I >> n = I + * -I >> n = -I + * -I >> I = -I + * n >> I = I + * -n >> I = -1 + * 0 >> n = 0 + * + * @param {BigNumber} value + * @param {BigNumber} value + * @return {BigNumber} Result of `x` >> `y` + * + */ + +function rightArithShiftBigNumber(x, y) { + if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) { + throw new Error('Integers expected in function rightArithShift'); + } + + var BigNumber = x.constructor; + + if (x.isNaN() || y.isNaN() || y.isNegative() && !y.isZero()) { + return new BigNumber(NaN); + } + + if (x.isZero() || y.isZero()) { + return x; + } + + if (!y.isFinite()) { + if (x.isNegative()) { + return new BigNumber(-1); + } + + if (!x.isFinite()) { + return new BigNumber(NaN); + } + + return new BigNumber(0); + } // Math.pow(2, y) is fully precise for y < 55, and fast + + + if (y.lt(55)) { + return x.div(Math.pow(2, y.toNumber()) + '').floor(); + } + + return x.div(new BigNumber(2).pow(y)).floor(); +} +// CONCATENATED MODULE: ./src/plain/number/bitwise.js + +var bitwise_n1 = 'number'; +var bitwise_n2 = 'number, number'; +function bitAndNumber(x, y) { + if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) { + throw new Error('Integers expected in function bitAnd'); + } + + return x & y; +} +bitAndNumber.signature = bitwise_n2; +function bitNotNumber(x) { + if (!Object(utils_number["i" /* isInteger */])(x)) { + throw new Error('Integer expected in function bitNot'); + } + + return ~x; +} +bitNotNumber.signature = bitwise_n1; +function bitOrNumber(x, y) { + if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) { + throw new Error('Integers expected in function bitOr'); + } + + return x | y; +} +bitOrNumber.signature = bitwise_n2; +function bitXorNumber(x, y) { + if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) { + throw new Error('Integers expected in function bitXor'); + } + + return x ^ y; +} +bitXorNumber.signature = bitwise_n2; +function leftShiftNumber(x, y) { + if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) { + throw new Error('Integers expected in function leftShift'); + } + + return x << y; +} +leftShiftNumber.signature = bitwise_n2; +function rightArithShiftNumber(x, y) { + if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) { + throw new Error('Integers expected in function rightArithShift'); + } + + return x >> y; +} +rightArithShiftNumber.signature = bitwise_n2; +function rightLogShiftNumber(x, y) { + if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) { + throw new Error('Integers expected in function rightLogShift'); + } + + return x >>> y; +} +rightLogShiftNumber.signature = bitwise_n2; +// CONCATENATED MODULE: ./src/function/bitwise/bitAnd.js + + + + + + + + +var bitAnd_name = 'bitAnd'; +var bitAnd_dependencies = ['typed', 'matrix', 'equalScalar']; +var createBitAnd = /* #__PURE__ */Object(factory["a" /* factory */])(bitAnd_name, bitAnd_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm06 = createAlgorithm06({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Bitwise AND two values, `x & y`. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.bitAnd(x, y) + * + * Examples: + * + * math.bitAnd(53, 131) // returns number 1 + * + * math.bitAnd([1, 12, 31], 42) // returns Array [0, 8, 10] + * + * See also: + * + * bitNot, bitOr, bitXor, leftShift, rightArithShift, rightLogShift + * + * @param {number | BigNumber | Array | Matrix} x First value to and + * @param {number | BigNumber | Array | Matrix} y Second value to and + * @return {number | BigNumber | Array | Matrix} AND of `x` and `y` + */ + + var bitAnd = typed(bitAnd_name, { + 'number, number': bitAndNumber, + 'BigNumber, BigNumber': bitAndBigNumber, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm06(x, y, bitAnd, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, bitAnd, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm02(x, y, bitAnd, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, bitAnd); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return bitAnd(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return bitAnd(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return bitAnd(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, bitAnd, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, bitAnd, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm11(y, x, bitAnd, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, bitAnd, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, bitAnd, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, bitAnd, true).valueOf(); + } + }); + return bitAnd; +}); +// CONCATENATED MODULE: ./src/function/bitwise/bitNot.js + + + + +var bitNot_name = 'bitNot'; +var bitNot_dependencies = ['typed']; +var createBitNot = /* #__PURE__ */Object(factory["a" /* factory */])(bitNot_name, bitNot_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Bitwise NOT value, `~x`. + * For matrices, the function is evaluated element wise. + * For units, the function is evaluated on the best prefix base. + * + * Syntax: + * + * math.bitNot(x) + * + * Examples: + * + * math.bitNot(1) // returns number -2 + * + * math.bitNot([2, -3, 4]) // returns Array [-3, 2, 5] + * + * See also: + * + * bitAnd, bitOr, bitXor, leftShift, rightArithShift, rightLogShift + * + * @param {number | BigNumber | Array | Matrix} x Value to not + * @return {number | BigNumber | Array | Matrix} NOT of `x` + */ + var bitNot = typed(bitNot_name, { + number: bitNotNumber, + BigNumber: bitNotBigNumber, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, bitNot); + } + }); + return bitNot; +}); +// CONCATENATED MODULE: ./src/function/bitwise/bitOr.js + + + + + + + + +var bitOr_name = 'bitOr'; +var bitOr_dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix']; +var createBitOr = /* #__PURE__ */Object(factory["a" /* factory */])(bitOr_name, bitOr_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm04 = createAlgorithm04({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Bitwise OR two values, `x | y`. + * For matrices, the function is evaluated element wise. + * For units, the function is evaluated on the lowest print base. + * + * Syntax: + * + * math.bitOr(x, y) + * + * Examples: + * + * math.bitOr(1, 2) // returns number 3 + * + * math.bitOr([1, 2, 3], 4) // returns Array [5, 6, 7] + * + * See also: + * + * bitAnd, bitNot, bitXor, leftShift, rightArithShift, rightLogShift + * + * @param {number | BigNumber | Array | Matrix} x First value to or + * @param {number | BigNumber | Array | Matrix} y Second value to or + * @return {number | BigNumber | Array | Matrix} OR of `x` and `y` + */ + + var bitOr = typed(bitOr_name, { + 'number, number': bitOrNumber, + 'BigNumber, BigNumber': bitOrBigNumber, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm04(x, y, bitOr); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm01(y, x, bitOr, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm01(x, y, bitOr, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, bitOr); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return bitOr(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return bitOr(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return bitOr(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm10(x, y, bitOr, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, bitOr, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm10(y, x, bitOr, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, bitOr, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, bitOr, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, bitOr, true).valueOf(); + } + }); + return bitOr; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm07.js + + +var algorithm07_name = 'algorithm07'; +var algorithm07_dependencies = ['typed', 'DenseMatrix']; +var createAlgorithm07 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm07_name, algorithm07_dependencies, function (_ref) { + var typed = _ref.typed, + DenseMatrix = _ref.DenseMatrix; + + /** + * Iterates over SparseMatrix A and SparseMatrix B items (zero and nonzero) and invokes the callback function f(Aij, Bij). + * Callback function invoked MxN times. + * + * C(i,j) = f(Aij, Bij) + * + * @param {Matrix} a The SparseMatrix instance (A) + * @param {Matrix} b The SparseMatrix instance (B) + * @param {Function} callback The f(Aij,Bij) operation to invoke + * + * @return {Matrix} DenseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294 + */ + return function algorithm07(a, b, callback) { + // sparse matrix arrays + var asize = a._size; + var adt = a._datatype; // sparse matrix arrays + + var bsize = b._size; + var bdt = b._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // vars + + + var i, j; // result arrays + + var cdata = []; // initialize c + + for (i = 0; i < rows; i++) { + cdata[i] = []; + } // workspaces + + + var xa = []; + var xb = []; // marks indicating we have a value in x for a given column + + var wa = []; + var wb = []; // loop columns + + for (j = 0; j < columns; j++) { + // columns mark + var mark = j + 1; // scatter the values of A(:,j) into workspace + + _scatter(a, j, wa, xa, mark); // scatter the values of B(:,j) into workspace + + + _scatter(b, j, wb, xb, mark); // loop rows + + + for (i = 0; i < rows; i++) { + // matrix values @ i,j + var va = wa[i] === mark ? xa[i] : zero; + var vb = wb[i] === mark ? xb[i] : zero; // invoke callback + + cdata[i][j] = cf(va, vb); + } + } // return dense matrix + + + return new DenseMatrix({ + data: cdata, + size: [rows, columns], + datatype: dt + }); + }; + + function _scatter(m, j, w, x, mark) { + // a arrays + var values = m._values; + var index = m._index; + var ptr = m._ptr; // loop values in column j + + for (var k = ptr[j], k1 = ptr[j + 1]; k < k1; k++) { + // row + var i = index[k]; // update workspace + + w[i] = mark; + x[i] = values[k]; + } + } +}); +// CONCATENATED MODULE: ./src/function/bitwise/bitXor.js + + + + + + + + +var bitXor_name = 'bitXor'; +var bitXor_dependencies = ['typed', 'matrix', 'DenseMatrix']; +var createBitXor = /* #__PURE__ */Object(factory["a" /* factory */])(bitXor_name, bitXor_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Bitwise XOR two values, `x ^ y`. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.bitXor(x, y) + * + * Examples: + * + * math.bitXor(1, 2) // returns number 3 + * + * math.bitXor([2, 3, 4], 4) // returns Array [6, 7, 0] + * + * See also: + * + * bitAnd, bitNot, bitOr, leftShift, rightArithShift, rightLogShift + * + * @param {number | BigNumber | Array | Matrix} x First value to xor + * @param {number | BigNumber | Array | Matrix} y Second value to xor + * @return {number | BigNumber | Array | Matrix} XOR of `x` and `y` + */ + + var bitXor = typed(bitXor_name, { + 'number, number': bitXorNumber, + 'BigNumber, BigNumber': bitwise_bitXor, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, bitXor); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, bitXor, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, bitXor, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, bitXor); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return bitXor(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return bitXor(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return bitXor(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, bitXor, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, bitXor, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, bitXor, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, bitXor, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, bitXor, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, bitXor, true).valueOf(); + } + }); + return bitXor; +}); +// CONCATENATED MODULE: ./src/function/complex/arg.js + + +var arg_name = 'arg'; +var arg_dependencies = ['typed']; +var createArg = /* #__PURE__ */Object(factory["a" /* factory */])(arg_name, arg_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the argument of a complex value. + * For a complex number `a + bi`, the argument is computed as `atan2(b, a)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.arg(x) + * + * Examples: + * + * const a = math.complex(2, 2) + * math.arg(a) / math.pi // returns number 0.25 + * + * const b = math.complex('2 + 3i') + * math.arg(b) // returns number 0.982793723247329 + * math.atan2(3, 2) // returns number 0.982793723247329 + * + * See also: + * + * re, im, conj, abs + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * A complex number or array with complex numbers + * @return {number | BigNumber | Array | Matrix} The argument of x + */ + var arg = typed(arg_name, { + number: function number(x) { + return Math.atan2(0, x); + }, + BigNumber: function BigNumber(x) { + return x.constructor.atan2(0, x); + }, + Complex: function Complex(x) { + return x.arg(); + }, + // TODO: implement BigNumber support for function arg + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, arg); + } + }); + return arg; +}); +// CONCATENATED MODULE: ./src/function/complex/conj.js + + +var conj_name = 'conj'; +var conj_dependencies = ['typed']; +var createConj = /* #__PURE__ */Object(factory["a" /* factory */])(conj_name, conj_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the complex conjugate of a complex value. + * If `x = a+bi`, the complex conjugate of `x` is `a - bi`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.conj(x) + * + * Examples: + * + * math.conj(math.complex('2 + 3i')) // returns Complex 2 - 3i + * math.conj(math.complex('2 - 3i')) // returns Complex 2 + 3i + * math.conj(math.complex('-5.2i')) // returns Complex 5.2i + * + * See also: + * + * re, im, arg, abs + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * A complex number or array with complex numbers + * @return {number | BigNumber | Complex | Array | Matrix} + * The complex conjugate of x + */ + var conj = typed(conj_name, { + number: function number(x) { + return x; + }, + BigNumber: function BigNumber(x) { + return x; + }, + Complex: function Complex(x) { + return x.conjugate(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, conj); + } + }); + return conj; +}); +// CONCATENATED MODULE: ./src/function/complex/im.js + + +var im_name = 'im'; +var im_dependencies = ['typed']; +var createIm = /* #__PURE__ */Object(factory["a" /* factory */])(im_name, im_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Get the imaginary part of a complex number. + * For a complex number `a + bi`, the function returns `b`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.im(x) + * + * Examples: + * + * const a = math.complex(2, 3) + * math.re(a) // returns number 2 + * math.im(a) // returns number 3 + * + * math.re(math.complex('-5.2i')) // returns number -5.2 + * math.re(math.complex(2.4)) // returns number 0 + * + * See also: + * + * re, conj, abs, arg + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * A complex number or array with complex numbers + * @return {number | BigNumber | Array | Matrix} The imaginary part of x + */ + var im = typed(im_name, { + number: function number(x) { + return 0; + }, + BigNumber: function BigNumber(x) { + return x.mul(0); + }, + Complex: function Complex(x) { + return x.im; + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, im); + } + }); + return im; +}); +// CONCATENATED MODULE: ./src/function/complex/re.js + + +var re_name = 're'; +var re_dependencies = ['typed']; +var createRe = /* #__PURE__ */Object(factory["a" /* factory */])(re_name, re_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Get the real part of a complex number. + * For a complex number `a + bi`, the function returns `a`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.re(x) + * + * Examples: + * + * const a = math.complex(2, 3) + * math.re(a) // returns number 2 + * math.im(a) // returns number 3 + * + * math.re(math.complex('-5.2i')) // returns number 0 + * math.re(math.complex(2.4)) // returns number 2.4 + * + * See also: + * + * im, conj, abs, arg + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * A complex number or array with complex numbers + * @return {number | BigNumber | Array | Matrix} The real part of x + */ + var re = typed(re_name, { + number: function number(x) { + return x; + }, + BigNumber: function BigNumber(x) { + return x; + }, + Complex: function Complex(x) { + return x.re; + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, re); + } + }); + return re; +}); +// CONCATENATED MODULE: ./src/plain/number/logical.js +var logical_n1 = 'number'; +var logical_n2 = 'number, number'; +function notNumber(x) { + return !x; +} +notNumber.signature = logical_n1; +function orNumber(x, y) { + return !!(x || y); +} +orNumber.signature = logical_n2; +function xorNumber(x, y) { + return !!x !== !!y; +} +xorNumber.signature = logical_n2; +function andNumber(x, y) { + return !!(x && y); +} +andNumber.signature = logical_n2; +// CONCATENATED MODULE: ./src/function/logical/not.js + + + +var not_name = 'not'; +var not_dependencies = ['typed']; +var createNot = /* #__PURE__ */Object(factory["a" /* factory */])(not_name, not_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Logical `not`. Flips boolean value of a given parameter. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.not(x) + * + * Examples: + * + * math.not(2) // returns false + * math.not(0) // returns true + * math.not(true) // returns false + * + * a = [2, -7, 0] + * math.not(a) // returns [false, false, true] + * + * See also: + * + * and, or, xor + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check + * @return {boolean | Array | Matrix} + * Returns true when input is a zero or empty value. + */ + var not = typed(not_name, { + number: notNumber, + Complex: function Complex(x) { + return x.re === 0 && x.im === 0; + }, + BigNumber: function BigNumber(x) { + return x.isZero() || x.isNaN(); + }, + Unit: function Unit(x) { + return x.value !== null ? not(x.value) : true; + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, not); + } + }); + return not; +}); +// CONCATENATED MODULE: ./src/function/logical/or.js + + + + + + + +var or_name = 'or'; +var or_dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix']; +var createOr = /* #__PURE__ */Object(factory["a" /* factory */])(or_name, or_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm05 = createAlgorithm05({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Logical `or`. Test if at least one value is defined with a nonzero/nonempty value. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.or(x, y) + * + * Examples: + * + * math.or(2, 4) // returns true + * + * a = [2, 5, 0] + * b = [0, 22, 0] + * c = 0 + * + * math.or(a, b) // returns [true, true, false] + * math.or(b, c) // returns [false, true, false] + * + * See also: + * + * and, not, xor + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check + * @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check + * @return {boolean | Array | Matrix} + * Returns true when one of the inputs is defined with a nonzero/nonempty value. + */ + + var or = typed(or_name, { + 'number, number': orNumber, + 'Complex, Complex': function ComplexComplex(x, y) { + return x.re !== 0 || x.im !== 0 || y.re !== 0 || y.im !== 0; + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return !x.isZero() && !x.isNaN() || !y.isZero() && !y.isNaN(); + }, + 'Unit, Unit': function UnitUnit(x, y) { + return or(x.value || 0, y.value || 0); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm05(x, y, or); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, or, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, or, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, or); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return or(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return or(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return or(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, or, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, or, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, or, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, or, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, or, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, or, true).valueOf(); + } + }); + return or; +}); +// CONCATENATED MODULE: ./src/function/logical/xor.js + + + + + + + +var xor_name = 'xor'; +var xor_dependencies = ['typed', 'matrix', 'DenseMatrix']; +var createXor = /* #__PURE__ */Object(factory["a" /* factory */])(xor_name, xor_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Logical `xor`. Test whether one and only one value is defined with a nonzero/nonempty value. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.xor(x, y) + * + * Examples: + * + * math.xor(2, 4) // returns false + * + * a = [2, 0, 0] + * b = [2, 7, 0] + * c = 0 + * + * math.xor(a, b) // returns [false, true, false] + * math.xor(a, c) // returns [true, false, false] + * + * See also: + * + * and, not, or + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check + * @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check + * @return {boolean | Array | Matrix} + * Returns true when one and only one input is defined with a nonzero/nonempty value. + */ + + var xor = typed(xor_name, { + 'number, number': xorNumber, + 'Complex, Complex': function ComplexComplex(x, y) { + return (x.re !== 0 || x.im !== 0) !== (y.re !== 0 || y.im !== 0); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return (!x.isZero() && !x.isNaN()) !== (!y.isZero() && !y.isNaN()); + }, + 'Unit, Unit': function UnitUnit(x, y) { + return xor(x.value || 0, y.value || 0); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, xor); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, xor, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, xor, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, xor); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return xor(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return xor(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return xor(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, xor, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, xor, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, xor, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, xor, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, xor, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, xor, true).valueOf(); + } + }); + return xor; +}); +// CONCATENATED MODULE: ./src/function/matrix/concat.js + + + + + + +var concat_name = 'concat'; +var concat_dependencies = ['typed', 'matrix', 'isInteger']; +var createConcat = /* #__PURE__ */Object(factory["a" /* factory */])(concat_name, concat_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + isInteger = _ref.isInteger; + + /** + * Concatenate two or more matrices. + * + * Syntax: + * + * math.concat(A, B, C, ...) + * math.concat(A, B, C, ..., dim) + * + * Where: + * + * - `dim: number` is a zero-based dimension over which to concatenate the matrices. + * By default the last dimension of the matrices. + * + * Examples: + * + * const A = [[1, 2], [5, 6]] + * const B = [[3, 4], [7, 8]] + * + * math.concat(A, B) // returns [[1, 2, 3, 4], [5, 6, 7, 8]] + * math.concat(A, B, 0) // returns [[1, 2], [5, 6], [3, 4], [7, 8]] + * math.concat('hello', ' ', 'world') // returns 'hello world' + * + * See also: + * + * size, squeeze, subset, transpose + * + * @param {... Array | Matrix} args Two or more matrices + * @return {Array | Matrix} Concatenated matrix + */ + return typed(concat_name, { + // TODO: change signature to '...Array | Matrix, dim?' when supported + '...Array | Matrix | number | BigNumber': function ArrayMatrixNumberBigNumber(args) { + var i; + var len = args.length; + var dim = -1; // zero-based dimension + + var prevDim; + var asMatrix = false; + var matrices = []; // contains multi dimensional arrays + + for (i = 0; i < len; i++) { + var arg = args[i]; // test whether we need to return a Matrix (if not we return an Array) + + if (Object(is["v" /* isMatrix */])(arg)) { + asMatrix = true; + } + + if (Object(is["y" /* isNumber */])(arg) || Object(is["e" /* isBigNumber */])(arg)) { + if (i !== len - 1) { + throw new Error('Dimension must be specified as last argument'); + } // last argument contains the dimension on which to concatenate + + + prevDim = dim; + dim = arg.valueOf(); // change BigNumber to number + + if (!isInteger(dim)) { + throw new TypeError('Integer number expected for dimension'); + } + + if (dim < 0 || i > 0 && dim > prevDim) { + // TODO: would be more clear when throwing a DimensionError here + throw new IndexError["a" /* IndexError */](dim, prevDim + 1); + } + } else { + // this is a matrix or array + var m = Object(utils_object["a" /* clone */])(arg).valueOf(); + var size = Object(utils_array["a" /* arraySize */])(m); + matrices[i] = m; + prevDim = dim; + dim = size.length - 1; // verify whether each of the matrices has the same number of dimensions + + if (i > 0 && dim !== prevDim) { + throw new DimensionError["a" /* DimensionError */](prevDim + 1, dim + 1); + } + } + } + + if (matrices.length === 0) { + throw new SyntaxError('At least one matrix expected'); + } + + var res = matrices.shift(); + + while (matrices.length) { + res = _concat(res, matrices.shift(), dim, 0); + } + + return asMatrix ? matrix(res) : res; + }, + '...string': function string(args) { + return args.join(''); + } + }); +}); +/** + * Recursively concatenate two matrices. + * The contents of the matrices is not cloned. + * @param {Array} a Multi dimensional array + * @param {Array} b Multi dimensional array + * @param {number} concatDim The dimension on which to concatenate (zero-based) + * @param {number} dim The current dim (zero-based) + * @return {Array} c The concatenated matrix + * @private + */ + +function _concat(a, b, concatDim, dim) { + if (dim < concatDim) { + // recurse into next dimension + if (a.length !== b.length) { + throw new DimensionError["a" /* DimensionError */](a.length, b.length); + } + + var c = []; + + for (var i = 0; i < a.length; i++) { + c[i] = _concat(a[i], b[i], concatDim, dim + 1); + } + + return c; + } else { + // concatenate this dimension + return a.concat(b); + } +} +// CONCATENATED MODULE: ./src/function/matrix/column.js + + + +var column_name = 'column'; +var column_dependencies = ['typed', 'Index', 'matrix', 'range']; +var createColumn = /* #__PURE__ */Object(factory["a" /* factory */])(column_name, column_dependencies, function (_ref) { + var typed = _ref.typed, + Index = _ref.Index, + matrix = _ref.matrix, + range = _ref.range; + + /** + * Return a column from a Matrix. + * + * Syntax: + * + * math.column(value, index) + * + * Example: + * + * // get a column + * const d = [[1, 2], [3, 4]] + * math.column(d, 1) // returns [[2], [4]] + * + * See also: + * + * row + * + * @param {Array | Matrix } value An array or matrix + * @param {number} column The index of the column + * @return {Array | Matrix} The retrieved column + */ + var column = typed(column_name, { + 'Matrix, number': _column, + 'Array, number': function ArrayNumber(value, column) { + return _column(matrix(Object(utils_object["a" /* clone */])(value)), column).valueOf(); + } + }); + return column; + /** + * Retrieve a column of a matrix + * @param {Matrix } value A matrix + * @param {number} column The index of the column + * @return {Matrix} The retrieved column + */ + + function _column(value, column) { + // check dimensions + if (value.size().length !== 2) { + throw new Error('Only two dimensional matrix is supported'); + } + + Object(utils_array["s" /* validateIndex */])(column, value.size()[1]); + var rowRange = range(0, value.size()[0]); + var index = new Index(rowRange, column); + return value.subset(index); + } +}); +// CONCATENATED MODULE: ./src/function/matrix/cross.js + + +var cross_name = 'cross'; +var cross_dependencies = ['typed', 'matrix', 'subtract', 'multiply']; +var createCross = /* #__PURE__ */Object(factory["a" /* factory */])(cross_name, cross_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + subtract = _ref.subtract, + multiply = _ref.multiply; + + /** + * Calculate the cross product for two vectors in three dimensional space. + * The cross product of `A = [a1, a2, a3]` and `B = [b1, b2, b3]` is defined + * as: + * + * cross(A, B) = [ + * a2 * b3 - a3 * b2, + * a3 * b1 - a1 * b3, + * a1 * b2 - a2 * b1 + * ] + * + * If one of the input vectors has a dimension greater than 1, the output + * vector will be a 1x3 (2-dimensional) matrix. + * + * Syntax: + * + * math.cross(x, y) + * + * Examples: + * + * math.cross([1, 1, 0], [0, 1, 1]) // Returns [1, -1, 1] + * math.cross([3, -3, 1], [4, 9, 2]) // Returns [-15, -2, 39] + * math.cross([2, 3, 4], [5, 6, 7]) // Returns [-3, 6, -3] + * math.cross([[1, 2, 3]], [[4], [5], [6]]) // Returns [[-3, 6, -3]] + * + * See also: + * + * dot, multiply + * + * @param {Array | Matrix} x First vector + * @param {Array | Matrix} y Second vector + * @return {Array | Matrix} Returns the cross product of `x` and `y` + */ + return typed(cross_name, { + 'Matrix, Matrix': function MatrixMatrix(x, y) { + return matrix(_cross(x.toArray(), y.toArray())); + }, + 'Matrix, Array': function MatrixArray(x, y) { + return matrix(_cross(x.toArray(), y)); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + return matrix(_cross(x, y.toArray())); + }, + 'Array, Array': _cross + }); + /** + * Calculate the cross product for two arrays + * @param {Array} x First vector + * @param {Array} y Second vector + * @returns {Array} Returns the cross product of x and y + * @private + */ + + function _cross(x, y) { + var highestDimension = Math.max(Object(utils_array["a" /* arraySize */])(x).length, Object(utils_array["a" /* arraySize */])(y).length); + x = Object(utils_array["p" /* squeeze */])(x); + y = Object(utils_array["p" /* squeeze */])(y); + var xSize = Object(utils_array["a" /* arraySize */])(x); + var ySize = Object(utils_array["a" /* arraySize */])(y); + + if (xSize.length !== 1 || ySize.length !== 1 || xSize[0] !== 3 || ySize[0] !== 3) { + throw new RangeError('Vectors with length 3 expected ' + '(Size A = [' + xSize.join(', ') + '], B = [' + ySize.join(', ') + '])'); + } + + var product = [subtract(multiply(x[1], y[2]), multiply(x[2], y[1])), subtract(multiply(x[2], y[0]), multiply(x[0], y[2])), subtract(multiply(x[0], y[1]), multiply(x[1], y[0]))]; + + if (highestDimension > 1) { + return [product]; + } else { + return product; + } + } +}); +// CONCATENATED MODULE: ./src/function/matrix/diag.js + + + + +var diag_name = 'diag'; +var diag_dependencies = ['typed', 'matrix', 'DenseMatrix', 'SparseMatrix']; +var createDiag = /* #__PURE__ */Object(factory["a" /* factory */])(diag_name, diag_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix, + SparseMatrix = _ref.SparseMatrix; + + /** + * Create a diagonal matrix or retrieve the diagonal of a matrix + * + * When `x` is a vector, a matrix with vector `x` on the diagonal will be returned. + * When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector. + * When k is positive, the values are placed on the super diagonal. + * When k is negative, the values are placed on the sub diagonal. + * + * Syntax: + * + * math.diag(X) + * math.diag(X, format) + * math.diag(X, k) + * math.diag(X, k, format) + * + * Examples: + * + * // create a diagonal matrix + * math.diag([1, 2, 3]) // returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]] + * math.diag([1, 2, 3], 1) // returns [[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]] + * math.diag([1, 2, 3], -1) // returns [[0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3]] + * + * // retrieve the diagonal from a matrix + * const a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + * math.diag(a) // returns [1, 5, 9] + * + * See also: + * + * ones, zeros, identity + * + * @param {Matrix | Array} x A two dimensional matrix or a vector + * @param {number | BigNumber} [k=0] The diagonal where the vector will be filled + * in or retrieved. + * @param {string} [format='dense'] The matrix storage format. + * + * @returns {Matrix | Array} Diagonal matrix from input vector, or diagonal from input matrix. + */ + return typed(diag_name, { + // FIXME: simplify this huge amount of signatures as soon as typed-function supports optional arguments + Array: function Array(x) { + return _diag(x, 0, Object(utils_array["a" /* arraySize */])(x), null); + }, + 'Array, number': function ArrayNumber(x, k) { + return _diag(x, k, Object(utils_array["a" /* arraySize */])(x), null); + }, + 'Array, BigNumber': function ArrayBigNumber(x, k) { + return _diag(x, k.toNumber(), Object(utils_array["a" /* arraySize */])(x), null); + }, + 'Array, string': function ArrayString(x, format) { + return _diag(x, 0, Object(utils_array["a" /* arraySize */])(x), format); + }, + 'Array, number, string': function ArrayNumberString(x, k, format) { + return _diag(x, k, Object(utils_array["a" /* arraySize */])(x), format); + }, + 'Array, BigNumber, string': function ArrayBigNumberString(x, k, format) { + return _diag(x, k.toNumber(), Object(utils_array["a" /* arraySize */])(x), format); + }, + Matrix: function Matrix(x) { + return _diag(x, 0, x.size(), x.storage()); + }, + 'Matrix, number': function MatrixNumber(x, k) { + return _diag(x, k, x.size(), x.storage()); + }, + 'Matrix, BigNumber': function MatrixBigNumber(x, k) { + return _diag(x, k.toNumber(), x.size(), x.storage()); + }, + 'Matrix, string': function MatrixString(x, format) { + return _diag(x, 0, x.size(), format); + }, + 'Matrix, number, string': function MatrixNumberString(x, k, format) { + return _diag(x, k, x.size(), format); + }, + 'Matrix, BigNumber, string': function MatrixBigNumberString(x, k, format) { + return _diag(x, k.toNumber(), x.size(), format); + } + }); + /** + * Creeate diagonal matrix from a vector or vice versa + * @param {Array | Matrix} x + * @param {number} k + * @param {string} format Storage format for matrix. If null, + * an Array is returned + * @returns {Array | Matrix} + * @private + */ + + function _diag(x, k, size, format) { + if (!Object(utils_number["i" /* isInteger */])(k)) { + throw new TypeError('Second parameter in function diag must be an integer'); + } + + var kSuper = k > 0 ? k : 0; + var kSub = k < 0 ? -k : 0; // check dimensions + + switch (size.length) { + case 1: + return _createDiagonalMatrix(x, k, format, size[0], kSub, kSuper); + + case 2: + return _getDiagonal(x, k, format, size, kSub, kSuper); + } + + throw new RangeError('Matrix for function diag must be 2 dimensional'); + } + + function _createDiagonalMatrix(x, k, format, l, kSub, kSuper) { + // matrix size + var ms = [l + kSub, l + kSuper]; + + if (format && format !== 'sparse' && format !== 'dense') { + throw new TypeError("Unknown matrix type ".concat(format, "\"")); + } // create diagonal matrix + + + var m = format === 'sparse' ? SparseMatrix.diagonal(ms, x, k) : DenseMatrix.diagonal(ms, x, k); // check we need to return a matrix + + return format !== null ? m : m.valueOf(); + } + + function _getDiagonal(x, k, format, s, kSub, kSuper) { + // check x is a Matrix + if (Object(is["v" /* isMatrix */])(x)) { + // get diagonal matrix + var dm = x.diagonal(k); // check we need to return a matrix + + if (format !== null) { + // check we need to change matrix format + if (format !== dm.storage()) { + return matrix(dm, format); + } + + return dm; + } + + return dm.valueOf(); + } // vector size + + + var n = Math.min(s[0] - kSub, s[1] - kSuper); // diagonal values + + var vector = []; // loop diagonal + + for (var i = 0; i < n; i++) { + vector[i] = x[i + kSub][i + kSuper]; + } // check we need to return a matrix + + + return format !== null ? matrix(vector) : vector; + } +}); +// CONCATENATED MODULE: ./src/function/matrix/eye.js +// TODO: function eye is removed since v5.0.0 (June 2018). Remove it some day. + +var createEye = /* #__PURE__ */Object(factory["a" /* factory */])('eye', [], function () { + return function eye() { + throw new Error('Function "eye" is renamed to "identity" since mathjs version 5.0.0. ' + 'To keep eye working, create an alias for it using "math.import({eye: math.identity}, {override: true})"'); + }; +}); +// CONCATENATED MODULE: ./src/utils/function.js +function function_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { function_typeof = function _typeof(obj) { return typeof obj; }; } else { function_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return function_typeof(obj); } + +// function utils + +/** + * Memoize a given function by caching the computed result. + * The cache of a memoized function can be cleared by deleting the `cache` + * property of the function. + * + * @param {function} fn The function to be memoized. + * Must be a pure function. + * @param {function(args: Array)} [hasher] A custom hash builder. + * Is JSON.stringify by default. + * @return {function} Returns the memoized function + */ +function memoize(fn, hasher) { + return function memoize() { + if (function_typeof(memoize.cache) !== 'object') { + memoize.cache = {}; + } + + var args = []; + + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + var hash = hasher ? hasher(args) : JSON.stringify(args); + + if (!(hash in memoize.cache)) { + memoize.cache[hash] = fn.apply(fn, args); + } + + return memoize.cache[hash]; + }; +} +/** + * Memoize a given function by caching all results and the arguments, + * and comparing against the arguments of previous results before + * executing again. + * This is less performant than `memoize` which calculates a hash, + * which is very fast to compare. Use `memoizeCompare` only when it is + * not possible to create a unique serializable hash from the function + * arguments. + * The isEqual function must compare two sets of arguments + * and return true when equal (can be a deep equality check for example). + * @param {function} fn + * @param {function(a: *, b: *) : boolean} isEqual + * @returns {function} + */ + +function memoizeCompare(fn, isEqual) { + var memoize = function memoize() { + var args = []; + + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + for (var c = 0; c < memoize.cache.length; c++) { + var cached = memoize.cache[c]; + + if (isEqual(args, cached.args)) { + // TODO: move this cache entry to the top so recently used entries move up? + return cached.res; + } + } + + var res = fn.apply(fn, args); + memoize.cache.unshift({ + args: args, + res: res + }); + return res; + }; + + memoize.cache = []; + return memoize; +} +/** + * Find the maximum number of arguments expected by a typed function. + * @param {function} fn A typed function + * @return {number} Returns the maximum number of expected arguments. + * Returns -1 when no signatures where found on the function. + */ + +function maxArgumentCount(fn) { + return Object.keys(fn.signatures || {}).reduce(function (args, signature) { + var count = (signature.match(/,/g) || []).length + 1; + return Math.max(args, count); + }, -1); +} +// CONCATENATED MODULE: ./src/function/matrix/filter.js + + + +var filter_name = 'filter'; +var filter_dependencies = ['typed']; +var createFilter = /* #__PURE__ */Object(factory["a" /* factory */])(filter_name, filter_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Filter the items in an array or one dimensional matrix. + * + * Syntax: + * + * math.filter(x, test) + * + * Examples: + * + * function isPositive (x) { + * return x > 0 + * } + * math.filter([6, -2, -1, 4, 3], isPositive) // returns [6, 4, 3] + * + * math.filter(["23", "foo", "100", "55", "bar"], /[0-9]+/) // returns ["23", "100", "55"] + * + * See also: + * + * forEach, map, sort + * + * @param {Matrix | Array} x A one dimensional matrix or array to filter + * @param {Function | RegExp} test + * A function or regular expression to test items. + * All entries for which `test` returns true are returned. + * When `test` is a function, it is invoked with three parameters: + * the value of the element, the index of the element, and the + * matrix/array being traversed. The function must return a boolean. + * @return {Matrix | Array} Returns the filtered matrix. + */ + return typed('filter', { + 'Array, function': _filterCallback, + 'Matrix, function': function MatrixFunction(x, test) { + return x.create(_filterCallback(x.toArray(), test)); + }, + 'Array, RegExp': utils_array["d" /* filterRegExp */], + 'Matrix, RegExp': function MatrixRegExp(x, test) { + return x.create(Object(utils_array["d" /* filterRegExp */])(x.toArray(), test)); + } + }); +}); +/** + * Filter values in a callback given a callback function + * @param {Array} x + * @param {Function} callback + * @return {Array} Returns the filtered array + * @private + */ + +function _filterCallback(x, callback) { + // figure out what number of arguments the callback function expects + var args = maxArgumentCount(callback); + return Object(utils_array["c" /* filter */])(x, function (value, index, array) { + // invoke the callback function with the right number of arguments + if (args === 1) { + return callback(value); + } else if (args === 2) { + return callback(value, [index]); + } else { + // 3 or -1 + return callback(value, [index], array); + } + }); +} +// CONCATENATED MODULE: ./src/function/matrix/flatten.js + + + +var flatten_name = 'flatten'; +var flatten_dependencies = ['typed', 'matrix']; +var createFlatten = /* #__PURE__ */Object(factory["a" /* factory */])(flatten_name, flatten_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + + /** + * Flatten a multi dimensional matrix into a single dimensional matrix. + * + * Syntax: + * + * math.flatten(x) + * + * Examples: + * + * math.flatten([[1,2], [3,4]]) // returns [1, 2, 3, 4] + * + * See also: + * + * concat, resize, size, squeeze + * + * @param {Matrix | Array} x Matrix to be flattened + * @return {Matrix | Array} Returns the flattened matrix + */ + return typed(flatten_name, { + Array: function Array(x) { + return Object(utils_array["e" /* flatten */])(Object(utils_object["a" /* clone */])(x)); + }, + Matrix: function Matrix(x) { + var flat = Object(utils_array["e" /* flatten */])(Object(utils_object["a" /* clone */])(x.toArray())); // TODO: return the same matrix type as x + + return matrix(flat); + } + }); +}); +// CONCATENATED MODULE: ./src/function/matrix/forEach.js + + + +var forEach_name = 'forEach'; +var forEach_dependencies = ['typed']; +var createForEach = /* #__PURE__ */Object(factory["a" /* factory */])(forEach_name, forEach_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Iterate over all elements of a matrix/array, and executes the given callback function. + * + * Syntax: + * + * math.forEach(x, callback) + * + * Examples: + * + * math.forEach([1, 2, 3], function(value) { + * console.log(value) + * }) + * // outputs 1, 2, 3 + * + * See also: + * + * filter, map, sort + * + * @param {Matrix | Array} x The matrix to iterate on. + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix/array being traversed. + */ + return typed(forEach_name, { + 'Array, function': forEach_forEach, + 'Matrix, function': function MatrixFunction(x, callback) { + return x.forEach(callback); + } + }); +}); +/** + * forEach for a multi dimensional array + * @param {Array} array + * @param {Function} callback + * @private + */ + +function forEach_forEach(array, callback) { + // figure out what number of arguments the callback function expects + var args = maxArgumentCount(callback); + + var recurse = function recurse(value, index) { + if (Array.isArray(value)) { + Object(utils_array["f" /* forEach */])(value, function (child, i) { + // we create a copy of the index array and append the new index value + recurse(child, index.concat(i)); + }); + } else { + // invoke the callback function with the right number of arguments + if (args === 1) { + callback(value); + } else if (args === 2) { + callback(value, index); + } else { + // 3 or -1 + callback(value, index, array); + } + } + }; + + recurse(array, []); +} +// CONCATENATED MODULE: ./src/function/matrix/getMatrixDataType.js + + + +var getMatrixDataType_name = 'getMatrixDataType'; +var getMatrixDataType_dependencies = ['typed']; +var createGetMatrixDataType = /* #__PURE__ */Object(factory["a" /* factory */])(getMatrixDataType_name, getMatrixDataType_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Find the data type of all elements in a matrix or array, + * for example 'number' if all items are a number and 'Complex' if all values + * are complex numbers. + * If a matrix contains more than one data type, it will return 'mixed'. + * + * Syntax: + * + * math.getMatrixDataType(x) + * + * Examples: + * + * const x = [ [1, 2, 3], [4, 5, 6] ] + * const mixedX = [ [1, true], [2, 3] ] + * const fractionX = [ [math.fraction(1, 3)], [math.fraction(1, 3] ] + * const unitX = [ [math.unit('5cm')], [math.unit('5cm')] ] + * const bigNumberX = [ [math.bignumber(1)], [math.bignumber(0)] ] + * const sparse = math.sparse(x) + * const dense = math.matrix(x) + * math.getMatrixDataType(x) // returns 'number' + * math.getMatrixDataType(sparse) // returns 'number' + * math.getMatrixDataType(dense) // returns 'number' + * math.getMatrixDataType(mixedX) // returns 'mixed' + * math.getMatrixDataType(fractionX) // returns 'Fraction' + * math.getMatrixDataType(unitX) // returns 'Unit' + * math.getMatrixDataType(bigNumberX) // return 'BigNumber' + * + * See also: + * SparseMatrix, DenseMatrix + * + * @param {...Matrix | Array} x The Matrix with values. + * + * @return {string} A string representation of the matrix type + */ + return typed(getMatrixDataType_name, { + Array: function Array(x) { + return Object(utils_array["h" /* getArrayDataType */])(x, is["M" /* typeOf */]); + }, + Matrix: function Matrix(x) { + return x.getDataType(); + } + }); +}); +// CONCATENATED MODULE: ./src/function/matrix/identity.js + + + + +var identity_name = 'identity'; +var identity_dependencies = ['typed', 'config', 'matrix', 'BigNumber', 'DenseMatrix', 'SparseMatrix']; +var createIdentity = /* #__PURE__ */Object(factory["a" /* factory */])(identity_name, identity_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + BigNumber = _ref.BigNumber, + DenseMatrix = _ref.DenseMatrix, + SparseMatrix = _ref.SparseMatrix; + + /** + * Create a 2-dimensional identity matrix with size m x n or n x n. + * The matrix has ones on the diagonal and zeros elsewhere. + * + * Syntax: + * + * math.identity(n) + * math.identity(n, format) + * math.identity(m, n) + * math.identity(m, n, format) + * math.identity([m, n]) + * math.identity([m, n], format) + * + * Examples: + * + * math.identity(3) // returns [[1, 0, 0], [0, 1, 0], [0, 0, 1]] + * math.identity(3, 2) // returns [[1, 0], [0, 1], [0, 0]] + * + * const A = [[1, 2, 3], [4, 5, 6]] + * math.identity(math.size(A)) // returns [[1, 0, 0], [0, 1, 0]] + * + * See also: + * + * diag, ones, zeros, size, range + * + * @param {...number | Matrix | Array} size The size for the matrix + * @param {string} [format] The Matrix storage format + * + * @return {Matrix | Array | number} A matrix with ones on the diagonal. + */ + return typed(identity_name, { + '': function _() { + return config.matrix === 'Matrix' ? matrix([]) : []; + }, + string: function string(format) { + return matrix(format); + }, + 'number | BigNumber': function numberBigNumber(rows) { + return _identity(rows, rows, config.matrix === 'Matrix' ? 'dense' : undefined); + }, + 'number | BigNumber, string': function numberBigNumberString(rows, format) { + return _identity(rows, rows, format); + }, + 'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(rows, cols) { + return _identity(rows, cols, config.matrix === 'Matrix' ? 'dense' : undefined); + }, + 'number | BigNumber, number | BigNumber, string': function numberBigNumberNumberBigNumberString(rows, cols, format) { + return _identity(rows, cols, format); + }, + Array: function Array(size) { + return _identityVector(size); + }, + 'Array, string': function ArrayString(size, format) { + return _identityVector(size, format); + }, + Matrix: function Matrix(size) { + return _identityVector(size.valueOf(), size.storage()); + }, + 'Matrix, string': function MatrixString(size, format) { + return _identityVector(size.valueOf(), format); + } + }); + + function _identityVector(size, format) { + switch (size.length) { + case 0: + return format ? matrix(format) : []; + + case 1: + return _identity(size[0], size[0], format); + + case 2: + return _identity(size[0], size[1], format); + + default: + throw new Error('Vector containing two values expected'); + } + } + /** + * Create an identity matrix + * @param {number | BigNumber} rows + * @param {number | BigNumber} cols + * @param {string} [format] + * @returns {Matrix} + * @private + */ + + + function _identity(rows, cols, format) { + // BigNumber constructor with the right precision + var Big = Object(is["e" /* isBigNumber */])(rows) || Object(is["e" /* isBigNumber */])(cols) ? BigNumber : null; + if (Object(is["e" /* isBigNumber */])(rows)) rows = rows.toNumber(); + if (Object(is["e" /* isBigNumber */])(cols)) cols = cols.toNumber(); + + if (!Object(utils_number["i" /* isInteger */])(rows) || rows < 1) { + throw new Error('Parameters in function identity must be positive integers'); + } + + if (!Object(utils_number["i" /* isInteger */])(cols) || cols < 1) { + throw new Error('Parameters in function identity must be positive integers'); + } + + var one = Big ? new BigNumber(1) : 1; + var defaultValue = Big ? new Big(0) : 0; + var size = [rows, cols]; // check we need to return a matrix + + if (format) { + // create diagonal matrix (use optimized implementation for storage format) + if (format === 'sparse') { + return SparseMatrix.diagonal(size, one, 0, defaultValue); + } + + if (format === 'dense') { + return DenseMatrix.diagonal(size, one, 0, defaultValue); + } + + throw new TypeError("Unknown matrix type \"".concat(format, "\"")); + } // create and resize array + + + var res = Object(utils_array["o" /* resize */])([], size, defaultValue); // fill in ones on the diagonal + + var minimum = rows < cols ? rows : cols; // fill diagonal + + for (var d = 0; d < minimum; d++) { + res[d][d] = one; + } + + return res; + } +}); +// CONCATENATED MODULE: ./src/function/matrix/kron.js + + +var kron_name = 'kron'; +var kron_dependencies = ['typed', 'matrix', 'multiplyScalar']; +var createKron = /* #__PURE__ */Object(factory["a" /* factory */])(kron_name, kron_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + multiplyScalar = _ref.multiplyScalar; + + /** + * Calculates the kronecker product of 2 matrices or vectors. + * + * NOTE: If a one dimensional vector / matrix is given, it will be + * wrapped so its two dimensions. + * See the examples. + * + * Syntax: + * + * math.kron(x, y) + * + * Examples: + * + * math.kron([[1, 0], [0, 1]], [[1, 2], [3, 4]]) + * // returns [ [ 1, 2, 0, 0 ], [ 3, 4, 0, 0 ], [ 0, 0, 1, 2 ], [ 0, 0, 3, 4 ] ] + * + * math.kron([1,1], [2,3,4]) + * // returns [ [ 2, 3, 4, 2, 3, 4 ] ] + * + * See also: + * + * multiply, dot, cross + * + * @param {Array | Matrix} x First vector + * @param {Array | Matrix} y Second vector + * @return {Array | Matrix} Returns the kronecker product of `x` and `y` + */ + return typed(kron_name, { + 'Matrix, Matrix': function MatrixMatrix(x, y) { + return matrix(_kron(x.toArray(), y.toArray())); + }, + 'Matrix, Array': function MatrixArray(x, y) { + return matrix(_kron(x.toArray(), y)); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + return matrix(_kron(x, y.toArray())); + }, + 'Array, Array': _kron + }); + /** + * Calculate the kronecker product of two matrices / vectors + * @param {Array} a First vector + * @param {Array} b Second vector + * @returns {Array} Returns the kronecker product of x and y + * @private + */ + + function _kron(a, b) { + // Deal with the dimensions of the matricies. + if (Object(utils_array["a" /* arraySize */])(a).length === 1) { + // Wrap it in a 2D Matrix + a = [a]; + } + + if (Object(utils_array["a" /* arraySize */])(b).length === 1) { + // Wrap it in a 2D Matrix + b = [b]; + } + + if (Object(utils_array["a" /* arraySize */])(a).length > 2 || Object(utils_array["a" /* arraySize */])(b).length > 2) { + throw new RangeError('Vectors with dimensions greater then 2 are not supported expected ' + '(Size x = ' + JSON.stringify(a.length) + ', y = ' + JSON.stringify(b.length) + ')'); + } + + var t = []; + var r = []; + return a.map(function (a) { + return b.map(function (b) { + r = []; + t.push(r); + return a.map(function (y) { + return b.map(function (x) { + return r.push(multiplyScalar(y, x)); + }); + }); + }); + }) && t; + } +}); +// CONCATENATED MODULE: ./src/function/matrix/map.js + + +var map_name = 'map'; +var map_dependencies = ['typed']; +var createMap = /* #__PURE__ */Object(factory["a" /* factory */])(map_name, map_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Create a new matrix or array with the results of the callback function executed on + * each entry of the matrix/array. + * + * Syntax: + * + * math.map(x, callback) + * + * Examples: + * + * math.map([1, 2, 3], function(value) { + * return value * value + * }) // returns [1, 4, 9] + * + * See also: + * + * filter, forEach, sort + * + * @param {Matrix | Array} x The matrix to iterate on. + * @param {Function} callback The callback method is invoked with three + * parameters: the value of the element, the index + * of the element, and the matrix being traversed. + * @return {Matrix | array} Transformed map of x + */ + return typed(map_name, { + 'Array, function': map_map, + 'Matrix, function': function MatrixFunction(x, callback) { + return x.map(callback); + } + }); +}); +/** + * Map for a multi dimensional array + * @param {Array} array + * @param {Function} callback + * @return {Array} + * @private + */ + +function map_map(array, callback) { + // figure out what number of arguments the callback function expects + var args = maxArgumentCount(callback); + + var recurse = function recurse(value, index) { + if (Array.isArray(value)) { + return value.map(function (child, i) { + // we create a copy of the index array and append the new index value + return recurse(child, index.concat(i)); + }); + } else { + // invoke the callback function with the right number of arguments + if (args === 1) { + return callback(value); + } else if (args === 2) { + return callback(value, index); + } else { + // 3 or -1 + return callback(value, index, array); + } + } + }; + + return recurse(array, []); +} +// CONCATENATED MODULE: ./src/function/matrix/ones.js + + + + +var ones_name = 'ones'; +var ones_dependencies = ['typed', 'config', 'matrix', 'BigNumber']; +var createOnes = /* #__PURE__ */Object(factory["a" /* factory */])(ones_name, ones_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + BigNumber = _ref.BigNumber; + + /** + * Create a matrix filled with ones. The created matrix can have one or + * multiple dimensions. + * + * Syntax: + * + * math.ones(m) + * math.ones(m, format) + * math.ones(m, n) + * math.ones(m, n, format) + * math.ones([m, n]) + * math.ones([m, n], format) + * math.ones([m, n, p, ...]) + * math.ones([m, n, p, ...], format) + * + * Examples: + * + * math.ones(3) // returns [1, 1, 1] + * math.ones(3, 2) // returns [[1, 1], [1, 1], [1, 1]] + * math.ones(3, 2, 'dense') // returns Dense Matrix [[1, 1], [1, 1], [1, 1]] + * + * const A = [[1, 2, 3], [4, 5, 6]] + * math.ones(math.size(A)) // returns [[1, 1, 1], [1, 1, 1]] + * + * See also: + * + * zeros, identity, size, range + * + * @param {...number | Array} size The size of each dimension of the matrix + * @param {string} [format] The Matrix storage format + * + * @return {Array | Matrix | number} A matrix filled with ones + */ + return typed('ones', { + '': function _() { + return config.matrix === 'Array' ? _ones([]) : _ones([], 'default'); + }, + // math.ones(m, n, p, ..., format) + // TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this + '...number | BigNumber | string': function numberBigNumberString(size) { + var last = size[size.length - 1]; + + if (typeof last === 'string') { + var format = size.pop(); + return _ones(size, format); + } else if (config.matrix === 'Array') { + return _ones(size); + } else { + return _ones(size, 'default'); + } + }, + Array: _ones, + Matrix: function Matrix(size) { + var format = size.storage(); + return _ones(size.valueOf(), format); + }, + 'Array | Matrix, string': function ArrayMatrixString(size, format) { + return _ones(size.valueOf(), format); + } + }); + /** + * Create an Array or Matrix with ones + * @param {Array} size + * @param {string} [format='default'] + * @return {Array | Matrix} + * @private + */ + + function _ones(size, format) { + var hasBigNumbers = _normalize(size); + + var defaultValue = hasBigNumbers ? new BigNumber(1) : 1; + + _validate(size); + + if (format) { + // return a matrix + var m = matrix(format); + + if (size.length > 0) { + return m.resize(size, defaultValue); + } + + return m; + } else { + // return an Array + var arr = []; + + if (size.length > 0) { + return Object(utils_array["o" /* resize */])(arr, size, defaultValue); + } + + return arr; + } + } // replace BigNumbers with numbers, returns true if size contained BigNumbers + + + function _normalize(size) { + var hasBigNumbers = false; + size.forEach(function (value, index, arr) { + if (Object(is["e" /* isBigNumber */])(value)) { + hasBigNumbers = true; + arr[index] = value.toNumber(); + } + }); + return hasBigNumbers; + } // validate arguments + + + function _validate(size) { + size.forEach(function (value) { + if (typeof value !== 'number' || !Object(utils_number["i" /* isInteger */])(value) || value < 0) { + throw new Error('Parameters in function ones must be positive integers'); + } + }); + } +}); +// CONCATENATED MODULE: ./src/utils/noop.js +function noBignumber() { + throw new Error('No "bignumber" implementation available'); +} +function noFraction() { + throw new Error('No "fraction" implementation available'); +} +function noMatrix() { + throw new Error('No "matrix" implementation available'); +} +function noIndex() { + throw new Error('No "index" implementation available'); +} +function noSubset() { + throw new Error('No "matrix" implementation available'); +} +// CONCATENATED MODULE: ./src/function/matrix/range.js + + +var range_name = 'range'; +var range_dependencies = ['typed', 'config', '?matrix', '?bignumber', 'smaller', 'smallerEq', 'larger', 'largerEq']; +var range_createRange = /* #__PURE__ */Object(factory["a" /* factory */])(range_name, range_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + bignumber = _ref.bignumber, + smaller = _ref.smaller, + smallerEq = _ref.smallerEq, + larger = _ref.larger, + largerEq = _ref.largerEq; + + /** + * Create an array from a range. + * By default, the range end is excluded. This can be customized by providing + * an extra parameter `includeEnd`. + * + * Syntax: + * + * math.range(str [, includeEnd]) // Create a range from a string, + * // where the string contains the + * // start, optional step, and end, + * // separated by a colon. + * math.range(start, end [, includeEnd]) // Create a range with start and + * // end and a step size of 1. + * math.range(start, end, step [, includeEnd]) // Create a range with start, step, + * // and end. + * + * Where: + * + * - `str: string` + * A string 'start:end' or 'start:step:end' + * - `start: {number | BigNumber}` + * Start of the range + * - `end: number | BigNumber` + * End of the range, excluded by default, included when parameter includeEnd=true + * - `step: number | BigNumber` + * Step size. Default value is 1. + * - `includeEnd: boolean` + * Option to specify whether to include the end or not. False by default. + * + * Examples: + * + * math.range(2, 6) // [2, 3, 4, 5] + * math.range(2, -3, -1) // [2, 1, 0, -1, -2] + * math.range('2:1:6') // [2, 3, 4, 5] + * math.range(2, 6, true) // [2, 3, 4, 5, 6] + * + * See also: + * + * ones, zeros, size, subset + * + * @param {*} args Parameters describing the ranges `start`, `end`, and optional `step`. + * @return {Array | Matrix} range + */ + return typed(range_name, { + // TODO: simplify signatures when typed-function supports default values and optional arguments + // TODO: a number or boolean should not be converted to string here + string: _strRange, + 'string, boolean': _strRange, + 'number, number': function numberNumber(start, end) { + return _out(_rangeEx(start, end, 1)); + }, + 'number, number, number': function numberNumberNumber(start, end, step) { + return _out(_rangeEx(start, end, step)); + }, + 'number, number, boolean': function numberNumberBoolean(start, end, includeEnd) { + return includeEnd ? _out(_rangeInc(start, end, 1)) : _out(_rangeEx(start, end, 1)); + }, + 'number, number, number, boolean': function numberNumberNumberBoolean(start, end, step, includeEnd) { + return includeEnd ? _out(_rangeInc(start, end, step)) : _out(_rangeEx(start, end, step)); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(start, end) { + var BigNumber = start.constructor; + return _out(_bigRangeEx(start, end, new BigNumber(1))); + }, + 'BigNumber, BigNumber, BigNumber': function BigNumberBigNumberBigNumber(start, end, step) { + return _out(_bigRangeEx(start, end, step)); + }, + 'BigNumber, BigNumber, boolean': function BigNumberBigNumberBoolean(start, end, includeEnd) { + var BigNumber = start.constructor; + return includeEnd ? _out(_bigRangeInc(start, end, new BigNumber(1))) : _out(_bigRangeEx(start, end, new BigNumber(1))); + }, + 'BigNumber, BigNumber, BigNumber, boolean': function BigNumberBigNumberBigNumberBoolean(start, end, step, includeEnd) { + return includeEnd ? _out(_bigRangeInc(start, end, step)) : _out(_bigRangeEx(start, end, step)); + } + }); + + function _out(arr) { + if (config.matrix === 'Matrix') { + return matrix ? matrix(arr) : noMatrix(); + } + + return arr; + } + + function _strRange(str, includeEnd) { + var r = _parse(str); + + if (!r) { + throw new SyntaxError('String "' + str + '" is no valid range'); + } + + var fn; + + if (config.number === 'BigNumber') { + if (bignumber === undefined) { + noBignumber(); + } + + fn = includeEnd ? _bigRangeInc : _bigRangeEx; + return _out(fn(bignumber(r.start), bignumber(r.end), bignumber(r.step))); + } else { + fn = includeEnd ? _rangeInc : _rangeEx; + return _out(fn(r.start, r.end, r.step)); + } + } + /** + * Create a range with numbers. End is excluded + * @param {number} start + * @param {number} end + * @param {number} step + * @returns {Array} range + * @private + */ + + + function _rangeEx(start, end, step) { + var array = []; + var x = start; + + if (step > 0) { + while (smaller(x, end)) { + array.push(x); + x += step; + } + } else if (step < 0) { + while (larger(x, end)) { + array.push(x); + x += step; + } + } + + return array; + } + /** + * Create a range with numbers. End is included + * @param {number} start + * @param {number} end + * @param {number} step + * @returns {Array} range + * @private + */ + + + function _rangeInc(start, end, step) { + var array = []; + var x = start; + + if (step > 0) { + while (smallerEq(x, end)) { + array.push(x); + x += step; + } + } else if (step < 0) { + while (largerEq(x, end)) { + array.push(x); + x += step; + } + } + + return array; + } + /** + * Create a range with big numbers. End is excluded + * @param {BigNumber} start + * @param {BigNumber} end + * @param {BigNumber} step + * @returns {Array} range + * @private + */ + + + function _bigRangeEx(start, end, step) { + var zero = bignumber(0); + var array = []; + var x = start; + + if (step.gt(zero)) { + while (smaller(x, end)) { + array.push(x); + x = x.plus(step); + } + } else if (step.lt(zero)) { + while (larger(x, end)) { + array.push(x); + x = x.plus(step); + } + } + + return array; + } + /** + * Create a range with big numbers. End is included + * @param {BigNumber} start + * @param {BigNumber} end + * @param {BigNumber} step + * @returns {Array} range + * @private + */ + + + function _bigRangeInc(start, end, step) { + var zero = bignumber(0); + var array = []; + var x = start; + + if (step.gt(zero)) { + while (smallerEq(x, end)) { + array.push(x); + x = x.plus(step); + } + } else if (step.lt(zero)) { + while (largerEq(x, end)) { + array.push(x); + x = x.plus(step); + } + } + + return array; + } + /** + * Parse a string into a range, + * The string contains the start, optional step, and end, separated by a colon. + * If the string does not contain a valid range, null is returned. + * For example str='0:2:11'. + * @param {string} str + * @return {{start: number, end: number, step: number} | null} range Object containing properties start, end, step + * @private + */ + + + function _parse(str) { + var args = str.split(':'); // number + + var nums = args.map(function (arg) { + // use Number and not parseFloat as Number returns NaN on invalid garbage in the string + return Number(arg); + }); + var invalid = nums.some(function (num) { + return isNaN(num); + }); + + if (invalid) { + return null; + } + + switch (nums.length) { + case 2: + return { + start: nums[0], + end: nums[1], + step: 1 + }; + + case 3: + return { + start: nums[0], + end: nums[2], + step: nums[1] + }; + + default: + return null; + } + } +}); +// CONCATENATED MODULE: ./src/function/matrix/reshape.js + + +var reshape_name = 'reshape'; +var reshape_dependencies = ['typed', 'isInteger', 'matrix']; +var createReshape = /* #__PURE__ */Object(factory["a" /* factory */])(reshape_name, reshape_dependencies, function (_ref) { + var typed = _ref.typed, + isInteger = _ref.isInteger, + matrix = _ref.matrix; + + /** + * Reshape a multi dimensional array to fit the specified dimensions + * + * Syntax: + * + * math.reshape(x, sizes) + * + * Examples: + * + * math.reshape([1, 2, 3, 4, 5, 6], [2, 3]) + * // returns Array [[1, 2, 3], [4, 5, 6]] + * + * math.reshape([[1, 2], [3, 4]], [1, 4]) + * // returns Array [[1, 2, 3, 4]] + * + * math.reshape([[1, 2], [3, 4]], [4]) + * // returns Array [1, 2, 3, 4] + * + * const x = math.matrix([1, 2, 3, 4, 5, 6, 7, 8]) + * math.reshape(x, [2, 2, 2]) + * // returns Matrix [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + * + * See also: + * + * size, squeeze, resize + * + * @param {Array | Matrix | *} x Matrix to be reshaped + * @param {number[]} sizes One dimensional array with integral sizes for + * each dimension + * + * @return {* | Array | Matrix} A reshaped clone of matrix `x` + * + * @throws {TypeError} If `sizes` does not contain solely integers + * @throws {DimensionError} If the product of the new dimension sizes does + * not equal that of the old ones + */ + return typed(reshape_name, { + 'Matrix, Array': function MatrixArray(x, sizes) { + if (x.reshape) { + return x.reshape(sizes); + } else { + return matrix(Object(utils_array["n" /* reshape */])(x.valueOf(), sizes)); + } + }, + 'Array, Array': function ArrayArray(x, sizes) { + sizes.forEach(function (size) { + if (!isInteger(size)) { + throw new TypeError('Invalid size for dimension: ' + size); + } + }); + return Object(utils_array["n" /* reshape */])(x, sizes); + } + }); +}); +// EXTERNAL MODULE: ./src/error/ArgumentsError.js +var ArgumentsError = __webpack_require__(13); + +// CONCATENATED MODULE: ./src/function/matrix/resize.js + + + + + + + + +var resize_name = 'resize'; +var resize_dependencies = ['config', 'matrix']; +var createResize = /* #__PURE__ */Object(factory["a" /* factory */])(resize_name, resize_dependencies, function (_ref) { + var config = _ref.config, + matrix = _ref.matrix; + + /** + * Resize a matrix + * + * Syntax: + * + * math.resize(x, size) + * math.resize(x, size, defaultValue) + * + * Examples: + * + * math.resize([1, 2, 3, 4, 5], [3]) // returns Array [1, 2, 3] + * math.resize([1, 2, 3], [5], 0) // returns Array [1, 2, 3, 0, 0] + * math.resize(2, [2, 3], 0) // returns Matrix [[2, 0, 0], [0, 0, 0]] + * math.resize("hello", [8], "!") // returns string 'hello!!!' + * + * See also: + * + * size, squeeze, subset, reshape + * + * @param {Array | Matrix | *} x Matrix to be resized + * @param {Array | Matrix} size One dimensional array with numbers + * @param {number | string} [defaultValue=0] Zero by default, except in + * case of a string, in that case + * defaultValue = ' ' + * @return {* | Array | Matrix} A resized clone of matrix `x` + */ + // TODO: rework resize to a typed-function + return function resize(x, size, defaultValue) { + if (arguments.length !== 2 && arguments.length !== 3) { + throw new ArgumentsError["a" /* ArgumentsError */]('resize', arguments.length, 2, 3); + } + + if (Object(is["v" /* isMatrix */])(size)) { + size = size.valueOf(); // get Array + } + + if (Object(is["e" /* isBigNumber */])(size[0])) { + // convert bignumbers to numbers + size = size.map(function (value) { + return !Object(is["e" /* isBigNumber */])(value) ? value : value.toNumber(); + }); + } // check x is a Matrix + + + if (Object(is["v" /* isMatrix */])(x)) { + // use optimized matrix implementation, return copy + return x.resize(size, defaultValue, true); + } + + if (typeof x === 'string') { + // resize string + return _resizeString(x, size, defaultValue); + } // check result should be a matrix + + + var asMatrix = Array.isArray(x) ? false : config.matrix !== 'Array'; + + if (size.length === 0) { + // output a scalar + while (Array.isArray(x)) { + x = x[0]; + } + + return Object(utils_object["a" /* clone */])(x); + } else { + // output an array/matrix + if (!Array.isArray(x)) { + x = [x]; + } + + x = Object(utils_object["a" /* clone */])(x); + var res = Object(utils_array["o" /* resize */])(x, size, defaultValue); + return asMatrix ? matrix(res) : res; + } + }; + /** + * Resize a string + * @param {string} str + * @param {number[]} size + * @param {string} [defaultChar=' '] + * @private + */ + + function _resizeString(str, size, defaultChar) { + if (defaultChar !== undefined) { + if (typeof defaultChar !== 'string' || defaultChar.length !== 1) { + throw new TypeError('Single character expected as defaultValue'); + } + } else { + defaultChar = ' '; + } + + if (size.length !== 1) { + throw new DimensionError["a" /* DimensionError */](size.length, 1); + } + + var len = size[0]; + + if (typeof len !== 'number' || !Object(utils_number["i" /* isInteger */])(len)) { + throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + + if (str.length > len) { + return str.substring(0, len); + } else if (str.length < len) { + var res = str; + + for (var i = 0, ii = len - str.length; i < ii; i++) { + res += defaultChar; + } + + return res; + } else { + return str; + } + } +}); +// CONCATENATED MODULE: ./src/function/matrix/row.js + + + +var row_name = 'row'; +var row_dependencies = ['typed', 'Index', 'matrix', 'range']; +var createRow = /* #__PURE__ */Object(factory["a" /* factory */])(row_name, row_dependencies, function (_ref) { + var typed = _ref.typed, + Index = _ref.Index, + matrix = _ref.matrix, + range = _ref.range; + + /** + * Return a row from a Matrix. + * + * Syntax: + * + * math.row(value, index) + * + * Example: + * + * // get a row + * const d = [[1, 2], [3, 4]] + * math.row(d, 1) // returns [[3, 4]] + * + * See also: + * + * column + * + * @param {Array | Matrix } value An array or matrix + * @param {number} row The index of the row + * @return {Array | Matrix} The retrieved row + */ + var row = typed(row_name, { + 'Matrix, number': _row, + 'Array, number': function ArrayNumber(value, row) { + return _row(matrix(Object(utils_object["a" /* clone */])(value)), row).valueOf(); + } + }); + return row; + /** + * Retrieve a row of a matrix + * @param {Matrix } value A matrix + * @param {number} row The index of the row + * @return {Matrix} The retrieved row + */ + + function _row(value, row) { + // check dimensions + if (value.size().length !== 2) { + throw new Error('Only two dimensional matrix is supported'); + } + + Object(utils_array["s" /* validateIndex */])(row, value.size()[0]); + var columnRange = range(0, value.size()[1]); + var index = new Index(row, columnRange); + return value.subset(index); + } +}); +// CONCATENATED MODULE: ./src/function/matrix/size.js + + + +var size_name = 'size'; +var size_dependencies = ['typed', 'config', '?matrix']; +var createSize = /* #__PURE__ */Object(factory["a" /* factory */])(size_name, size_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix; + + /** + * Calculate the size of a matrix or scalar. + * + * Syntax: + * + * math.size(x) + * + * Examples: + * + * math.size(2.3) // returns [] + * math.size('hello world') // returns [11] + * + * const A = [[1, 2, 3], [4, 5, 6]] + * math.size(A) // returns [2, 3] + * math.size(math.range(1,6)) // returns [5] + * + * See also: + * + * resize, squeeze, subset + * + * @param {boolean | number | Complex | Unit | string | Array | Matrix} x A matrix + * @return {Array | Matrix} A vector with size of `x`. + */ + return typed(size_name, { + Matrix: function Matrix(x) { + return x.create(x.size()); + }, + Array: utils_array["a" /* arraySize */], + string: function string(x) { + return config.matrix === 'Array' ? [x.length] : matrix([x.length]); + }, + 'number | Complex | BigNumber | Unit | boolean | null': function numberComplexBigNumberUnitBooleanNull(x) { + // scalar + return config.matrix === 'Array' ? [] : matrix ? matrix([]) : noMatrix(); + } + }); +}); +// CONCATENATED MODULE: ./src/function/matrix/squeeze.js + + + +var squeeze_name = 'squeeze'; +var squeeze_dependencies = ['typed', 'matrix']; +var createSqueeze = /* #__PURE__ */Object(factory["a" /* factory */])(squeeze_name, squeeze_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + + /** + * Squeeze a matrix, remove inner and outer singleton dimensions from a matrix. + * + * Syntax: + * + * math.squeeze(x) + * + * Examples: + * + * math.squeeze([3]) // returns 3 + * math.squeeze([[3]]) // returns 3 + * + * const A = math.zeros(3, 1) // returns [[0], [0], [0]] (size 3x1) + * math.squeeze(A) // returns [0, 0, 0] (size 3) + * + * const B = math.zeros(1, 3) // returns [[0, 0, 0]] (size 1x3) + * math.squeeze(B) // returns [0, 0, 0] (size 3) + * + * // only inner and outer dimensions are removed + * const C = math.zeros(2, 1, 3) // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3) + * math.squeeze(C) // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3) + * + * See also: + * + * subset + * + * @param {Matrix | Array} x Matrix to be squeezed + * @return {Matrix | Array} Squeezed matrix + */ + return typed(squeeze_name, { + Array: function Array(x) { + return Object(utils_array["p" /* squeeze */])(Object(utils_object["a" /* clone */])(x)); + }, + Matrix: function Matrix(x) { + var res = Object(utils_array["p" /* squeeze */])(x.toArray()); // FIXME: return the same type of matrix as the input + + return Array.isArray(res) ? matrix(res) : res; + }, + any: function any(x) { + // scalar + return Object(utils_object["a" /* clone */])(x); + } + }); +}); +// CONCATENATED MODULE: ./src/utils/customs.js +function customs_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { customs_typeof = function _typeof(obj) { return typeof obj; }; } else { customs_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return customs_typeof(obj); } + + +/** + * Get a property of a plain object + * Throws an error in case the object is not a plain object or the + * property is not defined on the object itself + * @param {Object} object + * @param {string} prop + * @return {*} Returns the property value when safe + */ + +function getSafeProperty(object, prop) { + // only allow getting safe properties of a plain object + if (isPlainObject(object) && isSafeProperty(object, prop)) { + return object[prop]; + } + + if (typeof object[prop] === 'function' && isSafeMethod(object, prop)) { + throw new Error('Cannot access method "' + prop + '" as a property'); + } + + throw new Error('No access to property "' + prop + '"'); +} +/** + * Set a property on a plain object. + * Throws an error in case the object is not a plain object or the + * property would override an inherited property like .constructor or .toString + * @param {Object} object + * @param {string} prop + * @param {*} value + * @return {*} Returns the value + */ +// TODO: merge this function into access.js? + + +function setSafeProperty(object, prop, value) { + // only allow setting safe properties of a plain object + if (isPlainObject(object) && isSafeProperty(object, prop)) { + object[prop] = value; + return value; + } + + throw new Error('No access to property "' + prop + '"'); +} +/** + * Test whether a property is safe to use for an object. + * For example .toString and .constructor are not safe + * @param {string} prop + * @return {boolean} Returns true when safe + */ + + +function isSafeProperty(object, prop) { + if (!object || customs_typeof(object) !== 'object') { + return false; + } // SAFE: whitelisted + // e.g length + + + if (Object(utils_object["f" /* hasOwnProperty */])(safeNativeProperties, prop)) { + return true; + } // UNSAFE: inherited from Object prototype + // e.g constructor + + + if (prop in Object.prototype) { + // 'in' is used instead of hasOwnProperty for nodejs v0.10 + // which is inconsistent on root prototypes. It is safe + // here because Object.prototype is a root object + return false; + } // UNSAFE: inherited from Function prototype + // e.g call, apply + + + if (prop in Function.prototype) { + // 'in' is used instead of hasOwnProperty for nodejs v0.10 + // which is inconsistent on root prototypes. It is safe + // here because Function.prototype is a root object + return false; + } + + return true; +} +/** + * Validate whether a method is safe. + * Throws an error when that's not the case. + * @param {Object} object + * @param {string} method + */ +// TODO: merge this function into assign.js? + + +function validateSafeMethod(object, method) { + if (!isSafeMethod(object, method)) { + throw new Error('No access to method "' + method + '"'); + } +} +/** + * Check whether a method is safe. + * Throws an error when that's not the case (for example for `constructor`). + * @param {Object} object + * @param {string} method + * @return {boolean} Returns true when safe, false otherwise + */ + + +function isSafeMethod(object, method) { + if (object === null || object === undefined || typeof object[method] !== 'function') { + return false; + } // UNSAFE: ghosted + // e.g overridden toString + // Note that IE10 doesn't support __proto__ and we can't do this check there. + + + if (Object(utils_object["f" /* hasOwnProperty */])(object, method) && Object.getPrototypeOf && method in Object.getPrototypeOf(object)) { + return false; + } // SAFE: whitelisted + // e.g toString + + + if (Object(utils_object["f" /* hasOwnProperty */])(safeNativeMethods, method)) { + return true; + } // UNSAFE: inherited from Object prototype + // e.g constructor + + + if (method in Object.prototype) { + // 'in' is used instead of hasOwnProperty for nodejs v0.10 + // which is inconsistent on root prototypes. It is safe + // here because Object.prototype is a root object + return false; + } // UNSAFE: inherited from Function prototype + // e.g call, apply + + + if (method in Function.prototype) { + // 'in' is used instead of hasOwnProperty for nodejs v0.10 + // which is inconsistent on root prototypes. It is safe + // here because Function.prototype is a root object + return false; + } + + return true; +} + +function isPlainObject(object) { + return customs_typeof(object) === 'object' && object && object.constructor === Object; +} + +var safeNativeProperties = { + length: true, + name: true +}; +var safeNativeMethods = { + toString: true, + valueOf: true, + toLocaleString: true +}; + + + + + + +// CONCATENATED MODULE: ./src/function/matrix/subset.js + + + + + + +var subset_name = 'subset'; +var subset_dependencies = ['typed', 'matrix']; +var createSubset = /* #__PURE__ */Object(factory["a" /* factory */])(subset_name, subset_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + + /** + * Get or set a subset of a matrix or string. + * + * Syntax: + * math.subset(value, index) // retrieve a subset + * math.subset(value, index, replacement [, defaultValue]) // replace a subset + * + * Examples: + * + * // get a subset + * const d = [[1, 2], [3, 4]] + * math.subset(d, math.index(1, 0)) // returns 3 + * math.subset(d, math.index([0, 1], 1)) // returns [[2], [4]] + * + * // replace a subset + * const e = [] + * const f = math.subset(e, math.index(0, [0, 2]), [5, 6]) // f = [[5, 6]] + * const g = math.subset(f, math.index(1, 1), 7, 0) // g = [[5, 6], [0, 7]] + * + * See also: + * + * size, resize, squeeze, index + * + * @param {Array | Matrix | string} matrix An array, matrix, or string + * @param {Index} index An index containing ranges for each + * dimension + * @param {*} [replacement] An array, matrix, or scalar. + * If provided, the subset is replaced with replacement. + * If not provided, the subset is returned + * @param {*} [defaultValue=undefined] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * math.matrix elements will be left undefined. + * @return {Array | Matrix | string} Either the retrieved subset or the updated matrix. + */ + return typed(subset_name, { + // get subset + 'Array, Index': function ArrayIndex(value, index) { + var m = matrix(value); + var subset = m.subset(index); // returns a Matrix + + return index.isScalar() ? subset : subset.valueOf(); // return an Array (like the input) + }, + 'Matrix, Index': function MatrixIndex(value, index) { + return value.subset(index); + }, + 'Object, Index': _getObjectProperty, + 'string, Index': _getSubstring, + // set subset + 'Array, Index, any': function ArrayIndexAny(value, index, replacement) { + return matrix(Object(utils_object["a" /* clone */])(value)).subset(index, replacement, undefined).valueOf(); + }, + 'Array, Index, any, any': function ArrayIndexAnyAny(value, index, replacement, defaultValue) { + return matrix(Object(utils_object["a" /* clone */])(value)).subset(index, replacement, defaultValue).valueOf(); + }, + 'Matrix, Index, any': function MatrixIndexAny(value, index, replacement) { + return value.clone().subset(index, replacement); + }, + 'Matrix, Index, any, any': function MatrixIndexAnyAny(value, index, replacement, defaultValue) { + return value.clone().subset(index, replacement, defaultValue); + }, + 'string, Index, string': _setSubstring, + 'string, Index, string, string': _setSubstring, + 'Object, Index, any': _setObjectProperty + }); +}); +/** + * Retrieve a subset of a string + * @param {string} str string from which to get a substring + * @param {Index} index An index containing ranges for each dimension + * @returns {string} substring + * @private + */ + +function _getSubstring(str, index) { + if (!Object(is["t" /* isIndex */])(index)) { + // TODO: better error message + throw new TypeError('Index expected'); + } + + if (index.size().length !== 1) { + throw new DimensionError["a" /* DimensionError */](index.size().length, 1); + } // validate whether the range is out of range + + + var strLen = str.length; + Object(utils_array["s" /* validateIndex */])(index.min()[0], strLen); + Object(utils_array["s" /* validateIndex */])(index.max()[0], strLen); + var range = index.dimension(0); + var substr = ''; + range.forEach(function (v) { + substr += str.charAt(v); + }); + return substr; +} +/** + * Replace a substring in a string + * @param {string} str string to be replaced + * @param {Index} index An index containing ranges for each dimension + * @param {string} replacement Replacement string + * @param {string} [defaultValue] Default value to be uses when resizing + * the string. is ' ' by default + * @returns {string} result + * @private + */ + + +function _setSubstring(str, index, replacement, defaultValue) { + if (!index || index.isIndex !== true) { + // TODO: better error message + throw new TypeError('Index expected'); + } + + if (index.size().length !== 1) { + throw new DimensionError["a" /* DimensionError */](index.size().length, 1); + } + + if (defaultValue !== undefined) { + if (typeof defaultValue !== 'string' || defaultValue.length !== 1) { + throw new TypeError('Single character expected as defaultValue'); + } + } else { + defaultValue = ' '; + } + + var range = index.dimension(0); + var len = range.size()[0]; + + if (len !== replacement.length) { + throw new DimensionError["a" /* DimensionError */](range.size()[0], replacement.length); + } // validate whether the range is out of range + + + var strLen = str.length; + Object(utils_array["s" /* validateIndex */])(index.min()[0]); + Object(utils_array["s" /* validateIndex */])(index.max()[0]); // copy the string into an array with characters + + var chars = []; + + for (var i = 0; i < strLen; i++) { + chars[i] = str.charAt(i); + } + + range.forEach(function (v, i) { + chars[v] = replacement.charAt(i[0]); + }); // initialize undefined characters with a space + + if (chars.length > strLen) { + for (var _i = strLen - 1, _len = chars.length; _i < _len; _i++) { + if (!chars[_i]) { + chars[_i] = defaultValue; + } + } + } + + return chars.join(''); +} +/** + * Retrieve a property from an object + * @param {Object} object + * @param {Index} index + * @return {*} Returns the value of the property + * @private + */ + + +function _getObjectProperty(object, index) { + if (index.size().length !== 1) { + throw new DimensionError["a" /* DimensionError */](index.size(), 1); + } + + var key = index.dimension(0); + + if (typeof key !== 'string') { + throw new TypeError('String expected as index to retrieve an object property'); + } + + return getSafeProperty(object, key); +} +/** + * Set a property on an object + * @param {Object} object + * @param {Index} index + * @param {*} replacement + * @return {*} Returns the updated object + * @private + */ + + +function _setObjectProperty(object, index, replacement) { + if (index.size().length !== 1) { + throw new DimensionError["a" /* DimensionError */](index.size(), 1); + } + + var key = index.dimension(0); + + if (typeof key !== 'string') { + throw new TypeError('String expected as index to retrieve an object property'); + } // clone the object, and apply the property to the clone + + + var updated = Object(utils_object["a" /* clone */])(object); + setSafeProperty(updated, key, replacement); + return updated; +} +// CONCATENATED MODULE: ./src/function/matrix/transpose.js + + + +var transpose_name = 'transpose'; +var transpose_dependencies = ['typed', 'matrix']; +var createTranspose = /* #__PURE__ */Object(factory["a" /* factory */])(transpose_name, transpose_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + + /** + * Transpose a matrix. All values of the matrix are reflected over its + * main diagonal. Only applicable to two dimensional matrices containing + * a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional + * vectors and scalars return the input unchanged. + * + * Syntax: + * + * math.transpose(x) + * + * Examples: + * + * const A = [[1, 2, 3], [4, 5, 6]] + * math.transpose(A) // returns [[1, 4], [2, 5], [3, 6]] + * + * See also: + * + * diag, inv, subset, squeeze + * + * @param {Array | Matrix} x Matrix to be transposed + * @return {Array | Matrix} The transposed matrix + */ + var transpose = typed('transpose', { + Array: function Array(x) { + // use dense matrix implementation + return transpose(matrix(x)).valueOf(); + }, + Matrix: function Matrix(x) { + // matrix size + var size = x.size(); // result + + var c; // process dimensions + + switch (size.length) { + case 1: + // vector + c = x.clone(); + break; + + case 2: + { + // rows and columns + var rows = size[0]; + var columns = size[1]; // check columns + + if (columns === 0) { + // throw exception + throw new RangeError('Cannot transpose a 2D matrix with no columns (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } // process storage format + + + switch (x.storage()) { + case 'dense': + c = _denseTranspose(x, rows, columns); + break; + + case 'sparse': + c = _sparseTranspose(x, rows, columns); + break; + } + } + break; + + default: + // multi dimensional + throw new RangeError('Matrix must be a vector or two dimensional (size: ' + Object(utils_string["d" /* format */])(this._size) + ')'); + } + + return c; + }, + // scalars + any: function any(x) { + return Object(utils_object["a" /* clone */])(x); + } + }); + + function _denseTranspose(m, rows, columns) { + // matrix array + var data = m._data; // transposed matrix data + + var transposed = []; + var transposedRow; // loop columns + + for (var j = 0; j < columns; j++) { + // initialize row + transposedRow = transposed[j] = []; // loop rows + + for (var i = 0; i < rows; i++) { + // set data + transposedRow[i] = Object(utils_object["a" /* clone */])(data[i][j]); + } + } // return matrix + + + return m.createDenseMatrix({ + data: transposed, + size: [columns, rows], + datatype: m._datatype + }); + } + + function _sparseTranspose(m, rows, columns) { + // matrix arrays + var values = m._values; + var index = m._index; + var ptr = m._ptr; // result matrices + + var cvalues = values ? [] : undefined; + var cindex = []; + var cptr = []; // row counts + + var w = []; + + for (var x = 0; x < rows; x++) { + w[x] = 0; + } // vars + + + var p, l, j; // loop values in matrix + + for (p = 0, l = index.length; p < l; p++) { + // number of values in row + w[index[p]]++; + } // cumulative sum + + + var sum = 0; // initialize cptr with the cummulative sum of row counts + + for (var i = 0; i < rows; i++) { + // update cptr + cptr.push(sum); // update sum + + sum += w[i]; // update w + + w[i] = cptr[i]; + } // update cptr + + + cptr.push(sum); // loop columns + + for (j = 0; j < columns; j++) { + // values & index in column + for (var k0 = ptr[j], k1 = ptr[j + 1], k = k0; k < k1; k++) { + // C values & index + var q = w[index[k]]++; // C[j, i] = A[i, j] + + cindex[q] = j; // check we need to process values (pattern matrix) + + if (values) { + cvalues[q] = Object(utils_object["a" /* clone */])(values[k]); + } + } + } // return matrix + + + return m.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [columns, rows], + datatype: m._datatype + }); + } + + return transpose; +}); +// CONCATENATED MODULE: ./src/function/matrix/ctranspose.js + +var ctranspose_name = 'ctranspose'; +var ctranspose_dependencies = ['typed', 'transpose', 'conj']; +var createCtranspose = /* #__PURE__ */Object(factory["a" /* factory */])(ctranspose_name, ctranspose_dependencies, function (_ref) { + var typed = _ref.typed, + transpose = _ref.transpose, + conj = _ref.conj; + + /** + * Transpose and complex conjugate a matrix. All values of the matrix are + * reflected over its main diagonal and then the complex conjugate is + * taken. This is equivalent to complex conjugation for scalars and + * vectors. + * + * Syntax: + * + * math.ctranspose(x) + * + * Examples: + * + * const A = [[1, 2, 3], [4, 5, math.complex(6,7)]] + * math.ctranspose(A) // returns [[1, 4], [2, 5], [3, {re:6,im:7}]] + * + * See also: + * + * transpose, diag, inv, subset, squeeze + * + * @param {Array | Matrix} x Matrix to be ctransposed + * @return {Array | Matrix} The ctransposed matrix + */ + return typed(ctranspose_name, { + any: function any(x) { + return conj(transpose(x)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/matrix/zeros.js + + + + +var zeros_name = 'zeros'; +var zeros_dependencies = ['typed', 'config', 'matrix', 'BigNumber']; +var createZeros = /* #__PURE__ */Object(factory["a" /* factory */])(zeros_name, zeros_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + BigNumber = _ref.BigNumber; + + /** + * Create a matrix filled with zeros. The created matrix can have one or + * multiple dimensions. + * + * Syntax: + * + * math.zeros(m) + * math.zeros(m, format) + * math.zeros(m, n) + * math.zeros(m, n, format) + * math.zeros([m, n]) + * math.zeros([m, n], format) + * + * Examples: + * + * math.zeros(3) // returns [0, 0, 0] + * math.zeros(3, 2) // returns [[0, 0], [0, 0], [0, 0]] + * math.zeros(3, 'dense') // returns [0, 0, 0] + * + * const A = [[1, 2, 3], [4, 5, 6]] + * math.zeros(math.size(A)) // returns [[0, 0, 0], [0, 0, 0]] + * + * See also: + * + * ones, identity, size, range + * + * @param {...number | Array} size The size of each dimension of the matrix + * @param {string} [format] The Matrix storage format + * + * @return {Array | Matrix} A matrix filled with zeros + */ + return typed(zeros_name, { + '': function _() { + return config.matrix === 'Array' ? _zeros([]) : _zeros([], 'default'); + }, + // math.zeros(m, n, p, ..., format) + // TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this + '...number | BigNumber | string': function numberBigNumberString(size) { + var last = size[size.length - 1]; + + if (typeof last === 'string') { + var format = size.pop(); + return _zeros(size, format); + } else if (config.matrix === 'Array') { + return _zeros(size); + } else { + return _zeros(size, 'default'); + } + }, + Array: _zeros, + Matrix: function Matrix(size) { + var format = size.storage(); + return _zeros(size.valueOf(), format); + }, + 'Array | Matrix, string': function ArrayMatrixString(size, format) { + return _zeros(size.valueOf(), format); + } + }); + /** + * Create an Array or Matrix with zeros + * @param {Array} size + * @param {string} [format='default'] + * @return {Array | Matrix} + * @private + */ + + function _zeros(size, format) { + var hasBigNumbers = _normalize(size); + + var defaultValue = hasBigNumbers ? new BigNumber(0) : 0; + + _validate(size); + + if (format) { + // return a matrix + var m = matrix(format); + + if (size.length > 0) { + return m.resize(size, defaultValue); + } + + return m; + } else { + // return an Array + var arr = []; + + if (size.length > 0) { + return Object(utils_array["o" /* resize */])(arr, size, defaultValue); + } + + return arr; + } + } // replace BigNumbers with numbers, returns true if size contained BigNumbers + + + function _normalize(size) { + var hasBigNumbers = false; + size.forEach(function (value, index, arr) { + if (Object(is["e" /* isBigNumber */])(value)) { + hasBigNumbers = true; + arr[index] = value.toNumber(); + } + }); + return hasBigNumbers; + } // validate arguments + + + function _validate(size) { + size.forEach(function (value) { + if (typeof value !== 'number' || !Object(utils_number["i" /* isInteger */])(value) || value < 0) { + throw new Error('Parameters in function zeros must be positive integers'); + } + }); + } +}); // TODO: zeros contains almost the same code as ones. Reuse this? +// CONCATENATED MODULE: ./src/function/special/erf.js + + + +var erf_name = 'erf'; +var erf_dependencies = ['typed']; +var createErf = /* #__PURE__ */Object(factory["a" /* factory */])(erf_name, erf_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the erf function of a value using a rational Chebyshev + * approximations for different intervals of x. + * + * This is a translation of W. J. Cody's Fortran implementation from 1987 + * ( https://www.netlib.org/specfun/erf ). See the AMS publication + * "Rational Chebyshev Approximations for the Error Function" by W. J. Cody + * for an explanation of this process. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.erf(x) + * + * Examples: + * + * math.erf(0.2) // returns 0.22270258921047847 + * math.erf(-0.5) // returns -0.5204998778130465 + * math.erf(4) // returns 0.9999999845827421 + * + * @param {number | Array | Matrix} x A real number + * @return {number | Array | Matrix} The erf of `x` + */ + var erf = typed('name', { + number: function number(x) { + var y = Math.abs(x); + + if (y >= MAX_NUM) { + return Object(utils_number["n" /* sign */])(x); + } + + if (y <= THRESH) { + return Object(utils_number["n" /* sign */])(x) * erf1(y); + } + + if (y <= 4.0) { + return Object(utils_number["n" /* sign */])(x) * (1 - erfc2(y)); + } + + return Object(utils_number["n" /* sign */])(x) * (1 - erfc3(y)); + }, + 'Array | Matrix': function ArrayMatrix(n) { + return deepMap(n, erf); + } // TODO: For complex numbers, use the approximation for the Faddeeva function + // from "More Efficient Computation of the Complex Error Function" (AMS) + + }); + /** + * Approximates the error function erf() for x <= 0.46875 using this function: + * n + * erf(x) = x * sum (p_j * x^(2j)) / (q_j * x^(2j)) + * j=0 + */ + + function erf1(y) { + var ysq = y * y; + var xnum = erf_P[0][4] * ysq; + var xden = ysq; + var i; + + for (i = 0; i < 3; i += 1) { + xnum = (xnum + erf_P[0][i]) * ysq; + xden = (xden + Q[0][i]) * ysq; + } + + return y * (xnum + erf_P[0][3]) / (xden + Q[0][3]); + } + /** + * Approximates the complement of the error function erfc() for + * 0.46875 <= x <= 4.0 using this function: + * n + * erfc(x) = e^(-x^2) * sum (p_j * x^j) / (q_j * x^j) + * j=0 + */ + + + function erfc2(y) { + var xnum = erf_P[1][8] * y; + var xden = y; + var i; + + for (i = 0; i < 7; i += 1) { + xnum = (xnum + erf_P[1][i]) * y; + xden = (xden + Q[1][i]) * y; + } + + var result = (xnum + erf_P[1][7]) / (xden + Q[1][7]); + var ysq = parseInt(y * 16) / 16; + var del = (y - ysq) * (y + ysq); + return Math.exp(-ysq * ysq) * Math.exp(-del) * result; + } + /** + * Approximates the complement of the error function erfc() for x > 4.0 using + * this function: + * + * erfc(x) = (e^(-x^2) / x) * [ 1/sqrt(pi) + + * n + * 1/(x^2) * sum (p_j * x^(-2j)) / (q_j * x^(-2j)) ] + * j=0 + */ + + + function erfc3(y) { + var ysq = 1 / (y * y); + var xnum = erf_P[2][5] * ysq; + var xden = ysq; + var i; + + for (i = 0; i < 4; i += 1) { + xnum = (xnum + erf_P[2][i]) * ysq; + xden = (xden + Q[2][i]) * ysq; + } + + var result = ysq * (xnum + erf_P[2][4]) / (xden + Q[2][4]); + result = (SQRPI - result) / y; + ysq = parseInt(y * 16) / 16; + var del = (y - ysq) * (y + ysq); + return Math.exp(-ysq * ysq) * Math.exp(-del) * result; + } + + return erf; +}); +/** + * Upper bound for the first approximation interval, 0 <= x <= THRESH + * @constant + */ + +var THRESH = 0.46875; +/** + * Constant used by W. J. Cody's Fortran77 implementation to denote sqrt(pi) + * @constant + */ + +var SQRPI = 5.6418958354775628695e-1; +/** + * Coefficients for each term of the numerator sum (p_j) for each approximation + * interval (see W. J. Cody's paper for more details) + * @constant + */ + +var erf_P = [[3.16112374387056560e00, 1.13864154151050156e02, 3.77485237685302021e02, 3.20937758913846947e03, 1.85777706184603153e-1], [5.64188496988670089e-1, 8.88314979438837594e00, 6.61191906371416295e01, 2.98635138197400131e02, 8.81952221241769090e02, 1.71204761263407058e03, 2.05107837782607147e03, 1.23033935479799725e03, 2.15311535474403846e-8], [3.05326634961232344e-1, 3.60344899949804439e-1, 1.25781726111229246e-1, 1.60837851487422766e-2, 6.58749161529837803e-4, 1.63153871373020978e-2]]; +/** + * Coefficients for each term of the denominator sum (q_j) for each approximation + * interval (see W. J. Cody's paper for more details) + * @constant + */ + +var Q = [[2.36012909523441209e01, 2.44024637934444173e02, 1.28261652607737228e03, 2.84423683343917062e03], [1.57449261107098347e01, 1.17693950891312499e02, 5.37181101862009858e02, 1.62138957456669019e03, 3.29079923573345963e03, 4.36261909014324716e03, 3.43936767414372164e03, 1.23033935480374942e03], [2.56852019228982242e00, 1.87295284992346047e00, 5.27905102951428412e-1, 6.05183413124413191e-2, 2.33520497626869185e-3]]; +/** + * Maximum/minimum safe numbers to input to erf() (in ES6+, this number is + * Number.[MAX|MIN]_SAFE_INTEGER). erf() for all numbers beyond this limit will + * return 1 + */ + +var MAX_NUM = Math.pow(2, 53); +// CONCATENATED MODULE: ./src/function/statistics/mode.js + + +var mode_name = 'mode'; +var mode_dependencies = ['typed', 'isNaN', 'isNumeric']; +var createMode = /* #__PURE__ */Object(factory["a" /* factory */])(mode_name, mode_dependencies, function (_ref) { + var typed = _ref.typed, + isNaN = _ref.isNaN, + isNumeric = _ref.isNumeric; + + /** + * Computes the mode of a set of numbers or a list with values(numbers or characters). + * If there are more than one modes, it returns a list of those values. + * + * Syntax: + * + * math.mode(a, b, c, ...) + * math.mode(A) + * + * Examples: + * + * math.mode(2, 1, 4, 3, 1) // returns [1] + * math.mode([1, 2.7, 3.2, 4, 2.7]) // returns [2.7] + * math.mode(1, 4, 6, 1, 6) // returns [1, 6] + * math.mode('a','a','b','c') // returns ["a"] + * math.mode(1, 1.5, 'abc') // returns [1, 1.5, "abc"] + * + * See also: + * + * median, + * mean + * + * @param {... *} args A single matrix + * @return {*} The mode of all values + */ + return typed(mode_name, { + 'Array | Matrix': _mode, + '...': function _(args) { + return _mode(args); + } + }); + /** + * Calculates the mode in an 1-dimensional array + * @param {Array} values + * @return {Array} mode + * @private + */ + + function _mode(values) { + values = Object(utils_array["e" /* flatten */])(values.valueOf()); + var num = values.length; + + if (num === 0) { + throw new Error('Cannot calculate mode of an empty array'); + } + + var count = {}; + var mode = []; + var max = 0; + + for (var i = 0; i < values.length; i++) { + var value = values[i]; + + if (isNumeric(value) && isNaN(value)) { + throw new Error('Cannot calculate mode of an array containing NaN values'); + } + + if (!(value in count)) { + count[value] = 0; + } + + count[value]++; + + if (count[value] === max) { + mode.push(value); + } else if (count[value] > max) { + max = count[value]; + mode = [value]; + } + } + + return mode; + } +}); +// CONCATENATED MODULE: ./src/function/statistics/utils/improveErrorMessage.js + +/** + * Improve error messages for statistics functions. Errors are typically + * thrown in an internally used function like larger, causing the error + * not to mention the function (like max) which is actually used by the user. + * + * @param {Error} err + * @param {String} fnName + * @param {*} [value] + * @return {Error} + */ + +function improveErrorMessage(err, fnName, value) { + // TODO: add information with the index (also needs transform in expression parser) + var details; + + if (String(err).indexOf('Unexpected type') !== -1) { + details = arguments.length > 2 ? ' (type: ' + Object(is["M" /* typeOf */])(value) + ', value: ' + JSON.stringify(value) + ')' : ' (type: ' + err.data.actual + ')'; + return new TypeError('Cannot calculate ' + fnName + ', unexpected type of argument' + details); + } + + if (String(err).indexOf('complex numbers') !== -1) { + details = arguments.length > 2 ? ' (type: ' + Object(is["M" /* typeOf */])(value) + ', value: ' + JSON.stringify(value) + ')' : ''; + return new TypeError('Cannot calculate ' + fnName + ', no ordering relation is defined for complex numbers' + details); + } + + return err; +} +// CONCATENATED MODULE: ./src/function/statistics/prod.js + + + +var prod_name = 'prod'; +var prod_dependencies = ['typed', 'multiply']; +var createProd = /* #__PURE__ */Object(factory["a" /* factory */])(prod_name, prod_dependencies, function (_ref) { + var typed = _ref.typed, + multiply = _ref.multiply; + + /** + * Compute the product of a matrix or a list with values. + * In case of a (multi dimensional) array or matrix, the sum of all + * elements will be calculated. + * + * Syntax: + * + * math.prod(a, b, c, ...) + * math.prod(A) + * + * Examples: + * + * math.multiply(2, 3) // returns 6 + * math.prod(2, 3) // returns 6 + * math.prod(2, 3, 4) // returns 24 + * math.prod([2, 3, 4]) // returns 24 + * math.prod([[2, 5], [4, 3]]) // returns 120 + * + * See also: + * + * mean, median, min, max, sum, std, variance + * + * @param {... *} args A single matrix or or multiple scalar values + * @return {*} The product of all values + */ + return typed(prod_name, { + // prod([a, b, c, d, ...]) + 'Array | Matrix': _prod, + // prod([a, b, c, d, ...], dim) + 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) { + // TODO: implement prod(A, dim) + throw new Error('prod(A, dim) is not yet supported'); // return reduce(arguments[0], arguments[1], math.prod) + }, + // prod(a, b, c, d, ...) + '...': function _(args) { + return _prod(args); + } + }); + /** + * Recursively calculate the product of an n-dimensional array + * @param {Array} array + * @return {number} prod + * @private + */ + + function _prod(array) { + var prod; + deepForEach(array, function (value) { + try { + prod = prod === undefined ? value : multiply(prod, value); + } catch (err) { + throw improveErrorMessage(err, 'prod', value); + } + }); + + if (prod === undefined) { + throw new Error('Cannot calculate prod of an empty array'); + } + + return prod; + } +}); +// CONCATENATED MODULE: ./src/function/string/format.js + + +var format_name = 'format'; +var format_dependencies = ['typed']; +var createFormat = /* #__PURE__ */Object(factory["a" /* factory */])(format_name, format_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Format a value of any type into a string. + * + * Syntax: + * + * math.format(value) + * math.format(value, options) + * math.format(value, precision) + * math.format(value, callback) + * + * Where: + * + * - `value: *` + * The value to be formatted + * - `options: Object` + * An object with formatting options. Available options: + * - `notation: string` + * Number notation. Choose from: + * - 'fixed' + * Always use regular number notation. + * For example '123.40' and '14000000' + * - 'exponential' + * Always use exponential notation. + * For example '1.234e+2' and '1.4e+7' + * - 'engineering' + * Always use engineering notation: always have exponential notation, + * and select the exponent to be a multiple of 3. + * For example '123.4e+0' and '14.0e+6' + * - 'auto' (default) + * Regular number notation for numbers having an absolute value between + * `lower` and `upper` bounds, and uses exponential notation elsewhere. + * Lower bound is included, upper bound is excluded. + * For example '123.4' and '1.4e7'. + * - `precision: number` + * A number between 0 and 16 to round the digits of the number. In case + * of notations 'exponential', 'engineering', and 'auto', `precision` + * defines the total number of significant digits returned. + * In case of notation 'fixed', `precision` defines the number of + * significant digits after the decimal point. + * `precision` is undefined by default. + * - `lowerExp: number` + * Exponent determining the lower boundary for formatting a value with + * an exponent when `notation='auto`. Default value is `-3`. + * - `upperExp: number` + * Exponent determining the upper boundary for formatting a value with + * an exponent when `notation='auto`. Default value is `5`. + * - `fraction: string`. Available values: 'ratio' (default) or 'decimal'. + * For example `format(fraction(1, 3))` will output '1/3' when 'ratio' is + * configured, and will output `0.(3)` when 'decimal' is configured. + * - `callback: function` + * A custom formatting function, invoked for all numeric elements in `value`, + * for example all elements of a matrix, or the real and imaginary + * parts of a complex number. This callback can be used to override the + * built-in numeric notation with any type of formatting. Function `callback` + * is called with `value` as parameter and must return a string. + * + * When `value` is an Object: + * + * - When the object contains a property `format` being a function, this function + * is invoked as `value.format(options)` and the result is returned. + * - When the object has its own `toString` method, this method is invoked + * and the result is returned. + * - In other cases the function will loop over all object properties and + * return JSON object notation like '{"a": 2, "b": 3}'. + * + * When value is a function: + * + * - When the function has a property `syntax`, it returns this + * syntax description. + * - In other cases, a string `'function'` is returned. + * + * Examples: + * + * math.format(6.4) // returns '6.4' + * math.format(1240000) // returns '1.24e6' + * math.format(1/3) // returns '0.3333333333333333' + * math.format(1/3, 3) // returns '0.333' + * math.format(21385, 2) // returns '21000' + * math.format(12e8, {notation: 'fixed'}) // returns '1200000000' + * math.format(2.3, {notation: 'fixed', precision: 4}) // returns '2.3000' + * math.format(52.8, {notation: 'exponential'}) // returns '5.28e+1' + * math.format(12400,{notation: 'engineering'}) // returns '12.400e+3' + * math.format(2000, {lowerExp: -2, upperExp: 2}) // returns '2e+3' + * + * function formatCurrency(value) { + * // return currency notation with two digits: + * return '$' + value.toFixed(2) + * + * // you could also use math.format inside the callback: + * // return '$' + math.format(value, {notation: 'fixed', precision: 2}) + * } + * math.format([2.1, 3, 0.016], formatCurrency} // returns '[$2.10, $3.00, $0.02]' + * + * See also: + * + * print + * + * @param {*} value Value to be stringified + * @param {Object | Function | number} [options] Formatting options + * @return {string} The formatted value + */ + return typed(format_name, { + any: utils_string["d" /* format */], + 'any, Object | function | number': utils_string["d" /* format */] + }); +}); +// CONCATENATED MODULE: ./src/function/string/print.js + + + +var print_name = 'print'; +var print_dependencies = ['typed']; +var createPrint = /* #__PURE__ */Object(factory["a" /* factory */])(print_name, print_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Interpolate values into a string template. + * + * Syntax: + * + * math.print(template, values) + * math.print(template, values, precision) + * math.print(template, values, options) + * + * Example usage: + * + * // the following outputs: 'Lucy is 5 years old' + * math.print('Lucy is $age years old', {age: 5}) + * + * // the following outputs: 'The value of pi is 3.141592654' + * math.print('The value of pi is $pi', {pi: math.pi}, 10) + * + * // the following outputs: 'hello Mary! The date is 2013-03-23' + * math.print('Hello $user.name! The date is $date', { + * user: { + * name: 'Mary', + * }, + * date: new Date(2013, 2, 23).toISOString().substring(0, 10) + * }) + * + * // the following outputs: 'My favorite fruits are apples and bananas !' + * math.print('My favorite fruits are $0 and $1 !', [ + * 'apples', + * 'bananas' + * ]) + * + * See also: + * + * format + * + * @param {string} template A string containing variable placeholders. + * @param {Object | Array | Matrix} values An object or array containing variables + * which will be filled in in the template. + * @param {number | Object} [options] Formatting options, + * or the number of digits to format numbers. + * See function math.format for a description + * of all options. + * @return {string} Interpolated string + */ + return typed(print_name, { + // note: Matrix will be converted automatically to an Array + 'string, Object | Array': _print, + 'string, Object | Array, number | Object': _print + }); +}); +/** + * Interpolate values into a string template. + * @param {string} template + * @param {Object} values + * @param {number | Object} [options] + * @returns {string} Interpolated string + * @private + */ + +function _print(template, values, options) { + return template.replace(/\$([\w.]+)/g, function (original, key) { + var keys = key.split('.'); + var value = values[keys.shift()]; + + while (keys.length && value !== undefined) { + var k = keys.shift(); + value = k ? value[k] : value + '.'; + } + + if (value !== undefined) { + if (!Object(is["I" /* isString */])(value)) { + return Object(utils_string["d" /* format */])(value, options); + } else { + return value; + } + } + + return original; + }); +} +// CONCATENATED MODULE: ./src/function/unit/to.js + + + +var to_name = 'to'; +var to_dependencies = ['typed', 'matrix']; +var createTo = /* #__PURE__ */Object(factory["a" /* factory */])(to_name, to_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Change the unit of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.to(x, unit) + * + * Examples: + * + * math.to(math.unit('2 inch'), 'cm') // returns Unit 5.08 cm + * math.to(math.unit('2 inch'), math.unit(null, 'cm')) // returns Unit 5.08 cm + * math.to(math.unit(16, 'bytes'), 'bits') // returns Unit 128 bits + * + * See also: + * + * unit + * + * @param {Unit | Array | Matrix} x The unit to be converted. + * @param {Unit | Array | Matrix} unit New unit. Can be a string like "cm" + * or a unit without value. + * @return {Unit | Array | Matrix} value with changed, fixed unit. + */ + + var to = typed(to_name, { + 'Unit, Unit | string': function UnitUnitString(x, unit) { + return x.to(unit); + }, + 'Matrix, Matrix': function MatrixMatrix(x, y) { + // SparseMatrix does not support Units + return algorithm13(x, y, to); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return to(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return to(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return to(x, matrix(y)); + }, + 'Matrix, any': function MatrixAny(x, y) { + // SparseMatrix does not support Units + return algorithm14(x, y, to, false); + }, + 'any, Matrix': function anyMatrix(x, y) { + // SparseMatrix does not support Units + return algorithm14(y, x, to, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, to, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, to, true).valueOf(); + } + }); + return to; +}); +// CONCATENATED MODULE: ./src/function/utils/isPrime.js + + +var isPrime_name = 'isPrime'; +var isPrime_dependencies = ['typed']; +var createIsPrime = /* #__PURE__ */Object(factory["a" /* factory */])(isPrime_name, isPrime_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is prime: has no divisors other than itself and one. + * The function supports type `number`, `bignumber`. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isPrime(x) + * + * Examples: + * + * math.isPrime(3) // returns true + * math.isPrime(-2) // returns false + * math.isPrime(0) // returns false + * math.isPrime(-0) // returns false + * math.isPrime(0.5) // returns false + * math.isPrime('2') // returns true + * math.isPrime([2, 17, 100]) // returns [true, true, false] + * + * See also: + * + * isNumeric, isZero, isNegative, isInteger + * + * @param {number | BigNumber | Array | Matrix} x Value to be tested + * @return {boolean} Returns true when `x` is larger than zero. + * Throws an error in case of an unknown data type. + */ + var isPrime = typed(isPrime_name, { + number: function number(x) { + if (x * 0 !== 0) { + return false; + } + + if (x <= 3) { + return x > 1; + } + + if (x % 2 === 0 || x % 3 === 0) { + return false; + } + + for (var i = 5; i * i <= x; i += 6) { + if (x % i === 0 || x % (i + 2) === 0) { + return false; + } + } + + return true; + }, + BigNumber: function BigNumber(n) { + if (n.toNumber() * 0 !== 0) { + return false; + } + + if (n.lte(3)) return n.gt(1); + if (n.mod(2).eq(0) || n.mod(3).eq(0)) return false; + + for (var i = 5; n.gte(i * i); i += 6) { + if (n.mod(i).eq(0) || n.mod(i + 2).eq(0)) { + return false; + } + } + + return true; + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, isPrime); + } + }); + return isPrime; +}); +// CONCATENATED MODULE: ./src/function/utils/numeric.js + + + +var numeric_name = 'numeric'; +var numeric_dependencies = ['number', '?bignumber', '?fraction']; +var createNumeric = /* #__PURE__ */Object(factory["a" /* factory */])(numeric_name, numeric_dependencies, function (_ref) { + var _number = _ref.number, + bignumber = _ref.bignumber, + fraction = _ref.fraction; + var validInputTypes = { + string: true, + number: true, + BigNumber: true, + Fraction: true + }; // Load the conversion functions for each output type + + var validOutputTypes = { + number: function number(x) { + return _number(x); + }, + BigNumber: bignumber ? function (x) { + return bignumber(x); + } : noBignumber, + Fraction: fraction ? function (x) { + return fraction(x); + } : noFraction + }; + /** + * Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction. + * + * Syntax: + * + * math.numeric(x) + * + * Examples: + * + * math.numeric('4') // returns number 4 + * math.numeric('4', 'number') // returns number 4 + * math.numeric('4', 'BigNumber') // returns BigNumber 4 + * math.numeric('4', 'Fraction') // returns Fraction 4 + * math.numeric(4, 'Fraction') // returns Fraction 4 + * math.numeric(math.fraction(2, 5), 'number') // returns number 0.4 + * + * See also: + * + * number, fraction, bignumber, string, format + * + * @param {string | number | BigNumber | Fraction } value + * A numeric value or a string containing a numeric value + * @param {string} outputType + * Desired numeric output type. + * Available values: 'number', 'BigNumber', or 'Fraction' + * @return {number | BigNumber | Fraction} + * Returns an instance of the numeric in the requested type + */ + + return function numeric(value, outputType) { + var inputType = Object(is["M" /* typeOf */])(value); + + if (!(inputType in validInputTypes)) { + throw new TypeError('Cannot convert ' + value + ' of type "' + inputType + '"; valid input types are ' + Object.keys(validInputTypes).join(', ')); + } + + if (!(outputType in validOutputTypes)) { + throw new TypeError('Cannot convert ' + value + ' to type "' + outputType + '"; valid output types are ' + Object.keys(validOutputTypes).join(', ')); + } + + if (outputType === inputType) { + return value; + } else { + return validOutputTypes[outputType](value); + } + }; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/divideScalar.js + + +var divideScalar_name = 'divideScalar'; +var divideScalar_dependencies = ['typed', 'numeric']; +var createDivideScalar = /* #__PURE__ */Object(factory["a" /* factory */])(divideScalar_name, divideScalar_dependencies, function (_ref) { + var typed = _ref.typed, + numeric = _ref.numeric; + + /** + * Divide two scalar values, `x / y`. + * This function is meant for internal use: it is used by the public functions + * `divide` and `inv`. + * + * This function does not support collections (Array or Matrix). + * + * @param {number | BigNumber | Fraction | Complex | Unit} x Numerator + * @param {number | BigNumber | Fraction | Complex} y Denominator + * @return {number | BigNumber | Fraction | Complex | Unit} Quotient, `x / y` + * @private + */ + var divideScalar = typed(divideScalar_name, { + 'number, number': function numberNumber(x, y) { + return x / y; + }, + 'Complex, Complex': function ComplexComplex(x, y) { + return x.div(y); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.div(y); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.div(y); + }, + 'Unit, number | Fraction | BigNumber': function UnitNumberFractionBigNumber(x, y) { + var res = x.clone(); // TODO: move the divide function to Unit.js, it uses internals of Unit + + var one = numeric(1, Object(is["M" /* typeOf */])(y)); + res.value = divideScalar(res.value === null ? res._normalize(one) : res.value, y); + return res; + }, + 'number | Fraction | BigNumber, Unit': function numberFractionBigNumberUnit(x, y) { + var res = y.clone(); + res = res.pow(-1); // TODO: move the divide function to Unit.js, it uses internals of Unit + + var one = numeric(1, Object(is["M" /* typeOf */])(x)); + res.value = divideScalar(x, y.value === null ? y._normalize(one) : y.value); + return res; + }, + 'Unit, Unit': function UnitUnit(x, y) { + return x.divide(y); + } + }); + return divideScalar; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/pow.js + + + + +var pow_name = 'pow'; +var pow_dependencies = ['typed', 'config', 'identity', 'multiply', 'matrix', 'fraction', 'number', 'Complex']; +var createPow = /* #__PURE__ */Object(factory["a" /* factory */])(pow_name, pow_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + identity = _ref.identity, + multiply = _ref.multiply, + matrix = _ref.matrix, + number = _ref.number, + fraction = _ref.fraction, + Complex = _ref.Complex; + + /** + * Calculates the power of x to y, `x ^ y`. + * Matrix exponentiation is supported for square matrices `x`, and positive + * integer exponents `y`. + * + * For cubic roots of negative numbers, the function returns the principal + * root by default. In order to let the function return the real root, + * math.js can be configured with `math.config({predictable: true})`. + * To retrieve all cubic roots of a value, use `math.cbrt(x, true)`. + * + * Syntax: + * + * math.pow(x, y) + * + * Examples: + * + * math.pow(2, 3) // returns number 8 + * + * const a = math.complex(2, 3) + * math.pow(a, 2) // returns Complex -5 + 12i + * + * const b = [[1, 2], [4, 3]] + * math.pow(b, 2) // returns Array [[9, 8], [16, 17]] + * + * See also: + * + * multiply, sqrt, cbrt, nthRoot + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x The base + * @param {number | BigNumber | Complex} y The exponent + * @return {number | BigNumber | Complex | Array | Matrix} The value of `x` to the power `y` + */ + return typed(pow_name, { + 'number, number': _pow, + 'Complex, Complex': function ComplexComplex(x, y) { + return x.pow(y); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + if (y.isInteger() || x >= 0 || config.predictable) { + return x.pow(y); + } else { + return new Complex(x.toNumber(), 0).pow(y.toNumber(), 0); + } + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + if (y.d !== 1) { + if (config.predictable) { + throw new Error('Function pow does not support non-integer exponents for fractions.'); + } else { + return _pow(x.valueOf(), y.valueOf()); + } + } else { + return x.pow(y); + } + }, + 'Array, number': _powArray, + 'Array, BigNumber': function ArrayBigNumber(x, y) { + return _powArray(x, y.toNumber()); + }, + 'Matrix, number': _powMatrix, + 'Matrix, BigNumber': function MatrixBigNumber(x, y) { + return _powMatrix(x, y.toNumber()); + }, + 'Unit, number | BigNumber': function UnitNumberBigNumber(x, y) { + return x.pow(y); + } + }); + /** + * Calculates the power of x to y, x^y, for two numbers. + * @param {number} x + * @param {number} y + * @return {number | Complex} res + * @private + */ + + function _pow(x, y) { + // Alternatively could define a 'realmode' config option or something, but + // 'predictable' will work for now + if (config.predictable && !Object(utils_number["i" /* isInteger */])(y) && x < 0) { + // Check to see if y can be represented as a fraction + try { + var yFrac = fraction(y); + var yNum = number(yFrac); + + if (y === yNum || Math.abs((y - yNum) / y) < 1e-14) { + if (yFrac.d % 2 === 1) { + return (yFrac.n % 2 === 0 ? 1 : -1) * Math.pow(-x, y); + } + } + } catch (ex) {} // fraction() throws an error if y is Infinity, etc. + // Unable to express y as a fraction, so continue on + + } // **for predictable mode** x^Infinity === NaN if x < -1 + // N.B. this behavour is different from `Math.pow` which gives + // (-2)^Infinity === Infinity + + + if (config.predictable && (x < -1 && y === Infinity || x > -1 && x < 0 && y === -Infinity)) { + return NaN; + } + + if (Object(utils_number["i" /* isInteger */])(y) || x >= 0 || config.predictable) { + return powNumber(x, y); + } else { + // TODO: the following infinity checks are duplicated from powNumber. Deduplicate this somehow + // x^Infinity === 0 if -1 < x < 1 + // A real number 0 is returned instead of complex(0) + if (x * x < 1 && y === Infinity || x * x > 1 && y === -Infinity) { + return 0; + } + + return new Complex(x, 0).pow(y, 0); + } + } + /** + * Calculate the power of a 2d array + * @param {Array} x must be a 2 dimensional, square matrix + * @param {number} y a positive, integer value + * @returns {Array} + * @private + */ + + + function _powArray(x, y) { + if (!Object(utils_number["i" /* isInteger */])(y) || y < 0) { + throw new TypeError('For A^b, b must be a positive integer (value is ' + y + ')'); + } // verify that A is a 2 dimensional square matrix + + + var s = Object(utils_array["a" /* arraySize */])(x); + + if (s.length !== 2) { + throw new Error('For A^b, A must be 2 dimensional (A has ' + s.length + ' dimensions)'); + } + + if (s[0] !== s[1]) { + throw new Error('For A^b, A must be square (size is ' + s[0] + 'x' + s[1] + ')'); + } + + var res = identity(s[0]).valueOf(); + var px = x; + + while (y >= 1) { + if ((y & 1) === 1) { + res = multiply(px, res); + } + + y >>= 1; + px = multiply(px, px); + } + + return res; + } + /** + * Calculate the power of a 2d matrix + * @param {Matrix} x must be a 2 dimensional, square matrix + * @param {number} y a positive, integer value + * @returns {Matrix} + * @private + */ + + + function _powMatrix(x, y) { + return matrix(_powArray(x.valueOf(), y)); + } +}); +// CONCATENATED MODULE: ./src/function/arithmetic/round.js +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + + + + + + + +var NO_INT = 'Number of decimals in function round must be an integer'; +var round_name = 'round'; +var round_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'BigNumber', 'DenseMatrix']; +var createRound = /* #__PURE__ */Object(factory["a" /* factory */])(round_name, round_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + zeros = _ref.zeros, + BigNumber = _ref.BigNumber, + DenseMatrix = _ref.DenseMatrix; + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Round a value towards the nearest integer. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.round(x) + * math.round(x, n) + * + * Examples: + * + * math.round(3.2) // returns number 3 + * math.round(3.8) // returns number 4 + * math.round(-4.2) // returns number -4 + * math.round(-4.7) // returns number -5 + * math.round(math.pi, 3) // returns number 3.142 + * math.round(123.45678, 2) // returns number 123.46 + * + * const c = math.complex(3.2, -2.7) + * math.round(c) // returns Complex 3 - 3i + * + * math.round([3.2, 3.8, -4.7]) // returns Array [3, 4, -5] + * + * See also: + * + * ceil, fix, floor + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded + * @param {number | BigNumber | Array} [n=0] Number of decimals + * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value + */ + + var round = typed(round_name, _objectSpread(_objectSpread({}, roundNumberSignatures), {}, { + Complex: function Complex(x) { + return x.round(); + }, + 'Complex, number': function ComplexNumber(x, n) { + if (n % 1) { + throw new TypeError(NO_INT); + } + + return x.round(n); + }, + 'Complex, BigNumber': function ComplexBigNumber(x, n) { + if (!n.isInteger()) { + throw new TypeError(NO_INT); + } + + var _n = n.toNumber(); + + return x.round(_n); + }, + 'number, BigNumber': function numberBigNumber(x, n) { + if (!n.isInteger()) { + throw new TypeError(NO_INT); + } + + return new BigNumber(x).toDecimalPlaces(n.toNumber()); + }, + BigNumber: function BigNumber(x) { + return x.toDecimalPlaces(0); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, n) { + if (!n.isInteger()) { + throw new TypeError(NO_INT); + } + + return x.toDecimalPlaces(n.toNumber()); + }, + Fraction: function Fraction(x) { + return x.round(); + }, + 'Fraction, number': function FractionNumber(x, n) { + if (n % 1) { + throw new TypeError(NO_INT); + } + + return x.round(n); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since round(0) = 0 + return deepMap(x, round, true); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + return algorithm11(x, y, round, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + return algorithm14(x, y, round, false); + }, + 'number | Complex | BigNumber, SparseMatrix': function numberComplexBigNumberSparseMatrix(x, y) { + // check scalar is zero + if (equalScalar(x, 0)) { + // do not execute algorithm, result will be a zero matrix + return zeros(y.size(), y.storage()); + } + + return algorithm12(y, x, round, true); + }, + 'number | Complex | BigNumber, DenseMatrix': function numberComplexBigNumberDenseMatrix(x, y) { + // check scalar is zero + if (equalScalar(x, 0)) { + // do not execute algorithm, result will be a zero matrix + return zeros(y.size(), y.storage()); + } + + return algorithm14(y, x, round, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, round, false).valueOf(); + }, + 'number | Complex | BigNumber, Array': function numberComplexBigNumberArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, round, true).valueOf(); + } + })); + return round; +}); +var roundNumberSignatures = { + number: roundNumber, + 'number, number': function numberNumber(x, n) { + if (!Object(utils_number["i" /* isInteger */])(n)) { + throw new TypeError(NO_INT); + } + + if (n < 0 || n > 15) { + throw new Error('Number of decimals in function round must be in te range of 0-15'); + } + + return roundNumber(x, n); + } +}; +var createRoundNumber = /* #__PURE__ */Object(factory["a" /* factory */])(round_name, ['typed'], function (_ref2) { + var typed = _ref2.typed; + return typed(round_name, roundNumberSignatures); +}); +// CONCATENATED MODULE: ./src/function/arithmetic/log.js + + + +var log_name = 'log'; +var log_dependencies = ['config', 'typed', 'divideScalar', 'Complex']; +var createLog = /* #__PURE__ */Object(factory["a" /* factory */])(log_name, log_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + divideScalar = _ref.divideScalar, + Complex = _ref.Complex; + + /** + * Calculate the logarithm of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.log(x) + * math.log(x, base) + * + * Examples: + * + * math.log(3.5) // returns 1.252762968495368 + * math.exp(math.log(2.4)) // returns 2.4 + * + * math.pow(10, 4) // returns 10000 + * math.log(10000, 10) // returns 4 + * math.log(10000) / math.log(10) // returns 4 + * + * math.log(1024, 2) // returns 10 + * math.pow(2, 10) // returns 1024 + * + * See also: + * + * exp, log2, log10, log1p + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * Value for which to calculate the logarithm. + * @param {number | BigNumber | Complex} [base=e] + * Optional base for the logarithm. If not provided, the natural + * logarithm of `x` is calculated. + * @return {number | BigNumber | Complex | Array | Matrix} + * Returns the logarithm of `x` + */ + var log = typed(log_name, { + number: function number(x) { + if (x >= 0 || config.predictable) { + return logNumber(x); + } else { + // negative value -> complex value computation + return new Complex(x, 0).log(); + } + }, + Complex: function Complex(x) { + return x.log(); + }, + BigNumber: function BigNumber(x) { + if (!x.isNegative() || config.predictable) { + return x.ln(); + } else { + // downgrade to number, return Complex valued result + return new Complex(x.toNumber(), 0).log(); + } + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, log); + }, + 'any, any': function anyAny(x, base) { + // calculate logarithm for a specified base, log(x, base) + return divideScalar(log(x), log(base)); + } + }); + return log; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/log1p.js + + + +var log1p_name = 'log1p'; +var log1p_dependencies = ['typed', 'config', 'divideScalar', 'log', 'Complex']; +var createLog1p = /* #__PURE__ */Object(factory["a" /* factory */])(log1p_name, log1p_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + divideScalar = _ref.divideScalar, + log = _ref.log, + Complex = _ref.Complex; + + /** + * Calculate the logarithm of a `value+1`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.log1p(x) + * math.log1p(x, base) + * + * Examples: + * + * math.log1p(2.5) // returns 1.252762968495368 + * math.exp(math.log1p(1.4)) // returns 2.4 + * + * math.pow(10, 4) // returns 10000 + * math.log1p(9999, 10) // returns 4 + * math.log1p(9999) / math.log(10) // returns 4 + * + * See also: + * + * exp, log, log2, log10 + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * Value for which to calculate the logarithm of `x+1`. + * @param {number | BigNumber | Complex} [base=e] + * Optional base for the logarithm. If not provided, the natural + * logarithm of `x+1` is calculated. + * @return {number | BigNumber | Complex | Array | Matrix} + * Returns the logarithm of `x+1` + */ + var log1p = typed(log1p_name, { + number: function number(x) { + if (x >= -1 || config.predictable) { + return Object(utils_number["k" /* log1p */])(x); + } else { + // negative value -> complex value computation + return _log1pComplex(new Complex(x, 0)); + } + }, + Complex: _log1pComplex, + BigNumber: function BigNumber(x) { + var y = x.plus(1); + + if (!y.isNegative() || config.predictable) { + return y.ln(); + } else { + // downgrade to number, return Complex valued result + return _log1pComplex(new Complex(x.toNumber(), 0)); + } + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, log1p); + }, + 'any, any': function anyAny(x, base) { + // calculate logarithm for a specified base, log1p(x, base) + return divideScalar(log1p(x), log(base)); + } + }); + /** + * Calculate the natural logarithm of a complex number + 1 + * @param {Complex} x + * @returns {Complex} + * @private + */ + + function _log1pComplex(x) { + var xRe1p = x.re + 1; + return new Complex(Math.log(Math.sqrt(xRe1p * xRe1p + x.im * x.im)), Math.atan2(x.im, xRe1p)); + } + + return log1p; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/nthRoots.js + +var nthRoots_name = 'nthRoots'; +var nthRoots_dependencies = ['config', 'typed', 'divideScalar', 'Complex']; +var createNthRoots = /* #__PURE__ */Object(factory["a" /* factory */])(nthRoots_name, nthRoots_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + divideScalar = _ref.divideScalar, + Complex = _ref.Complex; + + /** + * Calculate the nth roots of a value. + * An nth root of a positive real number A, + * is a positive real solution of the equation "x^root = A". + * This function returns an array of complex values. + * + * Syntax: + * + * math.nthRoots(x) + * math.nthRoots(x, root) + * + * Examples: + * + * math.nthRoots(1) + * // returns [ + * // {re: 1, im: 0}, + * // {re: -1, im: 0} + * // ] + * nthRoots(1, 3) + * // returns [ + * // { re: 1, im: 0 }, + * // { re: -0.4999999999999998, im: 0.8660254037844387 }, + * // { re: -0.5000000000000004, im: -0.8660254037844385 } + * ] + * + * See also: + * + * nthRoot, pow, sqrt + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded + * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value + */ + var nthRoots = typed(nthRoots_name, { + Complex: function Complex(x) { + return _nthComplexRoots(x, 2); + }, + 'Complex, number': _nthComplexRoots + }); + /** + * Each function here returns a real multiple of i as a Complex value. + * @param {number} val + * @return {Complex} val, i*val, -val or -i*val for index 0, 1, 2, 3 + */ + // This is used to fix float artifacts for zero-valued components. + + var _calculateExactResult = [function realPos(val) { + return new Complex(val, 0); + }, function imagPos(val) { + return new Complex(0, val); + }, function realNeg(val) { + return new Complex(-val, 0); + }, function imagNeg(val) { + return new Complex(0, -val); + }]; + /** + * Calculate the nth root of a Complex Number a using De Movire's Theorem. + * @param {Complex} a + * @param {number} root + * @return {Array} array of n Complex Roots + */ + + function _nthComplexRoots(a, root) { + if (root < 0) throw new Error('Root must be greater than zero'); + if (root === 0) throw new Error('Root must be non-zero'); + if (root % 1 !== 0) throw new Error('Root must be an integer'); + if (a === 0 || a.abs() === 0) return [new Complex(0, 0)]; + var aIsNumeric = typeof a === 'number'; + var offset; // determine the offset (argument of a)/(pi/2) + + if (aIsNumeric || a.re === 0 || a.im === 0) { + if (aIsNumeric) { + offset = 2 * +(a < 0); // numeric value on the real axis + } else if (a.im === 0) { + offset = 2 * +(a.re < 0); // complex value on the real axis + } else { + offset = 2 * +(a.im < 0) + 1; // complex value on the imaginary axis + } + } + + var arg = a.arg(); + var abs = a.abs(); + var roots = []; + var r = Math.pow(abs, 1 / root); + + for (var k = 0; k < root; k++) { + var halfPiFactor = (offset + 4 * k) / root; + /** + * If (offset + 4*k)/root is an integral multiple of pi/2 + * then we can produce a more exact result. + */ + + if (halfPiFactor === Math.round(halfPiFactor)) { + roots.push(_calculateExactResult[halfPiFactor % 4](r)); + continue; + } + + roots.push(new Complex({ + r: r, + phi: (arg + 2 * Math.PI * k) / root + })); + } + + return roots; + } + + return nthRoots; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/dotPow.js + + + + + + + +var dotPow_name = 'dotPow'; +var dotPow_dependencies = ['typed', 'equalScalar', 'matrix', 'pow', 'DenseMatrix']; +var createDotPow = /* #__PURE__ */Object(factory["a" /* factory */])(dotPow_name, dotPow_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar, + matrix = _ref.matrix, + pow = _ref.pow, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Calculates the power of x to y element wise. + * + * Syntax: + * + * math.dotPow(x, y) + * + * Examples: + * + * math.dotPow(2, 3) // returns number 8 + * + * const a = [[1, 2], [4, 3]] + * math.dotPow(a, 2) // returns Array [[1, 4], [16, 9]] + * math.pow(a, 2) // returns Array [[9, 8], [16, 17]] + * + * See also: + * + * pow, sqrt, multiply + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x The base + * @param {number | BigNumber | Complex | Unit | Array | Matrix} y The exponent + * @return {number | BigNumber | Complex | Unit | Array | Matrix} The value of `x` to the power `y` + */ + + var dotPow = typed(dotPow_name, { + 'any, any': pow, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, pow, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, pow, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, pow, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, pow); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return dotPow(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return dotPow(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return dotPow(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, dotPow, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, dotPow, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, dotPow, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, dotPow, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, dotPow, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, dotPow, true).valueOf(); + } + }); + return dotPow; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/dotDivide.js + + + + + + + + +var dotDivide_name = 'dotDivide'; +var dotDivide_dependencies = ['typed', 'matrix', 'equalScalar', 'divideScalar', 'DenseMatrix']; +var createDotDivide = /* #__PURE__ */Object(factory["a" /* factory */])(dotDivide_name, dotDivide_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + divideScalar = _ref.divideScalar, + DenseMatrix = _ref.DenseMatrix; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Divide two matrices element wise. The function accepts both matrices and + * scalar values. + * + * Syntax: + * + * math.dotDivide(x, y) + * + * Examples: + * + * math.dotDivide(2, 4) // returns 0.5 + * + * a = [[9, 5], [6, 1]] + * b = [[3, 2], [5, 2]] + * + * math.dotDivide(a, b) // returns [[3, 2.5], [1.2, 0.5]] + * math.divide(a, b) // returns [[1.75, 0.75], [-1.75, 2.25]] + * + * See also: + * + * divide, multiply, dotMultiply + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Denominator + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Quotient, `x ./ y` + */ + + var dotDivide = typed(dotDivide_name, { + 'any, any': divideScalar, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, divideScalar, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, divideScalar, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, divideScalar, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, divideScalar); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return dotDivide(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return dotDivide(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return dotDivide(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, divideScalar, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, divideScalar, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, divideScalar, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, divideScalar, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, divideScalar, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, divideScalar, true).valueOf(); + } + }); + return dotDivide; +}); +// CONCATENATED MODULE: ./src/function/algebra/solver/utils/solveValidation.js + + + +function createSolveValidation(_ref) { + var DenseMatrix = _ref.DenseMatrix; + + /** + * Validates matrix and column vector b for backward/forward substitution algorithms. + * + * @param {Matrix} m An N x N matrix + * @param {Array | Matrix} b A column vector + * @param {Boolean} copy Return a copy of vector b + * + * @return {DenseMatrix} Dense column vector b + */ + return function solveValidation(m, b, copy) { + // matrix size + var size = m.size(); // validate matrix dimensions + + if (size.length !== 2) { + throw new RangeError('Matrix must be two dimensional (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } // rows & columns + + + var rows = size[0]; + var columns = size[1]; // validate rows & columns + + if (rows !== columns) { + throw new RangeError('Matrix must be square (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } // vars + + + var data, i, bdata; // check b is matrix + + if (Object(is["v" /* isMatrix */])(b)) { + // matrix size + var msize = b.size(); // vector + + if (msize.length === 1) { + // check vector length + if (msize[0] !== rows) { + throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); + } // create data array + + + data = []; // matrix data (DenseMatrix) + + bdata = b._data; // loop b data + + for (i = 0; i < rows; i++) { + // row array + data[i] = [bdata[i]]; + } // return Dense Matrix + + + return new DenseMatrix({ + data: data, + size: [rows, 1], + datatype: b._datatype + }); + } // two dimensions + + + if (msize.length === 2) { + // array must be a column vector + if (msize[0] !== rows || msize[1] !== 1) { + throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); + } // check matrix type + + + if (Object(is["n" /* isDenseMatrix */])(b)) { + // check a copy is needed + if (copy) { + // create data array + data = []; // matrix data (DenseMatrix) + + bdata = b._data; // loop b data + + for (i = 0; i < rows; i++) { + // row array + data[i] = [bdata[i][0]]; + } // return Dense Matrix + + + return new DenseMatrix({ + data: data, + size: [rows, 1], + datatype: b._datatype + }); + } // b is already a column vector + + + return b; + } // create data array + + + data = []; + + for (i = 0; i < rows; i++) { + data[i] = [0]; + } // sparse matrix arrays + + + var values = b._values; + var index = b._index; + var ptr = b._ptr; // loop values in column 0 + + for (var k1 = ptr[1], k = ptr[0]; k < k1; k++) { + // row + i = index[k]; // add to data + + data[i][0] = values[k]; + } // return Dense Matrix + + + return new DenseMatrix({ + data: data, + size: [rows, 1], + datatype: b._datatype + }); + } // throw error + + + throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); + } // check b is array + + + if (Object(is["b" /* isArray */])(b)) { + // size + var asize = Object(utils_array["a" /* arraySize */])(b); // check matrix dimensions, vector + + if (asize.length === 1) { + // check vector length + if (asize[0] !== rows) { + throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); + } // create data array + + + data = []; // loop b + + for (i = 0; i < rows; i++) { + // row array + data[i] = [b[i]]; + } // return Dense Matrix + + + return new DenseMatrix({ + data: data, + size: [rows, 1] + }); + } + + if (asize.length === 2) { + // array must be a column vector + if (asize[0] !== rows || asize[1] !== 1) { + throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); + } // create data array + + + data = []; // loop b data + + for (i = 0; i < rows; i++) { + // row array + data[i] = [b[i][0]]; + } // return Dense Matrix + + + return new DenseMatrix({ + data: data, + size: [rows, 1] + }); + } // throw error + + + throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); + } + }; +} +// CONCATENATED MODULE: ./src/function/algebra/solver/lsolve.js + + +var lsolve_name = 'lsolve'; +var lsolve_dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtract', 'equalScalar', 'DenseMatrix']; +var createLsolve = /* #__PURE__ */Object(factory["a" /* factory */])(lsolve_name, lsolve_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + divideScalar = _ref.divideScalar, + multiplyScalar = _ref.multiplyScalar, + subtract = _ref.subtract, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix; + var solveValidation = createSolveValidation({ + DenseMatrix: DenseMatrix + }); + /** + * Solves the linear equation system by forwards substitution. Matrix must be a lower triangular matrix. + * + * `L * x = b` + * + * Syntax: + * + * math.lsolve(L, b) + * + * Examples: + * + * const a = [[-2, 3], [2, 1]] + * const b = [11, 9] + * const x = lsolve(a, b) // [[-5.5], [20]] + * + * See also: + * + * lup, slu, usolve, lusolve + * + * @param {Matrix, Array} L A N x N matrix or array (L) + * @param {Matrix, Array} b A column vector with the b values + * + * @return {DenseMatrix | Array} A column vector with the linear system solution (x) + */ + + return typed(lsolve_name, { + 'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(m, b) { + // process matrix + return _sparseForwardSubstitution(m, b); + }, + 'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(m, b) { + // process matrix + return _denseForwardSubstitution(m, b); + }, + 'Array, Array | Matrix': function ArrayArrayMatrix(a, b) { + // create dense matrix from array + var m = matrix(a); // use matrix implementation + + var r = _denseForwardSubstitution(m, b); // result + + + return r.valueOf(); + } + }); + + function _denseForwardSubstitution(m, b) { + // validate matrix and vector, return copy of column vector b + b = solveValidation(m, b, true); // column vector data + + var bdata = b._data; // rows & columns + + var rows = m._size[0]; + var columns = m._size[1]; // result + + var x = []; // data + + var data = m._data; // forward solve m * x = b, loop columns + + for (var j = 0; j < columns; j++) { + // b[j] + var bj = bdata[j][0] || 0; // x[j] + + var xj = void 0; // forward substitution (outer product) avoids inner looping when bj === 0 + + if (!equalScalar(bj, 0)) { + // value @ [j, j] + var vjj = data[j][j]; // check vjj + + if (equalScalar(vjj, 0)) { + // system cannot be solved + throw new Error('Linear system cannot be solved since matrix is singular'); + } // calculate xj + + + xj = divideScalar(bj, vjj); // loop rows + + for (var i = j + 1; i < rows; i++) { + // update copy of b + bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, data[i][j]))]; + } + } else { + // zero @ j + xj = 0; + } // update x + + + x[j] = [xj]; + } // return vector + + + return new DenseMatrix({ + data: x, + size: [rows, 1] + }); + } + + function _sparseForwardSubstitution(m, b) { + // validate matrix and vector, return copy of column vector b + b = solveValidation(m, b, true); // column vector data + + var bdata = b._data; // rows & columns + + var rows = m._size[0]; + var columns = m._size[1]; // matrix arrays + + var values = m._values; + var index = m._index; + var ptr = m._ptr; // vars + + var i, k; // result + + var x = []; // forward solve m * x = b, loop columns + + for (var j = 0; j < columns; j++) { + // b[j] + var bj = bdata[j][0] || 0; // forward substitution (outer product) avoids inner looping when bj === 0 + + if (!equalScalar(bj, 0)) { + // value @ [j, j] + var vjj = 0; // lower triangular matrix values & index (column j) + + var jvalues = []; + var jindex = []; // last index in column + + var l = ptr[j + 1]; // values in column, find value @ [j, j] + + for (k = ptr[j]; k < l; k++) { + // row + i = index[k]; // check row (rows are not sorted!) + + if (i === j) { + // update vjj + vjj = values[k]; + } else if (i > j) { + // store lower triangular + jvalues.push(values[k]); + jindex.push(i); + } + } // at this point we must have a value @ [j, j] + + + if (equalScalar(vjj, 0)) { + // system cannot be solved, there is no value @ [j, j] + throw new Error('Linear system cannot be solved since matrix is singular'); + } // calculate xj + + + var xj = divideScalar(bj, vjj); // loop lower triangular + + for (k = 0, l = jindex.length; k < l; k++) { + // row + i = jindex[k]; // update copy of b + + bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, jvalues[k]))]; + } // update x + + + x[j] = [xj]; + } else { + // update x + x[j] = [0]; + } + } // return vector + + + return new DenseMatrix({ + data: x, + size: [rows, 1] + }); + } +}); +// CONCATENATED MODULE: ./src/function/algebra/solver/usolve.js + + +var usolve_name = 'usolve'; +var usolve_dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtract', 'equalScalar', 'DenseMatrix']; +var createUsolve = /* #__PURE__ */Object(factory["a" /* factory */])(usolve_name, usolve_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + divideScalar = _ref.divideScalar, + multiplyScalar = _ref.multiplyScalar, + subtract = _ref.subtract, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix; + var solveValidation = createSolveValidation({ + DenseMatrix: DenseMatrix + }); + /** + * Solves the linear equation system by backward substitution. Matrix must be an upper triangular matrix. + * + * `U * x = b` + * + * Syntax: + * + * math.usolve(U, b) + * + * Examples: + * + * const a = [[-2, 3], [2, 1]] + * const b = [11, 9] + * const x = usolve(a, b) // [[8], [9]] + * + * See also: + * + * lup, slu, usolve, lusolve + * + * @param {Matrix, Array} U A N x N matrix or array (U) + * @param {Matrix, Array} b A column vector with the b values + * + * @return {DenseMatrix | Array} A column vector with the linear system solution (x) + */ + + return typed(usolve_name, { + 'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(m, b) { + // process matrix + return _sparseBackwardSubstitution(m, b); + }, + 'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(m, b) { + // process matrix + return _denseBackwardSubstitution(m, b); + }, + 'Array, Array | Matrix': function ArrayArrayMatrix(a, b) { + // create dense matrix from array + var m = matrix(a); // use matrix implementation + + var r = _denseBackwardSubstitution(m, b); // result + + + return r.valueOf(); + } + }); + + function _denseBackwardSubstitution(m, b) { + // validate matrix and vector, return copy of column vector b + b = solveValidation(m, b, true); // column vector data + + var bdata = b._data; // rows & columns + + var rows = m._size[0]; + var columns = m._size[1]; // result + + var x = []; // arrays + + var data = m._data; // backward solve m * x = b, loop columns (backwards) + + for (var j = columns - 1; j >= 0; j--) { + // b[j] + var bj = bdata[j][0] || 0; // x[j] + + var xj = void 0; // backward substitution (outer product) avoids inner looping when bj === 0 + + if (!equalScalar(bj, 0)) { + // value @ [j, j] + var vjj = data[j][j]; // check vjj + + if (equalScalar(vjj, 0)) { + // system cannot be solved + throw new Error('Linear system cannot be solved since matrix is singular'); + } // calculate xj + + + xj = divideScalar(bj, vjj); // loop rows + + for (var i = j - 1; i >= 0; i--) { + // update copy of b + bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, data[i][j]))]; + } + } else { + // zero value @ j + xj = 0; + } // update x + + + x[j] = [xj]; + } // return column vector + + + return new DenseMatrix({ + data: x, + size: [rows, 1] + }); + } + + function _sparseBackwardSubstitution(m, b) { + // validate matrix and vector, return copy of column vector b + b = solveValidation(m, b, true); // column vector data + + var bdata = b._data; // rows & columns + + var rows = m._size[0]; + var columns = m._size[1]; // matrix arrays + + var values = m._values; + var index = m._index; + var ptr = m._ptr; // vars + + var i, k; // result + + var x = []; // backward solve m * x = b, loop columns (backwards) + + for (var j = columns - 1; j >= 0; j--) { + // b[j] + var bj = bdata[j][0] || 0; // backward substitution (outer product) avoids inner looping when bj === 0 + + if (!equalScalar(bj, 0)) { + // value @ [j, j] + var vjj = 0; // upper triangular matrix values & index (column j) + + var jvalues = []; + var jindex = []; // first & last indeces in column + + var f = ptr[j]; + var l = ptr[j + 1]; // values in column, find value @ [j, j], loop backwards + + for (k = l - 1; k >= f; k--) { + // row + i = index[k]; // check row + + if (i === j) { + // update vjj + vjj = values[k]; + } else if (i < j) { + // store upper triangular + jvalues.push(values[k]); + jindex.push(i); + } + } // at this point we must have a value @ [j, j] + + + if (equalScalar(vjj, 0)) { + // system cannot be solved, there is no value @ [j, j] + throw new Error('Linear system cannot be solved since matrix is singular'); + } // calculate xj + + + var xj = divideScalar(bj, vjj); // loop upper triangular + + for (k = 0, l = jindex.length; k < l; k++) { + // row + i = jindex[k]; // update copy of b + + bdata[i] = [subtract(bdata[i][0], multiplyScalar(xj, jvalues[k]))]; + } // update x + + + x[j] = [xj]; + } else { + // update x + x[j] = [0]; + } + } // return vector + + + return new DenseMatrix({ + data: x, + size: [rows, 1] + }); + } +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm08.js + + +var algorithm08_name = 'algorithm08'; +var algorithm08_dependencies = ['typed', 'equalScalar']; +var createAlgorithm08 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm08_name, algorithm08_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij). + * Callback function invoked MAX(NNZA, NNZB) times + * + * + * ┌ f(Aij, Bij) ; A(i,j) !== 0 && B(i,j) !== 0 + * C(i,j) = ┤ A(i,j) ; A(i,j) !== 0 + * └ 0 ; otherwise + * + * + * @param {Matrix} a The SparseMatrix instance (A) + * @param {Matrix} b The SparseMatrix instance (B) + * @param {Function} callback The f(Aij,Bij) operation to invoke + * + * @return {Matrix} SparseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294 + */ + return function algorithm08(a, b, callback) { + // sparse matrix arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; + var adt = a._datatype; // sparse matrix arrays + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; + var bsize = b._size; + var bdt = b._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // sparse matrix cannot be a Pattern matrix + + + if (!avalues || !bvalues) { + throw new Error('Cannot perform operation on Pattern Sparse Matrices'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cvalues = []; + var cindex = []; + var cptr = []; // workspace + + var x = []; // marks indicating we have a value in x for a given column + + var w = []; // vars + + var k, k0, k1, i; // loop columns + + for (var j = 0; j < columns; j++) { + // update cptr + cptr[j] = cindex.length; // columns mark + + var mark = j + 1; // loop values in a + + for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + i = aindex[k]; // mark workspace + + w[i] = mark; // set value + + x[i] = avalues[k]; // add index + + cindex.push(i); + } // loop values in b + + + for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) { + // row + i = bindex[k]; // check value exists in workspace + + if (w[i] === mark) { + // evaluate callback + x[i] = cf(x[i], bvalues[k]); + } + } // initialize first index in j + + + k = cptr[j]; // loop index in j + + while (k < cindex.length) { + // row + i = cindex[k]; // value @ i + + var v = x[i]; // check for zero value + + if (!eq(v, zero)) { + // push value + cvalues.push(v); // increment pointer + + k++; + } else { + // remove value @ i, do not increment pointer + cindex.splice(k, 1); + } + } + } // update cptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/function/bitwise/leftShift.js + + + + + + + + + + +var leftShift_name = 'leftShift'; +var leftShift_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix']; +var createLeftShift = /* #__PURE__ */Object(factory["a" /* factory */])(leftShift_name, leftShift_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + zeros = _ref.zeros, + DenseMatrix = _ref.DenseMatrix; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm08 = createAlgorithm08({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Bitwise left logical shift of a value x by y number of bits, `x << y`. + * For matrices, the function is evaluated element wise. + * For units, the function is evaluated on the best prefix base. + * + * Syntax: + * + * math.leftShift(x, y) + * + * Examples: + * + * math.leftShift(1, 2) // returns number 4 + * + * math.leftShift([1, 2, 3], 4) // returns Array [16, 32, 64] + * + * See also: + * + * leftShift, bitNot, bitOr, bitXor, rightArithShift, rightLogShift + * + * @param {number | BigNumber | Array | Matrix} x Value to be shifted + * @param {number | BigNumber} y Amount of shifts + * @return {number | BigNumber | Array | Matrix} `x` shifted left `y` times + */ + + var leftShift = typed(leftShift_name, { + 'number, number': leftShiftNumber, + 'BigNumber, BigNumber': leftShiftBigNumber, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm08(x, y, leftShift, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, leftShift, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm01(x, y, leftShift, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, leftShift); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return leftShift(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return leftShift(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return leftShift(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + // check scalar + if (equalScalar(y, 0)) { + return x.clone(); + } + + return algorithm11(x, y, leftShift, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + // check scalar + if (equalScalar(y, 0)) { + return x.clone(); + } + + return algorithm14(x, y, leftShift, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + // check scalar + if (equalScalar(x, 0)) { + return zeros(y.size(), y.storage()); + } + + return algorithm10(y, x, leftShift, true); + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + // check scalar + if (equalScalar(x, 0)) { + return zeros(y.size(), y.storage()); + } + + return algorithm14(y, x, leftShift, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return leftShift(matrix(x), y).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + // use matrix implementation + return leftShift(x, matrix(y)).valueOf(); + } + }); + return leftShift; +}); +// CONCATENATED MODULE: ./src/function/bitwise/rightArithShift.js + + + + + + + + + + +var rightArithShift_name = 'rightArithShift'; +var rightArithShift_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix']; +var createRightArithShift = /* #__PURE__ */Object(factory["a" /* factory */])(rightArithShift_name, rightArithShift_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + zeros = _ref.zeros, + DenseMatrix = _ref.DenseMatrix; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm08 = createAlgorithm08({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Bitwise right arithmetic shift of a value x by y number of bits, `x >> y`. + * For matrices, the function is evaluated element wise. + * For units, the function is evaluated on the best prefix base. + * + * Syntax: + * + * math.rightArithShift(x, y) + * + * Examples: + * + * math.rightArithShift(4, 2) // returns number 1 + * + * math.rightArithShift([16, -32, 64], 4) // returns Array [1, -2, 3] + * + * See also: + * + * bitAnd, bitNot, bitOr, bitXor, rightArithShift, rightLogShift + * + * @param {number | BigNumber | Array | Matrix} x Value to be shifted + * @param {number | BigNumber} y Amount of shifts + * @return {number | BigNumber | Array | Matrix} `x` sign-filled shifted right `y` times + */ + + var rightArithShift = typed(rightArithShift_name, { + 'number, number': rightArithShiftNumber, + 'BigNumber, BigNumber': rightArithShiftBigNumber, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm08(x, y, rightArithShift, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, rightArithShift, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm01(x, y, rightArithShift, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, rightArithShift); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return rightArithShift(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return rightArithShift(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return rightArithShift(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + // check scalar + if (equalScalar(y, 0)) { + return x.clone(); + } + + return algorithm11(x, y, rightArithShift, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + // check scalar + if (equalScalar(y, 0)) { + return x.clone(); + } + + return algorithm14(x, y, rightArithShift, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + // check scalar + if (equalScalar(x, 0)) { + return zeros(y.size(), y.storage()); + } + + return algorithm10(y, x, rightArithShift, true); + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + // check scalar + if (equalScalar(x, 0)) { + return zeros(y.size(), y.storage()); + } + + return algorithm14(y, x, rightArithShift, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return rightArithShift(matrix(x), y).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + // use matrix implementation + return rightArithShift(x, matrix(y)).valueOf(); + } + }); + return rightArithShift; +}); +// CONCATENATED MODULE: ./src/function/bitwise/rightLogShift.js + + + + + + + + + +var rightLogShift_name = 'rightLogShift'; +var rightLogShift_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix']; +var createRightLogShift = /* #__PURE__ */Object(factory["a" /* factory */])(rightLogShift_name, rightLogShift_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + zeros = _ref.zeros, + DenseMatrix = _ref.DenseMatrix; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm08 = createAlgorithm08({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Bitwise right logical shift of value x by y number of bits, `x >>> y`. + * For matrices, the function is evaluated element wise. + * For units, the function is evaluated on the best prefix base. + * + * Syntax: + * + * math.rightLogShift(x, y) + * + * Examples: + * + * math.rightLogShift(4, 2) // returns number 1 + * + * math.rightLogShift([16, -32, 64], 4) // returns Array [1, 2, 3] + * + * See also: + * + * bitAnd, bitNot, bitOr, bitXor, leftShift, rightLogShift + * + * @param {number | Array | Matrix} x Value to be shifted + * @param {number} y Amount of shifts + * @return {number | Array | Matrix} `x` zero-filled shifted right `y` times + */ + + var rightLogShift = typed(rightLogShift_name, { + 'number, number': rightLogShiftNumber, + // 'BigNumber, BigNumber': ..., // TODO: implement BigNumber support for rightLogShift + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm08(x, y, rightLogShift, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, rightLogShift, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm01(x, y, rightLogShift, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, rightLogShift); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return rightLogShift(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return rightLogShift(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return rightLogShift(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + // check scalar + if (equalScalar(y, 0)) { + return x.clone(); + } + + return algorithm11(x, y, rightLogShift, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + // check scalar + if (equalScalar(y, 0)) { + return x.clone(); + } + + return algorithm14(x, y, rightLogShift, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + // check scalar + if (equalScalar(x, 0)) { + return zeros(y.size(), y.storage()); + } + + return algorithm10(y, x, rightLogShift, true); + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + // check scalar + if (equalScalar(x, 0)) { + return zeros(y.size(), y.storage()); + } + + return algorithm14(y, x, rightLogShift, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return rightLogShift(matrix(x), y).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + // use matrix implementation + return rightLogShift(x, matrix(y)).valueOf(); + } + }); + return rightLogShift; +}); +// CONCATENATED MODULE: ./src/function/logical/and.js + + + + + + + +var and_name = 'and'; +var and_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'not']; +var createAnd = /* #__PURE__ */Object(factory["a" /* factory */])(and_name, and_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + zeros = _ref.zeros, + not = _ref.not; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm06 = createAlgorithm06({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Logical `and`. Test whether two values are both defined with a nonzero/nonempty value. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.and(x, y) + * + * Examples: + * + * math.and(2, 4) // returns true + * + * a = [2, 0, 0] + * b = [3, 7, 0] + * c = 0 + * + * math.and(a, b) // returns [true, false, false] + * math.and(a, c) // returns [false, false, false] + * + * See also: + * + * not, or, xor + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check + * @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check + * @return {boolean | Array | Matrix} + * Returns true when both inputs are defined with a nonzero/nonempty value. + */ + + var and = typed(and_name, { + 'number, number': andNumber, + 'Complex, Complex': function ComplexComplex(x, y) { + return (x.re !== 0 || x.im !== 0) && (y.re !== 0 || y.im !== 0); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return !x.isZero() && !y.isZero() && !x.isNaN() && !y.isNaN(); + }, + 'Unit, Unit': function UnitUnit(x, y) { + return and(x.value || 0, y.value || 0); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm06(x, y, and, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, and, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm02(x, y, and, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, and); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return and(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return and(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return and(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + // check scalar + if (not(y)) { + // return zero matrix + return zeros(x.size(), x.storage()); + } + + return algorithm11(x, y, and, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + // check scalar + if (not(y)) { + // return zero matrix + return zeros(x.size(), x.storage()); + } + + return algorithm14(x, y, and, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + // check scalar + if (not(x)) { + // return zero matrix + return zeros(x.size(), x.storage()); + } + + return algorithm11(y, x, and, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + // check scalar + if (not(x)) { + // return zero matrix + return zeros(x.size(), x.storage()); + } + + return algorithm14(y, x, and, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return and(matrix(x), y).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return and(x, matrix(y)).valueOf(); + } + }); + return and; +}); +// CONCATENATED MODULE: ./src/function/relational/compare.js + + + + + + + + +var compare_name = 'compare'; +var compare_dependencies = ['typed', 'config', 'matrix', 'equalScalar', 'BigNumber', 'Fraction', 'DenseMatrix']; +var createCompare = /* #__PURE__ */Object(factory["a" /* factory */])(compare_name, compare_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + equalScalar = _ref.equalScalar, + matrix = _ref.matrix, + BigNumber = _ref.BigNumber, + Fraction = _ref.Fraction, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm05 = createAlgorithm05({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y. + * + * x and y are considered equal when the relative difference between x and y + * is smaller than the configured epsilon. The function cannot be used to + * compare values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * Strings are compared by their numerical value. + * + * Syntax: + * + * math.compare(x, y) + * + * Examples: + * + * math.compare(6, 1) // returns 1 + * math.compare(2, 3) // returns -1 + * math.compare(7, 7) // returns 0 + * math.compare('10', '2') // returns 1 + * math.compare('1000', '1e3') // returns 0 + * + * const a = math.unit('5 cm') + * const b = math.unit('40 mm') + * math.compare(a, b) // returns 1 + * + * math.compare(2, [1, 2, 3]) // returns [1, 0, -1] + * + * See also: + * + * equal, unequal, smaller, smallerEq, larger, largerEq, compareNatural, compareText + * + * @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} x First value to compare + * @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} y Second value to compare + * @return {number | BigNumber | Fraction | Array | Matrix} Returns the result of the comparison: + * 1 when x > y, -1 when x < y, and 0 when x == y. + */ + + var compare = typed(compare_name, { + 'boolean, boolean': function booleanBoolean(x, y) { + return x === y ? 0 : x > y ? 1 : -1; + }, + 'number, number': function numberNumber(x, y) { + return Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon) ? 0 : x > y ? 1 : -1; + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return nearlyEqual(x, y, config.epsilon) ? new BigNumber(0) : new BigNumber(x.cmp(y)); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return new Fraction(x.compare(y)); + }, + 'Complex, Complex': function ComplexComplex() { + throw new TypeError('No ordering relation is defined for complex numbers'); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (!x.equalBase(y)) { + throw new Error('Cannot compare units with different base'); + } + + return compare(x.value, y.value); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm05(x, y, compare); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, compare, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, compare, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, compare); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return compare(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return compare(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return compare(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, compare, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, compare, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, compare, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, compare, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, compare, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, compare, true).valueOf(); + } + }); + return compare; +}); +var createCompareNumber = /* #__PURE__ */Object(factory["a" /* factory */])(compare_name, ['typed', 'config'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config; + return typed(compare_name, { + 'number, number': function numberNumber(x, y) { + return Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon) ? 0 : x > y ? 1 : -1; + } + }); +}); +// EXTERNAL MODULE: ./node_modules/javascript-natural-sort/naturalSort.js +var naturalSort = __webpack_require__(12); +var naturalSort_default = /*#__PURE__*/__webpack_require__.n(naturalSort); + +// CONCATENATED MODULE: ./src/function/relational/compareNatural.js + + + +var compareNatural_name = 'compareNatural'; +var compareNatural_dependencies = ['typed', 'compare']; +var createCompareNatural = /* #__PURE__ */Object(factory["a" /* factory */])(compareNatural_name, compareNatural_dependencies, function (_ref) { + var typed = _ref.typed, + compare = _ref.compare; + var compareBooleans = compare.signatures['boolean,boolean']; + /** + * Compare two values of any type in a deterministic, natural way. + * + * For numeric values, the function works the same as `math.compare`. + * For types of values that can't be compared mathematically, + * the function compares in a natural way. + * + * For numeric values, x and y are considered equal when the relative + * difference between x and y is smaller than the configured epsilon. + * The function cannot be used to compare values smaller than + * approximately 2.22e-16. + * + * For Complex numbers, first the real parts are compared. If equal, + * the imaginary parts are compared. + * + * Strings are compared with a natural sorting algorithm, which + * orders strings in a "logic" way following some heuristics. + * This differs from the function `compare`, which converts the string + * into a numeric value and compares that. The function `compareText` + * on the other hand compares text lexically. + * + * Arrays and Matrices are compared value by value until there is an + * unequal pair of values encountered. Objects are compared by sorted + * keys until the keys or their values are unequal. + * + * Syntax: + * + * math.compareNatural(x, y) + * + * Examples: + * + * math.compareNatural(6, 1) // returns 1 + * math.compareNatural(2, 3) // returns -1 + * math.compareNatural(7, 7) // returns 0 + * + * math.compareNatural('10', '2') // returns 1 + * math.compareText('10', '2') // returns -1 + * math.compare('10', '2') // returns 1 + * + * math.compareNatural('Answer: 10', 'Answer: 2') // returns 1 + * math.compareText('Answer: 10', 'Answer: 2') // returns -1 + * math.compare('Answer: 10', 'Answer: 2') + * // Error: Cannot convert "Answer: 10" to a number + * + * const a = math.unit('5 cm') + * const b = math.unit('40 mm') + * math.compareNatural(a, b) // returns 1 + * + * const c = math.complex('2 + 3i') + * const d = math.complex('2 + 4i') + * math.compareNatural(c, d) // returns -1 + * + * math.compareNatural([1, 2, 4], [1, 2, 3]) // returns 1 + * math.compareNatural([1, 2, 3], [1, 2]) // returns 1 + * math.compareNatural([1, 5], [1, 2, 3]) // returns 1 + * math.compareNatural([1, 2], [1, 2]) // returns 0 + * + * math.compareNatural({a: 2}, {a: 4}) // returns -1 + * + * See also: + * + * compare, compareText + * + * @param {*} x First value to compare + * @param {*} y Second value to compare + * @return {number} Returns the result of the comparison: + * 1 when x > y, -1 when x < y, and 0 when x == y. + */ + + var compareNatural = typed(compareNatural_name, { + 'any, any': function anyAny(x, y) { + var typeX = Object(is["M" /* typeOf */])(x); + var typeY = Object(is["M" /* typeOf */])(y); + var c; // numeric types + + if ((typeX === 'number' || typeX === 'BigNumber' || typeX === 'Fraction') && (typeY === 'number' || typeY === 'BigNumber' || typeY === 'Fraction')) { + c = compare(x, y); + + if (c.toString() !== '0') { + // c can be number, BigNumber, or Fraction + return c > 0 ? 1 : -1; // return a number + } else { + return naturalSort_default()(typeX, typeY); + } + } // matrix types + + + if (typeX === 'Array' || typeX === 'Matrix' || typeY === 'Array' || typeY === 'Matrix') { + c = compareMatricesAndArrays(x, y); + + if (c !== 0) { + return c; + } else { + return naturalSort_default()(typeX, typeY); + } + } // in case of different types, order by name of type, i.e. 'BigNumber' < 'Complex' + + + if (typeX !== typeY) { + return naturalSort_default()(typeX, typeY); + } + + if (typeX === 'Complex') { + return compareComplexNumbers(x, y); + } + + if (typeX === 'Unit') { + if (x.equalBase(y)) { + return compareNatural(x.value, y.value); + } // compare by units + + + return compareArrays(x.formatUnits(), y.formatUnits()); + } + + if (typeX === 'boolean') { + return compareBooleans(x, y); + } + + if (typeX === 'string') { + return naturalSort_default()(x, y); + } + + if (typeX === 'Object') { + return compareObjects(x, y); + } + + if (typeX === 'null') { + return 0; + } + + if (typeX === 'undefined') { + return 0; + } // this should not occur... + + + throw new TypeError('Unsupported type of value "' + typeX + '"'); + } + }); + /** + * Compare mixed matrix/array types, by converting to same-shaped array. + * This comparator is non-deterministic regarding input types. + * @param {Array | SparseMatrix | DenseMatrix | *} x + * @param {Array | SparseMatrix | DenseMatrix | *} y + * @returns {number} Returns the comparison result: -1, 0, or 1 + */ + + function compareMatricesAndArrays(x, y) { + if (Object(is["H" /* isSparseMatrix */])(x) && Object(is["H" /* isSparseMatrix */])(y)) { + return compareArrays(x.toJSON().values, y.toJSON().values); + } + + if (Object(is["H" /* isSparseMatrix */])(x)) { + // note: convert to array is expensive + return compareMatricesAndArrays(x.toArray(), y); + } + + if (Object(is["H" /* isSparseMatrix */])(y)) { + // note: convert to array is expensive + return compareMatricesAndArrays(x, y.toArray()); + } // convert DenseArray into Array + + + if (Object(is["n" /* isDenseMatrix */])(x)) { + return compareMatricesAndArrays(x.toJSON().data, y); + } + + if (Object(is["n" /* isDenseMatrix */])(y)) { + return compareMatricesAndArrays(x, y.toJSON().data); + } // convert scalars to array + + + if (!Array.isArray(x)) { + return compareMatricesAndArrays([x], y); + } + + if (!Array.isArray(y)) { + return compareMatricesAndArrays(x, [y]); + } + + return compareArrays(x, y); + } + /** + * Compare two Arrays + * + * - First, compares value by value + * - Next, if all corresponding values are equal, + * look at the length: longest array will be considered largest + * + * @param {Array} x + * @param {Array} y + * @returns {number} Returns the comparison result: -1, 0, or 1 + */ + + + function compareArrays(x, y) { + // compare each value + for (var i = 0, ii = Math.min(x.length, y.length); i < ii; i++) { + var v = compareNatural(x[i], y[i]); + + if (v !== 0) { + return v; + } + } // compare the size of the arrays + + + if (x.length > y.length) { + return 1; + } + + if (x.length < y.length) { + return -1; + } // both Arrays have equal size and content + + + return 0; + } + /** + * Compare two objects + * + * - First, compare sorted property names + * - Next, compare the property values + * + * @param {Object} x + * @param {Object} y + * @returns {number} Returns the comparison result: -1, 0, or 1 + */ + + + function compareObjects(x, y) { + var keysX = Object.keys(x); + var keysY = Object.keys(y); // compare keys + + keysX.sort(naturalSort_default.a); + keysY.sort(naturalSort_default.a); + var c = compareArrays(keysX, keysY); + + if (c !== 0) { + return c; + } // compare values + + + for (var i = 0; i < keysX.length; i++) { + var v = compareNatural(x[keysX[i]], y[keysY[i]]); + + if (v !== 0) { + return v; + } + } + + return 0; + } + + return compareNatural; +}); +/** + * Compare two complex numbers, `x` and `y`: + * + * - First, compare the real values of `x` and `y` + * - If equal, compare the imaginary values of `x` and `y` + * + * @params {Complex} x + * @params {Complex} y + * @returns {number} Returns the comparison result: -1, 0, or 1 + */ + +function compareComplexNumbers(x, y) { + if (x.re > y.re) { + return 1; + } + + if (x.re < y.re) { + return -1; + } + + if (x.im > y.im) { + return 1; + } + + if (x.im < y.im) { + return -1; + } + + return 0; +} +// CONCATENATED MODULE: ./src/function/relational/compareText.js + + + + +var compareText_name = 'compareText'; +var compareText_dependencies = ['typed', 'matrix']; +var createCompareText = /* #__PURE__ */Object(factory["a" /* factory */])(compareText_name, compareText_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Compare two strings lexically. Comparison is case sensitive. + * Returns 1 when x > y, -1 when x < y, and 0 when x == y. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.compareText(x, y) + * + * Examples: + * + * math.compareText('B', 'A') // returns 1 + * math.compareText('2', '10') // returns 1 + * math.compare('2', '10') // returns -1 + * math.compareNatural('2', '10') // returns -1 + * + * math.compareText('B', ['A', 'B', 'C']) // returns [1, 0, -1] + * + * See also: + * + * equal, equalText, compare, compareNatural + * + * @param {string | Array | DenseMatrix} x First string to compare + * @param {string | Array | DenseMatrix} y Second string to compare + * @return {number | Array | DenseMatrix} Returns the result of the comparison: + * 1 when x > y, -1 when x < y, and 0 when x == y. + */ + + var compareText = typed(compareText_name, { + 'any, any': utils_string["a" /* compareText */], + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, utils_string["a" /* compareText */]); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return compareText(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return compareText(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return compareText(x, matrix(y)); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, utils_string["a" /* compareText */], false); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, utils_string["a" /* compareText */], true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, utils_string["a" /* compareText */], false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, utils_string["a" /* compareText */], true).valueOf(); + } + }); + return compareText; +}); +var createCompareTextNumber = /* #__PURE__ */Object(factory["a" /* factory */])(compareText_name, ['typed'], function (_ref2) { + var typed = _ref2.typed; + return typed(compareText_name, { + 'any, any': utils_string["a" /* compareText */] + }); +}); +// CONCATENATED MODULE: ./src/function/relational/equal.js + + + + + + +var equal_name = 'equal'; +var equal_dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix']; +var createEqual = /* #__PURE__ */Object(factory["a" /* factory */])(equal_name, equal_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Test whether two values are equal. + * + * The function tests whether the relative difference between x and y is + * smaller than the configured epsilon. The function cannot be used to + * compare values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * In case of complex numbers, x.re must equal y.re, and x.im must equal y.im. + * + * Values `null` and `undefined` are compared strictly, thus `null` is only + * equal to `null` and nothing else, and `undefined` is only equal to + * `undefined` and nothing else. Strings are compared by their numerical value. + * + * Syntax: + * + * math.equal(x, y) + * + * Examples: + * + * math.equal(2 + 2, 3) // returns false + * math.equal(2 + 2, 4) // returns true + * + * const a = math.unit('50 cm') + * const b = math.unit('5 m') + * math.equal(a, b) // returns true + * + * const c = [2, 5, 1] + * const d = [2, 7, 1] + * + * math.equal(c, d) // returns [true, false, true] + * math.deepEqual(c, d) // returns false + * + * math.equal("1000", "1e3") // returns true + * math.equal(0, null) // returns false + * + * See also: + * + * unequal, smaller, smallerEq, larger, largerEq, compare, deepEqual, equalText + * + * @param {number | BigNumber | boolean | Complex | Unit | string | Array | Matrix} x First value to compare + * @param {number | BigNumber | boolean | Complex | Unit | string | Array | Matrix} y Second value to compare + * @return {boolean | Array | Matrix} Returns true when the compared values are equal, else returns false + */ + + var equal = typed(equal_name, { + 'any, any': function anyAny(x, y) { + // strict equality for null and undefined? + if (x === null) { + return y === null; + } + + if (y === null) { + return x === null; + } + + if (x === undefined) { + return y === undefined; + } + + if (y === undefined) { + return x === undefined; + } + + return equalScalar(x, y); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, equalScalar); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, equalScalar, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, equalScalar, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, equalScalar); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return equal(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return equal(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return equal(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, equalScalar, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, equalScalar, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, equalScalar, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, equalScalar, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, equalScalar, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, equalScalar, true).valueOf(); + } + }); + return equal; +}); +var createEqualNumber = Object(factory["a" /* factory */])(equal_name, ['typed', 'equalScalar'], function (_ref2) { + var typed = _ref2.typed, + equalScalar = _ref2.equalScalar; + return typed(equal_name, { + 'any, any': function anyAny(x, y) { + // strict equality for null and undefined? + if (x === null) { + return y === null; + } + + if (y === null) { + return x === null; + } + + if (x === undefined) { + return y === undefined; + } + + if (y === undefined) { + return x === undefined; + } + + return equalScalar(x, y); + } + }); +}); +// CONCATENATED MODULE: ./src/function/relational/equalText.js + +var equalText_name = 'equalText'; +var equalText_dependencies = ['typed', 'compareText', 'isZero']; +var createEqualText = /* #__PURE__ */Object(factory["a" /* factory */])(equalText_name, equalText_dependencies, function (_ref) { + var typed = _ref.typed, + compareText = _ref.compareText, + isZero = _ref.isZero; + + /** + * Check equality of two strings. Comparison is case sensitive. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.equalText(x, y) + * + * Examples: + * + * math.equalText('Hello', 'Hello') // returns true + * math.equalText('a', 'A') // returns false + * math.equal('2e3', '2000') // returns true + * math.equalText('2e3', '2000') // returns false + * + * math.equalText('B', ['A', 'B', 'C']) // returns [false, true, false] + * + * See also: + * + * equal, compareText, compare, compareNatural + * + * @param {string | Array | DenseMatrix} x First string to compare + * @param {string | Array | DenseMatrix} y Second string to compare + * @return {number | Array | DenseMatrix} Returns true if the values are equal, and false if not. + */ + return typed(equalText_name, { + 'any, any': function anyAny(x, y) { + return isZero(compareText(x, y)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/relational/smaller.js + + + + + + + + +var smaller_name = 'smaller'; +var smaller_dependencies = ['typed', 'config', 'matrix', 'DenseMatrix']; +var createSmaller = /* #__PURE__ */Object(factory["a" /* factory */])(smaller_name, smaller_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Test whether value x is smaller than y. + * + * The function returns true when x is smaller than y and the relative + * difference between x and y is smaller than the configured epsilon. The + * function cannot be used to compare values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * Strings are compared by their numerical value. + * + * Syntax: + * + * math.smaller(x, y) + * + * Examples: + * + * math.smaller(2, 3) // returns true + * math.smaller(5, 2 * 2) // returns false + * + * const a = math.unit('5 cm') + * const b = math.unit('2 inch') + * math.smaller(a, b) // returns true + * + * See also: + * + * equal, unequal, smallerEq, smaller, smallerEq, compare + * + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare + * @return {boolean | Array | Matrix} Returns true when the x is smaller than y, else returns false + */ + + var smaller = typed(smaller_name, { + 'boolean, boolean': function booleanBoolean(x, y) { + return x < y; + }, + 'number, number': function numberNumber(x, y) { + return x < y && !Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.lt(y) && !nearlyEqual(x, y, config.epsilon); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.compare(y) === -1; + }, + 'Complex, Complex': function ComplexComplex(x, y) { + throw new TypeError('No ordering relation is defined for complex numbers'); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (!x.equalBase(y)) { + throw new Error('Cannot compare units with different base'); + } + + return smaller(x.value, y.value); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, smaller); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, smaller, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, smaller, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, smaller); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return smaller(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return smaller(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return smaller(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, smaller, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, smaller, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, smaller, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, smaller, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, smaller, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, smaller, true).valueOf(); + } + }); + return smaller; +}); +var createSmallerNumber = /* #__PURE__ */Object(factory["a" /* factory */])(smaller_name, ['typed', 'config'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config; + return typed(smaller_name, { + 'number, number': function numberNumber(x, y) { + return x < y && !Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + } + }); +}); +// CONCATENATED MODULE: ./src/function/relational/smallerEq.js + + + + + + + + +var smallerEq_name = 'smallerEq'; +var smallerEq_dependencies = ['typed', 'config', 'matrix', 'DenseMatrix']; +var createSmallerEq = /* #__PURE__ */Object(factory["a" /* factory */])(smallerEq_name, smallerEq_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Test whether value x is smaller or equal to y. + * + * The function returns true when x is smaller than y or the relative + * difference between x and y is smaller than the configured epsilon. The + * function cannot be used to compare values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * Strings are compared by their numerical value. + * + * Syntax: + * + * math.smallerEq(x, y) + * + * Examples: + * + * math.smaller(1 + 2, 3) // returns false + * math.smallerEq(1 + 2, 3) // returns true + * + * See also: + * + * equal, unequal, smaller, larger, largerEq, compare + * + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare + * @return {boolean | Array | Matrix} Returns true when the x is smaller than y, else returns false + */ + + var smallerEq = typed(smallerEq_name, { + 'boolean, boolean': function booleanBoolean(x, y) { + return x <= y; + }, + 'number, number': function numberNumber(x, y) { + return x <= y || Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.lte(y) || nearlyEqual(x, y, config.epsilon); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.compare(y) !== 1; + }, + 'Complex, Complex': function ComplexComplex() { + throw new TypeError('No ordering relation is defined for complex numbers'); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (!x.equalBase(y)) { + throw new Error('Cannot compare units with different base'); + } + + return smallerEq(x.value, y.value); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, smallerEq); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, smallerEq, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, smallerEq, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, smallerEq); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return smallerEq(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return smallerEq(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return smallerEq(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, smallerEq, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, smallerEq, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, smallerEq, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, smallerEq, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, smallerEq, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, smallerEq, true).valueOf(); + } + }); + return smallerEq; +}); +var createSmallerEqNumber = /* #__PURE__ */Object(factory["a" /* factory */])(smallerEq_name, ['typed', 'config'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config; + return typed(smallerEq_name, { + 'number, number': function numberNumber(x, y) { + return x <= y || Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + } + }); +}); +// CONCATENATED MODULE: ./src/function/relational/larger.js + + + + + + + + +var larger_name = 'larger'; +var larger_dependencies = ['typed', 'config', 'matrix', 'DenseMatrix']; +var createLarger = /* #__PURE__ */Object(factory["a" /* factory */])(larger_name, larger_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Test whether value x is larger than y. + * + * The function returns true when x is larger than y and the relative + * difference between x and y is larger than the configured epsilon. The + * function cannot be used to compare values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * Strings are compared by their numerical value. + * + * Syntax: + * + * math.larger(x, y) + * + * Examples: + * + * math.larger(2, 3) // returns false + * math.larger(5, 2 + 2) // returns true + * + * const a = math.unit('5 cm') + * const b = math.unit('2 inch') + * math.larger(a, b) // returns false + * + * See also: + * + * equal, unequal, smaller, smallerEq, largerEq, compare + * + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare + * @return {boolean | Array | Matrix} Returns true when the x is larger than y, else returns false + */ + + var larger = typed(larger_name, { + 'boolean, boolean': function booleanBoolean(x, y) { + return x > y; + }, + 'number, number': function numberNumber(x, y) { + return x > y && !Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.gt(y) && !nearlyEqual(x, y, config.epsilon); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.compare(y) === 1; + }, + 'Complex, Complex': function ComplexComplex() { + throw new TypeError('No ordering relation is defined for complex numbers'); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (!x.equalBase(y)) { + throw new Error('Cannot compare units with different base'); + } + + return larger(x.value, y.value); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, larger); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, larger, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, larger, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, larger); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return larger(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return larger(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return larger(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, larger, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, larger, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, larger, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, larger, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, larger, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, larger, true).valueOf(); + } + }); + return larger; +}); +var createLargerNumber = /* #__PURE__ */Object(factory["a" /* factory */])(larger_name, ['typed', 'config'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config; + return typed(larger_name, { + 'number, number': function numberNumber(x, y) { + return x > y && !Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + } + }); +}); +// CONCATENATED MODULE: ./src/function/relational/largerEq.js + + + + + + + + +var largerEq_name = 'largerEq'; +var largerEq_dependencies = ['typed', 'config', 'matrix', 'DenseMatrix']; +var createLargerEq = /* #__PURE__ */Object(factory["a" /* factory */])(largerEq_name, largerEq_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Test whether value x is larger or equal to y. + * + * The function returns true when x is larger than y or the relative + * difference between x and y is smaller than the configured epsilon. The + * function cannot be used to compare values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * Strings are compared by their numerical value. + * + * Syntax: + * + * math.largerEq(x, y) + * + * Examples: + * + * math.larger(2, 1 + 1) // returns false + * math.largerEq(2, 1 + 1) // returns true + * + * See also: + * + * equal, unequal, smaller, smallerEq, larger, compare + * + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare + * @return {boolean | Array | Matrix} Returns true when the x is larger or equal to y, else returns false + */ + + var largerEq = typed(largerEq_name, { + 'boolean, boolean': function booleanBoolean(x, y) { + return x >= y; + }, + 'number, number': function numberNumber(x, y) { + return x >= y || Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.gte(y) || nearlyEqual(x, y, config.epsilon); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.compare(y) !== -1; + }, + 'Complex, Complex': function ComplexComplex() { + throw new TypeError('No ordering relation is defined for complex numbers'); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (!x.equalBase(y)) { + throw new Error('Cannot compare units with different base'); + } + + return largerEq(x.value, y.value); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, largerEq); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, largerEq, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, largerEq, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, largerEq); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return largerEq(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return largerEq(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return largerEq(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, largerEq, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, largerEq, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, largerEq, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, largerEq, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, largerEq, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, largerEq, true).valueOf(); + } + }); + return largerEq; +}); +var createLargerEqNumber = /* #__PURE__ */Object(factory["a" /* factory */])(largerEq_name, ['typed', 'config'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config; + return typed(largerEq_name, { + 'number, number': function numberNumber(x, y) { + return x >= y || Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + } + }); +}); +// CONCATENATED MODULE: ./src/function/relational/deepEqual.js + +var deepEqual_name = 'deepEqual'; +var deepEqual_dependencies = ['typed', 'equal']; +var createDeepEqual = /* #__PURE__ */Object(factory["a" /* factory */])(deepEqual_name, deepEqual_dependencies, function (_ref) { + var typed = _ref.typed, + equal = _ref.equal; + + /** + * Test element wise whether two matrices are equal. + * The function accepts both matrices and scalar values. + * + * Strings are compared by their numerical value. + * + * Syntax: + * + * math.deepEqual(x, y) + * + * Examples: + * + * math.deepEqual(2, 4) // returns false + * + * a = [2, 5, 1] + * b = [2, 7, 1] + * + * math.deepEqual(a, b) // returns false + * math.equal(a, b) // returns [true, false, true] + * + * See also: + * + * equal, unequal + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First matrix to compare + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second matrix to compare + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} + * Returns true when the input matrices have the same size and each of their elements is equal. + */ + return typed(deepEqual_name, { + 'any, any': function anyAny(x, y) { + return _deepEqual(x.valueOf(), y.valueOf()); + } + }); + /** + * Test whether two arrays have the same size and all elements are equal + * @param {Array | *} x + * @param {Array | *} y + * @return {boolean} Returns true if both arrays are deep equal + */ + + function _deepEqual(x, y) { + if (Array.isArray(x)) { + if (Array.isArray(y)) { + var len = x.length; + + if (len !== y.length) { + return false; + } + + for (var i = 0; i < len; i++) { + if (!_deepEqual(x[i], y[i])) { + return false; + } + } + + return true; + } else { + return false; + } + } else { + if (Array.isArray(y)) { + return false; + } else { + return equal(x, y); + } + } + } +}); +// CONCATENATED MODULE: ./src/function/relational/unequal.js + + + + + + +var unequal_name = 'unequal'; +var unequal_dependencies = ['typed', 'config', 'equalScalar', 'matrix', 'DenseMatrix']; +var createUnequal = /* #__PURE__ */Object(factory["a" /* factory */])(unequal_name, unequal_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + equalScalar = _ref.equalScalar, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Test whether two values are unequal. + * + * The function tests whether the relative difference between x and y is + * larger than the configured epsilon. The function cannot be used to compare + * values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * In case of complex numbers, x.re must unequal y.re, or x.im must unequal y.im. + * Strings are compared by their numerical value. + * + * Values `null` and `undefined` are compared strictly, thus `null` is unequal + * with everything except `null`, and `undefined` is unequal with everything + * except `undefined`. + * + * Syntax: + * + * math.unequal(x, y) + * + * Examples: + * + * math.unequal(2 + 2, 3) // returns true + * math.unequal(2 + 2, 4) // returns false + * + * const a = math.unit('50 cm') + * const b = math.unit('5 m') + * math.unequal(a, b) // returns false + * + * const c = [2, 5, 1] + * const d = [2, 7, 1] + * + * math.unequal(c, d) // returns [false, true, false] + * math.deepEqual(c, d) // returns false + * + * math.unequal(0, null) // returns true + * See also: + * + * equal, deepEqual, smaller, smallerEq, larger, largerEq, compare + * + * @param {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} x First value to compare + * @param {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} y Second value to compare + * @return {boolean | Array | Matrix} Returns true when the compared values are unequal, else returns false + */ + + var unequal = typed('unequal', { + 'any, any': function anyAny(x, y) { + // strict equality for null and undefined? + if (x === null) { + return y !== null; + } + + if (y === null) { + return x !== null; + } + + if (x === undefined) { + return y !== undefined; + } + + if (y === undefined) { + return x !== undefined; + } + + return _unequal(x, y); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, _unequal); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, _unequal, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, _unequal, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, _unequal); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return unequal(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return unequal(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return unequal(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, _unequal, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, _unequal, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, _unequal, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, _unequal, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, _unequal, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, _unequal, true).valueOf(); + } + }); + + function _unequal(x, y) { + return !equalScalar(x, y); + } + + return unequal; +}); +var createUnequalNumber = Object(factory["a" /* factory */])(unequal_name, ['typed', 'equalScalar'], function (_ref2) { + var typed = _ref2.typed, + equalScalar = _ref2.equalScalar; + return typed(unequal_name, { + 'any, any': function anyAny(x, y) { + // strict equality for null and undefined? + if (x === null) { + return y !== null; + } + + if (y === null) { + return x !== null; + } + + if (x === undefined) { + return y !== undefined; + } + + if (y === undefined) { + return x !== undefined; + } + + return !equalScalar(x, y); + } + }); +}); +// CONCATENATED MODULE: ./src/function/matrix/partitionSelect.js + + + +var partitionSelect_name = 'partitionSelect'; +var partitionSelect_dependencies = ['typed', 'isNumeric', 'isNaN', 'compare']; +var createPartitionSelect = /* #__PURE__ */Object(factory["a" /* factory */])(partitionSelect_name, partitionSelect_dependencies, function (_ref) { + var typed = _ref.typed, + isNumeric = _ref.isNumeric, + isNaN = _ref.isNaN, + compare = _ref.compare; + var asc = compare; + + var desc = function desc(a, b) { + return -compare(a, b); + }; + /** + * Partition-based selection of an array or 1D matrix. + * Will find the kth smallest value, and mutates the input array. + * Uses Quickselect. + * + * Syntax: + * + * math.partitionSelect(x, k) + * math.partitionSelect(x, k, compare) + * + * Examples: + * + * math.partitionSelect([5, 10, 1], 2) // returns 10 + * math.partitionSelect(['C', 'B', 'A', 'D'], 1) // returns 'B' + * + * function sortByLength (a, b) { + * return a.length - b.length + * } + * math.partitionSelect(['Langdon', 'Tom', 'Sara'], 2, sortByLength) // returns 'Langdon' + * + * See also: + * + * sort + * + * @param {Matrix | Array} x A one dimensional matrix or array to sort + * @param {Number} k The kth smallest value to be retrieved zero-based index + * @param {Function | 'asc' | 'desc'} [compare='asc'] + * An optional comparator function. The function is called as + * `compare(a, b)`, and must return 1 when a > b, -1 when a < b, + * and 0 when a == b. + * @return {*} Returns the kth lowest value. + */ + + + return typed(partitionSelect_name, { + 'Array | Matrix, number': function ArrayMatrixNumber(x, k) { + return _partitionSelect(x, k, asc); + }, + 'Array | Matrix, number, string': function ArrayMatrixNumberString(x, k, compare) { + if (compare === 'asc') { + return _partitionSelect(x, k, asc); + } else if (compare === 'desc') { + return _partitionSelect(x, k, desc); + } else { + throw new Error('Compare string must be "asc" or "desc"'); + } + }, + 'Array | Matrix, number, function': _partitionSelect + }); + + function _partitionSelect(x, k, compare) { + if (!Object(utils_number["i" /* isInteger */])(k) || k < 0) { + throw new Error('k must be a non-negative integer'); + } + + if (Object(is["v" /* isMatrix */])(x)) { + var size = x.size(); + + if (size.length > 1) { + throw new Error('Only one dimensional matrices supported'); + } + + return quickSelect(x.valueOf(), k, compare); + } + + if (Array.isArray(x)) { + return quickSelect(x, k, compare); + } + } + /** + * Quickselect algorithm. + * Code adapted from: + * https://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html + * + * @param {Array} arr + * @param {Number} k + * @param {Function} compare + * @private + */ + + + function quickSelect(arr, k, compare) { + if (k >= arr.length) { + throw new Error('k out of bounds'); + } // check for NaN values since these can cause an infinite while loop + + + for (var i = 0; i < arr.length; i++) { + if (isNumeric(arr[i]) && isNaN(arr[i])) { + return arr[i]; // return NaN + } + } + + var from = 0; + var to = arr.length - 1; // if from == to we reached the kth element + + while (from < to) { + var r = from; + var w = to; + var pivot = arr[Math.floor(Math.random() * (to - from + 1)) + from]; // stop if the reader and writer meets + + while (r < w) { + // arr[r] >= pivot + if (compare(arr[r], pivot) >= 0) { + // put the large values at the end + var tmp = arr[w]; + arr[w] = arr[r]; + arr[r] = tmp; + --w; + } else { + // the value is smaller than the pivot, skip + ++r; + } + } // if we stepped up (r++) we need to step one down (arr[r] > pivot) + + + if (compare(arr[r], pivot) > 0) { + --r; + } // the r pointer is on the end of the first k elements + + + if (k <= r) { + to = r; + } else { + from = r + 1; + } + } + + return arr[k]; + } +}); +// CONCATENATED MODULE: ./src/function/matrix/sort.js + + +var sort_name = 'sort'; +var sort_dependencies = ['typed', 'matrix', 'compare', 'compareNatural']; +var createSort = /* #__PURE__ */Object(factory["a" /* factory */])(sort_name, sort_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + compare = _ref.compare, + compareNatural = _ref.compareNatural; + var compareAsc = compare; + + var compareDesc = function compareDesc(a, b) { + return -compare(a, b); + }; + /** + * Sort the items in a matrix. + * + * Syntax: + * + * math.sort(x) + * math.sort(x, compare) + * + * Examples: + * + * math.sort([5, 10, 1]) // returns [1, 5, 10] + * math.sort(['C', 'B', 'A', 'D'], math.compareNatural) + * // returns ['A', 'B', 'C', 'D'] + * + * function sortByLength (a, b) { + * return a.length - b.length + * } + * math.sort(['Langdon', 'Tom', 'Sara'], sortByLength) + * // returns ['Tom', 'Sara', 'Langdon'] + * + * See also: + * + * filter, forEach, map, compare, compareNatural + * + * @param {Matrix | Array} x A one dimensional matrix or array to sort + * @param {Function | 'asc' | 'desc' | 'natural'} [compare='asc'] + * An optional _comparator function or name. The function is called as + * `compare(a, b)`, and must return 1 when a > b, -1 when a < b, + * and 0 when a == b. + * @return {Matrix | Array} Returns the sorted matrix. + */ + + + return typed(sort_name, { + Array: function Array(x) { + _arrayIsVector(x); + + return x.sort(compareAsc); + }, + Matrix: function Matrix(x) { + _matrixIsVector(x); + + return matrix(x.toArray().sort(compareAsc), x.storage()); + }, + 'Array, function': function ArrayFunction(x, _comparator) { + _arrayIsVector(x); + + return x.sort(_comparator); + }, + 'Matrix, function': function MatrixFunction(x, _comparator) { + _matrixIsVector(x); + + return matrix(x.toArray().sort(_comparator), x.storage()); + }, + 'Array, string': function ArrayString(x, order) { + _arrayIsVector(x); + + return x.sort(_comparator(order)); + }, + 'Matrix, string': function MatrixString(x, order) { + _matrixIsVector(x); + + return matrix(x.toArray().sort(_comparator(order)), x.storage()); + } + }); + /** + * Get the comparator for given order ('asc', 'desc', 'natural') + * @param {'asc' | 'desc' | 'natural'} order + * @return {Function} Returns a _comparator function + */ + + function _comparator(order) { + if (order === 'asc') { + return compareAsc; + } else if (order === 'desc') { + return compareDesc; + } else if (order === 'natural') { + return compareNatural; + } else { + throw new Error('String "asc", "desc", or "natural" expected'); + } + } + /** + * Validate whether an array is one dimensional + * Throws an error when this is not the case + * @param {Array} array + * @private + */ + + + function _arrayIsVector(array) { + if (Object(utils_array["a" /* arraySize */])(array).length !== 1) { + throw new Error('One dimensional array expected'); + } + } + /** + * Validate whether a matrix is one dimensional + * Throws an error when this is not the case + * @param {Matrix} matrix + * @private + */ + + + function _matrixIsVector(matrix) { + if (matrix.size().length !== 1) { + throw new Error('One dimensional matrix expected'); + } + } +}); +// CONCATENATED MODULE: ./src/function/statistics/max.js + + + +var max_name = 'max'; +var max_dependencies = ['typed', 'larger']; +var createMax = /* #__PURE__ */Object(factory["a" /* factory */])(max_name, max_dependencies, function (_ref) { + var typed = _ref.typed, + larger = _ref.larger; + + /** + * Compute the maximum value of a matrix or a list with values. + * In case of a multi dimensional array, the maximum of the flattened array + * will be calculated. When `dim` is provided, the maximum over the selected + * dimension will be calculated. Parameter `dim` is zero-based. + * + * Syntax: + * + * math.max(a, b, c, ...) + * math.max(A) + * math.max(A, dim) + * + * Examples: + * + * math.max(2, 1, 4, 3) // returns 4 + * math.max([2, 1, 4, 3]) // returns 4 + * + * // maximum over a specified dimension (zero-based) + * math.max([[2, 5], [4, 3], [1, 7]], 0) // returns [4, 7] + * math.max([[2, 5], [4, 3]], [1, 7], 1) // returns [5, 4, 7] + * + * math.max(2.7, 7.1, -4.5, 2.0, 4.1) // returns 7.1 + * math.min(2.7, 7.1, -4.5, 2.0, 4.1) // returns -4.5 + * + * See also: + * + * mean, median, min, prod, std, sum, variance + * + * @param {... *} args A single matrix or or multiple scalar values + * @return {*} The maximum value + */ + return typed(max_name, { + // max([a, b, c, d, ...]) + 'Array | Matrix': _max, + // max([a, b, c, d, ...], dim) + 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) { + return reduce(array, dim.valueOf(), _largest); + }, + // max(a, b, c, d, ...) + '...': function _(args) { + if (containsCollections(args)) { + throw new TypeError('Scalar values expected in function max'); + } + + return _max(args); + } + }); + /** + * Return the largest of two values + * @param {*} x + * @param {*} y + * @returns {*} Returns x when x is largest, or y when y is largest + * @private + */ + + function _largest(x, y) { + try { + return larger(x, y) ? x : y; + } catch (err) { + throw improveErrorMessage(err, 'max', y); + } + } + /** + * Recursively calculate the maximum value in an n-dimensional array + * @param {Array} array + * @return {number} max + * @private + */ + + + function _max(array) { + var res; + deepForEach(array, function (value) { + try { + if (isNaN(value) && typeof value === 'number') { + res = NaN; + } else if (res === undefined || larger(value, res)) { + res = value; + } + } catch (err) { + throw improveErrorMessage(err, 'max', value); + } + }); + + if (res === undefined) { + throw new Error('Cannot calculate max of an empty array'); + } + + return res; + } +}); +// CONCATENATED MODULE: ./src/function/statistics/min.js + + + +var min_name = 'min'; +var min_dependencies = ['typed', 'smaller']; +var createMin = /* #__PURE__ */Object(factory["a" /* factory */])(min_name, min_dependencies, function (_ref) { + var typed = _ref.typed, + smaller = _ref.smaller; + + /** + * Compute the minimum value of a matrix or a list of values. + * In case of a multi dimensional array, the minimum of the flattened array + * will be calculated. When `dim` is provided, the minimum over the selected + * dimension will be calculated. Parameter `dim` is zero-based. + * + * Syntax: + * + * math.min(a, b, c, ...) + * math.min(A) + * math.min(A, dim) + * + * Examples: + * + * math.min(2, 1, 4, 3) // returns 1 + * math.min([2, 1, 4, 3]) // returns 1 + * + * // minimum over a specified dimension (zero-based) + * math.min([[2, 5], [4, 3], [1, 7]], 0) // returns [1, 3] + * math.min([[2, 5], [4, 3], [1, 7]], 1) // returns [2, 3, 1] + * + * math.max(2.7, 7.1, -4.5, 2.0, 4.1) // returns 7.1 + * math.min(2.7, 7.1, -4.5, 2.0, 4.1) // returns -4.5 + * + * See also: + * + * mean, median, max, prod, std, sum, variance + * + * @param {... *} args A single matrix or or multiple scalar values + * @return {*} The minimum value + */ + return typed(min_name, { + // min([a, b, c, d, ...]) + 'Array | Matrix': _min, + // min([a, b, c, d, ...], dim) + 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) { + return reduce(array, dim.valueOf(), _smallest); + }, + // min(a, b, c, d, ...) + '...': function _(args) { + if (containsCollections(args)) { + throw new TypeError('Scalar values expected in function min'); + } + + return _min(args); + } + }); + /** + * Return the smallest of two values + * @param {*} x + * @param {*} y + * @returns {*} Returns x when x is smallest, or y when y is smallest + * @private + */ + + function _smallest(x, y) { + try { + return smaller(x, y) ? x : y; + } catch (err) { + throw improveErrorMessage(err, 'min', y); + } + } + /** + * Recursively calculate the minimum value in an n-dimensional array + * @param {Array} array + * @return {number} min + * @private + */ + + + function _min(array) { + var min; + deepForEach(array, function (value) { + try { + if (isNaN(value) && typeof value === 'number') { + min = NaN; + } else if (min === undefined || smaller(value, min)) { + min = value; + } + } catch (err) { + throw improveErrorMessage(err, 'min', value); + } + }); + + if (min === undefined) { + throw new Error('Cannot calculate min of an empty array'); + } + + return min; + } +}); +// CONCATENATED MODULE: ./src/type/matrix/ImmutableDenseMatrix.js + + + +var ImmutableDenseMatrix_name = 'ImmutableDenseMatrix'; +var ImmutableDenseMatrix_dependencies = ['smaller', 'DenseMatrix']; +var createImmutableDenseMatrixClass = /* #__PURE__ */Object(factory["a" /* factory */])(ImmutableDenseMatrix_name, ImmutableDenseMatrix_dependencies, function (_ref) { + var smaller = _ref.smaller, + DenseMatrix = _ref.DenseMatrix; + + function ImmutableDenseMatrix(data, datatype) { + if (!(this instanceof ImmutableDenseMatrix)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (datatype && !Object(is["I" /* isString */])(datatype)) { + throw new Error('Invalid datatype: ' + datatype); + } + + if (Object(is["v" /* isMatrix */])(data) || Object(is["b" /* isArray */])(data)) { + // use DenseMatrix implementation + var matrix = new DenseMatrix(data, datatype); // internal structures + + this._data = matrix._data; + this._size = matrix._size; + this._datatype = matrix._datatype; + this._min = null; + this._max = null; + } else if (data && Object(is["b" /* isArray */])(data.data) && Object(is["b" /* isArray */])(data.size)) { + // initialize fields from JSON representation + this._data = data.data; + this._size = data.size; + this._datatype = data.datatype; + this._min = typeof data.min !== 'undefined' ? data.min : null; + this._max = typeof data.max !== 'undefined' ? data.max : null; + } else if (data) { + // unsupported type + throw new TypeError('Unsupported type of data (' + Object(is["M" /* typeOf */])(data) + ')'); + } else { + // nothing provided + this._data = []; + this._size = [0]; + this._datatype = datatype; + this._min = null; + this._max = null; + } + } + + ImmutableDenseMatrix.prototype = new DenseMatrix(); + /** + * Attach type information + */ + + ImmutableDenseMatrix.prototype.type = 'ImmutableDenseMatrix'; + ImmutableDenseMatrix.prototype.isImmutableDenseMatrix = true; + /** + * Get a subset of the matrix, or replace a subset of the matrix. + * + * Usage: + * const subset = matrix.subset(index) // retrieve subset + * const value = matrix.subset(index, replacement) // replace subset + * + * @param {Index} index + * @param {Array | ImmutableDenseMatrix | *} [replacement] + * @param {*} [defaultValue=0] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be filled with zeros. + */ + + ImmutableDenseMatrix.prototype.subset = function (index) { + switch (arguments.length) { + case 1: + { + // use base implementation + var m = DenseMatrix.prototype.subset.call(this, index); // check result is a matrix + + if (Object(is["v" /* isMatrix */])(m)) { + // return immutable matrix + return new ImmutableDenseMatrix({ + data: m._data, + size: m._size, + datatype: m._datatype + }); + } + + return m; + } + // intentional fall through + + case 2: + case 3: + throw new Error('Cannot invoke set subset on an Immutable Matrix instance'); + + default: + throw new SyntaxError('Wrong number of arguments'); + } + }; + /** + * Replace a single element in the matrix. + * @param {Number[]} index Zero-based index + * @param {*} value + * @param {*} [defaultValue] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be left undefined. + * @return {ImmutableDenseMatrix} self + */ + + + ImmutableDenseMatrix.prototype.set = function () { + throw new Error('Cannot invoke set on an Immutable Matrix instance'); + }; + /** + * Resize the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (resize in place). + * + * @param {Number[]} size The new size the matrix should have. + * @param {*} [defaultValue=0] Default value, filled in on new entries. + * If not provided, the matrix elements will + * be filled with zeros. + * @param {boolean} [copy] Return a resized copy of the matrix + * + * @return {Matrix} The resized matrix + */ + + + ImmutableDenseMatrix.prototype.resize = function () { + throw new Error('Cannot invoke resize on an Immutable Matrix instance'); + }; + /** + * Disallows reshaping in favor of immutability. + * + * @throws {Error} Operation not allowed + */ + + + ImmutableDenseMatrix.prototype.reshape = function () { + throw new Error('Cannot invoke reshape on an Immutable Matrix instance'); + }; + /** + * Create a clone of the matrix + * @return {ImmutableDenseMatrix} clone + */ + + + ImmutableDenseMatrix.prototype.clone = function () { + return new ImmutableDenseMatrix({ + data: Object(utils_object["a" /* clone */])(this._data), + size: Object(utils_object["a" /* clone */])(this._size), + datatype: this._datatype + }); + }; + /** + * Get a JSON representation of the matrix + * @returns {Object} + */ + + + ImmutableDenseMatrix.prototype.toJSON = function () { + return { + mathjs: 'ImmutableDenseMatrix', + data: this._data, + size: this._size, + datatype: this._datatype + }; + }; + /** + * Generate a matrix from a JSON object + * @param {Object} json An object structured like + * `{"mathjs": "ImmutableDenseMatrix", data: [], size: []}`, + * where mathjs is optional + * @returns {ImmutableDenseMatrix} + */ + + + ImmutableDenseMatrix.fromJSON = function (json) { + return new ImmutableDenseMatrix(json); + }; + /** + * Swap rows i and j in Matrix. + * + * @param {Number} i Matrix row index 1 + * @param {Number} j Matrix row index 2 + * + * @return {Matrix} The matrix reference + */ + + + ImmutableDenseMatrix.prototype.swapRows = function () { + throw new Error('Cannot invoke swapRows on an Immutable Matrix instance'); + }; + /** + * Calculate the minimum value in the set + * @return {Number | undefined} min + */ + + + ImmutableDenseMatrix.prototype.min = function () { + // check min has been calculated before + if (this._min === null) { + // minimum + var m = null; // compute min + + this.forEach(function (v) { + if (m === null || smaller(v, m)) { + m = v; + } + }); + this._min = m !== null ? m : undefined; + } + + return this._min; + }; + /** + * Calculate the maximum value in the set + * @return {Number | undefined} max + */ + + + ImmutableDenseMatrix.prototype.max = function () { + // check max has been calculated before + if (this._max === null) { + // maximum + var m = null; // compute max + + this.forEach(function (v) { + if (m === null || smaller(m, v)) { + m = v; + } + }); + this._max = m !== null ? m : undefined; + } + + return this._max; + }; + + return ImmutableDenseMatrix; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/matrix/MatrixIndex.js + + + + +var MatrixIndex_name = 'Index'; +var MatrixIndex_dependencies = ['ImmutableDenseMatrix']; +var createIndexClass = /* #__PURE__ */Object(factory["a" /* factory */])(MatrixIndex_name, MatrixIndex_dependencies, function (_ref) { + var ImmutableDenseMatrix = _ref.ImmutableDenseMatrix; + + /** + * Create an index. An Index can store ranges and sets for multiple dimensions. + * Matrix.get, Matrix.set, and math.subset accept an Index as input. + * + * Usage: + * const index = new Index(range1, range2, matrix1, array1, ...) + * + * Where each parameter can be any of: + * A number + * A string (containing a name of an object property) + * An instance of Range + * An Array with the Set values + * A Matrix with the Set values + * + * The parameters start, end, and step must be integer numbers. + * + * @class Index + * @Constructor Index + * @param {...*} ranges + */ + function Index(ranges) { + if (!(this instanceof Index)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this._dimensions = []; + this._isScalar = true; + + for (var i = 0, ii = arguments.length; i < ii; i++) { + var arg = arguments[i]; + + if (Object(is["D" /* isRange */])(arg)) { + this._dimensions.push(arg); + + this._isScalar = false; + } else if (Array.isArray(arg) || Object(is["v" /* isMatrix */])(arg)) { + // create matrix + var m = _createImmutableMatrix(arg.valueOf()); + + this._dimensions.push(m); // size + + + var size = m.size(); // scalar + + if (size.length !== 1 || size[0] !== 1) { + this._isScalar = false; + } + } else if (typeof arg === 'number') { + this._dimensions.push(_createImmutableMatrix([arg])); + } else if (typeof arg === 'string') { + // object property (arguments.count should be 1) + this._dimensions.push(arg); + } else { + throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range'); + } // TODO: implement support for wildcard '*' + + } + } + /** + * Attach type information + */ + + + Index.prototype.type = 'Index'; + Index.prototype.isIndex = true; + + function _createImmutableMatrix(arg) { + // loop array elements + for (var i = 0, l = arg.length; i < l; i++) { + if (typeof arg[i] !== 'number' || !Object(utils_number["i" /* isInteger */])(arg[i])) { + throw new TypeError('Index parameters must be positive integer numbers'); + } + } // create matrix + + + return new ImmutableDenseMatrix(arg); + } + /** + * Create a clone of the index + * @memberof Index + * @return {Index} clone + */ + + + Index.prototype.clone = function () { + var index = new Index(); + index._dimensions = Object(utils_object["a" /* clone */])(this._dimensions); + index._isScalar = this._isScalar; + return index; + }; + /** + * Create an index from an array with ranges/numbers + * @memberof Index + * @param {Array.} ranges + * @return {Index} index + * @private + */ + + + Index.create = function (ranges) { + var index = new Index(); + Index.apply(index, ranges); + return index; + }; + /** + * Retrieve the size of the index, the number of elements for each dimension. + * @memberof Index + * @returns {number[]} size + */ + + + Index.prototype.size = function () { + var size = []; + + for (var i = 0, ii = this._dimensions.length; i < ii; i++) { + var d = this._dimensions[i]; + size[i] = typeof d === 'string' ? 1 : d.size()[0]; + } + + return size; + }; + /** + * Get the maximum value for each of the indexes ranges. + * @memberof Index + * @returns {number[]} max + */ + + + Index.prototype.max = function () { + var values = []; + + for (var i = 0, ii = this._dimensions.length; i < ii; i++) { + var range = this._dimensions[i]; + values[i] = typeof range === 'string' ? range : range.max(); + } + + return values; + }; + /** + * Get the minimum value for each of the indexes ranges. + * @memberof Index + * @returns {number[]} min + */ + + + Index.prototype.min = function () { + var values = []; + + for (var i = 0, ii = this._dimensions.length; i < ii; i++) { + var range = this._dimensions[i]; + values[i] = typeof range === 'string' ? range : range.min(); + } + + return values; + }; + /** + * Loop over each of the ranges of the index + * @memberof Index + * @param {Function} callback Called for each range with a Range as first + * argument, the dimension as second, and the + * index object as third. + */ + + + Index.prototype.forEach = function (callback) { + for (var i = 0, ii = this._dimensions.length; i < ii; i++) { + callback(this._dimensions[i], i, this); + } + }; + /** + * Retrieve the dimension for the given index + * @memberof Index + * @param {Number} dim Number of the dimension + * @returns {Range | null} range + */ + + + Index.prototype.dimension = function (dim) { + return this._dimensions[dim] || null; + }; + /** + * Test whether this index contains an object property + * @returns {boolean} Returns true if the index is an object property + */ + + + Index.prototype.isObjectProperty = function () { + return this._dimensions.length === 1 && typeof this._dimensions[0] === 'string'; + }; + /** + * Returns the object property name when the Index holds a single object property, + * else returns null + * @returns {string | null} + */ + + + Index.prototype.getObjectProperty = function () { + return this.isObjectProperty() ? this._dimensions[0] : null; + }; + /** + * Test whether this index contains only a single value. + * + * This is the case when the index is created with only scalar values as ranges, + * not for ranges resolving into a single value. + * @memberof Index + * @return {boolean} isScalar + */ + + + Index.prototype.isScalar = function () { + return this._isScalar; + }; + /** + * Expand the Index into an array. + * For example new Index([0,3], [2,7]) returns [[0,1,2], [2,3,4,5,6]] + * @memberof Index + * @returns {Array} array + */ + + + Index.prototype.toArray = function () { + var array = []; + + for (var i = 0, ii = this._dimensions.length; i < ii; i++) { + var dimension = this._dimensions[i]; + array.push(typeof dimension === 'string' ? dimension : dimension.toArray()); + } + + return array; + }; + /** + * Get the primitive value of the Index, a two dimensional array. + * Equivalent to Index.toArray(). + * @memberof Index + * @returns {Array} array + */ + + + Index.prototype.valueOf = Index.prototype.toArray; + /** + * Get the string representation of the index, for example '[2:6]' or '[0:2:10, 4:7, [1,2,3]]' + * @memberof Index + * @returns {String} str + */ + + Index.prototype.toString = function () { + var strings = []; + + for (var i = 0, ii = this._dimensions.length; i < ii; i++) { + var dimension = this._dimensions[i]; + + if (typeof dimension === 'string') { + strings.push(JSON.stringify(dimension)); + } else { + strings.push(dimension.toString()); + } + } + + return '[' + strings.join(', ') + ']'; + }; + /** + * Get a JSON representation of the Index + * @memberof Index + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "Index", "ranges": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}` + */ + + + Index.prototype.toJSON = function () { + return { + mathjs: 'Index', + dimensions: this._dimensions + }; + }; + /** + * Instantiate an Index from a JSON object + * @memberof Index + * @param {Object} json A JSON object structured as: + * `{"mathjs": "Index", "dimensions": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}` + * @return {Index} + */ + + + Index.fromJSON = function (json) { + return Index.create(json.dimensions); + }; + + return Index; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/matrix/FibonacciHeap.js + +var FibonacciHeap_name = 'FibonacciHeap'; +var FibonacciHeap_dependencies = ['smaller', 'larger']; +var createFibonacciHeapClass = /* #__PURE__ */Object(factory["a" /* factory */])(FibonacciHeap_name, FibonacciHeap_dependencies, function (_ref) { + var smaller = _ref.smaller, + larger = _ref.larger; + var oneOverLogPhi = 1.0 / Math.log((1.0 + Math.sqrt(5.0)) / 2.0); + /** + * Fibonacci Heap implementation, used interally for Matrix math. + * @class FibonacciHeap + * @constructor FibonacciHeap + */ + + function FibonacciHeap() { + if (!(this instanceof FibonacciHeap)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // initialize fields + + + this._minimum = null; + this._size = 0; + } + /** + * Attach type information + */ + + + FibonacciHeap.prototype.type = 'FibonacciHeap'; + FibonacciHeap.prototype.isFibonacciHeap = true; + /** + * Inserts a new data element into the heap. No heap consolidation is + * performed at this time, the new node is simply inserted into the root + * list of this heap. Running time: O(1) actual. + * @memberof FibonacciHeap + */ + + FibonacciHeap.prototype.insert = function (key, value) { + // create node + var node = { + key: key, + value: value, + degree: 0 + }; // check we have a node in the minimum + + if (this._minimum) { + // minimum node + var minimum = this._minimum; // update left & right of node + + node.left = minimum; + node.right = minimum.right; + minimum.right = node; + node.right.left = node; // update minimum node in heap if needed + + if (smaller(key, minimum.key)) { + // node has a smaller key, use it as minimum + this._minimum = node; + } + } else { + // set left & right + node.left = node; + node.right = node; // this is the first node + + this._minimum = node; + } // increment number of nodes in heap + + + this._size++; // return node + + return node; + }; + /** + * Returns the number of nodes in heap. Running time: O(1) actual. + * @memberof FibonacciHeap + */ + + + FibonacciHeap.prototype.size = function () { + return this._size; + }; + /** + * Removes all elements from this heap. + * @memberof FibonacciHeap + */ + + + FibonacciHeap.prototype.clear = function () { + this._minimum = null; + this._size = 0; + }; + /** + * Returns true if the heap is empty, otherwise false. + * @memberof FibonacciHeap + */ + + + FibonacciHeap.prototype.isEmpty = function () { + return this._size === 0; + }; + /** + * Extracts the node with minimum key from heap. Amortized running + * time: O(log n). + * @memberof FibonacciHeap + */ + + + FibonacciHeap.prototype.extractMinimum = function () { + // node to remove + var node = this._minimum; // check we have a minimum + + if (node === null) { + return node; + } // current minimum + + + var minimum = this._minimum; // get number of children + + var numberOfChildren = node.degree; // pointer to the first child + + var x = node.child; // for each child of node do... + + while (numberOfChildren > 0) { + // store node in right side + var tempRight = x.right; // remove x from child list + + x.left.right = x.right; + x.right.left = x.left; // add x to root list of heap + + x.left = minimum; + x.right = minimum.right; + minimum.right = x; + x.right.left = x; // set Parent[x] to null + + x.parent = null; + x = tempRight; + numberOfChildren--; + } // remove node from root list of heap + + + node.left.right = node.right; + node.right.left = node.left; // update minimum + + if (node === node.right) { + // empty + minimum = null; + } else { + // update minimum + minimum = node.right; // we need to update the pointer to the root with minimum key + + minimum = _findMinimumNode(minimum, this._size); + } // decrement size of heap + + + this._size--; // update minimum + + this._minimum = minimum; // return node + + return node; + }; + /** + * Removes a node from the heap given the reference to the node. The trees + * in the heap will be consolidated, if necessary. This operation may fail + * to remove the correct element if there are nodes with key value -Infinity. + * Running time: O(log n) amortized. + * @memberof FibonacciHeap + */ + + + FibonacciHeap.prototype.remove = function (node) { + // decrease key value + this._minimum = _decreaseKey(this._minimum, node, -1); // remove the smallest + + this.extractMinimum(); + }; + /** + * Decreases the key value for a heap node, given the new value to take on. + * The structure of the heap may be changed and will not be consolidated. + * Running time: O(1) amortized. + * @memberof FibonacciHeap + */ + + + function _decreaseKey(minimum, node, key) { + // set node key + node.key = key; // get parent node + + var parent = node.parent; + + if (parent && smaller(node.key, parent.key)) { + // remove node from parent + _cut(minimum, node, parent); // remove all nodes from parent to the root parent + + + _cascadingCut(minimum, parent); + } // update minimum node if needed + + + if (smaller(node.key, minimum.key)) { + minimum = node; + } // return minimum + + + return minimum; + } + /** + * The reverse of the link operation: removes node from the child list of parent. + * This method assumes that min is non-null. Running time: O(1). + * @memberof FibonacciHeap + */ + + + function _cut(minimum, node, parent) { + // remove node from parent children and decrement Degree[parent] + node.left.right = node.right; + node.right.left = node.left; + parent.degree--; // reset y.child if necessary + + if (parent.child === node) { + parent.child = node.right; + } // remove child if degree is 0 + + + if (parent.degree === 0) { + parent.child = null; + } // add node to root list of heap + + + node.left = minimum; + node.right = minimum.right; + minimum.right = node; + node.right.left = node; // set parent[node] to null + + node.parent = null; // set mark[node] to false + + node.mark = false; + } + /** + * Performs a cascading cut operation. This cuts node from its parent and then + * does the same for its parent, and so on up the tree. + * Running time: O(log n); O(1) excluding the recursion. + * @memberof FibonacciHeap + */ + + + function _cascadingCut(minimum, node) { + // store parent node + var parent = node.parent; // if there's a parent... + + if (!parent) { + return; + } // if node is unmarked, set it marked + + + if (!node.mark) { + node.mark = true; + } else { + // it's marked, cut it from parent + _cut(minimum, node, parent); // cut its parent as well + + + _cascadingCut(parent); + } + } + /** + * Make the first node a child of the second one. Running time: O(1) actual. + * @memberof FibonacciHeap + */ + + + var _linkNodes = function _linkNodes(node, parent) { + // remove node from root list of heap + node.left.right = node.right; + node.right.left = node.left; // make node a Child of parent + + node.parent = parent; + + if (!parent.child) { + parent.child = node; + node.right = node; + node.left = node; + } else { + node.left = parent.child; + node.right = parent.child.right; + parent.child.right = node; + node.right.left = node; + } // increase degree[parent] + + + parent.degree++; // set mark[node] false + + node.mark = false; + }; + + function _findMinimumNode(minimum, size) { + // to find trees of the same degree efficiently we use an array of length O(log n) in which we keep a pointer to one root of each degree + var arraySize = Math.floor(Math.log(size) * oneOverLogPhi) + 1; // create list with initial capacity + + var array = new Array(arraySize); // find the number of root nodes. + + var numRoots = 0; + var x = minimum; + + if (x) { + numRoots++; + x = x.right; + + while (x !== minimum) { + numRoots++; + x = x.right; + } + } // vars + + + var y; // For each node in root list do... + + while (numRoots > 0) { + // access this node's degree.. + var d = x.degree; // get next node + + var next = x.right; // check if there is a node already in array with the same degree + + while (true) { + // get node with the same degree is any + y = array[d]; + + if (!y) { + break; + } // make one node with the same degree a child of the other, do this based on the key value. + + + if (larger(x.key, y.key)) { + var temp = y; + y = x; + x = temp; + } // make y a child of x + + + _linkNodes(y, x); // we have handled this degree, go to next one. + + + array[d] = null; + d++; + } // save this node for later when we might encounter another of the same degree. + + + array[d] = x; // move forward through list. + + x = next; + numRoots--; + } // Set min to null (effectively losing the root list) and reconstruct the root list from the array entries in array[]. + + + minimum = null; // loop nodes in array + + for (var i = 0; i < arraySize; i++) { + // get current node + y = array[i]; + + if (!y) { + continue; + } // check if we have a linked list + + + if (minimum) { + // First remove node from root list. + y.left.right = y.right; + y.right.left = y.left; // now add to root list, again. + + y.left = minimum; + y.right = minimum.right; + minimum.right = y; + y.right.left = y; // check if this is a new min. + + if (smaller(y.key, minimum.key)) { + minimum = y; + } + } else { + minimum = y; + } + } + + return minimum; + } + + return FibonacciHeap; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/matrix/Spa.js + +var Spa_name = 'Spa'; +var Spa_dependencies = ['addScalar', 'equalScalar', 'FibonacciHeap']; +var createSpaClass = /* #__PURE__ */Object(factory["a" /* factory */])(Spa_name, Spa_dependencies, function (_ref) { + var addScalar = _ref.addScalar, + equalScalar = _ref.equalScalar, + FibonacciHeap = _ref.FibonacciHeap; + + /** + * An ordered Sparse Accumulator is a representation for a sparse vector that includes a dense array + * of the vector elements and an ordered list of non-zero elements. + */ + function Spa() { + if (!(this instanceof Spa)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // allocate vector, TODO use typed arrays + + + this._values = []; + this._heap = new FibonacciHeap(); + } + /** + * Attach type information + */ + + + Spa.prototype.type = 'Spa'; + Spa.prototype.isSpa = true; + /** + * Set the value for index i. + * + * @param {number} i The index + * @param {number | BigNumber | Complex} The value at index i + */ + + Spa.prototype.set = function (i, v) { + // check we have a value @ i + if (!this._values[i]) { + // insert in heap + var node = this._heap.insert(i, v); // set the value @ i + + + this._values[i] = node; + } else { + // update the value @ i + this._values[i].value = v; + } + }; + + Spa.prototype.get = function (i) { + var node = this._values[i]; + + if (node) { + return node.value; + } + + return 0; + }; + + Spa.prototype.accumulate = function (i, v) { + // node @ i + var node = this._values[i]; + + if (!node) { + // insert in heap + node = this._heap.insert(i, v); // initialize value + + this._values[i] = node; + } else { + // accumulate value + node.value = addScalar(node.value, v); + } + }; + + Spa.prototype.forEach = function (from, to, callback) { + // references + var heap = this._heap; + var values = this._values; // nodes + + var nodes = []; // node with minimum key, save it + + var node = heap.extractMinimum(); + + if (node) { + nodes.push(node); + } // extract nodes from heap (ordered) + + + while (node && node.key <= to) { + // check it is in range + if (node.key >= from) { + // check value is not zero + if (!equalScalar(node.value, 0)) { + // invoke callback + callback(node.key, node.value, this); + } + } // extract next node, save it + + + node = heap.extractMinimum(); + + if (node) { + nodes.push(node); + } + } // reinsert all nodes in heap + + + for (var i = 0; i < nodes.length; i++) { + // current node + var n = nodes[i]; // insert node in heap + + node = heap.insert(n.key, n.value); // update values + + values[node.key] = node; + } + }; + + Spa.prototype.swap = function (i, j) { + // node @ i and j + var nodei = this._values[i]; + var nodej = this._values[j]; // check we need to insert indeces + + if (!nodei && nodej) { + // insert in heap + nodei = this._heap.insert(i, nodej.value); // remove from heap + + this._heap.remove(nodej); // set values + + + this._values[i] = nodei; + this._values[j] = undefined; + } else if (nodei && !nodej) { + // insert in heap + nodej = this._heap.insert(j, nodei.value); // remove from heap + + this._heap.remove(nodei); // set values + + + this._values[j] = nodej; + this._values[i] = undefined; + } else if (nodei && nodej) { + // swap values + var v = nodei.value; + nodei.value = nodej.value; + nodej.value = v; + } + }; + + return Spa; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/utils/bignumber/constants.js + +/** + * Calculate BigNumber e + * @param {function} BigNumber BigNumber constructor + * @returns {BigNumber} Returns e + */ + +var createBigNumberE = memoize(function (BigNumber) { + return new BigNumber(1).exp(); +}, hasher); +/** + * Calculate BigNumber golden ratio, phi = (1+sqrt(5))/2 + * @param {function} BigNumber BigNumber constructor + * @returns {BigNumber} Returns phi + */ + +var createBigNumberPhi = memoize(function (BigNumber) { + return new BigNumber(1).plus(new BigNumber(5).sqrt()).div(2); +}, hasher); +/** + * Calculate BigNumber pi. + * @param {function} BigNumber BigNumber constructor + * @returns {BigNumber} Returns pi + */ + +var createBigNumberPi = memoize(function (BigNumber) { + return BigNumber.acos(-1); +}, hasher); +/** + * Calculate BigNumber tau, tau = 2 * pi + * @param {function} BigNumber BigNumber constructor + * @returns {BigNumber} Returns tau + */ + +var createBigNumberTau = memoize(function (BigNumber) { + return createBigNumberPi(BigNumber).times(2); +}, hasher); +/** + * Create a hash for a BigNumber constructor function. The created has is + * the configured precision + * @param {Array} args Supposed to contain a single entry with + * a BigNumber constructor + * @return {number} precision + * @private + */ + +function hasher(args) { + return args[0].precision; +} +// CONCATENATED MODULE: ./src/type/unit/Unit.js +function Unit_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { Unit_typeof = function _typeof(obj) { return typeof obj; }; } else { Unit_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return Unit_typeof(obj); } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + + + + + + +var Unit_name = 'Unit'; +var Unit_dependencies = ['?on', 'config', 'addScalar', 'subtract', 'multiplyScalar', 'divideScalar', 'pow', 'abs', 'fix', 'round', 'equal', 'isNumeric', 'format', 'number', 'Complex', 'BigNumber', 'Fraction']; +var createUnitClass = /* #__PURE__ */Object(factory["a" /* factory */])(Unit_name, Unit_dependencies, function (_ref) { + var on = _ref.on, + config = _ref.config, + addScalar = _ref.addScalar, + subtract = _ref.subtract, + multiplyScalar = _ref.multiplyScalar, + divideScalar = _ref.divideScalar, + pow = _ref.pow, + abs = _ref.abs, + fix = _ref.fix, + round = _ref.round, + equal = _ref.equal, + isNumeric = _ref.isNumeric, + format = _ref.format, + number = _ref.number, + Complex = _ref.Complex, + _BigNumber = _ref.BigNumber, + _Fraction = _ref.Fraction; + var toNumber = number; + /** + * A unit can be constructed in the following ways: + * + * const a = new Unit(value, name) + * const b = new Unit(null, name) + * const c = Unit.parse(str) + * + * Example usage: + * + * const a = new Unit(5, 'cm') // 50 mm + * const b = Unit.parse('23 kg') // 23 kg + * const c = math.in(a, new Unit(null, 'm') // 0.05 m + * const d = new Unit(9.81, "m/s^2") // 9.81 m/s^2 + * + * @class Unit + * @constructor Unit + * @param {number | BigNumber | Fraction | Complex | boolean} [value] A value like 5.2 + * @param {string} [name] A unit name like "cm" or "inch", or a derived unit of the form: "u1[^ex1] [u2[^ex2] ...] [/ u3[^ex3] [u4[^ex4]]]", such as "kg m^2/s^2", where each unit appearing after the forward slash is taken to be in the denominator. "kg m^2 s^-2" is a synonym and is also acceptable. Any of the units can include a prefix. + */ + + function Unit(value, name) { + if (!(this instanceof Unit)) { + throw new Error('Constructor must be called with the new operator'); + } + + if (!(value === null || value === undefined || isNumeric(value) || Object(is["j" /* isComplex */])(value))) { + throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined'); + } + + if (name !== undefined && (typeof name !== 'string' || name === '')) { + throw new TypeError('Second parameter in Unit constructor must be a string'); + } + + if (name !== undefined) { + var u = Unit.parse(name); + this.units = u.units; + this.dimensions = u.dimensions; + } else { + this.units = [{ + unit: UNIT_NONE, + prefix: PREFIXES.NONE, + // link to a list with supported prefixes + power: 0 + }]; + this.dimensions = []; + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + this.dimensions[i] = 0; + } + } + + this.value = value !== undefined && value !== null ? this._normalize(value) : null; + this.fixPrefix = false; // if true, function format will not search for the + // best prefix but leave it as initially provided. + // fixPrefix is set true by the method Unit.to + // The justification behind this is that if the constructor is explicitly called, + // the caller wishes the units to be returned exactly as he supplied. + + this.skipAutomaticSimplification = true; + } + /** + * Attach type information + */ + + + Unit.prototype.type = 'Unit'; + Unit.prototype.isUnit = true; // private variables and functions for the Unit parser + + var text, index, c; + + function skipWhitespace() { + while (c === ' ' || c === '\t') { + next(); + } + } + + function isDigitDot(c) { + return c >= '0' && c <= '9' || c === '.'; + } + + function isDigit(c) { + return c >= '0' && c <= '9'; + } + + function next() { + index++; + c = text.charAt(index); + } + + function revert(oldIndex) { + index = oldIndex; + c = text.charAt(index); + } + + function parseNumber() { + var number = ''; + var oldIndex = index; + + if (c === '+') { + next(); + } else if (c === '-') { + number += c; + next(); + } + + if (!isDigitDot(c)) { + // a + or - must be followed by a digit + revert(oldIndex); + return null; + } // get number, can have a single dot + + + if (c === '.') { + number += c; + next(); + + if (!isDigit(c)) { + // this is no legal number, it is just a dot + revert(oldIndex); + return null; + } + } else { + while (isDigit(c)) { + number += c; + next(); + } + + if (c === '.') { + number += c; + next(); + } + } + + while (isDigit(c)) { + number += c; + next(); + } // check for exponential notation like "2.3e-4" or "1.23e50" + + + if (c === 'E' || c === 'e') { + // The grammar branches here. This could either be part of an exponent or the start of a unit that begins with the letter e, such as "4exabytes" + var tentativeNumber = ''; + var tentativeIndex = index; + tentativeNumber += c; + next(); + + if (c === '+' || c === '-') { + tentativeNumber += c; + next(); + } // Scientific notation MUST be followed by an exponent (otherwise we assume it is not scientific notation) + + + if (!isDigit(c)) { + // The e or E must belong to something else, so return the number without the e or E. + revert(tentativeIndex); + return number; + } // We can now safely say that this is scientific notation. + + + number = number + tentativeNumber; + + while (isDigit(c)) { + number += c; + next(); + } + } + + return number; + } + + function parseUnit() { + var unitName = ''; // Alphanumeric characters only; matches [a-zA-Z0-9] + + var code = text.charCodeAt(index); + + while (code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122) { + unitName += c; + next(); + code = text.charCodeAt(index); + } // Must begin with [a-zA-Z] + + + code = unitName.charCodeAt(0); + + if (code >= 65 && code <= 90 || code >= 97 && code <= 122) { + return unitName || null; + } else { + return null; + } + } + + function parseCharacter(toFind) { + if (c === toFind) { + next(); + return toFind; + } else { + return null; + } + } + /** + * Parse a string into a unit. The value of the unit is parsed as number, + * BigNumber, or Fraction depending on the math.js config setting `number`. + * + * Throws an exception if the provided string does not contain a valid unit or + * cannot be parsed. + * @memberof Unit + * @param {string} str A string like "5.2 inch", "4e2 cm/s^2" + * @return {Unit} unit + */ + + + Unit.parse = function (str, options) { + options = options || {}; + text = str; + index = -1; + c = ''; + + if (typeof text !== 'string') { + throw new TypeError('Invalid argument in Unit.parse, string expected'); + } + + var unit = new Unit(); + unit.units = []; + var powerMultiplierCurrent = 1; + var expectingUnit = false; // A unit should follow this pattern: + // [number] ...[ [*/] unit[^number] ] + // unit[^number] ... [ [*/] unit[^number] ] + // Rules: + // number is any floating point number. + // unit is any alphanumeric string beginning with an alpha. Units with names like e3 should be avoided because they look like the exponent of a floating point number! + // The string may optionally begin with a number. + // Each unit may optionally be followed by ^number. + // Whitespace or a forward slash is recommended between consecutive units, although the following technically is parseable: + // 2m^2kg/s^2 + // it is not good form. If a unit starts with e, then it could be confused as a floating point number: + // 4erg + + next(); + skipWhitespace(); // Optional number at the start of the string + + var valueStr = parseNumber(); + var value = null; + + if (valueStr) { + if (config.number === 'BigNumber') { + value = new _BigNumber(valueStr); + } else if (config.number === 'Fraction') { + try { + // not all numbers can be turned in Fractions, for example very small numbers not + value = new _Fraction(valueStr); + } catch (err) { + value = parseFloat(valueStr); + } + } else { + // number + value = parseFloat(valueStr); + } + + skipWhitespace(); // Whitespace is not required here + // handle multiplication or division right after the value, like '1/s' + + if (parseCharacter('*')) { + powerMultiplierCurrent = 1; + expectingUnit = true; + } else if (parseCharacter('/')) { + powerMultiplierCurrent = -1; + expectingUnit = true; + } + } // Stack to keep track of powerMultipliers applied to each parentheses group + + + var powerMultiplierStack = []; // Running product of all elements in powerMultiplierStack + + var powerMultiplierStackProduct = 1; + + while (true) { + skipWhitespace(); // Check for and consume opening parentheses, pushing powerMultiplierCurrent to the stack + // A '(' will always appear directly before a unit. + + while (c === '(') { + powerMultiplierStack.push(powerMultiplierCurrent); + powerMultiplierStackProduct *= powerMultiplierCurrent; + powerMultiplierCurrent = 1; + next(); + skipWhitespace(); + } // Is there something here? + + + var uStr = void 0; + + if (c) { + var oldC = c; + uStr = parseUnit(); + + if (uStr === null) { + throw new SyntaxError('Unexpected "' + oldC + '" in "' + text + '" at index ' + index.toString()); + } + } else { + // End of input. + break; + } // Verify the unit exists and get the prefix (if any) + + + var res = _findUnit(uStr); + + if (res === null) { + // Unit not found. + throw new SyntaxError('Unit "' + uStr + '" not found.'); + } + + var power = powerMultiplierCurrent * powerMultiplierStackProduct; // Is there a "^ number"? + + skipWhitespace(); + + if (parseCharacter('^')) { + skipWhitespace(); + var p = parseNumber(); + + if (p === null) { + // No valid number found for the power! + throw new SyntaxError('In "' + str + '", "^" must be followed by a floating-point number'); + } + + power *= p; + } // Add the unit to the list + + + unit.units.push({ + unit: res.unit, + prefix: res.prefix, + power: power + }); + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + unit.dimensions[i] += (res.unit.dimensions[i] || 0) * power; + } // Check for and consume closing parentheses, popping from the stack. + // A ')' will always follow a unit. + + + skipWhitespace(); + + while (c === ')') { + if (powerMultiplierStack.length === 0) { + throw new SyntaxError('Unmatched ")" in "' + text + '" at index ' + index.toString()); + } + + powerMultiplierStackProduct /= powerMultiplierStack.pop(); + next(); + skipWhitespace(); + } // "*" and "/" should mean we are expecting something to come next. + // Is there a forward slash? If so, negate powerMultiplierCurrent. The next unit or paren group is in the denominator. + + + expectingUnit = false; + + if (parseCharacter('*')) { + // explicit multiplication + powerMultiplierCurrent = 1; + expectingUnit = true; + } else if (parseCharacter('/')) { + // division + powerMultiplierCurrent = -1; + expectingUnit = true; + } else { + // implicit multiplication + powerMultiplierCurrent = 1; + } // Replace the unit into the auto unit system + + + if (res.unit.base) { + var baseDim = res.unit.base.key; + UNIT_SYSTEMS.auto[baseDim] = { + unit: res.unit, + prefix: res.prefix + }; + } + } // Has the string been entirely consumed? + + + skipWhitespace(); + + if (c) { + throw new SyntaxError('Could not parse: "' + str + '"'); + } // Is there a trailing slash? + + + if (expectingUnit) { + throw new SyntaxError('Trailing characters: "' + str + '"'); + } // Is the parentheses stack empty? + + + if (powerMultiplierStack.length !== 0) { + throw new SyntaxError('Unmatched "(" in "' + text + '"'); + } // Are there any units at all? + + + if (unit.units.length === 0 && !options.allowNoUnits) { + throw new SyntaxError('"' + str + '" contains no units'); + } + + unit.value = value !== undefined ? unit._normalize(value) : null; + return unit; + }; + /** + * create a copy of this unit + * @memberof Unit + * @return {Unit} Returns a cloned version of the unit + */ + + + Unit.prototype.clone = function () { + var unit = new Unit(); + unit.fixPrefix = this.fixPrefix; + unit.skipAutomaticSimplification = this.skipAutomaticSimplification; + unit.value = Object(utils_object["a" /* clone */])(this.value); + unit.dimensions = this.dimensions.slice(0); + unit.units = []; + + for (var i = 0; i < this.units.length; i++) { + unit.units[i] = {}; + + for (var p in this.units[i]) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.units[i], p)) { + unit.units[i][p] = this.units[i][p]; + } + } + } + + return unit; + }; + /** + * Return whether the unit is derived (such as m/s, or cm^2, but not N) + * @memberof Unit + * @return {boolean} True if the unit is derived + */ + + + Unit.prototype._isDerived = function () { + if (this.units.length === 0) { + return false; + } + + return this.units.length > 1 || Math.abs(this.units[0].power - 1.0) > 1e-15; + }; + /** + * Normalize a value, based on its currently set unit(s) + * @memberof Unit + * @param {number | BigNumber | Fraction | boolean} value + * @return {number | BigNumber | Fraction | boolean} normalized value + * @private + */ + + + Unit.prototype._normalize = function (value) { + var unitValue, unitOffset, unitPower, unitPrefixValue; + var convert; + + if (value === null || value === undefined || this.units.length === 0) { + return value; + } else if (this._isDerived()) { + // This is a derived unit, so do not apply offsets. + // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset. + var res = value; + convert = Unit._getNumberConverter(Object(is["M" /* typeOf */])(value)); // convert to Fraction or BigNumber if needed + + for (var i = 0; i < this.units.length; i++) { + unitValue = convert(this.units[i].unit.value); + unitPrefixValue = convert(this.units[i].prefix.value); + unitPower = convert(this.units[i].power); + res = multiplyScalar(res, pow(multiplyScalar(unitValue, unitPrefixValue), unitPower)); + } + + return res; + } else { + // This is a single unit of power 1, like kg or degC + convert = Unit._getNumberConverter(Object(is["M" /* typeOf */])(value)); // convert to Fraction or BigNumber if needed + + unitValue = convert(this.units[0].unit.value); + unitOffset = convert(this.units[0].unit.offset); + unitPrefixValue = convert(this.units[0].prefix.value); + return multiplyScalar(addScalar(value, unitOffset), multiplyScalar(unitValue, unitPrefixValue)); + } + }; + /** + * Denormalize a value, based on its currently set unit(s) + * @memberof Unit + * @param {number} value + * @param {number} [prefixValue] Optional prefix value to be used (ignored if this is a derived unit) + * @return {number} denormalized value + * @private + */ + + + Unit.prototype._denormalize = function (value, prefixValue) { + var unitValue, unitOffset, unitPower, unitPrefixValue; + var convert; + + if (value === null || value === undefined || this.units.length === 0) { + return value; + } else if (this._isDerived()) { + // This is a derived unit, so do not apply offsets. + // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset. + // Also, prefixValue is ignored--but we will still use the prefix value stored in each unit, since kg is usually preferable to g unless the user decides otherwise. + var res = value; + convert = Unit._getNumberConverter(Object(is["M" /* typeOf */])(value)); // convert to Fraction or BigNumber if needed + + for (var i = 0; i < this.units.length; i++) { + unitValue = convert(this.units[i].unit.value); + unitPrefixValue = convert(this.units[i].prefix.value); + unitPower = convert(this.units[i].power); + res = divideScalar(res, pow(multiplyScalar(unitValue, unitPrefixValue), unitPower)); + } + + return res; + } else { + // This is a single unit of power 1, like kg or degC + convert = Unit._getNumberConverter(Object(is["M" /* typeOf */])(value)); // convert to Fraction or BigNumber if needed + + unitValue = convert(this.units[0].unit.value); + unitPrefixValue = convert(this.units[0].prefix.value); + unitOffset = convert(this.units[0].unit.offset); + + if (prefixValue === undefined || prefixValue === null) { + return subtract(divideScalar(divideScalar(value, unitValue), unitPrefixValue), unitOffset); + } else { + return subtract(divideScalar(divideScalar(value, unitValue), prefixValue), unitOffset); + } + } + }; + /** + * Find a unit from a string + * @memberof Unit + * @param {string} str A string like 'cm' or 'inch' + * @returns {Object | null} result When found, an object with fields unit and + * prefix is returned. Else, null is returned. + * @private + */ + + + function _findUnit(str) { + // First, match units names exactly. For example, a user could define 'mm' as 10^-4 m, which is silly, but then we would want 'mm' to match the user-defined unit. + if (Object(utils_object["f" /* hasOwnProperty */])(UNITS, str)) { + var unit = UNITS[str]; + var prefix = unit.prefixes['']; + return { + unit: unit, + prefix: prefix + }; + } + + for (var _name in UNITS) { + if (Object(utils_object["f" /* hasOwnProperty */])(UNITS, _name)) { + if (Object(utils_string["b" /* endsWith */])(str, _name)) { + var _unit = UNITS[_name]; + var prefixLen = str.length - _name.length; + var prefixName = str.substring(0, prefixLen); + + var _prefix = Object(utils_object["f" /* hasOwnProperty */])(_unit.prefixes, prefixName) ? _unit.prefixes[prefixName] : undefined; + + if (_prefix !== undefined) { + // store unit, prefix, and value + return { + unit: _unit, + prefix: _prefix + }; + } + } + } + } + + return null; + } + /** + * Test if the given expression is a unit. + * The unit can have a prefix but cannot have a value. + * @memberof Unit + * @param {string} name A string to be tested whether it is a value less unit. + * The unit can have prefix, like "cm" + * @return {boolean} true if the given string is a unit + */ + + + Unit.isValuelessUnit = function (name) { + return _findUnit(name) !== null; + }; + /** + * check if this unit has given base unit + * If this unit is a derived unit, this will ALWAYS return false, since by definition base units are not derived. + * @memberof Unit + * @param {BASE_UNITS | string | undefined} base + */ + + + Unit.prototype.hasBase = function (base) { + if (typeof base === 'string') { + base = BASE_UNITS[base]; + } + + if (!base) { + return false; + } // All dimensions must be the same + + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + if (Math.abs((this.dimensions[i] || 0) - (base.dimensions[i] || 0)) > 1e-12) { + return false; + } + } + + return true; + }; + /** + * Check if this unit has a base or bases equal to another base or bases + * For derived units, the exponent on each base also must match + * @memberof Unit + * @param {Unit} other + * @return {boolean} true if equal base + */ + + + Unit.prototype.equalBase = function (other) { + // All dimensions must be the same + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + if (Math.abs((this.dimensions[i] || 0) - (other.dimensions[i] || 0)) > 1e-12) { + return false; + } + } + + return true; + }; + /** + * Check if this unit equals another unit + * @memberof Unit + * @param {Unit} other + * @return {boolean} true if both units are equal + */ + + + Unit.prototype.equals = function (other) { + return this.equalBase(other) && equal(this.value, other.value); + }; + /** + * Multiply this unit with another one + * @memberof Unit + * @param {Unit} other + * @return {Unit} product of this unit and the other unit + */ + + + Unit.prototype.multiply = function (other) { + var res = this.clone(); + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + // Dimensions arrays may be of different lengths. Default to 0. + res.dimensions[i] = (this.dimensions[i] || 0) + (other.dimensions[i] || 0); + } // Append other's units list onto res + + + for (var _i = 0; _i < other.units.length; _i++) { + // Make a deep copy + var inverted = {}; + + for (var key in other.units[_i]) { + inverted[key] = other.units[_i][key]; + } + + res.units.push(inverted); + } // If at least one operand has a value, then the result should also have a value + + + if (this.value !== null || other.value !== null) { + var valThis = this.value === null ? this._normalize(1) : this.value; + var valOther = other.value === null ? other._normalize(1) : other.value; + res.value = multiplyScalar(valThis, valOther); + } else { + res.value = null; + } + + res.skipAutomaticSimplification = false; + return getNumericIfUnitless(res); + }; + /** + * Divide this unit by another one + * @memberof Unit + * @param {Unit} other + * @return {Unit} result of dividing this unit by the other unit + */ + + + Unit.prototype.divide = function (other) { + var res = this.clone(); + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + // Dimensions arrays may be of different lengths. Default to 0. + res.dimensions[i] = (this.dimensions[i] || 0) - (other.dimensions[i] || 0); + } // Invert and append other's units list onto res + + + for (var _i2 = 0; _i2 < other.units.length; _i2++) { + // Make a deep copy + var inverted = {}; + + for (var key in other.units[_i2]) { + inverted[key] = other.units[_i2][key]; + } + + inverted.power = -inverted.power; + res.units.push(inverted); + } // If at least one operand has a value, the result should have a value + + + if (this.value !== null || other.value !== null) { + var valThis = this.value === null ? this._normalize(1) : this.value; + var valOther = other.value === null ? other._normalize(1) : other.value; + res.value = divideScalar(valThis, valOther); + } else { + res.value = null; + } + + res.skipAutomaticSimplification = false; + return getNumericIfUnitless(res); + }; + /** + * Calculate the power of a unit + * @memberof Unit + * @param {number | Fraction | BigNumber} p + * @returns {Unit} The result: this^p + */ + + + Unit.prototype.pow = function (p) { + var res = this.clone(); + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + // Dimensions arrays may be of different lengths. Default to 0. + res.dimensions[i] = (this.dimensions[i] || 0) * p; + } // Adjust the power of each unit in the list + + + for (var _i3 = 0; _i3 < res.units.length; _i3++) { + res.units[_i3].power *= p; + } + + if (res.value !== null) { + res.value = pow(res.value, p); // only allow numeric output, we don't want to return a Complex number + // if (!isNumeric(res.value)) { + // res.value = NaN + // } + // Update: Complex supported now + } else { + res.value = null; + } + + res.skipAutomaticSimplification = false; + return getNumericIfUnitless(res); + }; + /** + * Return the numeric value of this unit if it is dimensionless, has a value, and config.predictable == false; or the original unit otherwise + * @param {Unit} unit + * @returns {number | Fraction | BigNumber | Unit} The numeric value of the unit if conditions are met, or the original unit otherwise + */ + + + function getNumericIfUnitless(unit) { + if (unit.equalBase(BASE_UNITS.NONE) && unit.value !== null && !config.predictable) { + return unit.value; + } else { + return unit; + } + } + /** + * Calculate the absolute value of a unit + * @memberof Unit + * @param {number | Fraction | BigNumber} x + * @returns {Unit} The result: |x|, absolute value of x + */ + + + Unit.prototype.abs = function () { + // This gives correct, but unexpected, results for units with an offset. + // For example, abs(-283.15 degC) = -263.15 degC !!! + var ret = this.clone(); + ret.value = ret.value !== null ? abs(ret.value) : null; + + for (var i in ret.units) { + if (ret.units[i].unit.name === 'VA' || ret.units[i].unit.name === 'VAR') { + ret.units[i].unit = UNITS.W; + } + } + + return ret; + }; + /** + * Convert the unit to a specific unit name. + * @memberof Unit + * @param {string | Unit} valuelessUnit A unit without value. Can have prefix, like "cm" + * @returns {Unit} Returns a clone of the unit with a fixed prefix and unit. + */ + + + Unit.prototype.to = function (valuelessUnit) { + var other; + var value = this.value === null ? this._normalize(1) : this.value; + + if (typeof valuelessUnit === 'string') { + // other = new Unit(null, valuelessUnit) + other = Unit.parse(valuelessUnit); + + if (!this.equalBase(other)) { + throw new Error("Units do not match ('".concat(other.toString(), "' != '").concat(this.toString(), "')")); + } + + if (other.value !== null) { + throw new Error('Cannot convert to a unit with a value'); + } + + other.value = Object(utils_object["a" /* clone */])(value); + other.fixPrefix = true; + other.skipAutomaticSimplification = true; + return other; + } else if (Object(is["L" /* isUnit */])(valuelessUnit)) { + if (!this.equalBase(valuelessUnit)) { + throw new Error("Units do not match ('".concat(valuelessUnit.toString(), "' != '").concat(this.toString(), "')")); + } + + if (valuelessUnit.value !== null) { + throw new Error('Cannot convert to a unit with a value'); + } + + other = valuelessUnit.clone(); + other.value = Object(utils_object["a" /* clone */])(value); + other.fixPrefix = true; + other.skipAutomaticSimplification = true; + return other; + } else { + throw new Error('String or Unit expected as parameter'); + } + }; + /** + * Return the value of the unit when represented with given valueless unit + * @memberof Unit + * @param {string | Unit} valuelessUnit For example 'cm' or 'inch' + * @return {number} Returns the unit value as number. + */ + // TODO: deprecate Unit.toNumber? It's always better to use toNumeric + + + Unit.prototype.toNumber = function (valuelessUnit) { + return toNumber(this.toNumeric(valuelessUnit)); + }; + /** + * Return the value of the unit in the original numeric type + * @memberof Unit + * @param {string | Unit} valuelessUnit For example 'cm' or 'inch' + * @return {number | BigNumber | Fraction} Returns the unit value + */ + + + Unit.prototype.toNumeric = function (valuelessUnit) { + var other; + + if (valuelessUnit) { + // Allow getting the numeric value without converting to a different unit + other = this.to(valuelessUnit); + } else { + other = this.clone(); + } + + if (other._isDerived() || other.units.length === 0) { + return other._denormalize(other.value); + } else { + return other._denormalize(other.value, other.units[0].prefix.value); + } + }; + /** + * Get a string representation of the unit. + * @memberof Unit + * @return {string} + */ + + + Unit.prototype.toString = function () { + return this.format(); + }; + /** + * Get a JSON representation of the unit + * @memberof Unit + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}` + */ + + + Unit.prototype.toJSON = function () { + return { + mathjs: 'Unit', + value: this._denormalize(this.value), + unit: this.formatUnits(), + fixPrefix: this.fixPrefix + }; + }; + /** + * Instantiate a Unit from a JSON object + * @memberof Unit + * @param {Object} json A JSON object structured as: + * `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}` + * @return {Unit} + */ + + + Unit.fromJSON = function (json) { + var unit = new Unit(json.value, json.unit); + unit.fixPrefix = json.fixPrefix || false; + return unit; + }; + /** + * Returns the string representation of the unit. + * @memberof Unit + * @return {string} + */ + + + Unit.prototype.valueOf = Unit.prototype.toString; + /** + * Simplify this Unit's unit list and return a new Unit with the simplified list. + * The returned Unit will contain a list of the "best" units for formatting. + */ + + Unit.prototype.simplify = function () { + var ret = this.clone(); + var proposedUnitList = []; // Search for a matching base + + var matchingBase; + + for (var key in currentUnitSystem) { + if (ret.hasBase(BASE_UNITS[key])) { + matchingBase = key; + break; + } + } + + if (matchingBase === 'NONE') { + ret.units = []; + } else { + var matchingUnit; + + if (matchingBase) { + // Does the unit system have a matching unit? + if (Object(utils_object["f" /* hasOwnProperty */])(currentUnitSystem, matchingBase)) { + matchingUnit = currentUnitSystem[matchingBase]; + } + } + + if (matchingUnit) { + ret.units = [{ + unit: matchingUnit.unit, + prefix: matchingUnit.prefix, + power: 1.0 + }]; + } else { + // Multiple units or units with powers are formatted like this: + // 5 (kg m^2) / (s^3 mol) + // Build an representation from the base units of the current unit system + var missingBaseDim = false; + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + var baseDim = BASE_DIMENSIONS[i]; + + if (Math.abs(ret.dimensions[i] || 0) > 1e-12) { + if (Object(utils_object["f" /* hasOwnProperty */])(currentUnitSystem, baseDim)) { + proposedUnitList.push({ + unit: currentUnitSystem[baseDim].unit, + prefix: currentUnitSystem[baseDim].prefix, + power: ret.dimensions[i] || 0 + }); + } else { + missingBaseDim = true; + } + } + } // Is the proposed unit list "simpler" than the existing one? + + + if (proposedUnitList.length < ret.units.length && !missingBaseDim) { + // Replace this unit list with the proposed list + ret.units = proposedUnitList; + } + } + } + + return ret; + }; + /** + * Returns a new Unit in the SI system with the same value as this one + */ + + + Unit.prototype.toSI = function () { + var ret = this.clone(); + var proposedUnitList = []; // Multiple units or units with powers are formatted like this: + // 5 (kg m^2) / (s^3 mol) + // Build an representation from the base units of the SI unit system + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + var baseDim = BASE_DIMENSIONS[i]; + + if (Math.abs(ret.dimensions[i] || 0) > 1e-12) { + if (Object(utils_object["f" /* hasOwnProperty */])(UNIT_SYSTEMS.si, baseDim)) { + proposedUnitList.push({ + unit: UNIT_SYSTEMS.si[baseDim].unit, + prefix: UNIT_SYSTEMS.si[baseDim].prefix, + power: ret.dimensions[i] || 0 + }); + } else { + throw new Error('Cannot express custom unit ' + baseDim + ' in SI units'); + } + } + } // Replace this unit list with the proposed list + + + ret.units = proposedUnitList; + ret.fixPrefix = true; + ret.skipAutomaticSimplification = true; + return ret; + }; + /** + * Get a string representation of the units of this Unit, without the value. The unit list is formatted as-is without first being simplified. + * @memberof Unit + * @return {string} + */ + + + Unit.prototype.formatUnits = function () { + var strNum = ''; + var strDen = ''; + var nNum = 0; + var nDen = 0; + + for (var i = 0; i < this.units.length; i++) { + if (this.units[i].power > 0) { + nNum++; + strNum += ' ' + this.units[i].prefix.name + this.units[i].unit.name; + + if (Math.abs(this.units[i].power - 1.0) > 1e-15) { + strNum += '^' + this.units[i].power; + } + } else if (this.units[i].power < 0) { + nDen++; + } + } + + if (nDen > 0) { + for (var _i4 = 0; _i4 < this.units.length; _i4++) { + if (this.units[_i4].power < 0) { + if (nNum > 0) { + strDen += ' ' + this.units[_i4].prefix.name + this.units[_i4].unit.name; + + if (Math.abs(this.units[_i4].power + 1.0) > 1e-15) { + strDen += '^' + -this.units[_i4].power; + } + } else { + strDen += ' ' + this.units[_i4].prefix.name + this.units[_i4].unit.name; + strDen += '^' + this.units[_i4].power; + } + } + } + } // Remove leading " " + + + strNum = strNum.substr(1); + strDen = strDen.substr(1); // Add parans for better copy/paste back into evaluate, for example, or for better pretty print formatting + + if (nNum > 1 && nDen > 0) { + strNum = '(' + strNum + ')'; + } + + if (nDen > 1 && nNum > 0) { + strDen = '(' + strDen + ')'; + } + + var str = strNum; + + if (nNum > 0 && nDen > 0) { + str += ' / '; + } + + str += strDen; + return str; + }; + /** + * Get a string representation of the Unit, with optional formatting options. + * @memberof Unit + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @return {string} + */ + + + Unit.prototype.format = function (options) { + // Simplfy the unit list, unless it is valueless or was created directly in the + // constructor or as the result of to or toSI + var simp = this.skipAutomaticSimplification || this.value === null ? this.clone() : this.simplify(); // Apply some custom logic for handling VA and VAR. The goal is to express the value of the unit as a real value, if possible. Otherwise, use a real-valued unit instead of a complex-valued one. + + var isImaginary = false; + + if (typeof simp.value !== 'undefined' && simp.value !== null && Object(is["j" /* isComplex */])(simp.value)) { + // TODO: Make this better, for example, use relative magnitude of re and im rather than absolute + isImaginary = Math.abs(simp.value.re) < 1e-14; + } + + for (var i in simp.units) { + if (simp.units[i].unit) { + if (simp.units[i].unit.name === 'VA' && isImaginary) { + simp.units[i].unit = UNITS.VAR; + } else if (simp.units[i].unit.name === 'VAR' && !isImaginary) { + simp.units[i].unit = UNITS.VA; + } + } + } // Now apply the best prefix + // Units must have only one unit and not have the fixPrefix flag set + + + if (simp.units.length === 1 && !simp.fixPrefix) { + // Units must have integer powers, otherwise the prefix will change the + // outputted value by not-an-integer-power-of-ten + if (Math.abs(simp.units[0].power - Math.round(simp.units[0].power)) < 1e-14) { + // Apply the best prefix + simp.units[0].prefix = simp._bestPrefix(); + } + } + + var value = simp._denormalize(simp.value); + + var str = simp.value !== null ? format(value, options || {}) : ''; + var unitStr = simp.formatUnits(); + + if (simp.value && Object(is["j" /* isComplex */])(simp.value)) { + str = '(' + str + ')'; // Surround complex values with ( ) to enable better parsing + } + + if (unitStr.length > 0 && str.length > 0) { + str += ' '; + } + + str += unitStr; + return str; + }; + /** + * Calculate the best prefix using current value. + * @memberof Unit + * @returns {Object} prefix + * @private + */ + + + Unit.prototype._bestPrefix = function () { + if (this.units.length !== 1) { + throw new Error('Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!'); + } + + if (Math.abs(this.units[0].power - Math.round(this.units[0].power)) >= 1e-14) { + throw new Error('Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!'); + } // find the best prefix value (resulting in the value of which + // the absolute value of the log10 is closest to zero, + // though with a little offset of 1.2 for nicer values: you get a + // sequence 1mm 100mm 500mm 0.6m 1m 10m 100m 500m 0.6km 1km ... + // Note: the units value can be any numeric type, but to find the best + // prefix it's enough to work with limited precision of a regular number + // Update: using mathjs abs since we also allow complex numbers + + + var absValue = this.value !== null ? abs(this.value) : 0; + var absUnitValue = abs(this.units[0].unit.value); + var bestPrefix = this.units[0].prefix; + + if (absValue === 0) { + return bestPrefix; + } + + var power = this.units[0].power; + var bestDiff = Math.log(absValue / Math.pow(bestPrefix.value * absUnitValue, power)) / Math.LN10 - 1.2; + if (bestDiff > -2.200001 && bestDiff < 1.800001) return bestPrefix; // Allow the original prefix + + bestDiff = Math.abs(bestDiff); + var prefixes = this.units[0].unit.prefixes; + + for (var p in prefixes) { + if (Object(utils_object["f" /* hasOwnProperty */])(prefixes, p)) { + var prefix = prefixes[p]; + + if (prefix.scientific) { + var diff = Math.abs(Math.log(absValue / Math.pow(prefix.value * absUnitValue, power)) / Math.LN10 - 1.2); + + if (diff < bestDiff || diff === bestDiff && prefix.name.length < bestPrefix.name.length) { + // choose the prefix with the smallest diff, or if equal, choose the one + // with the shortest name (can happen with SHORTLONG for example) + bestPrefix = prefix; + bestDiff = diff; + } + } + } + } + + return bestPrefix; + }; + /** + * Returns an array of units whose sum is equal to this unit + * @memberof Unit + * @param {Array} [parts] An array of strings or valueless units. + * + * Example: + * + * const u = new Unit(1, 'm') + * u.splitUnit(['feet', 'inch']) + * [ 3 feet, 3.3700787401575 inch ] + * + * @return {Array} An array of units. + */ + + + Unit.prototype.splitUnit = function (parts) { + var x = this.clone(); + var ret = []; + + for (var i = 0; i < parts.length; i++) { + // Convert x to the requested unit + x = x.to(parts[i]); + if (i === parts.length - 1) break; // Get the numeric value of this unit + + var xNumeric = x.toNumeric(); // Check to see if xNumeric is nearly equal to an integer, + // since fix can incorrectly round down if there is round-off error + + var xRounded = round(xNumeric); + var xFixed = void 0; + var isNearlyEqual = equal(xRounded, xNumeric); + + if (isNearlyEqual) { + xFixed = xRounded; + } else { + xFixed = fix(x.toNumeric()); + } + + var y = new Unit(xFixed, parts[i].toString()); + ret.push(y); + x = subtract(x, y); + } // This little bit fixes a bug where the remainder should be 0 but is a little bit off. + // But instead of comparing x, the remainder, with zero--we will compare the sum of + // all the parts so far with the original value. If they are nearly equal, + // we set the remainder to 0. + + + var testSum = 0; + + for (var _i5 = 0; _i5 < ret.length; _i5++) { + testSum = addScalar(testSum, ret[_i5].value); + } + + if (equal(testSum, this.value)) { + x.value = 0; + } + + ret.push(x); + return ret; + }; + + var PREFIXES = { + NONE: { + '': { + name: '', + value: 1, + scientific: true + } + }, + SHORT: { + '': { + name: '', + value: 1, + scientific: true + }, + da: { + name: 'da', + value: 1e1, + scientific: false + }, + h: { + name: 'h', + value: 1e2, + scientific: false + }, + k: { + name: 'k', + value: 1e3, + scientific: true + }, + M: { + name: 'M', + value: 1e6, + scientific: true + }, + G: { + name: 'G', + value: 1e9, + scientific: true + }, + T: { + name: 'T', + value: 1e12, + scientific: true + }, + P: { + name: 'P', + value: 1e15, + scientific: true + }, + E: { + name: 'E', + value: 1e18, + scientific: true + }, + Z: { + name: 'Z', + value: 1e21, + scientific: true + }, + Y: { + name: 'Y', + value: 1e24, + scientific: true + }, + d: { + name: 'd', + value: 1e-1, + scientific: false + }, + c: { + name: 'c', + value: 1e-2, + scientific: false + }, + m: { + name: 'm', + value: 1e-3, + scientific: true + }, + u: { + name: 'u', + value: 1e-6, + scientific: true + }, + n: { + name: 'n', + value: 1e-9, + scientific: true + }, + p: { + name: 'p', + value: 1e-12, + scientific: true + }, + f: { + name: 'f', + value: 1e-15, + scientific: true + }, + a: { + name: 'a', + value: 1e-18, + scientific: true + }, + z: { + name: 'z', + value: 1e-21, + scientific: true + }, + y: { + name: 'y', + value: 1e-24, + scientific: true + } + }, + LONG: { + '': { + name: '', + value: 1, + scientific: true + }, + deca: { + name: 'deca', + value: 1e1, + scientific: false + }, + hecto: { + name: 'hecto', + value: 1e2, + scientific: false + }, + kilo: { + name: 'kilo', + value: 1e3, + scientific: true + }, + mega: { + name: 'mega', + value: 1e6, + scientific: true + }, + giga: { + name: 'giga', + value: 1e9, + scientific: true + }, + tera: { + name: 'tera', + value: 1e12, + scientific: true + }, + peta: { + name: 'peta', + value: 1e15, + scientific: true + }, + exa: { + name: 'exa', + value: 1e18, + scientific: true + }, + zetta: { + name: 'zetta', + value: 1e21, + scientific: true + }, + yotta: { + name: 'yotta', + value: 1e24, + scientific: true + }, + deci: { + name: 'deci', + value: 1e-1, + scientific: false + }, + centi: { + name: 'centi', + value: 1e-2, + scientific: false + }, + milli: { + name: 'milli', + value: 1e-3, + scientific: true + }, + micro: { + name: 'micro', + value: 1e-6, + scientific: true + }, + nano: { + name: 'nano', + value: 1e-9, + scientific: true + }, + pico: { + name: 'pico', + value: 1e-12, + scientific: true + }, + femto: { + name: 'femto', + value: 1e-15, + scientific: true + }, + atto: { + name: 'atto', + value: 1e-18, + scientific: true + }, + zepto: { + name: 'zepto', + value: 1e-21, + scientific: true + }, + yocto: { + name: 'yocto', + value: 1e-24, + scientific: true + } + }, + SQUARED: { + '': { + name: '', + value: 1, + scientific: true + }, + da: { + name: 'da', + value: 1e2, + scientific: false + }, + h: { + name: 'h', + value: 1e4, + scientific: false + }, + k: { + name: 'k', + value: 1e6, + scientific: true + }, + M: { + name: 'M', + value: 1e12, + scientific: true + }, + G: { + name: 'G', + value: 1e18, + scientific: true + }, + T: { + name: 'T', + value: 1e24, + scientific: true + }, + P: { + name: 'P', + value: 1e30, + scientific: true + }, + E: { + name: 'E', + value: 1e36, + scientific: true + }, + Z: { + name: 'Z', + value: 1e42, + scientific: true + }, + Y: { + name: 'Y', + value: 1e48, + scientific: true + }, + d: { + name: 'd', + value: 1e-2, + scientific: false + }, + c: { + name: 'c', + value: 1e-4, + scientific: false + }, + m: { + name: 'm', + value: 1e-6, + scientific: true + }, + u: { + name: 'u', + value: 1e-12, + scientific: true + }, + n: { + name: 'n', + value: 1e-18, + scientific: true + }, + p: { + name: 'p', + value: 1e-24, + scientific: true + }, + f: { + name: 'f', + value: 1e-30, + scientific: true + }, + a: { + name: 'a', + value: 1e-36, + scientific: true + }, + z: { + name: 'z', + value: 1e-42, + scientific: true + }, + y: { + name: 'y', + value: 1e-48, + scientific: true + } + }, + CUBIC: { + '': { + name: '', + value: 1, + scientific: true + }, + da: { + name: 'da', + value: 1e3, + scientific: false + }, + h: { + name: 'h', + value: 1e6, + scientific: false + }, + k: { + name: 'k', + value: 1e9, + scientific: true + }, + M: { + name: 'M', + value: 1e18, + scientific: true + }, + G: { + name: 'G', + value: 1e27, + scientific: true + }, + T: { + name: 'T', + value: 1e36, + scientific: true + }, + P: { + name: 'P', + value: 1e45, + scientific: true + }, + E: { + name: 'E', + value: 1e54, + scientific: true + }, + Z: { + name: 'Z', + value: 1e63, + scientific: true + }, + Y: { + name: 'Y', + value: 1e72, + scientific: true + }, + d: { + name: 'd', + value: 1e-3, + scientific: false + }, + c: { + name: 'c', + value: 1e-6, + scientific: false + }, + m: { + name: 'm', + value: 1e-9, + scientific: true + }, + u: { + name: 'u', + value: 1e-18, + scientific: true + }, + n: { + name: 'n', + value: 1e-27, + scientific: true + }, + p: { + name: 'p', + value: 1e-36, + scientific: true + }, + f: { + name: 'f', + value: 1e-45, + scientific: true + }, + a: { + name: 'a', + value: 1e-54, + scientific: true + }, + z: { + name: 'z', + value: 1e-63, + scientific: true + }, + y: { + name: 'y', + value: 1e-72, + scientific: true + } + }, + BINARY_SHORT_SI: { + '': { + name: '', + value: 1, + scientific: true + }, + k: { + name: 'k', + value: 1e3, + scientific: true + }, + M: { + name: 'M', + value: 1e6, + scientific: true + }, + G: { + name: 'G', + value: 1e9, + scientific: true + }, + T: { + name: 'T', + value: 1e12, + scientific: true + }, + P: { + name: 'P', + value: 1e15, + scientific: true + }, + E: { + name: 'E', + value: 1e18, + scientific: true + }, + Z: { + name: 'Z', + value: 1e21, + scientific: true + }, + Y: { + name: 'Y', + value: 1e24, + scientific: true + } + }, + BINARY_SHORT_IEC: { + '': { + name: '', + value: 1, + scientific: true + }, + Ki: { + name: 'Ki', + value: 1024, + scientific: true + }, + Mi: { + name: 'Mi', + value: Math.pow(1024, 2), + scientific: true + }, + Gi: { + name: 'Gi', + value: Math.pow(1024, 3), + scientific: true + }, + Ti: { + name: 'Ti', + value: Math.pow(1024, 4), + scientific: true + }, + Pi: { + name: 'Pi', + value: Math.pow(1024, 5), + scientific: true + }, + Ei: { + name: 'Ei', + value: Math.pow(1024, 6), + scientific: true + }, + Zi: { + name: 'Zi', + value: Math.pow(1024, 7), + scientific: true + }, + Yi: { + name: 'Yi', + value: Math.pow(1024, 8), + scientific: true + } + }, + BINARY_LONG_SI: { + '': { + name: '', + value: 1, + scientific: true + }, + kilo: { + name: 'kilo', + value: 1e3, + scientific: true + }, + mega: { + name: 'mega', + value: 1e6, + scientific: true + }, + giga: { + name: 'giga', + value: 1e9, + scientific: true + }, + tera: { + name: 'tera', + value: 1e12, + scientific: true + }, + peta: { + name: 'peta', + value: 1e15, + scientific: true + }, + exa: { + name: 'exa', + value: 1e18, + scientific: true + }, + zetta: { + name: 'zetta', + value: 1e21, + scientific: true + }, + yotta: { + name: 'yotta', + value: 1e24, + scientific: true + } + }, + BINARY_LONG_IEC: { + '': { + name: '', + value: 1, + scientific: true + }, + kibi: { + name: 'kibi', + value: 1024, + scientific: true + }, + mebi: { + name: 'mebi', + value: Math.pow(1024, 2), + scientific: true + }, + gibi: { + name: 'gibi', + value: Math.pow(1024, 3), + scientific: true + }, + tebi: { + name: 'tebi', + value: Math.pow(1024, 4), + scientific: true + }, + pebi: { + name: 'pebi', + value: Math.pow(1024, 5), + scientific: true + }, + exi: { + name: 'exi', + value: Math.pow(1024, 6), + scientific: true + }, + zebi: { + name: 'zebi', + value: Math.pow(1024, 7), + scientific: true + }, + yobi: { + name: 'yobi', + value: Math.pow(1024, 8), + scientific: true + } + }, + BTU: { + '': { + name: '', + value: 1, + scientific: true + }, + MM: { + name: 'MM', + value: 1e6, + scientific: true + } + } + }; + PREFIXES.SHORTLONG = _extends({}, PREFIXES.SHORT, PREFIXES.LONG); + PREFIXES.BINARY_SHORT = _extends({}, PREFIXES.BINARY_SHORT_SI, PREFIXES.BINARY_SHORT_IEC); + PREFIXES.BINARY_LONG = _extends({}, PREFIXES.BINARY_LONG_SI, PREFIXES.BINARY_LONG_IEC); + /* Internally, each unit is represented by a value and a dimension array. The elements of the dimensions array have the following meaning: + * Index Dimension + * ----- --------- + * 0 Length + * 1 Mass + * 2 Time + * 3 Current + * 4 Temperature + * 5 Luminous intensity + * 6 Amount of substance + * 7 Angle + * 8 Bit (digital) + * For example, the unit "298.15 K" is a pure temperature and would have a value of 298.15 and a dimension array of [0, 0, 0, 0, 1, 0, 0, 0, 0]. The unit "1 cal / (gm °C)" can be written in terms of the 9 fundamental dimensions as [length^2] / ([time^2] * [temperature]), and would a value of (after conversion to SI) 4184.0 and a dimensions array of [2, 0, -2, 0, -1, 0, 0, 0, 0]. + * + */ + + var BASE_DIMENSIONS = ['MASS', 'LENGTH', 'TIME', 'CURRENT', 'TEMPERATURE', 'LUMINOUS_INTENSITY', 'AMOUNT_OF_SUBSTANCE', 'ANGLE', 'BIT']; + var BASE_UNITS = { + NONE: { + dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 0] + }, + MASS: { + dimensions: [1, 0, 0, 0, 0, 0, 0, 0, 0] + }, + LENGTH: { + dimensions: [0, 1, 0, 0, 0, 0, 0, 0, 0] + }, + TIME: { + dimensions: [0, 0, 1, 0, 0, 0, 0, 0, 0] + }, + CURRENT: { + dimensions: [0, 0, 0, 1, 0, 0, 0, 0, 0] + }, + TEMPERATURE: { + dimensions: [0, 0, 0, 0, 1, 0, 0, 0, 0] + }, + LUMINOUS_INTENSITY: { + dimensions: [0, 0, 0, 0, 0, 1, 0, 0, 0] + }, + AMOUNT_OF_SUBSTANCE: { + dimensions: [0, 0, 0, 0, 0, 0, 1, 0, 0] + }, + FORCE: { + dimensions: [1, 1, -2, 0, 0, 0, 0, 0, 0] + }, + SURFACE: { + dimensions: [0, 2, 0, 0, 0, 0, 0, 0, 0] + }, + VOLUME: { + dimensions: [0, 3, 0, 0, 0, 0, 0, 0, 0] + }, + ENERGY: { + dimensions: [1, 2, -2, 0, 0, 0, 0, 0, 0] + }, + POWER: { + dimensions: [1, 2, -3, 0, 0, 0, 0, 0, 0] + }, + PRESSURE: { + dimensions: [1, -1, -2, 0, 0, 0, 0, 0, 0] + }, + ELECTRIC_CHARGE: { + dimensions: [0, 0, 1, 1, 0, 0, 0, 0, 0] + }, + ELECTRIC_CAPACITANCE: { + dimensions: [-1, -2, 4, 2, 0, 0, 0, 0, 0] + }, + ELECTRIC_POTENTIAL: { + dimensions: [1, 2, -3, -1, 0, 0, 0, 0, 0] + }, + ELECTRIC_RESISTANCE: { + dimensions: [1, 2, -3, -2, 0, 0, 0, 0, 0] + }, + ELECTRIC_INDUCTANCE: { + dimensions: [1, 2, -2, -2, 0, 0, 0, 0, 0] + }, + ELECTRIC_CONDUCTANCE: { + dimensions: [-1, -2, 3, 2, 0, 0, 0, 0, 0] + }, + MAGNETIC_FLUX: { + dimensions: [1, 2, -2, -1, 0, 0, 0, 0, 0] + }, + MAGNETIC_FLUX_DENSITY: { + dimensions: [1, 0, -2, -1, 0, 0, 0, 0, 0] + }, + FREQUENCY: { + dimensions: [0, 0, -1, 0, 0, 0, 0, 0, 0] + }, + ANGLE: { + dimensions: [0, 0, 0, 0, 0, 0, 0, 1, 0] + }, + BIT: { + dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 1] + } + }; + + for (var key in BASE_UNITS) { + BASE_UNITS[key].key = key; + } + + var BASE_UNIT_NONE = {}; + var UNIT_NONE = { + name: '', + base: BASE_UNIT_NONE, + value: 1, + offset: 0, + dimensions: BASE_DIMENSIONS.map(function (x) { + return 0; + }) + }; + var UNITS = { + // length + meter: { + name: 'meter', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + inch: { + name: 'inch', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.0254, + offset: 0 + }, + foot: { + name: 'foot', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.3048, + offset: 0 + }, + yard: { + name: 'yard', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.9144, + offset: 0 + }, + mile: { + name: 'mile', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 1609.344, + offset: 0 + }, + link: { + name: 'link', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.201168, + offset: 0 + }, + rod: { + name: 'rod', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 5.0292, + offset: 0 + }, + chain: { + name: 'chain', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 20.1168, + offset: 0 + }, + angstrom: { + name: 'angstrom', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 1e-10, + offset: 0 + }, + m: { + name: 'm', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + "in": { + name: 'in', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.0254, + offset: 0 + }, + ft: { + name: 'ft', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.3048, + offset: 0 + }, + yd: { + name: 'yd', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.9144, + offset: 0 + }, + mi: { + name: 'mi', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 1609.344, + offset: 0 + }, + li: { + name: 'li', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.201168, + offset: 0 + }, + rd: { + name: 'rd', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 5.029210, + offset: 0 + }, + ch: { + name: 'ch', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 20.1168, + offset: 0 + }, + mil: { + name: 'mil', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.0000254, + offset: 0 + }, + // 1/1000 inch + // Surface + m2: { + name: 'm2', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.SQUARED, + value: 1, + offset: 0 + }, + sqin: { + name: 'sqin', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 0.00064516, + offset: 0 + }, + // 645.16 mm2 + sqft: { + name: 'sqft', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 0.09290304, + offset: 0 + }, + // 0.09290304 m2 + sqyd: { + name: 'sqyd', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 0.83612736, + offset: 0 + }, + // 0.83612736 m2 + sqmi: { + name: 'sqmi', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 2589988.110336, + offset: 0 + }, + // 2.589988110336 km2 + sqrd: { + name: 'sqrd', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 25.29295, + offset: 0 + }, + // 25.29295 m2 + sqch: { + name: 'sqch', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 404.6873, + offset: 0 + }, + // 404.6873 m2 + sqmil: { + name: 'sqmil', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 6.4516e-10, + offset: 0 + }, + // 6.4516 * 10^-10 m2 + acre: { + name: 'acre', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 4046.86, + offset: 0 + }, + // 4046.86 m2 + hectare: { + name: 'hectare', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 10000, + offset: 0 + }, + // 10000 m2 + // Volume + m3: { + name: 'm3', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.CUBIC, + value: 1, + offset: 0 + }, + L: { + name: 'L', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.SHORT, + value: 0.001, + offset: 0 + }, + // litre + l: { + name: 'l', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.SHORT, + value: 0.001, + offset: 0 + }, + // litre + litre: { + name: 'litre', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.LONG, + value: 0.001, + offset: 0 + }, + cuin: { + name: 'cuin', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 1.6387064e-5, + offset: 0 + }, + // 1.6387064e-5 m3 + cuft: { + name: 'cuft', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.028316846592, + offset: 0 + }, + // 28.316 846 592 L + cuyd: { + name: 'cuyd', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.764554857984, + offset: 0 + }, + // 764.554 857 984 L + teaspoon: { + name: 'teaspoon', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.000005, + offset: 0 + }, + // 5 mL + tablespoon: { + name: 'tablespoon', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.000015, + offset: 0 + }, + // 15 mL + // {name: 'cup', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.000240, offset: 0}, // 240 mL // not possible, we have already another cup + drop: { + name: 'drop', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 5e-8, + offset: 0 + }, + // 0.05 mL = 5e-8 m3 + gtt: { + name: 'gtt', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 5e-8, + offset: 0 + }, + // 0.05 mL = 5e-8 m3 + // Liquid volume + minim: { + name: 'minim', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.00000006161152, + offset: 0 + }, + // 0.06161152 mL + fluiddram: { + name: 'fluiddram', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0000036966911, + offset: 0 + }, + // 3.696691 mL + fluidounce: { + name: 'fluidounce', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.00002957353, + offset: 0 + }, + // 29.57353 mL + gill: { + name: 'gill', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0001182941, + offset: 0 + }, + // 118.2941 mL + cc: { + name: 'cc', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 1e-6, + offset: 0 + }, + // 1e-6 L + cup: { + name: 'cup', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0002365882, + offset: 0 + }, + // 236.5882 mL + pint: { + name: 'pint', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0004731765, + offset: 0 + }, + // 473.1765 mL + quart: { + name: 'quart', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0009463529, + offset: 0 + }, + // 946.3529 mL + gallon: { + name: 'gallon', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.003785412, + offset: 0 + }, + // 3.785412 L + beerbarrel: { + name: 'beerbarrel', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.1173478, + offset: 0 + }, + // 117.3478 L + oilbarrel: { + name: 'oilbarrel', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.1589873, + offset: 0 + }, + // 158.9873 L + hogshead: { + name: 'hogshead', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.2384810, + offset: 0 + }, + // 238.4810 L + // {name: 'min', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.00000006161152, offset: 0}, // 0.06161152 mL // min is already in use as minute + fldr: { + name: 'fldr', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0000036966911, + offset: 0 + }, + // 3.696691 mL + floz: { + name: 'floz', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.00002957353, + offset: 0 + }, + // 29.57353 mL + gi: { + name: 'gi', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0001182941, + offset: 0 + }, + // 118.2941 mL + cp: { + name: 'cp', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0002365882, + offset: 0 + }, + // 236.5882 mL + pt: { + name: 'pt', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0004731765, + offset: 0 + }, + // 473.1765 mL + qt: { + name: 'qt', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0009463529, + offset: 0 + }, + // 946.3529 mL + gal: { + name: 'gal', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.003785412, + offset: 0 + }, + // 3.785412 L + bbl: { + name: 'bbl', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.1173478, + offset: 0 + }, + // 117.3478 L + obl: { + name: 'obl', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.1589873, + offset: 0 + }, + // 158.9873 L + // {name: 'hogshead', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.2384810, offset: 0}, // 238.4810 L // TODO: hh? + // Mass + g: { + name: 'g', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.SHORT, + value: 0.001, + offset: 0 + }, + gram: { + name: 'gram', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.LONG, + value: 0.001, + offset: 0 + }, + ton: { + name: 'ton', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.SHORT, + value: 907.18474, + offset: 0 + }, + t: { + name: 't', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.SHORT, + value: 1000, + offset: 0 + }, + tonne: { + name: 'tonne', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.LONG, + value: 1000, + offset: 0 + }, + grain: { + name: 'grain', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 64.79891e-6, + offset: 0 + }, + dram: { + name: 'dram', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 1.7718451953125e-3, + offset: 0 + }, + ounce: { + name: 'ounce', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 28.349523125e-3, + offset: 0 + }, + poundmass: { + name: 'poundmass', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 453.59237e-3, + offset: 0 + }, + hundredweight: { + name: 'hundredweight', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 45.359237, + offset: 0 + }, + stick: { + name: 'stick', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 115e-3, + offset: 0 + }, + stone: { + name: 'stone', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 6.35029318, + offset: 0 + }, + gr: { + name: 'gr', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 64.79891e-6, + offset: 0 + }, + dr: { + name: 'dr', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 1.7718451953125e-3, + offset: 0 + }, + oz: { + name: 'oz', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 28.349523125e-3, + offset: 0 + }, + lbm: { + name: 'lbm', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 453.59237e-3, + offset: 0 + }, + cwt: { + name: 'cwt', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 45.359237, + offset: 0 + }, + // Time + s: { + name: 's', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + min: { + name: 'min', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 60, + offset: 0 + }, + h: { + name: 'h', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 3600, + offset: 0 + }, + second: { + name: 'second', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + sec: { + name: 'sec', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + minute: { + name: 'minute', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 60, + offset: 0 + }, + hour: { + name: 'hour', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 3600, + offset: 0 + }, + day: { + name: 'day', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 86400, + offset: 0 + }, + week: { + name: 'week', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 7 * 86400, + offset: 0 + }, + month: { + name: 'month', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 2629800, + // 1/12th of Julian year + offset: 0 + }, + year: { + name: 'year', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 31557600, + // Julian year + offset: 0 + }, + decade: { + name: 'decade', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 315576000, + // Julian decade + offset: 0 + }, + century: { + name: 'century', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 3155760000, + // Julian century + offset: 0 + }, + millennium: { + name: 'millennium', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 31557600000, + // Julian millennium + offset: 0 + }, + // Frequency + hertz: { + name: 'Hertz', + base: BASE_UNITS.FREQUENCY, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0, + reciprocal: true + }, + Hz: { + name: 'Hz', + base: BASE_UNITS.FREQUENCY, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0, + reciprocal: true + }, + // Angle + rad: { + name: 'rad', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + radian: { + name: 'radian', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + // deg = rad / (2*pi) * 360 = rad / 0.017453292519943295769236907684888 + deg: { + name: 'deg', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.SHORT, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + degree: { + name: 'degree', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.LONG, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + // grad = rad / (2*pi) * 400 = rad / 0.015707963267948966192313216916399 + grad: { + name: 'grad', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.SHORT, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + gradian: { + name: 'gradian', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.LONG, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + // cycle = rad / (2*pi) = rad / 6.2831853071795864769252867665793 + cycle: { + name: 'cycle', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.NONE, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + // arcsec = rad / (3600 * (360 / 2 * pi)) = rad / 0.0000048481368110953599358991410235795 + arcsec: { + name: 'arcsec', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.NONE, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + // arcmin = rad / (60 * (360 / 2 * pi)) = rad / 0.00029088820866572159615394846141477 + arcmin: { + name: 'arcmin', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.NONE, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + // Electric current + A: { + name: 'A', + base: BASE_UNITS.CURRENT, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + ampere: { + name: 'ampere', + base: BASE_UNITS.CURRENT, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + // Temperature + // K(C) = °C + 273.15 + // K(F) = (°F + 459.67) / 1.8 + // K(R) = °R / 1.8 + K: { + name: 'K', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1, + offset: 0 + }, + degC: { + name: 'degC', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1, + offset: 273.15 + }, + degF: { + name: 'degF', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1 / 1.8, + offset: 459.67 + }, + degR: { + name: 'degR', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1 / 1.8, + offset: 0 + }, + kelvin: { + name: 'kelvin', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1, + offset: 0 + }, + celsius: { + name: 'celsius', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1, + offset: 273.15 + }, + fahrenheit: { + name: 'fahrenheit', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1 / 1.8, + offset: 459.67 + }, + rankine: { + name: 'rankine', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1 / 1.8, + offset: 0 + }, + // amount of substance + mol: { + name: 'mol', + base: BASE_UNITS.AMOUNT_OF_SUBSTANCE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + mole: { + name: 'mole', + base: BASE_UNITS.AMOUNT_OF_SUBSTANCE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + // luminous intensity + cd: { + name: 'cd', + base: BASE_UNITS.LUMINOUS_INTENSITY, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + candela: { + name: 'candela', + base: BASE_UNITS.LUMINOUS_INTENSITY, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + // TODO: units STERADIAN + // {name: 'sr', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0}, + // {name: 'steradian', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0}, + // Force + N: { + name: 'N', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + newton: { + name: 'newton', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + dyn: { + name: 'dyn', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.SHORT, + value: 0.00001, + offset: 0 + }, + dyne: { + name: 'dyne', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.LONG, + value: 0.00001, + offset: 0 + }, + lbf: { + name: 'lbf', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.NONE, + value: 4.4482216152605, + offset: 0 + }, + poundforce: { + name: 'poundforce', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.NONE, + value: 4.4482216152605, + offset: 0 + }, + kip: { + name: 'kip', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.LONG, + value: 4448.2216, + offset: 0 + }, + // Energy + J: { + name: 'J', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + joule: { + name: 'joule', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + erg: { + name: 'erg', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.NONE, + value: 1e-7, + offset: 0 + }, + Wh: { + name: 'Wh', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.SHORT, + value: 3600, + offset: 0 + }, + BTU: { + name: 'BTU', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.BTU, + value: 1055.05585262, + offset: 0 + }, + eV: { + name: 'eV', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.SHORT, + value: 1.602176565e-19, + offset: 0 + }, + electronvolt: { + name: 'electronvolt', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.LONG, + value: 1.602176565e-19, + offset: 0 + }, + // Power + W: { + name: 'W', + base: BASE_UNITS.POWER, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + watt: { + name: 'watt', + base: BASE_UNITS.POWER, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + hp: { + name: 'hp', + base: BASE_UNITS.POWER, + prefixes: PREFIXES.NONE, + value: 745.6998715386, + offset: 0 + }, + // Electrical power units + VAR: { + name: 'VAR', + base: BASE_UNITS.POWER, + prefixes: PREFIXES.SHORT, + value: Complex.I, + offset: 0 + }, + VA: { + name: 'VA', + base: BASE_UNITS.POWER, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Pressure + Pa: { + name: 'Pa', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + psi: { + name: 'psi', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.NONE, + value: 6894.75729276459, + offset: 0 + }, + atm: { + name: 'atm', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.NONE, + value: 101325, + offset: 0 + }, + bar: { + name: 'bar', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.SHORTLONG, + value: 100000, + offset: 0 + }, + torr: { + name: 'torr', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.NONE, + value: 133.322, + offset: 0 + }, + mmHg: { + name: 'mmHg', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.NONE, + value: 133.322, + offset: 0 + }, + mmH2O: { + name: 'mmH2O', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.NONE, + value: 9.80665, + offset: 0 + }, + cmH2O: { + name: 'cmH2O', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.NONE, + value: 98.0665, + offset: 0 + }, + // Electric charge + coulomb: { + name: 'coulomb', + base: BASE_UNITS.ELECTRIC_CHARGE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + C: { + name: 'C', + base: BASE_UNITS.ELECTRIC_CHARGE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Electric capacitance + farad: { + name: 'farad', + base: BASE_UNITS.ELECTRIC_CAPACITANCE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + F: { + name: 'F', + base: BASE_UNITS.ELECTRIC_CAPACITANCE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Electric potential + volt: { + name: 'volt', + base: BASE_UNITS.ELECTRIC_POTENTIAL, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + V: { + name: 'V', + base: BASE_UNITS.ELECTRIC_POTENTIAL, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Electric resistance + ohm: { + name: 'ohm', + base: BASE_UNITS.ELECTRIC_RESISTANCE, + prefixes: PREFIXES.SHORTLONG, + // Both Mohm and megaohm are acceptable + value: 1, + offset: 0 + }, + + /* + * Unicode breaks in browsers if charset is not specified + Ω: { + name: 'Ω', + base: BASE_UNITS.ELECTRIC_RESISTANCE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + */ + // Electric inductance + henry: { + name: 'henry', + base: BASE_UNITS.ELECTRIC_INDUCTANCE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + H: { + name: 'H', + base: BASE_UNITS.ELECTRIC_INDUCTANCE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Electric conductance + siemens: { + name: 'siemens', + base: BASE_UNITS.ELECTRIC_CONDUCTANCE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + S: { + name: 'S', + base: BASE_UNITS.ELECTRIC_CONDUCTANCE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Magnetic flux + weber: { + name: 'weber', + base: BASE_UNITS.MAGNETIC_FLUX, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + Wb: { + name: 'Wb', + base: BASE_UNITS.MAGNETIC_FLUX, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Magnetic flux density + tesla: { + name: 'tesla', + base: BASE_UNITS.MAGNETIC_FLUX_DENSITY, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + T: { + name: 'T', + base: BASE_UNITS.MAGNETIC_FLUX_DENSITY, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Binary + b: { + name: 'b', + base: BASE_UNITS.BIT, + prefixes: PREFIXES.BINARY_SHORT, + value: 1, + offset: 0 + }, + bits: { + name: 'bits', + base: BASE_UNITS.BIT, + prefixes: PREFIXES.BINARY_LONG, + value: 1, + offset: 0 + }, + B: { + name: 'B', + base: BASE_UNITS.BIT, + prefixes: PREFIXES.BINARY_SHORT, + value: 8, + offset: 0 + }, + bytes: { + name: 'bytes', + base: BASE_UNITS.BIT, + prefixes: PREFIXES.BINARY_LONG, + value: 8, + offset: 0 + } + }; // aliases (formerly plurals) + + var ALIASES = { + meters: 'meter', + inches: 'inch', + feet: 'foot', + yards: 'yard', + miles: 'mile', + links: 'link', + rods: 'rod', + chains: 'chain', + angstroms: 'angstrom', + lt: 'l', + litres: 'litre', + liter: 'litre', + liters: 'litre', + teaspoons: 'teaspoon', + tablespoons: 'tablespoon', + minims: 'minim', + fluiddrams: 'fluiddram', + fluidounces: 'fluidounce', + gills: 'gill', + cups: 'cup', + pints: 'pint', + quarts: 'quart', + gallons: 'gallon', + beerbarrels: 'beerbarrel', + oilbarrels: 'oilbarrel', + hogsheads: 'hogshead', + gtts: 'gtt', + grams: 'gram', + tons: 'ton', + tonnes: 'tonne', + grains: 'grain', + drams: 'dram', + ounces: 'ounce', + poundmasses: 'poundmass', + hundredweights: 'hundredweight', + sticks: 'stick', + lb: 'lbm', + lbs: 'lbm', + kips: 'kip', + acres: 'acre', + hectares: 'hectare', + sqfeet: 'sqft', + sqyard: 'sqyd', + sqmile: 'sqmi', + sqmiles: 'sqmi', + mmhg: 'mmHg', + mmh2o: 'mmH2O', + cmh2o: 'cmH2O', + seconds: 'second', + secs: 'second', + minutes: 'minute', + mins: 'minute', + hours: 'hour', + hr: 'hour', + hrs: 'hour', + days: 'day', + weeks: 'week', + months: 'month', + years: 'year', + decades: 'decade', + centuries: 'century', + millennia: 'millennium', + hertz: 'hertz', + radians: 'radian', + degrees: 'degree', + gradians: 'gradian', + cycles: 'cycle', + arcsecond: 'arcsec', + arcseconds: 'arcsec', + arcminute: 'arcmin', + arcminutes: 'arcmin', + BTUs: 'BTU', + watts: 'watt', + joules: 'joule', + amperes: 'ampere', + coulombs: 'coulomb', + volts: 'volt', + ohms: 'ohm', + farads: 'farad', + webers: 'weber', + teslas: 'tesla', + electronvolts: 'electronvolt', + moles: 'mole', + bit: 'bits', + "byte": 'bytes' + }; + /** + * Calculate the values for the angle units. + * Value is calculated as number or BigNumber depending on the configuration + * @param {{number: 'number' | 'BigNumber'}} config + */ + + function calculateAngleValues(config) { + if (config.number === 'BigNumber') { + var pi = createBigNumberPi(_BigNumber); + UNITS.rad.value = new _BigNumber(1); + UNITS.deg.value = pi.div(180); // 2 * pi / 360 + + UNITS.grad.value = pi.div(200); // 2 * pi / 400 + + UNITS.cycle.value = pi.times(2); // 2 * pi + + UNITS.arcsec.value = pi.div(648000); // 2 * pi / 360 / 3600 + + UNITS.arcmin.value = pi.div(10800); // 2 * pi / 360 / 60 + } else { + // number + UNITS.rad.value = 1; + UNITS.deg.value = Math.PI / 180; // 2 * pi / 360 + + UNITS.grad.value = Math.PI / 200; // 2 * pi / 400 + + UNITS.cycle.value = Math.PI * 2; // 2 * pi + + UNITS.arcsec.value = Math.PI / 648000; // 2 * pi / 360 / 3600 + + UNITS.arcmin.value = Math.PI / 10800; // 2 * pi / 360 / 60 + } // copy to the full names of the angles + + + UNITS.radian.value = UNITS.rad.value; + UNITS.degree.value = UNITS.deg.value; + UNITS.gradian.value = UNITS.grad.value; + } // apply the angle values now + + + calculateAngleValues(config); + + if (on) { + // recalculate the values on change of configuration + on('config', function (curr, prev) { + if (curr.number !== prev.number) { + calculateAngleValues(curr); + } + }); + } + /** + * A unit system is a set of dimensionally independent base units plus a set of derived units, formed by multiplication and division of the base units, that are by convention used with the unit system. + * A user perhaps could issue a command to select a preferred unit system, or use the default (see below). + * Auto unit system: The default unit system is updated on the fly anytime a unit is parsed. The corresponding unit in the default unit system is updated, so that answers are given in the same units the user supplies. + */ + + + var UNIT_SYSTEMS = { + si: { + // Base units + NONE: { + unit: UNIT_NONE, + prefix: PREFIXES.NONE[''] + }, + LENGTH: { + unit: UNITS.m, + prefix: PREFIXES.SHORT[''] + }, + MASS: { + unit: UNITS.g, + prefix: PREFIXES.SHORT.k + }, + TIME: { + unit: UNITS.s, + prefix: PREFIXES.SHORT[''] + }, + CURRENT: { + unit: UNITS.A, + prefix: PREFIXES.SHORT[''] + }, + TEMPERATURE: { + unit: UNITS.K, + prefix: PREFIXES.SHORT[''] + }, + LUMINOUS_INTENSITY: { + unit: UNITS.cd, + prefix: PREFIXES.SHORT[''] + }, + AMOUNT_OF_SUBSTANCE: { + unit: UNITS.mol, + prefix: PREFIXES.SHORT[''] + }, + ANGLE: { + unit: UNITS.rad, + prefix: PREFIXES.SHORT[''] + }, + BIT: { + unit: UNITS.bits, + prefix: PREFIXES.SHORT[''] + }, + // Derived units + FORCE: { + unit: UNITS.N, + prefix: PREFIXES.SHORT[''] + }, + ENERGY: { + unit: UNITS.J, + prefix: PREFIXES.SHORT[''] + }, + POWER: { + unit: UNITS.W, + prefix: PREFIXES.SHORT[''] + }, + PRESSURE: { + unit: UNITS.Pa, + prefix: PREFIXES.SHORT[''] + }, + ELECTRIC_CHARGE: { + unit: UNITS.C, + prefix: PREFIXES.SHORT[''] + }, + ELECTRIC_CAPACITANCE: { + unit: UNITS.F, + prefix: PREFIXES.SHORT[''] + }, + ELECTRIC_POTENTIAL: { + unit: UNITS.V, + prefix: PREFIXES.SHORT[''] + }, + ELECTRIC_RESISTANCE: { + unit: UNITS.ohm, + prefix: PREFIXES.SHORT[''] + }, + ELECTRIC_INDUCTANCE: { + unit: UNITS.H, + prefix: PREFIXES.SHORT[''] + }, + ELECTRIC_CONDUCTANCE: { + unit: UNITS.S, + prefix: PREFIXES.SHORT[''] + }, + MAGNETIC_FLUX: { + unit: UNITS.Wb, + prefix: PREFIXES.SHORT[''] + }, + MAGNETIC_FLUX_DENSITY: { + unit: UNITS.T, + prefix: PREFIXES.SHORT[''] + }, + FREQUENCY: { + unit: UNITS.Hz, + prefix: PREFIXES.SHORT[''] + } + } + }; // Clone to create the other unit systems + + UNIT_SYSTEMS.cgs = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si)); + UNIT_SYSTEMS.cgs.LENGTH = { + unit: UNITS.m, + prefix: PREFIXES.SHORT.c + }; + UNIT_SYSTEMS.cgs.MASS = { + unit: UNITS.g, + prefix: PREFIXES.SHORT[''] + }; + UNIT_SYSTEMS.cgs.FORCE = { + unit: UNITS.dyn, + prefix: PREFIXES.SHORT[''] + }; + UNIT_SYSTEMS.cgs.ENERGY = { + unit: UNITS.erg, + prefix: PREFIXES.NONE[''] + }; // there are wholly 4 unique cgs systems for electricity and magnetism, + // so let's not worry about it unless somebody complains + + UNIT_SYSTEMS.us = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si)); + UNIT_SYSTEMS.us.LENGTH = { + unit: UNITS.ft, + prefix: PREFIXES.NONE[''] + }; + UNIT_SYSTEMS.us.MASS = { + unit: UNITS.lbm, + prefix: PREFIXES.NONE[''] + }; + UNIT_SYSTEMS.us.TEMPERATURE = { + unit: UNITS.degF, + prefix: PREFIXES.NONE[''] + }; + UNIT_SYSTEMS.us.FORCE = { + unit: UNITS.lbf, + prefix: PREFIXES.NONE[''] + }; + UNIT_SYSTEMS.us.ENERGY = { + unit: UNITS.BTU, + prefix: PREFIXES.BTU[''] + }; + UNIT_SYSTEMS.us.POWER = { + unit: UNITS.hp, + prefix: PREFIXES.NONE[''] + }; + UNIT_SYSTEMS.us.PRESSURE = { + unit: UNITS.psi, + prefix: PREFIXES.NONE[''] + }; // Add additional unit systems here. + // Choose a unit system to seed the auto unit system. + + UNIT_SYSTEMS.auto = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si)); // Set the current unit system + + var currentUnitSystem = UNIT_SYSTEMS.auto; + /** + * Set a unit system for formatting derived units. + * @param {string} [name] The name of the unit system. + */ + + Unit.setUnitSystem = function (name) { + if (Object(utils_object["f" /* hasOwnProperty */])(UNIT_SYSTEMS, name)) { + currentUnitSystem = UNIT_SYSTEMS[name]; + } else { + throw new Error('Unit system ' + name + ' does not exist. Choices are: ' + Object.keys(UNIT_SYSTEMS).join(', ')); + } + }; + /** + * Return the current unit system. + * @return {string} The current unit system. + */ + + + Unit.getUnitSystem = function () { + for (var _key in UNIT_SYSTEMS) { + if (UNIT_SYSTEMS[_key] === currentUnitSystem) { + return _key; + } + } + }; + /** + * Converters to convert from number to an other numeric type like BigNumber + * or Fraction + */ + + + Unit.typeConverters = { + BigNumber: function BigNumber(x) { + return new _BigNumber(x + ''); // stringify to prevent constructor error + }, + Fraction: function Fraction(x) { + return new _Fraction(x); + }, + Complex: function Complex(x) { + return x; + }, + number: function number(x) { + return x; + } + }; + /** + * Retrieve the right convertor function corresponding with the type + * of provided exampleValue. + * + * @param {string} type A string 'number', 'BigNumber', or 'Fraction' + * In case of an unknown type, + * @return {Function} + */ + + Unit._getNumberConverter = function (type) { + if (!Unit.typeConverters[type]) { + throw new TypeError('Unsupported type "' + type + '"'); + } + + return Unit.typeConverters[type]; + }; // Add dimensions to each built-in unit + + + for (var _key2 in UNITS) { + var unit = UNITS[_key2]; + unit.dimensions = unit.base.dimensions; + } // Create aliases + + + for (var _name2 in ALIASES) { + if (Object(utils_object["f" /* hasOwnProperty */])(ALIASES, _name2)) { + var _unit2 = UNITS[ALIASES[_name2]]; + var alias = {}; + + for (var _key3 in _unit2) { + if (Object(utils_object["f" /* hasOwnProperty */])(_unit2, _key3)) { + alias[_key3] = _unit2[_key3]; + } + } + + alias.name = _name2; + UNITS[_name2] = alias; + } + } + + function assertUnitNameIsValid(name) { + for (var i = 0; i < name.length; i++) { + var _c = name.charAt(i); + + var isValidAlpha = function isValidAlpha(p) { + return /^[a-zA-Z]$/.test(p); + }; + + var _isDigit = function _isDigit(c) { + return c >= '0' && c <= '9'; + }; + + if (i === 0 && !isValidAlpha(_c)) { + throw new Error('Invalid unit name (must begin with alpha character): "' + name + '"'); + } + + if (i > 0 && !(isValidAlpha(_c) || _isDigit(_c))) { + throw new Error('Invalid unit name (only alphanumeric characters are allowed): "' + name + '"'); + } + } + } + /** + * Wrapper around createUnitSingle. + * Example: + * createUnit({ + * foo: { }, + * bar: { + * definition: 'kg/foo', + * aliases: ['ba', 'barr', 'bars'], + * offset: 200 + * }, + * baz: '4 bar' + * }, + * { + * override: true + * }) + * @param {object} obj Object map. Each key becomes a unit which is defined by its value. + * @param {object} options + */ + + + Unit.createUnit = function (obj, options) { + if (Unit_typeof(obj) !== 'object') { + throw new TypeError("createUnit expects first parameter to be of type 'Object'"); + } // Remove all units and aliases we are overriding + + + if (options && options.override) { + for (var _key4 in obj) { + if (Object(utils_object["f" /* hasOwnProperty */])(obj, _key4)) { + Unit.deleteUnit(_key4); + } + + if (obj[_key4].aliases) { + for (var i = 0; i < obj[_key4].aliases.length; i++) { + Unit.deleteUnit(obj[_key4].aliases[i]); + } + } + } + } // TODO: traverse multiple times until all units have been added + + + var lastUnit; + + for (var _key5 in obj) { + if (Object(utils_object["f" /* hasOwnProperty */])(obj, _key5)) { + lastUnit = Unit.createUnitSingle(_key5, obj[_key5]); + } + } + + return lastUnit; + }; + /** + * Create a user-defined unit and register it with the Unit type. + * Example: + * createUnitSingle('knot', '0.514444444 m/s') + * createUnitSingle('acre', new Unit(43560, 'ft^2')) + * + * @param {string} name The name of the new unit. Must be unique. Example: 'knot' + * @param {string, Unit, Object} definition Definition of the unit in terms + * of existing units. For example, '0.514444444 m / s'. Can be a Unit, a string, + * or an Object. If an Object, may have the following properties: + * - definition {string|Unit} The definition of this unit. + * - prefixes {string} "none", "short", "long", "binary_short", or "binary_long". + * The default is "none". + * - aliases {Array} Array of strings. Example: ['knots', 'kt', 'kts'] + * - offset {Numeric} An offset to apply when converting from the unit. For + * example, the offset for celsius is 273.15 and the offset for farhenheit + * is 459.67. Default is 0. + * - baseName {string} If the unit's dimension does not match that of any other + * base unit, the name of the newly create base unit. Otherwise, this property + * has no effect. + * + * @param {Object} options (optional) An object containing any of the following + * properties: + * - override {boolean} Whether this unit should be allowed to override existing + * units. + * + * @return {Unit} + */ + + + Unit.createUnitSingle = function (name, obj, options) { + if (typeof obj === 'undefined' || obj === null) { + obj = {}; + } + + if (typeof name !== 'string') { + throw new TypeError("createUnitSingle expects first parameter to be of type 'string'"); + } // Check collisions with existing units + + + if (Object(utils_object["f" /* hasOwnProperty */])(UNITS, name)) { + throw new Error('Cannot create unit "' + name + '": a unit with that name already exists'); + } // TODO: Validate name for collisions with other built-in functions (like abs or cos, for example), and for acceptable variable names. For example, '42' is probably not a valid unit. Nor is '%', since it is also an operator. + + + assertUnitNameIsValid(name); + var defUnit = null; // The Unit from which the new unit will be created. + + var aliases = []; + var offset = 0; + var definition; + var prefixes; + var baseName; + + if (obj && obj.type === 'Unit') { + defUnit = obj.clone(); + } else if (typeof obj === 'string') { + if (obj !== '') { + definition = obj; + } + } else if (Unit_typeof(obj) === 'object') { + definition = obj.definition; + prefixes = obj.prefixes; + offset = obj.offset; + baseName = obj.baseName; + + if (obj.aliases) { + aliases = obj.aliases.valueOf(); // aliases could be a Matrix, so convert to Array + } + } else { + throw new TypeError('Cannot create unit "' + name + '" from "' + obj.toString() + '": expecting "string" or "Unit" or "Object"'); + } + + if (aliases) { + for (var i = 0; i < aliases.length; i++) { + if (Object(utils_object["f" /* hasOwnProperty */])(UNITS, aliases[i])) { + throw new Error('Cannot create alias "' + aliases[i] + '": a unit with that name already exists'); + } + } + } + + if (definition && typeof definition === 'string' && !defUnit) { + try { + defUnit = Unit.parse(definition, { + allowNoUnits: true + }); + } catch (ex) { + ex.message = 'Could not create unit "' + name + '" from "' + definition + '": ' + ex.message; + throw ex; + } + } else if (definition && definition.type === 'Unit') { + defUnit = definition.clone(); + } + + aliases = aliases || []; + offset = offset || 0; + + if (prefixes && prefixes.toUpperCase) { + prefixes = PREFIXES[prefixes.toUpperCase()] || PREFIXES.NONE; + } else { + prefixes = PREFIXES.NONE; + } // If defUnit is null, it is because the user did not + // specify a defintion. So create a new base dimension. + + + var newUnit = {}; + + if (!defUnit) { + // Add a new base dimension + baseName = baseName || name + '_STUFF'; // foo --> foo_STUFF, or the essence of foo + + if (BASE_DIMENSIONS.indexOf(baseName) >= 0) { + throw new Error('Cannot create new base unit "' + name + '": a base unit with that name already exists (and cannot be overridden)'); + } + + BASE_DIMENSIONS.push(baseName); // Push 0 onto existing base units + + for (var b in BASE_UNITS) { + if (Object(utils_object["f" /* hasOwnProperty */])(BASE_UNITS, b)) { + BASE_UNITS[b].dimensions[BASE_DIMENSIONS.length - 1] = 0; + } + } // Add the new base unit + + + var newBaseUnit = { + dimensions: [] + }; + + for (var _i6 = 0; _i6 < BASE_DIMENSIONS.length; _i6++) { + newBaseUnit.dimensions[_i6] = 0; + } + + newBaseUnit.dimensions[BASE_DIMENSIONS.length - 1] = 1; + newBaseUnit.key = baseName; + BASE_UNITS[baseName] = newBaseUnit; + newUnit = { + name: name, + value: 1, + dimensions: BASE_UNITS[baseName].dimensions.slice(0), + prefixes: prefixes, + offset: offset, + base: BASE_UNITS[baseName] + }; + currentUnitSystem[baseName] = { + unit: newUnit, + prefix: PREFIXES.NONE[''] + }; + } else { + newUnit = { + name: name, + value: defUnit.value, + dimensions: defUnit.dimensions.slice(0), + prefixes: prefixes, + offset: offset + }; // Create a new base if no matching base exists + + var anyMatch = false; + + for (var _i7 in BASE_UNITS) { + if (Object(utils_object["f" /* hasOwnProperty */])(BASE_UNITS, _i7)) { + var match = true; + + for (var j = 0; j < BASE_DIMENSIONS.length; j++) { + if (Math.abs((newUnit.dimensions[j] || 0) - (BASE_UNITS[_i7].dimensions[j] || 0)) > 1e-12) { + match = false; + break; + } + } + + if (match) { + anyMatch = true; + newUnit.base = BASE_UNITS[_i7]; + break; + } + } + } + + if (!anyMatch) { + baseName = baseName || name + '_STUFF'; // foo --> foo_STUFF, or the essence of foo + // Add the new base unit + + var _newBaseUnit = { + dimensions: defUnit.dimensions.slice(0) + }; + _newBaseUnit.key = baseName; + BASE_UNITS[baseName] = _newBaseUnit; + currentUnitSystem[baseName] = { + unit: newUnit, + prefix: PREFIXES.NONE[''] + }; + newUnit.base = BASE_UNITS[baseName]; + } + } + + Unit.UNITS[name] = newUnit; + + for (var _i8 = 0; _i8 < aliases.length; _i8++) { + var aliasName = aliases[_i8]; + var _alias = {}; + + for (var _key6 in newUnit) { + if (Object(utils_object["f" /* hasOwnProperty */])(newUnit, _key6)) { + _alias[_key6] = newUnit[_key6]; + } + } + + _alias.name = aliasName; + Unit.UNITS[aliasName] = _alias; + } + + return new Unit(null, name); + }; + + Unit.deleteUnit = function (name) { + delete Unit.UNITS[name]; + }; // expose arrays with prefixes, dimensions, units, systems + + + Unit.PREFIXES = PREFIXES; + Unit.BASE_DIMENSIONS = BASE_DIMENSIONS; + Unit.BASE_UNITS = BASE_UNITS; + Unit.UNIT_SYSTEMS = UNIT_SYSTEMS; + Unit.UNITS = UNITS; + return Unit; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/unit/function/unit.js + + +var unit_name = 'unit'; +var unit_dependencies = ['typed', 'Unit']; // This function is named createUnitFunction to prevent a naming conflict with createUnit + +var createUnitFunction = /* #__PURE__ */Object(factory["a" /* factory */])(unit_name, unit_dependencies, function (_ref) { + var typed = _ref.typed, + Unit = _ref.Unit; + + /** + * Create a unit. Depending on the passed arguments, the function + * will create and return a new math.Unit object. + * When a matrix is provided, all elements will be converted to units. + * + * Syntax: + * + * math.unit(unit : string) + * math.unit(value : number, unit : string) + * + * Examples: + * + * const a = math.unit(5, 'cm') // returns Unit 50 mm + * const b = math.unit('23 kg') // returns Unit 23 kg + * a.to('m') // returns Unit 0.05 m + * + * See also: + * + * bignumber, boolean, complex, index, matrix, number, string, createUnit + * + * @param {* | Array | Matrix} args A number and unit. + * @return {Unit | Array | Matrix} The created unit + */ + var unit = typed(unit_name, { + Unit: function Unit(x) { + return x.clone(); + }, + string: function string(x) { + if (Unit.isValuelessUnit(x)) { + return new Unit(null, x); // a pure unit + } + + return Unit.parse(x, { + allowNoUnits: true + }); // a unit with value, like '5cm' + }, + 'number | BigNumber | Fraction | Complex, string': function numberBigNumberFractionComplexString(value, unit) { + return new Unit(value, unit); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, unit); + } + }); + return unit; +}); +// CONCATENATED MODULE: ./src/type/matrix/function/sparse.js + +var sparse_name = 'sparse'; +var sparse_dependencies = ['typed', 'SparseMatrix']; +var createSparse = /* #__PURE__ */Object(factory["a" /* factory */])(sparse_name, sparse_dependencies, function (_ref) { + var typed = _ref.typed, + SparseMatrix = _ref.SparseMatrix; + + /** + * Create a Sparse Matrix. The function creates a new `math.Matrix` object from + * an `Array`. A Matrix has utility functions to manipulate the data in the + * matrix, like getting the size and getting or setting values in the matrix. + * + * Syntax: + * + * math.sparse() // creates an empty sparse matrix. + * math.sparse(data) // creates a sparse matrix with initial data. + * math.sparse(data, 'number') // creates a sparse matrix with initial data, number datatype. + * + * Examples: + * + * let m = math.sparse([[1, 2], [3, 4]]) + * m.size() // Array [2, 2] + * m.resize([3, 2], 5) + * m.valueOf() // Array [[1, 2], [3, 4], [5, 5]] + * m.get([1, 0]) // number 3 + * + * See also: + * + * bignumber, boolean, complex, index, number, string, unit, matrix + * + * @param {Array | Matrix} [data] A two dimensional array + * + * @return {Matrix} The created matrix + */ + return typed(sparse_name, { + '': function _() { + return new SparseMatrix([]); + }, + string: function string(datatype) { + return new SparseMatrix([], datatype); + }, + 'Array | Matrix': function ArrayMatrix(data) { + return new SparseMatrix(data); + }, + 'Array | Matrix, string': function ArrayMatrixString(data, datatype) { + return new SparseMatrix(data, datatype); + } + }); +}); +// CONCATENATED MODULE: ./src/type/unit/function/createUnit.js + +var createUnit_name = 'createUnit'; +var createUnit_dependencies = ['typed', 'Unit']; +var createCreateUnit = /* #__PURE__ */Object(factory["a" /* factory */])(createUnit_name, createUnit_dependencies, function (_ref) { + var typed = _ref.typed, + Unit = _ref.Unit; + + /** + * Create a user-defined unit and register it with the Unit type. + * + * Syntax: + * + * math.createUnit({ + * baseUnit1: { + * aliases: [string, ...] + * prefixes: object + * }, + * unit2: { + * definition: string, + * aliases: [string, ...] + * prefixes: object, + * offset: number + * }, + * unit3: string // Shortcut + * }) + * + * // Another shortcut: + * math.createUnit(string, unit : string, [object]) + * + * Examples: + * + * math.createUnit('foo') + * math.createUnit('knot', {definition: '0.514444444 m/s', aliases: ['knots', 'kt', 'kts']}) + * math.createUnit('mph', '1 mile/hour') + * + * @param {string} name The name of the new unit. Must be unique. Example: 'knot' + * @param {string, Unit} definition Definition of the unit in terms of existing units. For example, '0.514444444 m / s'. + * @param {Object} options (optional) An object containing any of the following properties: + * - `prefixes {string}` "none", "short", "long", "binary_short", or "binary_long". The default is "none". + * - `aliases {Array}` Array of strings. Example: ['knots', 'kt', 'kts'] + * - `offset {Numeric}` An offset to apply when converting from the unit. For example, the offset for celsius is 273.15. Default is 0. + * + * See also: + * + * unit + * + * @return {Unit} The new unit + */ + return typed(createUnit_name, { + // General function signature. First parameter is an object where each property is the definition of a new unit. The object keys are the unit names and the values are the definitions. The values can be objects, strings, or Units. If a property is an empty object or an empty string, a new base unit is created. The second parameter is the options. + 'Object, Object': function ObjectObject(obj, options) { + return Unit.createUnit(obj, options); + }, + // Same as above but without the options. + Object: function Object(obj) { + return Unit.createUnit(obj, {}); + }, + // Shortcut method for creating one unit. + 'string, Unit | string | Object, Object': function stringUnitStringObjectObject(name, def, options) { + var obj = {}; + obj[name] = def; + return Unit.createUnit(obj, options); + }, + // Same as above but without the options. + 'string, Unit | string | Object': function stringUnitStringObject(name, def) { + var obj = {}; + obj[name] = def; + return Unit.createUnit(obj, {}); + }, + // Without a definition, creates a base unit. + string: function string(name) { + var obj = {}; + obj[name] = {}; + return Unit.createUnit(obj, {}); + } + }); +}); +// CONCATENATED MODULE: ./src/function/trigonometry/acos.js + + +var acos_name = 'acos'; +var acos_dependencies = ['typed', 'config', 'Complex']; +var createAcos = /* #__PURE__ */Object(factory["a" /* factory */])(acos_name, acos_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex; + + /** + * Calculate the inverse cosine of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.acos(x) + * + * Examples: + * + * math.acos(0.5) // returns number 1.0471975511965979 + * math.acos(math.cos(1.5)) // returns number 1.5 + * + * math.acos(2) // returns Complex 0 + 1.3169578969248166 i + * + * See also: + * + * cos, atan, asin + * + * @param {number | BigNumber | Complex | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} The arc cosine of x + */ + var acos = typed(acos_name, { + number: function number(x) { + if (x >= -1 && x <= 1 || config.predictable) { + return Math.acos(x); + } else { + return new Complex(x, 0).acos(); + } + }, + Complex: function Complex(x) { + return x.acos(); + }, + BigNumber: function BigNumber(x) { + return x.acos(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, acos); + } + }); + return acos; +}); +// CONCATENATED MODULE: ./src/plain/number/trigonometry.js + +var trigonometry_n1 = 'number'; +var trigonometry_n2 = 'number, number'; +function acosNumber(x) { + return Math.acos(x); +} +acosNumber.signature = trigonometry_n1; +function acoshNumber(x) { + return Object(utils_number["a" /* acosh */])(x); +} +acoshNumber.signature = trigonometry_n1; +function acotNumber(x) { + return Math.atan(1 / x); +} +acotNumber.signature = trigonometry_n1; +function acothNumber(x) { + return isFinite(x) ? (Math.log((x + 1) / x) + Math.log(x / (x - 1))) / 2 : 0; +} +acothNumber.signature = trigonometry_n1; +function acscNumber(x) { + return Math.asin(1 / x); +} +acscNumber.signature = trigonometry_n1; +function acschNumber(x) { + var xInv = 1 / x; + return Math.log(xInv + Math.sqrt(xInv * xInv + 1)); +} +acschNumber.signature = trigonometry_n1; +function asecNumber(x) { + return Math.acos(1 / x); +} +asecNumber.signature = trigonometry_n1; +function asechNumber(x) { + var xInv = 1 / x; + var ret = Math.sqrt(xInv * xInv - 1); + return Math.log(ret + xInv); +} +asechNumber.signature = trigonometry_n1; +function asinNumber(x) { + return Math.asin(x); +} +asinNumber.signature = trigonometry_n1; +function asinhNumber(x) { + return Object(utils_number["b" /* asinh */])(x); +} +asinhNumber.signature = trigonometry_n1; +function atanNumber(x) { + return Math.atan(x); +} +atanNumber.signature = trigonometry_n1; +function atan2Number(y, x) { + return Math.atan2(y, x); +} +atan2Number.signature = trigonometry_n2; +function atanhNumber(x) { + return Object(utils_number["c" /* atanh */])(x); +} +atanhNumber.signature = trigonometry_n1; +function cosNumber(x) { + return Math.cos(x); +} +cosNumber.signature = trigonometry_n1; +function coshNumber(x) { + return Object(utils_number["e" /* cosh */])(x); +} +coshNumber.signature = trigonometry_n1; +function cotNumber(x) { + return 1 / Math.tan(x); +} +cotNumber.signature = trigonometry_n1; +function cothNumber(x) { + var e = Math.exp(2 * x); + return (e + 1) / (e - 1); +} +cothNumber.signature = trigonometry_n1; +function cscNumber(x) { + return 1 / Math.sin(x); +} +cscNumber.signature = trigonometry_n1; +function cschNumber(x) { + // consider values close to zero (+/-) + if (x === 0) { + return Number.POSITIVE_INFINITY; + } else { + return Math.abs(2 / (Math.exp(x) - Math.exp(-x))) * Object(utils_number["n" /* sign */])(x); + } +} +cschNumber.signature = trigonometry_n1; +function secNumber(x) { + return 1 / Math.cos(x); +} +secNumber.signature = trigonometry_n1; +function sechNumber(x) { + return 2 / (Math.exp(x) + Math.exp(-x)); +} +sechNumber.signature = trigonometry_n1; +function sinNumber(x) { + return Math.sin(x); +} +sinNumber.signature = trigonometry_n1; +function sinhNumber(x) { + return Object(utils_number["o" /* sinh */])(x); +} +sinhNumber.signature = trigonometry_n1; +function tanNumber(x) { + return Math.tan(x); +} +tanNumber.signature = trigonometry_n1; +function tanhNumber(x) { + return Object(utils_number["p" /* tanh */])(x); +} +tanhNumber.signature = trigonometry_n1; +// CONCATENATED MODULE: ./src/function/trigonometry/acosh.js + + + +var acosh_name = 'acosh'; +var acosh_dependencies = ['typed', 'config', 'Complex']; +var createAcosh = /* #__PURE__ */Object(factory["a" /* factory */])(acosh_name, acosh_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex; + + /** + * Calculate the hyperbolic arccos of a value, + * defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.acosh(x) + * + * Examples: + * + * math.acosh(1.5) // returns 0.9624236501192069 + * + * See also: + * + * cosh, asinh, atanh + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic arccosine of x + */ + var acosh = typed(acosh_name, { + number: function number(x) { + if (x >= 1 || config.predictable) { + return acoshNumber(x); + } + + if (x <= -1) { + return new Complex(Math.log(Math.sqrt(x * x - 1) - x), Math.PI); + } + + return new Complex(x, 0).acosh(); + }, + Complex: function Complex(x) { + return x.acosh(); + }, + BigNumber: function BigNumber(x) { + return x.acosh(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, acosh); + } + }); + return acosh; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/acot.js + + + +var acot_name = 'acot'; +var acot_dependencies = ['typed', 'BigNumber']; +var createAcot = /* #__PURE__ */Object(factory["a" /* factory */])(acot_name, acot_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.acot(x) + * + * Examples: + * + * math.acot(0.5) // returns number 0.4636476090008061 + * math.acot(math.cot(1.5)) // returns number 1.5 + * + * math.acot(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i + * + * See also: + * + * cot, atan + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} The arc cotangent of x + */ + var acot = typed(acot_name, { + number: acotNumber, + Complex: function Complex(x) { + return x.acot(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x).atan(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, acot); + } + }); + return acot; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/acoth.js + + + +var acoth_name = 'acoth'; +var acoth_dependencies = ['typed', 'config', 'Complex', 'BigNumber']; +var createAcoth = /* #__PURE__ */Object(factory["a" /* factory */])(acoth_name, acoth_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the hyperbolic arccotangent of a value, + * defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.acoth(x) + * + * Examples: + * + * math.acoth(0.5) // returns 0.8047189562170503 + * + * See also: + * + * acsch, asech + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic arccotangent of x + */ + var acoth = typed(acoth_name, { + number: function number(x) { + if (x >= 1 || x <= -1 || config.predictable) { + return acothNumber(x); + } + + return new Complex(x, 0).acoth(); + }, + Complex: function Complex(x) { + return x.acoth(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x).atanh(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, acoth); + } + }); + return acoth; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/acsc.js + + + +var acsc_name = 'acsc'; +var acsc_dependencies = ['typed', 'config', 'Complex', 'BigNumber']; +var createAcsc = /* #__PURE__ */Object(factory["a" /* factory */])(acsc_name, acsc_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.acsc(x) + * + * Examples: + * + * math.acsc(0.5) // returns number 0.5235987755982989 + * math.acsc(math.csc(1.5)) // returns number ~1.5 + * + * math.acsc(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i + * + * See also: + * + * csc, asin, asec + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} The arc cosecant of x + */ + var acsc = typed(acsc_name, { + number: function number(x) { + if (x <= -1 || x >= 1 || config.predictable) { + return acscNumber(x); + } + + return new Complex(x, 0).acsc(); + }, + Complex: function Complex(x) { + return x.acsc(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x).asin(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, acsc); + } + }); + return acsc; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/acsch.js + + + +var acsch_name = 'acsch'; +var acsch_dependencies = ['typed', 'BigNumber']; +var createAcsch = /* #__PURE__ */Object(factory["a" /* factory */])(acsch_name, acsch_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the hyperbolic arccosecant of a value, + * defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.acsch(x) + * + * Examples: + * + * math.acsch(0.5) // returns 1.4436354751788103 + * + * See also: + * + * asech, acoth + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic arccosecant of x + */ + var acsch = typed(acsch_name, { + number: acschNumber, + Complex: function Complex(x) { + return x.acsch(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x).asinh(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, acsch); + } + }); + return acsch; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/asec.js + + + +var asec_name = 'asec'; +var asec_dependencies = ['typed', 'config', 'Complex', 'BigNumber']; +var createAsec = /* #__PURE__ */Object(factory["a" /* factory */])(asec_name, asec_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the inverse secant of a value. Defined as `asec(x) = acos(1/x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.asec(x) + * + * Examples: + * + * math.asec(0.5) // returns 1.0471975511965979 + * math.asec(math.sec(1.5)) // returns 1.5 + * + * math.asec(2) // returns 0 + 1.3169578969248166 i + * + * See also: + * + * acos, acot, acsc + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} The arc secant of x + */ + var asec = typed(asec_name, { + number: function number(x) { + if (x <= -1 || x >= 1 || config.predictable) { + return asecNumber(x); + } + + return new Complex(x, 0).asec(); + }, + Complex: function Complex(x) { + return x.asec(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x).acos(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, asec); + } + }); + return asec; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/asech.js + + + +var asech_name = 'asech'; +var asech_dependencies = ['typed', 'config', 'Complex', 'BigNumber']; +var createAsech = /* #__PURE__ */Object(factory["a" /* factory */])(asech_name, asech_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the hyperbolic arcsecant of a value, + * defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.asech(x) + * + * Examples: + * + * math.asech(0.5) // returns 1.3169578969248166 + * + * See also: + * + * acsch, acoth + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic arcsecant of x + */ + var asech = typed(asech_name, { + number: function number(x) { + if (x <= 1 && x >= -1 || config.predictable) { + var xInv = 1 / x; + + if (xInv > 0 || config.predictable) { + return asechNumber(x); + } + + var ret = Math.sqrt(xInv * xInv - 1); + return new Complex(Math.log(ret - xInv), Math.PI); + } + + return new Complex(x, 0).asech(); + }, + Complex: function Complex(x) { + return x.asech(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x).acosh(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, asech); + } + }); + return asech; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/asin.js + + +var asin_name = 'asin'; +var asin_dependencies = ['typed', 'config', 'Complex']; +var createAsin = /* #__PURE__ */Object(factory["a" /* factory */])(asin_name, asin_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex; + + /** + * Calculate the inverse sine of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.asin(x) + * + * Examples: + * + * math.asin(0.5) // returns number 0.5235987755982989 + * math.asin(math.sin(1.5)) // returns number ~1.5 + * + * math.asin(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i + * + * See also: + * + * sin, atan, acos + * + * @param {number | BigNumber | Complex | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} The arc sine of x + */ + var asin = typed(asin_name, { + number: function number(x) { + if (x >= -1 && x <= 1 || config.predictable) { + return Math.asin(x); + } else { + return new Complex(x, 0).asin(); + } + }, + Complex: function Complex(x) { + return x.asin(); + }, + BigNumber: function BigNumber(x) { + return x.asin(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since asin(0) = 0 + return deepMap(x, asin, true); + } + }); + return asin; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/asinh.js + + + +var asinh_name = 'asinh'; +var asinh_dependencies = ['typed']; +var createAsinh = /* #__PURE__ */Object(factory["a" /* factory */])(asinh_name, asinh_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the hyperbolic arcsine of a value, + * defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.asinh(x) + * + * Examples: + * + * math.asinh(0.5) // returns 0.48121182505960347 + * + * See also: + * + * acosh, atanh + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic arcsine of x + */ + var asinh = typed('asinh', { + number: asinhNumber, + Complex: function Complex(x) { + return x.asinh(); + }, + BigNumber: function BigNumber(x) { + return x.asinh(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since asinh(0) = 0 + return deepMap(x, asinh, true); + } + }); + return asinh; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/atan.js + + +var atan_name = 'atan'; +var atan_dependencies = ['typed']; +var createAtan = /* #__PURE__ */Object(factory["a" /* factory */])(atan_name, atan_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the inverse tangent of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.atan(x) + * + * Examples: + * + * math.atan(0.5) // returns number 0.4636476090008061 + * math.atan(math.tan(1.5)) // returns number 1.5 + * + * math.atan(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i + * + * See also: + * + * tan, asin, acos + * + * @param {number | BigNumber | Complex | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} The arc tangent of x + */ + var atan = typed('atan', { + number: function number(x) { + return Math.atan(x); + }, + Complex: function Complex(x) { + return x.atan(); + }, + BigNumber: function BigNumber(x) { + return x.atan(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since atan(0) = 0 + return deepMap(x, atan, true); + } + }); + return atan; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/atan2.js + + + + + + + + +var atan2_name = 'atan2'; +var atan2_dependencies = ['typed', 'matrix', 'equalScalar', 'BigNumber', 'DenseMatrix']; +var createAtan2 = /* #__PURE__ */Object(factory["a" /* factory */])(atan2_name, atan2_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + BigNumber = _ref.BigNumber, + DenseMatrix = _ref.DenseMatrix; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm09 = createAlgorithm09({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Calculate the inverse tangent function with two arguments, y/x. + * By providing two arguments, the right quadrant of the computed angle can be + * determined. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.atan2(y, x) + * + * Examples: + * + * math.atan2(2, 2) / math.pi // returns number 0.25 + * + * const angle = math.unit(60, 'deg') // returns Unit 60 deg + * const x = math.cos(angle) + * const y = math.sin(angle) + * + * math.atan(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i + * + * See also: + * + * tan, atan, sin, cos + * + * @param {number | Array | Matrix} y Second dimension + * @param {number | Array | Matrix} x First dimension + * @return {number | Array | Matrix} Four-quadrant inverse tangent + */ + + var atan2 = typed(atan2_name, { + 'number, number': Math.atan2, + // Complex numbers doesn't seem to have a reasonable implementation of + // atan2(). Even Matlab removed the support, after they only calculated + // the atan only on base of the real part of the numbers and ignored the imaginary. + 'BigNumber, BigNumber': function BigNumberBigNumber(y, x) { + return BigNumber.atan2(y, x); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm09(x, y, atan2, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + // mind the order of y and x! + return algorithm02(y, x, atan2, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, atan2, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, atan2); + }, + 'Array, Array': function ArrayArray(x, y) { + return atan2(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + return atan2(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + return atan2(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + return algorithm11(x, y, atan2, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + return algorithm14(x, y, atan2, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + // mind the order of y and x + return algorithm12(y, x, atan2, true); + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + // mind the order of y and x + return algorithm14(y, x, atan2, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + return algorithm14(matrix(x), y, atan2, false).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + return algorithm14(matrix(y), x, atan2, true).valueOf(); + } + }); + return atan2; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/atanh.js + + + +var atanh_name = 'atanh'; +var atanh_dependencies = ['typed', 'config', 'Complex']; +var createAtanh = /* #__PURE__ */Object(factory["a" /* factory */])(atanh_name, atanh_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex; + + /** + * Calculate the hyperbolic arctangent of a value, + * defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.atanh(x) + * + * Examples: + * + * math.atanh(0.5) // returns 0.5493061443340549 + * + * See also: + * + * acosh, asinh + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic arctangent of x + */ + var atanh = typed(atanh_name, { + number: function number(x) { + if (x <= 1 && x >= -1 || config.predictable) { + return atanhNumber(x); + } + + return new Complex(x, 0).atanh(); + }, + Complex: function Complex(x) { + return x.atanh(); + }, + BigNumber: function BigNumber(x) { + return x.atanh(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since atanh(0) = 0 + return deepMap(x, atanh, true); + } + }); + return atanh; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/cos.js + + +var cos_name = 'cos'; +var cos_dependencies = ['typed']; +var createCos = /* #__PURE__ */Object(factory["a" /* factory */])(cos_name, cos_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the cosine of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.cos(x) + * + * Examples: + * + * math.cos(2) // returns number -0.4161468365471422 + * math.cos(math.pi / 4) // returns number 0.7071067811865475 + * math.cos(math.unit(180, 'deg')) // returns number -1 + * math.cos(math.unit(60, 'deg')) // returns number 0.5 + * + * const angle = 0.2 + * math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2) // returns number ~1 + * + * See also: + * + * cos, tan + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} Cosine of x + */ + var cos = typed(cos_name, { + number: Math.cos, + Complex: function Complex(x) { + return x.cos(); + }, + BigNumber: function BigNumber(x) { + return x.cos(); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function cos is no angle'); + } + + return cos(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, cos); + } + }); + return cos; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/cosh.js + + + +var cosh_name = 'cosh'; +var cosh_dependencies = ['typed']; +var createCosh = /* #__PURE__ */Object(factory["a" /* factory */])(cosh_name, cosh_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the hyperbolic cosine of a value, + * defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.cosh(x) + * + * Examples: + * + * math.cosh(0.5) // returns number 1.1276259652063807 + * + * See also: + * + * sinh, tanh + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic cosine of x + */ + var cosh = typed(cosh_name, { + number: utils_number["e" /* cosh */], + Complex: function Complex(x) { + return x.cosh(); + }, + BigNumber: function BigNumber(x) { + return x.cosh(); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function cosh is no angle'); + } + + return cosh(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, cosh); + } + }); + return cosh; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/cot.js + + + +var cot_name = 'cot'; +var cot_dependencies = ['typed', 'BigNumber']; +var createCot = /* #__PURE__ */Object(factory["a" /* factory */])(cot_name, cot_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the cotangent of a value. Defined as `cot(x) = 1 / tan(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.cot(x) + * + * Examples: + * + * math.cot(2) // returns number -0.45765755436028577 + * 1 / math.tan(2) // returns number -0.45765755436028577 + * + * See also: + * + * tan, sec, csc + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Cotangent of x + */ + var cot = typed(cot_name, { + number: cotNumber, + Complex: function Complex(x) { + return x.cot(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x.tan()); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function cot is no angle'); + } + + return cot(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, cot); + } + }); + return cot; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/coth.js + + + +var coth_name = 'coth'; +var coth_dependencies = ['typed', 'BigNumber']; +var createCoth = /* #__PURE__ */Object(factory["a" /* factory */])(coth_name, coth_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the hyperbolic cotangent of a value, + * defined as `coth(x) = 1 / tanh(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.coth(x) + * + * Examples: + * + * // coth(x) = 1 / tanh(x) + * math.coth(2) // returns 1.0373147207275482 + * 1 / math.tanh(2) // returns 1.0373147207275482 + * + * See also: + * + * sinh, tanh, cosh + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic cotangent of x + */ + var coth = typed(coth_name, { + number: cothNumber, + Complex: function Complex(x) { + return x.coth(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x.tanh()); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function coth is no angle'); + } + + return coth(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, coth); + } + }); + return coth; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/csc.js + + + +var csc_name = 'csc'; +var csc_dependencies = ['typed', 'BigNumber']; +var createCsc = /* #__PURE__ */Object(factory["a" /* factory */])(csc_name, csc_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the cosecant of a value, defined as `csc(x) = 1/sin(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.csc(x) + * + * Examples: + * + * math.csc(2) // returns number 1.099750170294617 + * 1 / math.sin(2) // returns number 1.099750170294617 + * + * See also: + * + * sin, sec, cot + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Cosecant of x + */ + var csc = typed(csc_name, { + number: cscNumber, + Complex: function Complex(x) { + return x.csc(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x.sin()); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function csc is no angle'); + } + + return csc(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, csc); + } + }); + return csc; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/csch.js + + + +var csch_name = 'csch'; +var csch_dependencies = ['typed', 'BigNumber']; +var createCsch = /* #__PURE__ */Object(factory["a" /* factory */])(csch_name, csch_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the hyperbolic cosecant of a value, + * defined as `csch(x) = 1 / sinh(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.csch(x) + * + * Examples: + * + * // csch(x) = 1/ sinh(x) + * math.csch(0.5) // returns 1.9190347513349437 + * 1 / math.sinh(0.5) // returns 1.9190347513349437 + * + * See also: + * + * sinh, sech, coth + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic cosecant of x + */ + var csch = typed(csch_name, { + number: cschNumber, + Complex: function Complex(x) { + return x.csch(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x.sinh()); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function csch is no angle'); + } + + return csch(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, csch); + } + }); + return csch; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/sec.js + + + +var sec_name = 'sec'; +var sec_dependencies = ['typed', 'BigNumber']; +var createSec = /* #__PURE__ */Object(factory["a" /* factory */])(sec_name, sec_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the secant of a value, defined as `sec(x) = 1/cos(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.sec(x) + * + * Examples: + * + * math.sec(2) // returns number -2.4029979617223822 + * 1 / math.cos(2) // returns number -2.4029979617223822 + * + * See also: + * + * cos, csc, cot + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Secant of x + */ + var sec = typed(sec_name, { + number: secNumber, + Complex: function Complex(x) { + return x.sec(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x.cos()); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function sec is no angle'); + } + + return sec(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, sec); + } + }); + return sec; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/sech.js + + + +var sech_name = 'sech'; +var sech_dependencies = ['typed', 'BigNumber']; +var createSech = /* #__PURE__ */Object(factory["a" /* factory */])(sech_name, sech_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the hyperbolic secant of a value, + * defined as `sech(x) = 1 / cosh(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.sech(x) + * + * Examples: + * + * // sech(x) = 1/ cosh(x) + * math.sech(0.5) // returns 0.886818883970074 + * 1 / math.cosh(0.5) // returns 0.886818883970074 + * + * See also: + * + * cosh, csch, coth + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic secant of x + */ + var sech = typed(sech_name, { + number: sechNumber, + Complex: function Complex(x) { + return x.sech(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x.cosh()); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function sech is no angle'); + } + + return sech(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, sech); + } + }); + return sech; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/sin.js + + +var sin_name = 'sin'; +var sin_dependencies = ['typed']; +var createSin = /* #__PURE__ */Object(factory["a" /* factory */])(sin_name, sin_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the sine of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.sin(x) + * + * Examples: + * + * math.sin(2) // returns number 0.9092974268256813 + * math.sin(math.pi / 4) // returns number 0.7071067811865475 + * math.sin(math.unit(90, 'deg')) // returns number 1 + * math.sin(math.unit(30, 'deg')) // returns number 0.5 + * + * const angle = 0.2 + * math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2) // returns number ~1 + * + * See also: + * + * cos, tan + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} Sine of x + */ + var sin = typed(sin_name, { + number: Math.sin, + Complex: function Complex(x) { + return x.sin(); + }, + BigNumber: function BigNumber(x) { + return x.sin(); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function sin is no angle'); + } + + return sin(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since sin(0) = 0 + return deepMap(x, sin, true); + } + }); + return sin; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/sinh.js + + + +var sinh_name = 'sinh'; +var sinh_dependencies = ['typed']; +var createSinh = /* #__PURE__ */Object(factory["a" /* factory */])(sinh_name, sinh_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the hyperbolic sine of a value, + * defined as `sinh(x) = 1/2 * (exp(x) - exp(-x))`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.sinh(x) + * + * Examples: + * + * math.sinh(0.5) // returns number 0.5210953054937474 + * + * See also: + * + * cosh, tanh + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic sine of x + */ + var sinh = typed(sinh_name, { + number: sinhNumber, + Complex: function Complex(x) { + return x.sinh(); + }, + BigNumber: function BigNumber(x) { + return x.sinh(); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function sinh is no angle'); + } + + return sinh(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since sinh(0) = 0 + return deepMap(x, sinh, true); + } + }); + return sinh; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/tan.js + + +var tan_name = 'tan'; +var tan_dependencies = ['typed']; +var createTan = /* #__PURE__ */Object(factory["a" /* factory */])(tan_name, tan_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the tangent of a value. `tan(x)` is equal to `sin(x) / cos(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.tan(x) + * + * Examples: + * + * math.tan(0.5) // returns number 0.5463024898437905 + * math.sin(0.5) / math.cos(0.5) // returns number 0.5463024898437905 + * math.tan(math.pi / 4) // returns number 1 + * math.tan(math.unit(45, 'deg')) // returns number 1 + * + * See also: + * + * atan, sin, cos + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} Tangent of x + */ + var tan = typed(tan_name, { + number: Math.tan, + Complex: function Complex(x) { + return x.tan(); + }, + BigNumber: function BigNumber(x) { + return x.tan(); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function tan is no angle'); + } + + return tan(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since tan(0) = 0 + return deepMap(x, tan, true); + } + }); + return tan; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/tanh.js + + + +var tanh_name = 'tanh'; +var tanh_dependencies = ['typed']; +var createTanh = /* #__PURE__ */Object(factory["a" /* factory */])(tanh_name, tanh_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the hyperbolic tangent of a value, + * defined as `tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.tanh(x) + * + * Examples: + * + * // tanh(x) = sinh(x) / cosh(x) = 1 / coth(x) + * math.tanh(0.5) // returns 0.46211715726000974 + * math.sinh(0.5) / math.cosh(0.5) // returns 0.46211715726000974 + * 1 / math.coth(0.5) // returns 0.46211715726000974 + * + * See also: + * + * sinh, cosh, coth + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic tangent of x + */ + var tanh = typed('tanh', { + number: utils_number["p" /* tanh */], + Complex: function Complex(x) { + return x.tanh(); + }, + BigNumber: function BigNumber(x) { + return x.tanh(); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function tanh is no angle'); + } + + return tanh(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since tanh(0) = 0 + return deepMap(x, tanh, true); + } + }); + return tanh; +}); +// CONCATENATED MODULE: ./src/function/set/setCartesian.js + + +var setCartesian_name = 'setCartesian'; +var setCartesian_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix']; +var createSetCartesian = /* #__PURE__ */Object(factory["a" /* factory */])(setCartesian_name, setCartesian_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index, + DenseMatrix = _ref.DenseMatrix; + + /** + * Create the cartesian product of two (multi)sets. + * Multi-dimension arrays will be converted to single-dimension arrays before the operation. + * + * Syntax: + * + * math.setCartesian(set1, set2) + * + * Examples: + * + * math.setCartesian([1, 2], [3, 4]) // returns [[1, 3], [1, 4], [2, 3], [2, 4]] + * + * See also: + * + * setUnion, setIntersect, setDifference, setPowerset + * + * @param {Array | Matrix} a1 A (multi)set + * @param {Array | Matrix} a2 A (multi)set + * @return {Array | Matrix} The cartesian product of two (multi)sets + */ + return typed(setCartesian_name, { + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) { + var result = []; + + if (subset(size(a1), new Index(0)) !== 0 && subset(size(a2), new Index(0)) !== 0) { + // if any of them is empty, return empty + var b1 = Object(utils_array["e" /* flatten */])(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural); + var b2 = Object(utils_array["e" /* flatten */])(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural); + result = []; + + for (var i = 0; i < b1.length; i++) { + for (var j = 0; j < b2.length; j++) { + result.push([b1[i], b2[j]]); + } + } + } // return an array, if both inputs were arrays + + + if (Array.isArray(a1) && Array.isArray(a2)) { + return result; + } // return a matrix otherwise + + + return new DenseMatrix(result); + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setDifference.js + + +var setDifference_name = 'setDifference'; +var setDifference_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix']; +var createSetDifference = /* #__PURE__ */Object(factory["a" /* factory */])(setDifference_name, setDifference_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index, + DenseMatrix = _ref.DenseMatrix; + + /** + * Create the difference of two (multi)sets: every element of set1, that is not the element of set2. + * Multi-dimension arrays will be converted to single-dimension arrays before the operation. + * + * Syntax: + * + * math.setDifference(set1, set2) + * + * Examples: + * + * math.setDifference([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2] + * math.setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2] + * + * See also: + * + * setUnion, setIntersect, setSymDifference + * + * @param {Array | Matrix} a1 A (multi)set + * @param {Array | Matrix} a2 A (multi)set + * @return {Array | Matrix} The difference of two (multi)sets + */ + return typed(setDifference_name, { + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) { + var result; + + if (subset(size(a1), new Index(0)) === 0) { + // empty-anything=empty + result = []; + } else if (subset(size(a2), new Index(0)) === 0) { + // anything-empty=anything + return Object(utils_array["e" /* flatten */])(a1.toArray()); + } else { + var b1 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural)); + var b2 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural)); + result = []; + var inb2; + + for (var i = 0; i < b1.length; i++) { + inb2 = false; + + for (var j = 0; j < b2.length; j++) { + if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) { + // the identifier is always a decimal int + inb2 = true; + break; + } + } + + if (!inb2) { + result.push(b1[i]); + } + } + } // return an array, if both inputs were arrays + + + if (Array.isArray(a1) && Array.isArray(a2)) { + return Object(utils_array["g" /* generalize */])(result); + } // return a matrix otherwise + + + return new DenseMatrix(Object(utils_array["g" /* generalize */])(result)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setDistinct.js + + +var setDistinct_name = 'setDistinct'; +var setDistinct_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix']; +var createSetDistinct = /* #__PURE__ */Object(factory["a" /* factory */])(setDistinct_name, setDistinct_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index, + DenseMatrix = _ref.DenseMatrix; + + /** + * Collect the distinct elements of a multiset. + * A multi-dimension array will be converted to a single-dimension array before the operation. + * + * Syntax: + * + * math.setDistinct(set) + * + * Examples: + * + * math.setDistinct([1, 1, 1, 2, 2, 3]) // returns [1, 2, 3] + * + * See also: + * + * setMultiplicity + * + * @param {Array | Matrix} a A multiset + * @return {Array | Matrix} A set containing the distinc elements of the multiset + */ + return typed(setDistinct_name, { + 'Array | Matrix': function ArrayMatrix(a) { + var result; + + if (subset(size(a), new Index(0)) === 0) { + // if empty, return empty + result = []; + } else { + var b = Object(utils_array["e" /* flatten */])(Array.isArray(a) ? a : a.toArray()).sort(compareNatural); + result = []; + result.push(b[0]); + + for (var i = 1; i < b.length; i++) { + if (compareNatural(b[i], b[i - 1]) !== 0) { + result.push(b[i]); + } + } + } // return an array, if the input was an array + + + if (Array.isArray(a)) { + return result; + } // return a matrix otherwise + + + return new DenseMatrix(result); + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setIntersect.js + + +var setIntersect_name = 'setIntersect'; +var setIntersect_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix']; +var createSetIntersect = /* #__PURE__ */Object(factory["a" /* factory */])(setIntersect_name, setIntersect_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index, + DenseMatrix = _ref.DenseMatrix; + + /** + * Create the intersection of two (multi)sets. + * Multi-dimension arrays will be converted to single-dimension arrays before the operation. + * + * Syntax: + * + * math.setIntersect(set1, set2) + * + * Examples: + * + * math.setIntersect([1, 2, 3, 4], [3, 4, 5, 6]) // returns [3, 4] + * math.setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [3, 4] + * + * See also: + * + * setUnion, setDifference + * + * @param {Array | Matrix} a1 A (multi)set + * @param {Array | Matrix} a2 A (multi)set + * @return {Array | Matrix} The intersection of two (multi)sets + */ + return typed(setIntersect_name, { + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) { + var result; + + if (subset(size(a1), new Index(0)) === 0 || subset(size(a2), new Index(0)) === 0) { + // of any of them is empty, return empty + result = []; + } else { + var b1 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural)); + var b2 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural)); + result = []; + + for (var i = 0; i < b1.length; i++) { + for (var j = 0; j < b2.length; j++) { + if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) { + // the identifier is always a decimal int + result.push(b1[i]); + break; + } + } + } + } // return an array, if both inputs were arrays + + + if (Array.isArray(a1) && Array.isArray(a2)) { + return Object(utils_array["g" /* generalize */])(result); + } // return a matrix otherwise + + + return new DenseMatrix(Object(utils_array["g" /* generalize */])(result)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setIsSubset.js + + +var setIsSubset_name = 'setIsSubset'; +var setIsSubset_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index']; +var createSetIsSubset = /* #__PURE__ */Object(factory["a" /* factory */])(setIsSubset_name, setIsSubset_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index; + + /** + * Check whether a (multi)set is a subset of another (multi)set. (Every element of set1 is the element of set2.) + * Multi-dimension arrays will be converted to single-dimension arrays before the operation. + * + * Syntax: + * + * math.setIsSubset(set1, set2) + * + * Examples: + * + * math.setIsSubset([1, 2], [3, 4, 5, 6]) // returns false + * math.setIsSubset([3, 4], [3, 4, 5, 6]) // returns true + * + * See also: + * + * setUnion, setIntersect, setDifference + * + * @param {Array | Matrix} a1 A (multi)set + * @param {Array | Matrix} a2 A (multi)set + * @return {boolean} true | false + */ + return typed(setIsSubset_name, { + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) { + if (subset(size(a1), new Index(0)) === 0) { + // empty is a subset of anything + return true; + } else if (subset(size(a2), new Index(0)) === 0) { + // anything is not a subset of empty + return false; + } + + var b1 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural)); + var b2 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural)); + var inb2; + + for (var i = 0; i < b1.length; i++) { + inb2 = false; + + for (var j = 0; j < b2.length; j++) { + if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) { + // the identifier is always a decimal int + inb2 = true; + break; + } + } + + if (inb2 === false) { + return false; + } + } + + return true; + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setMultiplicity.js + + +var setMultiplicity_name = 'setMultiplicity'; +var setMultiplicity_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index']; +var createSetMultiplicity = /* #__PURE__ */Object(factory["a" /* factory */])(setMultiplicity_name, setMultiplicity_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index; + + /** + * Count the multiplicity of an element in a multiset. + * A multi-dimension array will be converted to a single-dimension array before the operation. + * + * Syntax: + * + * math.setMultiplicity(element, set) + * + * Examples: + * + * math.setMultiplicity(1, [1, 2, 2, 4]) // returns 1 + * math.setMultiplicity(2, [1, 2, 2, 4]) // returns 2 + * + * See also: + * + * setDistinct, setSize + * + * @param {number | BigNumber | Fraction | Complex} e An element in the multiset + * @param {Array | Matrix} a A multiset + * @return {number} The number of how many times the multiset contains the element + */ + return typed(setMultiplicity_name, { + 'number | BigNumber | Fraction | Complex, Array | Matrix': function numberBigNumberFractionComplexArrayMatrix(e, a) { + if (subset(size(a), new Index(0)) === 0) { + // if empty, return 0 + return 0; + } + + var b = Object(utils_array["e" /* flatten */])(Array.isArray(a) ? a : a.toArray()); + var count = 0; + + for (var i = 0; i < b.length; i++) { + if (compareNatural(b[i], e) === 0) { + count++; + } + } + + return count; + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setPowerset.js + + +var setPowerset_name = 'setPowerset'; +var setPowerset_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index']; +var createSetPowerset = /* #__PURE__ */Object(factory["a" /* factory */])(setPowerset_name, setPowerset_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index; + + /** + * Create the powerset of a (multi)set. (The powerset contains very possible subsets of a (multi)set.) + * A multi-dimension array will be converted to a single-dimension array before the operation. + * + * Syntax: + * + * math.setPowerset(set) + * + * Examples: + * + * math.setPowerset([1, 2, 3]) // returns [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] + * + * See also: + * + * setCartesian + * + * @param {Array | Matrix} a A (multi)set + * @return {Array} The powerset of the (multi)set + */ + return typed(setPowerset_name, { + 'Array | Matrix': function ArrayMatrix(a) { + if (subset(size(a), new Index(0)) === 0) { + // if empty, return empty + return []; + } + + var b = Object(utils_array["e" /* flatten */])(Array.isArray(a) ? a : a.toArray()).sort(compareNatural); + var result = []; + var number = 0; + + while (number.toString(2).length <= b.length) { + result.push(_subset(b, number.toString(2).split('').reverse())); + number++; + } // can not return a matrix, because of the different size of the subarrays + + + return _sort(result); + } + }); // create subset + + function _subset(array, bitarray) { + var result = []; + + for (var i = 0; i < bitarray.length; i++) { + if (bitarray[i] === '1') { + result.push(array[i]); + } + } + + return result; + } // sort subsests by length + + + function _sort(array) { + var temp = []; + + for (var i = array.length - 1; i > 0; i--) { + for (var j = 0; j < i; j++) { + if (array[j].length > array[j + 1].length) { + temp = array[j]; + array[j] = array[j + 1]; + array[j + 1] = temp; + } + } + } + + return array; + } +}); +// CONCATENATED MODULE: ./src/function/set/setSize.js + + +var setSize_name = 'setSize'; +var setSize_dependencies = ['typed', 'compareNatural']; +var createSetSize = /* #__PURE__ */Object(factory["a" /* factory */])(setSize_name, setSize_dependencies, function (_ref) { + var typed = _ref.typed, + compareNatural = _ref.compareNatural; + + /** + * Count the number of elements of a (multi)set. When a second parameter is 'true', count only the unique values. + * A multi-dimension array will be converted to a single-dimension array before the operation. + * + * Syntax: + * + * math.setSize(set) + * math.setSize(set, unique) + * + * Examples: + * + * math.setSize([1, 2, 2, 4]) // returns 4 + * math.setSize([1, 2, 2, 4], true) // returns 3 + * + * See also: + * + * setUnion, setIntersect, setDifference + * + * @param {Array | Matrix} a A multiset + * @return {number} The number of elements of the (multi)set + */ + return typed(setSize_name, { + 'Array | Matrix': function ArrayMatrix(a) { + return Array.isArray(a) ? Object(utils_array["e" /* flatten */])(a).length : Object(utils_array["e" /* flatten */])(a.toArray()).length; + }, + 'Array | Matrix, boolean': function ArrayMatrixBoolean(a, unique) { + if (unique === false || a.length === 0) { + return Array.isArray(a) ? Object(utils_array["e" /* flatten */])(a).length : Object(utils_array["e" /* flatten */])(a.toArray()).length; + } else { + var b = Object(utils_array["e" /* flatten */])(Array.isArray(a) ? a : a.toArray()).sort(compareNatural); + var count = 1; + + for (var i = 1; i < b.length; i++) { + if (compareNatural(b[i], b[i - 1]) !== 0) { + count++; + } + } + + return count; + } + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setSymDifference.js + + +var setSymDifference_name = 'setSymDifference'; +var setSymDifference_dependencies = ['typed', 'size', 'concat', 'subset', 'setDifference', 'Index']; +var createSetSymDifference = /* #__PURE__ */Object(factory["a" /* factory */])(setSymDifference_name, setSymDifference_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + concat = _ref.concat, + subset = _ref.subset, + setDifference = _ref.setDifference, + Index = _ref.Index; + + /** + * Create the symmetric difference of two (multi)sets. + * Multi-dimension arrays will be converted to single-dimension arrays before the operation. + * + * Syntax: + * + * math.setSymDifference(set1, set2) + * + * Examples: + * + * math.setSymDifference([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2, 5, 6] + * math.setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2, 5, 6] + * + * See also: + * + * setUnion, setIntersect, setDifference + * + * @param {Array | Matrix} a1 A (multi)set + * @param {Array | Matrix} a2 A (multi)set + * @return {Array | Matrix} The symmetric difference of two (multi)sets + */ + return typed(setSymDifference_name, { + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) { + if (subset(size(a1), new Index(0)) === 0) { + // if any of them is empty, return the other one + return Object(utils_array["e" /* flatten */])(a2); + } else if (subset(size(a2), new Index(0)) === 0) { + return Object(utils_array["e" /* flatten */])(a1); + } + + var b1 = Object(utils_array["e" /* flatten */])(a1); + var b2 = Object(utils_array["e" /* flatten */])(a2); + return concat(setDifference(b1, b2), setDifference(b2, b1)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setUnion.js + + +var setUnion_name = 'setUnion'; +var setUnion_dependencies = ['typed', 'size', 'concat', 'subset', 'setIntersect', 'setSymDifference', 'Index']; +var createSetUnion = /* #__PURE__ */Object(factory["a" /* factory */])(setUnion_name, setUnion_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + concat = _ref.concat, + subset = _ref.subset, + setIntersect = _ref.setIntersect, + setSymDifference = _ref.setSymDifference, + Index = _ref.Index; + + /** + * Create the union of two (multi)sets. + * Multi-dimension arrays will be converted to single-dimension arrays before the operation. + * + * Syntax: + * + * math.setUnion(set1, set2) + * + * Examples: + * + * math.setUnion([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2, 3, 4, 5, 6] + * math.setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2, 3, 4, 5, 6] + * + * See also: + * + * setIntersect, setDifference + * + * @param {Array | Matrix} a1 A (multi)set + * @param {Array | Matrix} a2 A (multi)set + * @return {Array | Matrix} The union of two (multi)sets + */ + return typed(setUnion_name, { + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) { + if (subset(size(a1), new Index(0)) === 0) { + // if any of them is empty, return the other one + return Object(utils_array["e" /* flatten */])(a2); + } else if (subset(size(a2), new Index(0)) === 0) { + return Object(utils_array["e" /* flatten */])(a1); + } + + var b1 = Object(utils_array["e" /* flatten */])(a1); + var b2 = Object(utils_array["e" /* flatten */])(a2); + return concat(setSymDifference(b1, b2), setIntersect(b1, b2)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/arithmetic/add.js + + + + + + + +var add_name = 'add'; +var add_dependencies = ['typed', 'matrix', 'addScalar', 'equalScalar', 'DenseMatrix', 'SparseMatrix']; +var createAdd = /* #__PURE__ */Object(factory["a" /* factory */])(add_name, add_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + addScalar = _ref.addScalar, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix, + SparseMatrix = _ref.SparseMatrix; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm04 = createAlgorithm04({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Add two or more values, `x + y`. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.add(x, y) + * math.add(x, y, z, ...) + * + * Examples: + * + * math.add(2, 3) // returns number 5 + * math.add(2, 3, 4) // returns number 9 + * + * const a = math.complex(2, 3) + * const b = math.complex(-4, 1) + * math.add(a, b) // returns Complex -2 + 4i + * + * math.add([1, 2, 3], 4) // returns Array [5, 6, 7] + * + * const c = math.unit('5 cm') + * const d = math.unit('2.1 mm') + * math.add(c, d) // returns Unit 52.1 mm + * + * math.add("2.3", "4") // returns number 6.3 + * + * See also: + * + * subtract, sum + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First value to add + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second value to add + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Sum of `x` and `y` + */ + + var add = typed(add_name, Object(utils_object["e" /* extend */])({ + // we extend the signatures of addScalar with signatures dealing with matrices + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, addScalar); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm01(x, y, addScalar, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm01(y, x, addScalar, true); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm04(x, y, addScalar); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return add(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return add(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return add(x, matrix(y)); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, addScalar, false); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm10(x, y, addScalar, false); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, addScalar, true); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm10(y, x, addScalar, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, addScalar, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, addScalar, true).valueOf(); + }, + 'any, any': addScalar, + 'any, any, ...any': function anyAnyAny(x, y, rest) { + var result = add(x, y); + + for (var i = 0; i < rest.length; i++) { + result = add(result, rest[i]); + } + + return result; + } + }, addScalar.signatures)); + return add; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/hypot.js + + +var hypot_name = 'hypot'; +var hypot_dependencies = ['typed', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'sqrt', 'smaller', 'isPositive']; +var createHypot = /* #__PURE__ */Object(factory["a" /* factory */])(hypot_name, hypot_dependencies, function (_ref) { + var typed = _ref.typed, + abs = _ref.abs, + addScalar = _ref.addScalar, + divideScalar = _ref.divideScalar, + multiplyScalar = _ref.multiplyScalar, + sqrt = _ref.sqrt, + smaller = _ref.smaller, + isPositive = _ref.isPositive; + + /** + * Calculate the hypotenusa of a list with values. The hypotenusa is defined as: + * + * hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...) + * + * For matrix input, the hypotenusa is calculated for all values in the matrix. + * + * Syntax: + * + * math.hypot(a, b, ...) + * math.hypot([a, b, c, ...]) + * + * Examples: + * + * math.hypot(3, 4) // 5 + * math.hypot(3, 4, 5) // 7.0710678118654755 + * math.hypot([3, 4, 5]) // 7.0710678118654755 + * math.hypot(-2) // 2 + * + * See also: + * + * abs, norm + * + * @param {... number | BigNumber | Array | Matrix} args A list with numeric values or an Array or Matrix. + * Matrix and Array input is flattened and returns a + * single number for the whole matrix. + * @return {number | BigNumber} Returns the hypothenusa of the input values. + */ + var hypot = typed(hypot_name, { + '... number | BigNumber': _hypot, + Array: function Array(x) { + return hypot.apply(hypot, Object(utils_array["e" /* flatten */])(x)); + }, + Matrix: function Matrix(x) { + return hypot.apply(hypot, Object(utils_array["e" /* flatten */])(x.toArray())); + } + }); + /** + * Calculate the hypotenusa for an Array with values + * @param {Array.} args + * @return {number | BigNumber} Returns the result + * @private + */ + + function _hypot(args) { + // code based on `hypot` from es6-shim: + // https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1619-L1633 + var result = 0; + var largest = 0; + + for (var i = 0; i < args.length; i++) { + var value = abs(args[i]); + + if (smaller(largest, value)) { + result = multiplyScalar(result, multiplyScalar(divideScalar(largest, value), divideScalar(largest, value))); + result = addScalar(result, 1); + largest = value; + } else { + result = addScalar(result, isPositive(value) ? multiplyScalar(divideScalar(value, largest), divideScalar(value, largest)) : value); + } + } + + return multiplyScalar(largest, sqrt(result)); + } + + return hypot; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/norm.js + +var norm_name = 'norm'; +var norm_dependencies = ['typed', 'abs', 'add', 'pow', 'conj', 'sqrt', 'multiply', 'equalScalar', 'larger', 'smaller', 'matrix']; +var createNorm = /* #__PURE__ */Object(factory["a" /* factory */])(norm_name, norm_dependencies, function (_ref) { + var typed = _ref.typed, + abs = _ref.abs, + add = _ref.add, + pow = _ref.pow, + conj = _ref.conj, + sqrt = _ref.sqrt, + multiply = _ref.multiply, + equalScalar = _ref.equalScalar, + larger = _ref.larger, + smaller = _ref.smaller, + matrix = _ref.matrix; + + /** + * Calculate the norm of a number, vector or matrix. + * + * The second parameter p is optional. If not provided, it defaults to 2. + * + * Syntax: + * + * math.norm(x) + * math.norm(x, p) + * + * Examples: + * + * math.abs(-3.5) // returns 3.5 + * math.norm(-3.5) // returns 3.5 + * + * math.norm(math.complex(3, -4)) // returns 5 + * + * math.norm([1, 2, -3], Infinity) // returns 3 + * math.norm([1, 2, -3], -Infinity) // returns 1 + * + * math.norm([3, 4], 2) // returns 5 + * + * math.norm([[1, 2], [3, 4]], 1) // returns 6 + * math.norm([[1, 2], [3, 4]], 'inf') // returns 7 + * math.norm([[1, 2], [3, 4]], 'fro') // returns 5.477225575051661 + * + * See also: + * + * abs, hypot + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * Value for which to calculate the norm + * @param {number | BigNumber | string} [p=2] + * Vector space. + * Supported numbers include Infinity and -Infinity. + * Supported strings are: 'inf', '-inf', and 'fro' (The Frobenius norm) + * @return {number | BigNumber} the p-norm + */ + var norm = typed(norm_name, { + number: Math.abs, + Complex: function Complex(x) { + return x.abs(); + }, + BigNumber: function BigNumber(x) { + // norm(x) = abs(x) + return x.abs(); + }, + "boolean": function boolean(x) { + // norm(x) = abs(x) + return Math.abs(x); + }, + Array: function Array(x) { + return _norm(matrix(x), 2); + }, + Matrix: function Matrix(x) { + return _norm(x, 2); + }, + 'number | Complex | BigNumber | boolean, number | BigNumber | string': function numberComplexBigNumberBooleanNumberBigNumberString(x) { + // ignore second parameter, TODO: remove the option of second parameter for these types + return norm(x); + }, + 'Array, number | BigNumber | string': function ArrayNumberBigNumberString(x, p) { + return _norm(matrix(x), p); + }, + 'Matrix, number | BigNumber | string': function MatrixNumberBigNumberString(x, p) { + return _norm(x, p); + } + }); + /** + * Calculate the norm for an array + * @param {Matrix} x + * @param {number | string} p + * @returns {number} Returns the norm + * @private + */ + + function _norm(x, p) { + // size + var sizeX = x.size(); // check if it is a vector + + if (sizeX.length === 1) { + // check p + if (p === Number.POSITIVE_INFINITY || p === 'inf') { + // norm(x, Infinity) = max(abs(x)) + var pinf = 0; // skip zeros since abs(0) === 0 + + x.forEach(function (value) { + var v = abs(value); + + if (larger(v, pinf)) { + pinf = v; + } + }, true); + return pinf; + } + + if (p === Number.NEGATIVE_INFINITY || p === '-inf') { + // norm(x, -Infinity) = min(abs(x)) + var ninf; // skip zeros since abs(0) === 0 + + x.forEach(function (value) { + var v = abs(value); + + if (!ninf || smaller(v, ninf)) { + ninf = v; + } + }, true); + return ninf || 0; + } + + if (p === 'fro') { + return _norm(x, 2); + } + + if (typeof p === 'number' && !isNaN(p)) { + // check p != 0 + if (!equalScalar(p, 0)) { + // norm(x, p) = sum(abs(xi) ^ p) ^ 1/p + var n = 0; // skip zeros since abs(0) === 0 + + x.forEach(function (value) { + n = add(pow(abs(value), p), n); + }, true); + return pow(n, 1 / p); + } + + return Number.POSITIVE_INFINITY; + } // invalid parameter value + + + throw new Error('Unsupported parameter value'); + } // MxN matrix + + + if (sizeX.length === 2) { + // check p + if (p === 1) { + // norm(x) = the largest column sum + var c = []; // result + + var maxc = 0; // skip zeros since abs(0) == 0 + + x.forEach(function (value, index) { + var j = index[1]; + var cj = add(c[j] || 0, abs(value)); + + if (larger(cj, maxc)) { + maxc = cj; + } + + c[j] = cj; + }, true); + return maxc; + } + + if (p === Number.POSITIVE_INFINITY || p === 'inf') { + // norm(x) = the largest row sum + var r = []; // result + + var maxr = 0; // skip zeros since abs(0) == 0 + + x.forEach(function (value, index) { + var i = index[0]; + var ri = add(r[i] || 0, abs(value)); + + if (larger(ri, maxr)) { + maxr = ri; + } + + r[i] = ri; + }, true); + return maxr; + } + + if (p === 'fro') { + // norm(x) = sqrt(sum(diag(x'x))) + var fro = 0; + x.forEach(function (value, index) { + fro = add(fro, multiply(value, conj(value))); + }); + return abs(sqrt(fro)); + } + + if (p === 2) { + // not implemented + throw new Error('Unsupported parameter value, missing implementation of matrix singular value decomposition'); + } // invalid parameter value + + + throw new Error('Unsupported parameter value'); + } + } + + return norm; +}); +// CONCATENATED MODULE: ./src/function/matrix/dot.js + + +var dot_name = 'dot'; +var dot_dependencies = ['typed', 'add', 'multiply']; +var createDot = /* #__PURE__ */Object(factory["a" /* factory */])(dot_name, dot_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + multiply = _ref.multiply; + + /** + * Calculate the dot product of two vectors. The dot product of + * `A = [a1, a2, a3, ..., an]` and `B = [b1, b2, b3, ..., bn]` is defined as: + * + * dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn + * + * Syntax: + * + * math.dot(x, y) + * + * Examples: + * + * math.dot([2, 4, 1], [2, 2, 3]) // returns number 15 + * math.multiply([2, 4, 1], [2, 2, 3]) // returns number 15 + * + * See also: + * + * multiply, cross + * + * @param {Array | Matrix} x First vector + * @param {Array | Matrix} y Second vector + * @return {number} Returns the dot product of `x` and `y` + */ + return typed(dot_name, { + 'Matrix, Matrix': function MatrixMatrix(x, y) { + return _dot(x.toArray(), y.toArray()); + }, + 'Matrix, Array': function MatrixArray(x, y) { + return _dot(x.toArray(), y); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + return _dot(x, y.toArray()); + }, + 'Array, Array': _dot + }); + /** + * Calculate the dot product for two arrays + * @param {Array} x First vector + * @param {Array} y Second vector + * @returns {number} Returns the dot product of x and y + * @private + */ + // TODO: double code with math.multiply + + function _dot(x, y) { + var xSize = Object(utils_array["a" /* arraySize */])(x); + var ySize = Object(utils_array["a" /* arraySize */])(y); + var len = xSize[0]; + if (xSize.length !== 1 || ySize.length !== 1) throw new RangeError('Vector expected'); // TODO: better error message + + if (xSize[0] !== ySize[0]) throw new RangeError('Vectors must have equal length (' + xSize[0] + ' != ' + ySize[0] + ')'); + if (len === 0) throw new RangeError('Cannot calculate the dot product of empty vectors'); + var prod = 0; + + for (var i = 0; i < len; i++) { + prod = add(prod, multiply(x[i], y[i])); + } + + return prod; + } +}); +// CONCATENATED MODULE: ./src/function/matrix/trace.js + + + +var trace_name = 'trace'; +var trace_dependencies = ['typed', 'matrix', 'add']; +var createTrace = /* #__PURE__ */Object(factory["a" /* factory */])(trace_name, trace_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + add = _ref.add; + + /** + * Calculate the trace of a matrix: the sum of the elements on the main + * diagonal of a square matrix. + * + * Syntax: + * + * math.trace(x) + * + * Examples: + * + * math.trace([[1, 2], [3, 4]]) // returns 5 + * + * const A = [ + * [1, 2, 3], + * [-1, 2, 3], + * [2, 0, 3] + * ] + * math.trace(A) // returns 6 + * + * See also: + * + * diag + * + * @param {Array | Matrix} x A matrix + * + * @return {number} The trace of `x` + */ + return typed('trace', { + Array: function _arrayTrace(x) { + // use dense matrix implementation + return _denseTrace(matrix(x)); + }, + SparseMatrix: _sparseTrace, + DenseMatrix: _denseTrace, + any: utils_object["a" /* clone */] + }); + + function _denseTrace(m) { + // matrix size & data + var size = m._size; + var data = m._data; // process dimensions + + switch (size.length) { + case 1: + // vector + if (size[0] === 1) { + // return data[0] + return Object(utils_object["a" /* clone */])(data[0]); + } + + throw new RangeError('Matrix must be square (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + + case 2: + { + // two dimensional + var rows = size[0]; + var cols = size[1]; + + if (rows === cols) { + // calulate sum + var sum = 0; // loop diagonal + + for (var i = 0; i < rows; i++) { + sum = add(sum, data[i][i]); + } // return trace + + + return sum; + } else { + throw new RangeError('Matrix must be square (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + } + + default: + // multi dimensional + throw new RangeError('Matrix must be two dimensional (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + } + + function _sparseTrace(m) { + // matrix arrays + var values = m._values; + var index = m._index; + var ptr = m._ptr; + var size = m._size; // check dimensions + + var rows = size[0]; + var columns = size[1]; // matrix must be square + + if (rows === columns) { + // calulate sum + var sum = 0; // check we have data (avoid looping columns) + + if (values.length > 0) { + // loop columns + for (var j = 0; j < columns; j++) { + // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + var k0 = ptr[j]; + var k1 = ptr[j + 1]; // loop k within [k0, k1[ + + for (var k = k0; k < k1; k++) { + // row index + var i = index[k]; // check row + + if (i === j) { + // accumulate value + sum = add(sum, values[k]); // exit loop + + break; + } + + if (i > j) { + // exit loop, no value on the diagonal for column j + break; + } + } + } + } // return trace + + + return sum; + } + + throw new RangeError('Matrix must be square (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } +}); +// CONCATENATED MODULE: ./src/type/matrix/function/index.js + + +var function_name = 'index'; +var function_dependencies = ['typed', 'Index']; +var createIndex = /* #__PURE__ */Object(factory["a" /* factory */])(function_name, function_dependencies, function (_ref) { + var typed = _ref.typed, + Index = _ref.Index; + + /** + * Create an index. An Index can store ranges having start, step, and end + * for multiple dimensions. + * Matrix.get, Matrix.set, and math.subset accept an Index as input. + * + * Syntax: + * + * math.index(range1, range2, ...) + * + * Where each range can be any of: + * + * - A number + * - A string for getting/setting an object property + * - An instance of `Range` + * - A one-dimensional Array or a Matrix with numbers + * + * Indexes must be zero-based, integer numbers. + * + * Examples: + * + * const b = [1, 2, 3, 4, 5] + * math.subset(b, math.index([1, 2, 3])) // returns [2, 3, 4] + * + * const a = math.matrix([[1, 2], [3, 4]]) + * a.subset(math.index(0, 1)) // returns 2 + * + * See also: + * + * bignumber, boolean, complex, matrix, number, string, unit + * + * @param {...*} ranges Zero or more ranges or numbers. + * @return {Index} Returns the created index + */ + return typed(function_name, { + '...number | string | BigNumber | Range | Array | Matrix': function numberStringBigNumberRangeArrayMatrix(args) { + var ranges = args.map(function (arg) { + if (Object(is["e" /* isBigNumber */])(arg)) { + return arg.toNumber(); // convert BigNumber to Number + } else if (Array.isArray(arg) || Object(is["v" /* isMatrix */])(arg)) { + return arg.map(function (elem) { + // convert BigNumber to Number + return Object(is["e" /* isBigNumber */])(elem) ? elem.toNumber() : elem; + }); + } else { + return arg; + } + }); + var res = new Index(); + Index.apply(res, ranges); + return res; + } + }); +}); +// CONCATENATED MODULE: ./src/expression/keywords.js +// Reserved keywords not allowed to use in the parser +var keywords = { + end: true +}; +// CONCATENATED MODULE: ./src/expression/node/Node.js +function Node_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { Node_typeof = function _typeof(obj) { return typeof obj; }; } else { Node_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return Node_typeof(obj); } + + + + + + +var Node_name = 'Node'; +var Node_dependencies = ['mathWithTransform']; +var createNode = /* #__PURE__ */Object(factory["a" /* factory */])(Node_name, Node_dependencies, function (_ref) { + var mathWithTransform = _ref.mathWithTransform; + + /** + * Node + */ + function Node() { + if (!(this instanceof Node)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + } + /** + * Evaluate the node + * @param {Object} [scope] Scope to read/write variables + * @return {*} Returns the result + */ + + + Node.prototype.evaluate = function (scope) { + return this.compile().evaluate(scope); + }; + /** + * Evaluate the node + * @param {Object} [scope] Scope to read/write variables + * @return {*} Returns the result + */ + // TODO: Deprecated since v6.0.0. Clean up some day + + + Node.prototype.eval = function (scope) { + Object(utils_log["a" /* warnOnce */])('Method Node.eval is renamed to Node.evaluate. Please use the new method name.'); + return this.evaluate(scope); + }; + + Node.prototype.type = 'Node'; + Node.prototype.isNode = true; + Node.prototype.comment = ''; + /** + * Compile the node into an optimized, evauatable JavaScript function + * @return {{evaluate: function([Object])}} object + * Returns an object with a function 'evaluate', + * which can be invoked as expr.evaluate([scope: Object]), + * where scope is an optional object with + * variables. + */ + + Node.prototype.compile = function () { + var expr = this._compile(mathWithTransform, {}); + + var args = {}; + var context = null; + + function evaluate(scope) { + var s = scope || {}; + + _validateScope(s); + + return expr(s, args, context); + } + + return { + evaluate: evaluate, + // TODO: Deprecated since v6.0.0. Clean up some day + eval: function deprecatedEval(scope) { + Object(utils_log["a" /* warnOnce */])('Method eval is renamed to evaluate. Please use the new method.'); + return evaluate(scope); + } + }; + }; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + + Node.prototype._compile = function (math, argNames) { + throw new Error('Method _compile should be implemented by type ' + this.type); + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + Node.prototype.forEach = function (callback) { + // must be implemented by each of the Node implementations + throw new Error('Cannot run forEach on a Node interface'); + }; + /** + * Create a new Node having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {OperatorNode} Returns a transformed copy of the node + */ + + + Node.prototype.map = function (callback) { + // must be implemented by each of the Node implementations + throw new Error('Cannot run map on a Node interface'); + }; + /** + * Validate whether an object is a Node, for use with map + * @param {Node} node + * @returns {Node} Returns the input if it's a node, else throws an Error + * @protected + */ + + + Node.prototype._ifNode = function (node) { + if (!Object(is["w" /* isNode */])(node)) { + throw new TypeError('Callback function must return a Node'); + } + + return node; + }; + /** + * Recursively traverse all nodes in a node tree. Executes given callback for + * this node and each of its child nodes. + * @param {function(node: Node, path: string, parent: Node)} callback + * A callback called for every node in the node tree. + */ + + + Node.prototype.traverse = function (callback) { + // execute callback for itself + callback(this, null, null); // eslint-disable-line standard/no-callback-literal + // recursively traverse over all childs of a node + + function _traverse(node, callback) { + node.forEach(function (child, path, parent) { + callback(child, path, parent); + + _traverse(child, callback); + }); + } + + _traverse(this, callback); + }; + /** + * Recursively transform a node tree via a transform function. + * + * For example, to replace all nodes of type SymbolNode having name 'x' with a + * ConstantNode with value 2: + * + * const res = Node.transform(function (node, path, parent) { + * if (node && node.isSymbolNode) && (node.name === 'x')) { + * return new ConstantNode(2) + * } + * else { + * return node + * } + * }) + * + * @param {function(node: Node, path: string, parent: Node) : Node} callback + * A mapping function accepting a node, and returning + * a replacement for the node or the original node. + * Signature: callback(node: Node, index: string, parent: Node) : Node + * @return {Node} Returns the original node or its replacement + */ + + + Node.prototype.transform = function (callback) { + function _transform(child, path, parent) { + var replacement = callback(child, path, parent); + + if (replacement !== child) { + // stop iterating when the node is replaced + return replacement; + } + + return child.map(_transform); + } + + return _transform(this, null, null); + }; + /** + * Find any node in the node tree matching given filter function. For example, to + * find all nodes of type SymbolNode having name 'x': + * + * const results = Node.filter(function (node) { + * return (node && node.isSymbolNode) && (node.name === 'x') + * }) + * + * @param {function(node: Node, path: string, parent: Node) : Node} callback + * A test function returning true when a node matches, and false + * otherwise. Function signature: + * callback(node: Node, index: string, parent: Node) : boolean + * @return {Node[]} nodes An array with nodes matching given filter criteria + */ + + + Node.prototype.filter = function (callback) { + var nodes = []; + this.traverse(function (node, path, parent) { + if (callback(node, path, parent)) { + nodes.push(node); + } + }); + return nodes; + }; // TODO: deprecated since version 1.1.0, remove this some day + + + Node.prototype.find = function () { + throw new Error('Function Node.find is deprecated. Use Node.filter instead.'); + }; // TODO: deprecated since version 1.1.0, remove this some day + + + Node.prototype.match = function () { + throw new Error('Function Node.match is deprecated. See functions Node.filter, Node.transform, Node.traverse.'); + }; + /** + * Create a shallow clone of this node + * @return {Node} + */ + + + Node.prototype.clone = function () { + // must be implemented by each of the Node implementations + throw new Error('Cannot clone a Node interface'); + }; + /** + * Create a deep clone of this node + * @return {Node} + */ + + + Node.prototype.cloneDeep = function () { + return this.map(function (node) { + return node.cloneDeep(); + }); + }; + /** + * Deep compare this node with another node. + * @param {Node} other + * @return {boolean} Returns true when both nodes are of the same type and + * contain the same values (as do their childs) + */ + + + Node.prototype.equals = function (other) { + return other ? Object(utils_object["d" /* deepStrictEqual */])(this, other) : false; + }; + /** + * Get string representation. (wrapper function) + * + * This function can get an object of the following form: + * { + * handler: //This can be a callback function of the form + * // "function callback(node, options)"or + * // a map that maps function names (used in FunctionNodes) + * // to callbacks + * parenthesis: "keep" //the parenthesis option (This is optional) + * } + * + * @param {Object} [options] + * @return {string} + */ + + + Node.prototype.toString = function (options) { + var customString; + + if (options && Node_typeof(options) === 'object') { + switch (Node_typeof(options.handler)) { + case 'object': + case 'undefined': + break; + + case 'function': + customString = options.handler(this, options); + break; + + default: + throw new TypeError('Object or function expected as callback'); + } + } + + if (typeof customString !== 'undefined') { + return customString; + } + + return this._toString(options); + }; + /** + * Get a JSON representation of the node + * Both .toJSON() and the static .fromJSON(json) should be implemented by all + * implementations of Node + * @returns {Object} + */ + + + Node.prototype.toJSON = function () { + throw new Error('Cannot serialize object: toJSON not implemented by ' + this.type); + }; + /** + * Get HTML representation. (wrapper function) + * + * This function can get an object of the following form: + * { + * handler: //This can be a callback function of the form + * // "function callback(node, options)" or + * // a map that maps function names (used in FunctionNodes) + * // to callbacks + * parenthesis: "keep" //the parenthesis option (This is optional) + * } + * + * @param {Object} [options] + * @return {string} + */ + + + Node.prototype.toHTML = function (options) { + var customString; + + if (options && Node_typeof(options) === 'object') { + switch (Node_typeof(options.handler)) { + case 'object': + case 'undefined': + break; + + case 'function': + customString = options.handler(this, options); + break; + + default: + throw new TypeError('Object or function expected as callback'); + } + } + + if (typeof customString !== 'undefined') { + return customString; + } + + return this.toHTML(options); + }; + /** + * Internal function to generate the string output. + * This has to be implemented by every Node + * + * @throws {Error} + */ + + + Node.prototype._toString = function () { + // must be implemented by each of the Node implementations + throw new Error('_toString not implemented for ' + this.type); + }; + /** + * Get LaTeX representation. (wrapper function) + * + * This function can get an object of the following form: + * { + * handler: //This can be a callback function of the form + * // "function callback(node, options)"or + * // a map that maps function names (used in FunctionNodes) + * // to callbacks + * parenthesis: "keep" //the parenthesis option (This is optional) + * } + * + * @param {Object} [options] + * @return {string} + */ + + + Node.prototype.toTex = function (options) { + var customTex; + + if (options && Node_typeof(options) === 'object') { + switch (Node_typeof(options.handler)) { + case 'object': + case 'undefined': + break; + + case 'function': + customTex = options.handler(this, options); + break; + + default: + throw new TypeError('Object or function expected as callback'); + } + } + + if (typeof customTex !== 'undefined') { + return customTex; + } + + return this._toTex(options); + }; + /** + * Internal function to generate the LaTeX output. + * This has to be implemented by every Node + * + * @param {Object} [options] + * @throws {Error} + */ + + + Node.prototype._toTex = function (options) { + // must be implemented by each of the Node implementations + throw new Error('_toTex not implemented for ' + this.type); + }; + /** + * Get identifier. + * @return {string} + */ + + + Node.prototype.getIdentifier = function () { + return this.type; + }; + /** + * Get the content of the current Node. + * @return {Node} node + **/ + + + Node.prototype.getContent = function () { + return this; + }; + /** + * Validate the symbol names of a scope. + * Throws an error when the scope contains an illegal symbol. + * @param {Object} scope + */ + + + function _validateScope(scope) { + for (var symbol in scope) { + if (Object(utils_object["f" /* hasOwnProperty */])(scope, symbol)) { + if (symbol in keywords) { + throw new Error('Scope contains an illegal symbol, "' + symbol + '" is a reserved keyword'); + } + } + } + } + + return Node; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/transform/utils/errorTransform.js + +/** + * Transform zero-based indices to one-based indices in errors + * @param {Error} err + * @returns {Error | IndexError} Returns the transformed error + */ + +function errorTransform(err) { + if (err && err.isIndexError) { + return new IndexError["a" /* IndexError */](err.index + 1, err.min + 1, err.max !== undefined ? err.max + 1 : undefined); + } + + return err; +} +// CONCATENATED MODULE: ./src/expression/node/utils/access.js +function access_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { access_typeof = function _typeof(obj) { return typeof obj; }; } else { access_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return access_typeof(obj); } + + + +function accessFactory(_ref) { + var subset = _ref.subset; + + /** + * Retrieve part of an object: + * + * - Retrieve a property from an object + * - Retrieve a part of a string + * - Retrieve a matrix subset + * + * @param {Object | Array | Matrix | string} object + * @param {Index} index + * @return {Object | Array | Matrix | string} Returns the subset + */ + return function access(object, index) { + try { + if (Array.isArray(object)) { + return subset(object, index); + } else if (object && typeof object.subset === 'function') { + // Matrix + return object.subset(index); + } else if (typeof object === 'string') { + // TODO: move getStringSubset into a separate util file, use that + return subset(object, index); + } else if (access_typeof(object) === 'object') { + if (!index.isObjectProperty()) { + throw new TypeError('Cannot apply a numeric index as object property'); + } + + return getSafeProperty(object, index.getObjectProperty()); + } else { + throw new TypeError('Cannot apply index: unsupported type of object'); + } + } catch (err) { + throw errorTransform(err); + } + }; +} +// CONCATENATED MODULE: ./src/expression/node/AccessorNode.js + + + + +var AccessorNode_name = 'AccessorNode'; +var AccessorNode_dependencies = ['subset', 'Node']; +var createAccessorNode = /* #__PURE__ */Object(factory["a" /* factory */])(AccessorNode_name, AccessorNode_dependencies, function (_ref) { + var subset = _ref.subset, + Node = _ref.Node; + var access = accessFactory({ + subset: subset + }); + /** + * @constructor AccessorNode + * @extends {Node} + * Access an object property or get a matrix subset + * + * @param {Node} object The object from which to retrieve + * a property or subset. + * @param {IndexNode} index IndexNode containing ranges + */ + + function AccessorNode(object, index) { + if (!(this instanceof AccessorNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (!Object(is["w" /* isNode */])(object)) { + throw new TypeError('Node expected for parameter "object"'); + } + + if (!Object(is["u" /* isIndexNode */])(index)) { + throw new TypeError('IndexNode expected for parameter "index"'); + } + + this.object = object || null; + this.index = index; // readonly property name + + Object.defineProperty(this, 'name', { + get: function () { + if (this.index) { + return this.index.isObjectProperty() ? this.index.getObjectProperty() : ''; + } else { + return this.object.name || ''; + } + }.bind(this), + set: function set() { + throw new Error('Cannot assign a new name, name is read-only'); + } + }); + } + + AccessorNode.prototype = new Node(); + AccessorNode.prototype.type = 'AccessorNode'; + AccessorNode.prototype.isAccessorNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + AccessorNode.prototype._compile = function (math, argNames) { + var evalObject = this.object._compile(math, argNames); + + var evalIndex = this.index._compile(math, argNames); + + if (this.index.isObjectProperty()) { + var prop = this.index.getObjectProperty(); + return function evalAccessorNode(scope, args, context) { + return getSafeProperty(evalObject(scope, args, context), prop); + }; + } else { + return function evalAccessorNode(scope, args, context) { + var object = evalObject(scope, args, context); + var index = evalIndex(scope, args, object); // we pass object here instead of context + + return access(object, index); + }; + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + AccessorNode.prototype.forEach = function (callback) { + callback(this.object, 'object', this); + callback(this.index, 'index', this); + }; + /** + * Create a new AccessorNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {AccessorNode} Returns a transformed copy of the node + */ + + + AccessorNode.prototype.map = function (callback) { + return new AccessorNode(this._ifNode(callback(this.object, 'object', this)), this._ifNode(callback(this.index, 'index', this))); + }; + /** + * Create a clone of this node, a shallow copy + * @return {AccessorNode} + */ + + + AccessorNode.prototype.clone = function () { + return new AccessorNode(this.object, this.index); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} + */ + + + AccessorNode.prototype._toString = function (options) { + var object = this.object.toString(options); + + if (needParenthesis(this.object)) { + object = '(' + object + ')'; + } + + return object + this.index.toString(options); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} + */ + + + AccessorNode.prototype.toHTML = function (options) { + var object = this.object.toHTML(options); + + if (needParenthesis(this.object)) { + object = '(' + object + ')'; + } + + return object + this.index.toHTML(options); + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} + */ + + + AccessorNode.prototype._toTex = function (options) { + var object = this.object.toTex(options); + + if (needParenthesis(this.object)) { + object = '\\left(\' + object + \'\\right)'; + } + + return object + this.index.toTex(options); + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + AccessorNode.prototype.toJSON = function () { + return { + mathjs: 'AccessorNode', + object: this.object, + index: this.index + }; + }; + /** + * Instantiate an AccessorNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "AccessorNode", object: ..., index: ...}`, + * where mathjs is optional + * @returns {AccessorNode} + */ + + + AccessorNode.fromJSON = function (json) { + return new AccessorNode(json.object, json.index); + }; + /** + * Are parenthesis needed? + * @private + */ + + + function needParenthesis(node) { + // TODO: maybe make a method on the nodes which tells whether they need parenthesis? + return !(Object(is["a" /* isAccessorNode */])(node) || Object(is["c" /* isArrayNode */])(node) || Object(is["l" /* isConstantNode */])(node) || Object(is["r" /* isFunctionNode */])(node) || Object(is["A" /* isObjectNode */])(node) || Object(is["C" /* isParenthesisNode */])(node) || Object(is["J" /* isSymbolNode */])(node)); + } + + return AccessorNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/ArrayNode.js + + + +var ArrayNode_name = 'ArrayNode'; +var ArrayNode_dependencies = ['Node']; +var createArrayNode = /* #__PURE__ */Object(factory["a" /* factory */])(ArrayNode_name, ArrayNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * @constructor ArrayNode + * @extends {Node} + * Holds an 1-dimensional array with items + * @param {Node[]} [items] 1 dimensional array with items + */ + function ArrayNode(items) { + if (!(this instanceof ArrayNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.items = items || []; // validate input + + if (!Array.isArray(this.items) || !this.items.every(is["w" /* isNode */])) { + throw new TypeError('Array containing Nodes expected'); + } // TODO: deprecated since v3, remove some day + + + var deprecated = function deprecated() { + throw new Error('Property `ArrayNode.nodes` is deprecated, use `ArrayNode.items` instead'); + }; + + Object.defineProperty(this, 'nodes', { + get: deprecated, + set: deprecated + }); + } + + ArrayNode.prototype = new Node(); + ArrayNode.prototype.type = 'ArrayNode'; + ArrayNode.prototype.isArrayNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + ArrayNode.prototype._compile = function (math, argNames) { + var evalItems = Object(utils_array["m" /* map */])(this.items, function (item) { + return item._compile(math, argNames); + }); + var asMatrix = math.config.matrix !== 'Array'; + + if (asMatrix) { + var matrix = math.matrix; + return function evalArrayNode(scope, args, context) { + return matrix(Object(utils_array["m" /* map */])(evalItems, function (evalItem) { + return evalItem(scope, args, context); + })); + }; + } else { + return function evalArrayNode(scope, args, context) { + return Object(utils_array["m" /* map */])(evalItems, function (evalItem) { + return evalItem(scope, args, context); + }); + }; + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + ArrayNode.prototype.forEach = function (callback) { + for (var i = 0; i < this.items.length; i++) { + var node = this.items[i]; + callback(node, 'items[' + i + ']', this); + } + }; + /** + * Create a new ArrayNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {ArrayNode} Returns a transformed copy of the node + */ + + + ArrayNode.prototype.map = function (callback) { + var items = []; + + for (var i = 0; i < this.items.length; i++) { + items[i] = this._ifNode(callback(this.items[i], 'items[' + i + ']', this)); + } + + return new ArrayNode(items); + }; + /** + * Create a clone of this node, a shallow copy + * @return {ArrayNode} + */ + + + ArrayNode.prototype.clone = function () { + return new ArrayNode(this.items.slice(0)); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ArrayNode.prototype._toString = function (options) { + var items = this.items.map(function (node) { + return node.toString(options); + }); + return '[' + items.join(', ') + ']'; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + ArrayNode.prototype.toJSON = function () { + return { + mathjs: 'ArrayNode', + items: this.items + }; + }; + /** + * Instantiate an ArrayNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "ArrayNode", items: [...]}`, + * where mathjs is optional + * @returns {ArrayNode} + */ + + + ArrayNode.fromJSON = function (json) { + return new ArrayNode(json.items); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ArrayNode.prototype.toHTML = function (options) { + var items = this.items.map(function (node) { + return node.toHTML(options); + }); + return '[' + items.join(',') + ']'; + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + ArrayNode.prototype._toTex = function (options) { + var s = '\\begin{bmatrix}'; + this.items.forEach(function (node) { + if (node.items) { + s += node.items.map(function (childNode) { + return childNode.toTex(options); + }).join('&'); + } else { + s += node.toTex(options); + } // new line + + + s += '\\\\'; + }); + s += '\\end{bmatrix}'; + return s; + }; + + return ArrayNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/utils/assign.js +function assign_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { assign_typeof = function _typeof(obj) { return typeof obj; }; } else { assign_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return assign_typeof(obj); } + + + +function assignFactory(_ref) { + var subset = _ref.subset, + matrix = _ref.matrix; + + /** + * Replace part of an object: + * + * - Assign a property to an object + * - Replace a part of a string + * - Replace a matrix subset + * + * @param {Object | Array | Matrix | string} object + * @param {Index} index + * @param {*} value + * @return {Object | Array | Matrix | string} Returns the original object + * except in case of a string + */ + // TODO: change assign to return the value instead of the object + return function assign(object, index, value) { + try { + if (Array.isArray(object)) { + // we use matrix.subset here instead of the function subset because we must not clone the contents + return matrix(object).subset(index, value).valueOf(); + } else if (object && typeof object.subset === 'function') { + // Matrix + return object.subset(index, value); + } else if (typeof object === 'string') { + // TODO: move setStringSubset into a separate util file, use that + return subset(object, index, value); + } else if (assign_typeof(object) === 'object') { + if (!index.isObjectProperty()) { + throw TypeError('Cannot apply a numeric index as object property'); + } + + setSafeProperty(object, index.getObjectProperty(), value); + return object; + } else { + throw new TypeError('Cannot apply index: unsupported type of object'); + } + } catch (err) { + throw errorTransform(err); + } + }; +} +// CONCATENATED MODULE: ./src/expression/operators.js +// list of identifiers of nodes in order of their precedence +// also contains information about left/right associativity +// and which other operator the operator is associative with +// Example: +// addition is associative with addition and subtraction, because: +// (a+b)+c=a+(b+c) +// (a+b)-c=a+(b-c) +// +// postfix operators are left associative, prefix operators +// are right associative +// +// It's also possible to set the following properties: +// latexParens: if set to false, this node doesn't need to be enclosed +// in parentheses when using LaTeX +// latexLeftParens: if set to false, this !OperatorNode's! +// left argument doesn't need to be enclosed +// in parentheses +// latexRightParens: the same for the right argument + +var operators_properties = [{ + // assignment + AssignmentNode: {}, + FunctionAssignmentNode: {} +}, { + // conditional expression + ConditionalNode: { + latexLeftParens: false, + latexRightParens: false, + latexParens: false // conditionals don't need parentheses in LaTeX because + // they are 2 dimensional + + } +}, { + // logical or + 'OperatorNode:or': { + associativity: 'left', + associativeWith: [] + } +}, { + // logical xor + 'OperatorNode:xor': { + associativity: 'left', + associativeWith: [] + } +}, { + // logical and + 'OperatorNode:and': { + associativity: 'left', + associativeWith: [] + } +}, { + // bitwise or + 'OperatorNode:bitOr': { + associativity: 'left', + associativeWith: [] + } +}, { + // bitwise xor + 'OperatorNode:bitXor': { + associativity: 'left', + associativeWith: [] + } +}, { + // bitwise and + 'OperatorNode:bitAnd': { + associativity: 'left', + associativeWith: [] + } +}, { + // relational operators + 'OperatorNode:equal': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:unequal': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:smaller': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:larger': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:smallerEq': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:largerEq': { + associativity: 'left', + associativeWith: [] + }, + RelationalNode: { + associativity: 'left', + associativeWith: [] + } +}, { + // bitshift operators + 'OperatorNode:leftShift': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:rightArithShift': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:rightLogShift': { + associativity: 'left', + associativeWith: [] + } +}, { + // unit conversion + 'OperatorNode:to': { + associativity: 'left', + associativeWith: [] + } +}, { + // range + RangeNode: {} +}, { + // addition, subtraction + 'OperatorNode:add': { + associativity: 'left', + associativeWith: ['OperatorNode:add', 'OperatorNode:subtract'] + }, + 'OperatorNode:subtract': { + associativity: 'left', + associativeWith: [] + } +}, { + // multiply, divide, modulus + 'OperatorNode:multiply': { + associativity: 'left', + associativeWith: ['OperatorNode:multiply', 'OperatorNode:divide', 'Operator:dotMultiply', 'Operator:dotDivide'] + }, + 'OperatorNode:divide': { + associativity: 'left', + associativeWith: [], + latexLeftParens: false, + latexRightParens: false, + latexParens: false // fractions don't require parentheses because + // they're 2 dimensional, so parens aren't needed + // in LaTeX + + }, + 'OperatorNode:dotMultiply': { + associativity: 'left', + associativeWith: ['OperatorNode:multiply', 'OperatorNode:divide', 'OperatorNode:dotMultiply', 'OperatorNode:doDivide'] + }, + 'OperatorNode:dotDivide': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:mod': { + associativity: 'left', + associativeWith: [] + } +}, { + // unary prefix operators + 'OperatorNode:unaryPlus': { + associativity: 'right' + }, + 'OperatorNode:unaryMinus': { + associativity: 'right' + }, + 'OperatorNode:bitNot': { + associativity: 'right' + }, + 'OperatorNode:not': { + associativity: 'right' + } +}, { + // exponentiation + 'OperatorNode:pow': { + associativity: 'right', + associativeWith: [], + latexRightParens: false // the exponent doesn't need parentheses in + // LaTeX because it's 2 dimensional + // (it's on top) + + }, + 'OperatorNode:dotPow': { + associativity: 'right', + associativeWith: [] + } +}, { + // factorial + 'OperatorNode:factorial': { + associativity: 'left' + } +}, { + // matrix transpose + 'OperatorNode:transpose': { + associativity: 'left' + } +}]; +/** + * Get the precedence of a Node. + * Higher number for higher precedence, starting with 0. + * Returns null if the precedence is undefined. + * + * @param {Node} _node + * @param {string} parenthesis + * @return {number | null} + */ + +function getPrecedence(_node, parenthesis) { + var node = _node; + + if (parenthesis !== 'keep') { + // ParenthesisNodes are only ignored when not in 'keep' mode + node = _node.getContent(); + } + + var identifier = node.getIdentifier(); + + for (var i = 0; i < operators_properties.length; i++) { + if (identifier in operators_properties[i]) { + return i; + } + } + + return null; +} +/** + * Get the associativity of an operator (left or right). + * Returns a string containing 'left' or 'right' or null if + * the associativity is not defined. + * + * @param {Node} + * @param {string} parenthesis + * @return {string|null} + * @throws {Error} + */ + +function getAssociativity(_node, parenthesis) { + var node = _node; + + if (parenthesis !== 'keep') { + // ParenthesisNodes are only ignored when not in 'keep' mode + node = _node.getContent(); + } + + var identifier = node.getIdentifier(); + var index = getPrecedence(node, parenthesis); + + if (index === null) { + // node isn't in the list + return null; + } + + var property = operators_properties[index][identifier]; + + if (Object(utils_object["f" /* hasOwnProperty */])(property, 'associativity')) { + if (property.associativity === 'left') { + return 'left'; + } + + if (property.associativity === 'right') { + return 'right'; + } // associativity is invalid + + + throw Error('\'' + identifier + '\' has the invalid associativity \'' + property.associativity + '\'.'); + } // associativity is undefined + + + return null; +} +/** + * Check if an operator is associative with another operator. + * Returns either true or false or null if not defined. + * + * @param {Node} nodeA + * @param {Node} nodeB + * @param {string} parenthesis + * @return {boolean | null} + */ + +function isAssociativeWith(nodeA, nodeB, parenthesis) { + // ParenthesisNodes are only ignored when not in 'keep' mode + var a = parenthesis !== 'keep' ? nodeA.getContent() : nodeA; + var b = parenthesis !== 'keep' ? nodeA.getContent() : nodeB; + var identifierA = a.getIdentifier(); + var identifierB = b.getIdentifier(); + var index = getPrecedence(a, parenthesis); + + if (index === null) { + // node isn't in the list + return null; + } + + var property = operators_properties[index][identifierA]; + + if (Object(utils_object["f" /* hasOwnProperty */])(property, 'associativeWith') && property.associativeWith instanceof Array) { + for (var i = 0; i < property.associativeWith.length; i++) { + if (property.associativeWith[i] === identifierB) { + return true; + } + } + + return false; + } // associativeWith is not defined + + + return null; +} +// CONCATENATED MODULE: ./src/expression/node/AssignmentNode.js + + + + + + +var AssignmentNode_name = 'AssignmentNode'; +var AssignmentNode_dependencies = ['subset', '?matrix', // FIXME: should not be needed at all, should be handled by subset +'Node']; +var createAssignmentNode = /* #__PURE__ */Object(factory["a" /* factory */])(AssignmentNode_name, AssignmentNode_dependencies, function (_ref) { + var subset = _ref.subset, + matrix = _ref.matrix, + Node = _ref.Node; + var access = accessFactory({ + subset: subset + }); + var assign = assignFactory({ + subset: subset, + matrix: matrix + }); + /** + * @constructor AssignmentNode + * @extends {Node} + * + * Define a symbol, like `a=3.2`, update a property like `a.b=3.2`, or + * replace a subset of a matrix like `A[2,2]=42`. + * + * Syntax: + * + * new AssignmentNode(symbol, value) + * new AssignmentNode(object, index, value) + * + * Usage: + * + * new AssignmentNode(new SymbolNode('a'), new ConstantNode(2)) // a=2 + * new AssignmentNode(new SymbolNode('a'), new IndexNode('b'), new ConstantNode(2)) // a.b=2 + * new AssignmentNode(new SymbolNode('a'), new IndexNode(1, 2), new ConstantNode(3)) // a[1,2]=3 + * + * @param {SymbolNode | AccessorNode} object Object on which to assign a value + * @param {IndexNode} [index=null] Index, property name or matrix + * index. Optional. If not provided + * and `object` is a SymbolNode, + * the property is assigned to the + * global scope. + * @param {Node} value The value to be assigned + */ + + function AssignmentNode(object, index, value) { + if (!(this instanceof AssignmentNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.object = object; + this.index = value ? index : null; + this.value = value || index; // validate input + + if (!Object(is["J" /* isSymbolNode */])(object) && !Object(is["a" /* isAccessorNode */])(object)) { + throw new TypeError('SymbolNode or AccessorNode expected as "object"'); + } + + if (Object(is["J" /* isSymbolNode */])(object) && object.name === 'end') { + throw new Error('Cannot assign to symbol "end"'); + } + + if (this.index && !Object(is["u" /* isIndexNode */])(this.index)) { + // index is optional + throw new TypeError('IndexNode expected as "index"'); + } + + if (!Object(is["w" /* isNode */])(this.value)) { + throw new TypeError('Node expected as "value"'); + } // readonly property name + + + Object.defineProperty(this, 'name', { + get: function () { + if (this.index) { + return this.index.isObjectProperty() ? this.index.getObjectProperty() : ''; + } else { + return this.object.name || ''; + } + }.bind(this), + set: function set() { + throw new Error('Cannot assign a new name, name is read-only'); + } + }); + } + + AssignmentNode.prototype = new Node(); + AssignmentNode.prototype.type = 'AssignmentNode'; + AssignmentNode.prototype.isAssignmentNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + AssignmentNode.prototype._compile = function (math, argNames) { + var evalObject = this.object._compile(math, argNames); + + var evalIndex = this.index ? this.index._compile(math, argNames) : null; + + var evalValue = this.value._compile(math, argNames); + + var name = this.object.name; + + if (!this.index) { + // apply a variable to the scope, for example `a=2` + if (!Object(is["J" /* isSymbolNode */])(this.object)) { + throw new TypeError('SymbolNode expected as object'); + } + + return function evalAssignmentNode(scope, args, context) { + return setSafeProperty(scope, name, evalValue(scope, args, context)); + }; + } else if (this.index.isObjectProperty()) { + // apply an object property for example `a.b=2` + var prop = this.index.getObjectProperty(); + return function evalAssignmentNode(scope, args, context) { + var object = evalObject(scope, args, context); + var value = evalValue(scope, args, context); + return setSafeProperty(object, prop, value); + }; + } else if (Object(is["J" /* isSymbolNode */])(this.object)) { + // update a matrix subset, for example `a[2]=3` + return function evalAssignmentNode(scope, args, context) { + var childObject = evalObject(scope, args, context); + var value = evalValue(scope, args, context); + var index = evalIndex(scope, args, childObject); // Important: we pass childObject instead of context + + setSafeProperty(scope, name, assign(childObject, index, value)); + return value; + }; + } else { + // isAccessorNode(node.object) === true + // update a matrix subset, for example `a.b[2]=3` + // we will not use the compile function of the AccessorNode, but compile it + // ourselves here as we need the parent object of the AccessorNode: + // wee need to apply the updated object to parent object + var evalParentObject = this.object.object._compile(math, argNames); + + if (this.object.index.isObjectProperty()) { + var parentProp = this.object.index.getObjectProperty(); + return function evalAssignmentNode(scope, args, context) { + var parent = evalParentObject(scope, args, context); + var childObject = getSafeProperty(parent, parentProp); + var index = evalIndex(scope, args, childObject); // Important: we pass childObject instead of context + + var value = evalValue(scope, args, context); + setSafeProperty(parent, parentProp, assign(childObject, index, value)); + return value; + }; + } else { + // if some parameters use the 'end' parameter, we need to calculate the size + var evalParentIndex = this.object.index._compile(math, argNames); + + return function evalAssignmentNode(scope, args, context) { + var parent = evalParentObject(scope, args, context); + var parentIndex = evalParentIndex(scope, args, parent); // Important: we pass parent instead of context + + var childObject = access(parent, parentIndex); + var index = evalIndex(scope, args, childObject); // Important: we pass childObject instead of context + + var value = evalValue(scope, args, context); + assign(parent, parentIndex, assign(childObject, index, value)); + return value; + }; + } + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + AssignmentNode.prototype.forEach = function (callback) { + callback(this.object, 'object', this); + + if (this.index) { + callback(this.index, 'index', this); + } + + callback(this.value, 'value', this); + }; + /** + * Create a new AssignmentNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {AssignmentNode} Returns a transformed copy of the node + */ + + + AssignmentNode.prototype.map = function (callback) { + var object = this._ifNode(callback(this.object, 'object', this)); + + var index = this.index ? this._ifNode(callback(this.index, 'index', this)) : null; + + var value = this._ifNode(callback(this.value, 'value', this)); + + return new AssignmentNode(object, index, value); + }; + /** + * Create a clone of this node, a shallow copy + * @return {AssignmentNode} + */ + + + AssignmentNode.prototype.clone = function () { + return new AssignmentNode(this.object, this.index, this.value); + }; + /* + * Is parenthesis needed? + * @param {node} node + * @param {string} [parenthesis='keep'] + * @private + */ + + + function needParenthesis(node, parenthesis) { + if (!parenthesis) { + parenthesis = 'keep'; + } + + var precedence = getPrecedence(node, parenthesis); + var exprPrecedence = getPrecedence(node.value, parenthesis); + return parenthesis === 'all' || exprPrecedence !== null && exprPrecedence <= precedence; + } + /** + * Get string representation + * @param {Object} options + * @return {string} + */ + + + AssignmentNode.prototype._toString = function (options) { + var object = this.object.toString(options); + var index = this.index ? this.index.toString(options) : ''; + var value = this.value.toString(options); + + if (needParenthesis(this, options && options.parenthesis)) { + value = '(' + value + ')'; + } + + return object + index + ' = ' + value; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + AssignmentNode.prototype.toJSON = function () { + return { + mathjs: 'AssignmentNode', + object: this.object, + index: this.index, + value: this.value + }; + }; + /** + * Instantiate an AssignmentNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "AssignmentNode", object: ..., index: ..., value: ...}`, + * where mathjs is optional + * @returns {AssignmentNode} + */ + + + AssignmentNode.fromJSON = function (json) { + return new AssignmentNode(json.object, json.index, json.value); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} + */ + + + AssignmentNode.prototype.toHTML = function (options) { + var object = this.object.toHTML(options); + var index = this.index ? this.index.toHTML(options) : ''; + var value = this.value.toHTML(options); + + if (needParenthesis(this, options && options.parenthesis)) { + value = '(' + value + ')'; + } + + return object + index + '=' + value; + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} + */ + + + AssignmentNode.prototype._toTex = function (options) { + var object = this.object.toTex(options); + var index = this.index ? this.index.toTex(options) : ''; + var value = this.value.toTex(options); + + if (needParenthesis(this, options && options.parenthesis)) { + value = "\\left(".concat(value, "\\right)"); + } + + return object + index + ':=' + value; + }; + + return AssignmentNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/BlockNode.js + + + +var BlockNode_name = 'BlockNode'; +var BlockNode_dependencies = ['ResultSet', 'Node']; +var createBlockNode = /* #__PURE__ */Object(factory["a" /* factory */])(BlockNode_name, BlockNode_dependencies, function (_ref) { + var ResultSet = _ref.ResultSet, + Node = _ref.Node; + + /** + * @constructor BlockNode + * @extends {Node} + * Holds a set with blocks + * @param {Array.<{node: Node} | {node: Node, visible: boolean}>} blocks + * An array with blocks, where a block is constructed as an Object + * with properties block, which is a Node, and visible, which is + * a boolean. The property visible is optional and is true by default + */ + function BlockNode(blocks) { + if (!(this instanceof BlockNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // validate input, copy blocks + + + if (!Array.isArray(blocks)) throw new Error('Array expected'); + this.blocks = blocks.map(function (block) { + var node = block && block.node; + var visible = block && block.visible !== undefined ? block.visible : true; + if (!Object(is["w" /* isNode */])(node)) throw new TypeError('Property "node" must be a Node'); + if (typeof visible !== 'boolean') throw new TypeError('Property "visible" must be a boolean'); + return { + node: node, + visible: visible + }; + }); + } + + BlockNode.prototype = new Node(); + BlockNode.prototype.type = 'BlockNode'; + BlockNode.prototype.isBlockNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + BlockNode.prototype._compile = function (math, argNames) { + var evalBlocks = Object(utils_array["m" /* map */])(this.blocks, function (block) { + return { + evaluate: block.node._compile(math, argNames), + visible: block.visible + }; + }); + return function evalBlockNodes(scope, args, context) { + var results = []; + Object(utils_array["f" /* forEach */])(evalBlocks, function evalBlockNode(block) { + var result = block.evaluate(scope, args, context); + + if (block.visible) { + results.push(result); + } + }); + return new ResultSet(results); + }; + }; + /** + * Execute a callback for each of the child blocks of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + BlockNode.prototype.forEach = function (callback) { + for (var i = 0; i < this.blocks.length; i++) { + callback(this.blocks[i].node, 'blocks[' + i + '].node', this); + } + }; + /** + * Create a new BlockNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {BlockNode} Returns a transformed copy of the node + */ + + + BlockNode.prototype.map = function (callback) { + var blocks = []; + + for (var i = 0; i < this.blocks.length; i++) { + var block = this.blocks[i]; + + var node = this._ifNode(callback(block.node, 'blocks[' + i + '].node', this)); + + blocks[i] = { + node: node, + visible: block.visible + }; + } + + return new BlockNode(blocks); + }; + /** + * Create a clone of this node, a shallow copy + * @return {BlockNode} + */ + + + BlockNode.prototype.clone = function () { + var blocks = this.blocks.map(function (block) { + return { + node: block.node, + visible: block.visible + }; + }); + return new BlockNode(blocks); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + * @override + */ + + + BlockNode.prototype._toString = function (options) { + return this.blocks.map(function (param) { + return param.node.toString(options) + (param.visible ? '' : ';'); + }).join('\n'); + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + BlockNode.prototype.toJSON = function () { + return { + mathjs: 'BlockNode', + blocks: this.blocks + }; + }; + /** + * Instantiate an BlockNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "BlockNode", blocks: [{node: ..., visible: false}, ...]}`, + * where mathjs is optional + * @returns {BlockNode} + */ + + + BlockNode.fromJSON = function (json) { + return new BlockNode(json.blocks); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + * @override + */ + + + BlockNode.prototype.toHTML = function (options) { + return this.blocks.map(function (param) { + return param.node.toHTML(options) + (param.visible ? '' : ';'); + }).join('
'); + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + BlockNode.prototype._toTex = function (options) { + return this.blocks.map(function (param) { + return param.node.toTex(options) + (param.visible ? '' : ';'); + }).join('\\;\\;\n'); + }; + + return BlockNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/ConditionalNode.js + + + +var ConditionalNode_name = 'ConditionalNode'; +var ConditionalNode_dependencies = ['Node']; +var createConditionalNode = /* #__PURE__ */Object(factory["a" /* factory */])(ConditionalNode_name, ConditionalNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * A lazy evaluating conditional operator: 'condition ? trueExpr : falseExpr' + * + * @param {Node} condition Condition, must result in a boolean + * @param {Node} trueExpr Expression evaluated when condition is true + * @param {Node} falseExpr Expression evaluated when condition is true + * + * @constructor ConditionalNode + * @extends {Node} + */ + function ConditionalNode(condition, trueExpr, falseExpr) { + if (!(this instanceof ConditionalNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (!Object(is["w" /* isNode */])(condition)) throw new TypeError('Parameter condition must be a Node'); + if (!Object(is["w" /* isNode */])(trueExpr)) throw new TypeError('Parameter trueExpr must be a Node'); + if (!Object(is["w" /* isNode */])(falseExpr)) throw new TypeError('Parameter falseExpr must be a Node'); + this.condition = condition; + this.trueExpr = trueExpr; + this.falseExpr = falseExpr; + } + + ConditionalNode.prototype = new Node(); + ConditionalNode.prototype.type = 'ConditionalNode'; + ConditionalNode.prototype.isConditionalNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + ConditionalNode.prototype._compile = function (math, argNames) { + var evalCondition = this.condition._compile(math, argNames); + + var evalTrueExpr = this.trueExpr._compile(math, argNames); + + var evalFalseExpr = this.falseExpr._compile(math, argNames); + + return function evalConditionalNode(scope, args, context) { + return testCondition(evalCondition(scope, args, context)) ? evalTrueExpr(scope, args, context) : evalFalseExpr(scope, args, context); + }; + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + ConditionalNode.prototype.forEach = function (callback) { + callback(this.condition, 'condition', this); + callback(this.trueExpr, 'trueExpr', this); + callback(this.falseExpr, 'falseExpr', this); + }; + /** + * Create a new ConditionalNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {ConditionalNode} Returns a transformed copy of the node + */ + + + ConditionalNode.prototype.map = function (callback) { + return new ConditionalNode(this._ifNode(callback(this.condition, 'condition', this)), this._ifNode(callback(this.trueExpr, 'trueExpr', this)), this._ifNode(callback(this.falseExpr, 'falseExpr', this))); + }; + /** + * Create a clone of this node, a shallow copy + * @return {ConditionalNode} + */ + + + ConditionalNode.prototype.clone = function () { + return new ConditionalNode(this.condition, this.trueExpr, this.falseExpr); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + */ + + + ConditionalNode.prototype._toString = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var precedence = getPrecedence(this, parenthesis); // Enclose Arguments in parentheses if they are an OperatorNode + // or have lower or equal precedence + // NOTE: enclosing all OperatorNodes in parentheses is a decision + // purely based on aesthetics and readability + + var condition = this.condition.toString(options); + var conditionPrecedence = getPrecedence(this.condition, parenthesis); + + if (parenthesis === 'all' || this.condition.type === 'OperatorNode' || conditionPrecedence !== null && conditionPrecedence <= precedence) { + condition = '(' + condition + ')'; + } + + var trueExpr = this.trueExpr.toString(options); + var truePrecedence = getPrecedence(this.trueExpr, parenthesis); + + if (parenthesis === 'all' || this.trueExpr.type === 'OperatorNode' || truePrecedence !== null && truePrecedence <= precedence) { + trueExpr = '(' + trueExpr + ')'; + } + + var falseExpr = this.falseExpr.toString(options); + var falsePrecedence = getPrecedence(this.falseExpr, parenthesis); + + if (parenthesis === 'all' || this.falseExpr.type === 'OperatorNode' || falsePrecedence !== null && falsePrecedence <= precedence) { + falseExpr = '(' + falseExpr + ')'; + } + + return condition + ' ? ' + trueExpr + ' : ' + falseExpr; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + ConditionalNode.prototype.toJSON = function () { + return { + mathjs: 'ConditionalNode', + condition: this.condition, + trueExpr: this.trueExpr, + falseExpr: this.falseExpr + }; + }; + /** + * Instantiate an ConditionalNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "ConditionalNode", "condition": ..., "trueExpr": ..., "falseExpr": ...}`, + * where mathjs is optional + * @returns {ConditionalNode} + */ + + + ConditionalNode.fromJSON = function (json) { + return new ConditionalNode(json.condition, json.trueExpr, json.falseExpr); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + */ + + + ConditionalNode.prototype.toHTML = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var precedence = getPrecedence(this, parenthesis); // Enclose Arguments in parentheses if they are an OperatorNode + // or have lower or equal precedence + // NOTE: enclosing all OperatorNodes in parentheses is a decision + // purely based on aesthetics and readability + + var condition = this.condition.toHTML(options); + var conditionPrecedence = getPrecedence(this.condition, parenthesis); + + if (parenthesis === 'all' || this.condition.type === 'OperatorNode' || conditionPrecedence !== null && conditionPrecedence <= precedence) { + condition = '(' + condition + ')'; + } + + var trueExpr = this.trueExpr.toHTML(options); + var truePrecedence = getPrecedence(this.trueExpr, parenthesis); + + if (parenthesis === 'all' || this.trueExpr.type === 'OperatorNode' || truePrecedence !== null && truePrecedence <= precedence) { + trueExpr = '(' + trueExpr + ')'; + } + + var falseExpr = this.falseExpr.toHTML(options); + var falsePrecedence = getPrecedence(this.falseExpr, parenthesis); + + if (parenthesis === 'all' || this.falseExpr.type === 'OperatorNode' || falsePrecedence !== null && falsePrecedence <= precedence) { + falseExpr = '(' + falseExpr + ')'; + } + + return condition + '?' + trueExpr + ':' + falseExpr; + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + ConditionalNode.prototype._toTex = function (options) { + return '\\begin{cases} {' + this.trueExpr.toTex(options) + '}, &\\quad{\\text{if }\\;' + this.condition.toTex(options) + '}\\\\{' + this.falseExpr.toTex(options) + '}, &\\quad{\\text{otherwise}}\\end{cases}'; + }; + /** + * Test whether a condition is met + * @param {*} condition + * @returns {boolean} true if condition is true or non-zero, else false + */ + + + function testCondition(condition) { + if (typeof condition === 'number' || typeof condition === 'boolean' || typeof condition === 'string') { + return !!condition; + } + + if (condition) { + if (Object(is["e" /* isBigNumber */])(condition)) { + return !condition.isZero(); + } + + if (Object(is["j" /* isComplex */])(condition)) { + return !!(condition.re || condition.im); + } + + if (Object(is["L" /* isUnit */])(condition)) { + return !!condition.value; + } + } + + if (condition === null || condition === undefined) { + return false; + } + + throw new TypeError('Unsupported type of condition "' + Object(is["M" /* typeOf */])(condition) + '"'); + } + + return ConditionalNode; +}, { + isClass: true, + isNode: true +}); +// EXTERNAL MODULE: ./node_modules/escape-latex/dist/index.js +var dist = __webpack_require__(17); +var dist_default = /*#__PURE__*/__webpack_require__.n(dist); + +// CONCATENATED MODULE: ./src/utils/latex.js +/* eslint no-template-curly-in-string: "off" */ + + +var latexSymbols = { + // GREEK LETTERS + Alpha: 'A', + alpha: '\\alpha', + Beta: 'B', + beta: '\\beta', + Gamma: '\\Gamma', + gamma: '\\gamma', + Delta: '\\Delta', + delta: '\\delta', + Epsilon: 'E', + epsilon: '\\epsilon', + varepsilon: '\\varepsilon', + Zeta: 'Z', + zeta: '\\zeta', + Eta: 'H', + eta: '\\eta', + Theta: '\\Theta', + theta: '\\theta', + vartheta: '\\vartheta', + Iota: 'I', + iota: '\\iota', + Kappa: 'K', + kappa: '\\kappa', + varkappa: '\\varkappa', + Lambda: '\\Lambda', + lambda: '\\lambda', + Mu: 'M', + mu: '\\mu', + Nu: 'N', + nu: '\\nu', + Xi: '\\Xi', + xi: '\\xi', + Omicron: 'O', + omicron: 'o', + Pi: '\\Pi', + pi: '\\pi', + varpi: '\\varpi', + Rho: 'P', + rho: '\\rho', + varrho: '\\varrho', + Sigma: '\\Sigma', + sigma: '\\sigma', + varsigma: '\\varsigma', + Tau: 'T', + tau: '\\tau', + Upsilon: "\\Upsilon", + upsilon: "\\upsilon", + Phi: '\\Phi', + phi: '\\phi', + varphi: '\\varphi', + Chi: 'X', + chi: '\\chi', + Psi: '\\Psi', + psi: '\\psi', + Omega: '\\Omega', + omega: '\\omega', + // logic + "true": '\\mathrm{True}', + "false": '\\mathrm{False}', + // other + i: 'i', + // TODO use \i ?? + inf: '\\infty', + Inf: '\\infty', + infinity: '\\infty', + Infinity: '\\infty', + oo: '\\infty', + lim: '\\lim', + undefined: '\\mathbf{?}' +}; +var latexOperators = { + transpose: '^\\top', + ctranspose: '^H', + factorial: '!', + pow: '^', + dotPow: '.^\\wedge', + // TODO find ideal solution + unaryPlus: '+', + unaryMinus: '-', + bitNot: '\\~', + // TODO find ideal solution + not: '\\neg', + multiply: '\\cdot', + divide: '\\frac', + // TODO how to handle that properly? + dotMultiply: '.\\cdot', + // TODO find ideal solution + dotDivide: '.:', + // TODO find ideal solution + mod: '\\mod', + add: '+', + subtract: '-', + to: '\\rightarrow', + leftShift: '<<', + rightArithShift: '>>', + rightLogShift: '>>>', + equal: '=', + unequal: '\\neq', + smaller: '<', + larger: '>', + smallerEq: '\\leq', + largerEq: '\\geq', + bitAnd: '\\&', + bitXor: "\\underline{|}", + bitOr: '|', + and: '\\wedge', + xor: '\\veebar', + or: '\\vee' +}; +var latexFunctions = { + // arithmetic + abs: { + 1: '\\left|${args[0]}\\right|' + }, + add: { + 2: "\\left(${args[0]}".concat(latexOperators.add, "${args[1]}\\right)") + }, + cbrt: { + 1: '\\sqrt[3]{${args[0]}}' + }, + ceil: { + 1: '\\left\\lceil${args[0]}\\right\\rceil' + }, + cube: { + 1: '\\left(${args[0]}\\right)^3' + }, + divide: { + 2: '\\frac{${args[0]}}{${args[1]}}' + }, + dotDivide: { + 2: "\\left(${args[0]}".concat(latexOperators.dotDivide, "${args[1]}\\right)") + }, + dotMultiply: { + 2: "\\left(${args[0]}".concat(latexOperators.dotMultiply, "${args[1]}\\right)") + }, + dotPow: { + 2: "\\left(${args[0]}".concat(latexOperators.dotPow, "${args[1]}\\right)") + }, + exp: { + 1: '\\exp\\left(${args[0]}\\right)' + }, + expm1: "\\left(e".concat(latexOperators.pow, "{${args[0]}}-1\\right)"), + fix: { + 1: '\\mathrm{${name}}\\left(${args[0]}\\right)' + }, + floor: { + 1: '\\left\\lfloor${args[0]}\\right\\rfloor' + }, + gcd: '\\gcd\\left(${args}\\right)', + hypot: '\\hypot\\left(${args}\\right)', + log: { + 1: '\\ln\\left(${args[0]}\\right)', + 2: '\\log_{${args[1]}}\\left(${args[0]}\\right)' + }, + log10: { + 1: '\\log_{10}\\left(${args[0]}\\right)' + }, + log1p: { + 1: '\\ln\\left(${args[0]}+1\\right)', + 2: '\\log_{${args[1]}}\\left(${args[0]}+1\\right)' + }, + log2: '\\log_{2}\\left(${args[0]}\\right)', + mod: { + 2: "\\left(${args[0]}".concat(latexOperators.mod, "${args[1]}\\right)") + }, + multiply: { + 2: "\\left(${args[0]}".concat(latexOperators.multiply, "${args[1]}\\right)") + }, + norm: { + 1: '\\left\\|${args[0]}\\right\\|', + 2: undefined // use default template + + }, + nthRoot: { + 2: '\\sqrt[${args[1]}]{${args[0]}}' + }, + nthRoots: { + 2: '\\{y : $y^{args[1]} = {${args[0]}}\\}' + }, + pow: { + 2: "\\left(${args[0]}\\right)".concat(latexOperators.pow, "{${args[1]}}") + }, + round: { + 1: '\\left\\lfloor${args[0]}\\right\\rceil', + 2: undefined // use default template + + }, + sign: { + 1: '\\mathrm{${name}}\\left(${args[0]}\\right)' + }, + sqrt: { + 1: '\\sqrt{${args[0]}}' + }, + square: { + 1: '\\left(${args[0]}\\right)^2' + }, + subtract: { + 2: "\\left(${args[0]}".concat(latexOperators.subtract, "${args[1]}\\right)") + }, + unaryMinus: { + 1: "".concat(latexOperators.unaryMinus, "\\left(${args[0]}\\right)") + }, + unaryPlus: { + 1: "".concat(latexOperators.unaryPlus, "\\left(${args[0]}\\right)") + }, + // bitwise + bitAnd: { + 2: "\\left(${args[0]}".concat(latexOperators.bitAnd, "${args[1]}\\right)") + }, + bitNot: { + 1: latexOperators.bitNot + '\\left(${args[0]}\\right)' + }, + bitOr: { + 2: "\\left(${args[0]}".concat(latexOperators.bitOr, "${args[1]}\\right)") + }, + bitXor: { + 2: "\\left(${args[0]}".concat(latexOperators.bitXor, "${args[1]}\\right)") + }, + leftShift: { + 2: "\\left(${args[0]}".concat(latexOperators.leftShift, "${args[1]}\\right)") + }, + rightArithShift: { + 2: "\\left(${args[0]}".concat(latexOperators.rightArithShift, "${args[1]}\\right)") + }, + rightLogShift: { + 2: "\\left(${args[0]}".concat(latexOperators.rightLogShift, "${args[1]}\\right)") + }, + // combinatorics + bellNumbers: { + 1: '\\mathrm{B}_{${args[0]}}' + }, + catalan: { + 1: '\\mathrm{C}_{${args[0]}}' + }, + stirlingS2: { + 2: '\\mathrm{S}\\left(${args}\\right)' + }, + // complex + arg: { + 1: '\\arg\\left(${args[0]}\\right)' + }, + conj: { + 1: '\\left(${args[0]}\\right)^*' + }, + im: { + 1: '\\Im\\left\\lbrace${args[0]}\\right\\rbrace' + }, + re: { + 1: '\\Re\\left\\lbrace${args[0]}\\right\\rbrace' + }, + // logical + and: { + 2: "\\left(${args[0]}".concat(latexOperators.and, "${args[1]}\\right)") + }, + not: { + 1: latexOperators.not + '\\left(${args[0]}\\right)' + }, + or: { + 2: "\\left(${args[0]}".concat(latexOperators.or, "${args[1]}\\right)") + }, + xor: { + 2: "\\left(${args[0]}".concat(latexOperators.xor, "${args[1]}\\right)") + }, + // matrix + cross: { + 2: '\\left(${args[0]}\\right)\\times\\left(${args[1]}\\right)' + }, + ctranspose: { + 1: "\\left(${args[0]}\\right)".concat(latexOperators.ctranspose) + }, + det: { + 1: '\\det\\left(${args[0]}\\right)' + }, + dot: { + 2: '\\left(${args[0]}\\cdot${args[1]}\\right)' + }, + expm: { + 1: '\\exp\\left(${args[0]}\\right)' + }, + inv: { + 1: '\\left(${args[0]}\\right)^{-1}' + }, + sqrtm: { + 1: "{${args[0]}}".concat(latexOperators.pow, "{\\frac{1}{2}}") + }, + trace: { + 1: '\\mathrm{tr}\\left(${args[0]}\\right)' + }, + transpose: { + 1: "\\left(${args[0]}\\right)".concat(latexOperators.transpose) + }, + // probability + combinations: { + 2: '\\binom{${args[0]}}{${args[1]}}' + }, + combinationsWithRep: { + 2: '\\left(\\!\\!{\\binom{${args[0]}}{${args[1]}}}\\!\\!\\right)' + }, + factorial: { + 1: "\\left(${args[0]}\\right)".concat(latexOperators.factorial) + }, + gamma: { + 1: '\\Gamma\\left(${args[0]}\\right)' + }, + // relational + equal: { + 2: "\\left(${args[0]}".concat(latexOperators.equal, "${args[1]}\\right)") + }, + larger: { + 2: "\\left(${args[0]}".concat(latexOperators.larger, "${args[1]}\\right)") + }, + largerEq: { + 2: "\\left(${args[0]}".concat(latexOperators.largerEq, "${args[1]}\\right)") + }, + smaller: { + 2: "\\left(${args[0]}".concat(latexOperators.smaller, "${args[1]}\\right)") + }, + smallerEq: { + 2: "\\left(${args[0]}".concat(latexOperators.smallerEq, "${args[1]}\\right)") + }, + unequal: { + 2: "\\left(${args[0]}".concat(latexOperators.unequal, "${args[1]}\\right)") + }, + // special + erf: { + 1: 'erf\\left(${args[0]}\\right)' + }, + // statistics + max: '\\max\\left(${args}\\right)', + min: '\\min\\left(${args}\\right)', + variance: '\\mathrm{Var}\\left(${args}\\right)', + // trigonometry + acos: { + 1: '\\cos^{-1}\\left(${args[0]}\\right)' + }, + acosh: { + 1: '\\cosh^{-1}\\left(${args[0]}\\right)' + }, + acot: { + 1: '\\cot^{-1}\\left(${args[0]}\\right)' + }, + acoth: { + 1: '\\coth^{-1}\\left(${args[0]}\\right)' + }, + acsc: { + 1: '\\csc^{-1}\\left(${args[0]}\\right)' + }, + acsch: { + 1: '\\mathrm{csch}^{-1}\\left(${args[0]}\\right)' + }, + asec: { + 1: '\\sec^{-1}\\left(${args[0]}\\right)' + }, + asech: { + 1: '\\mathrm{sech}^{-1}\\left(${args[0]}\\right)' + }, + asin: { + 1: '\\sin^{-1}\\left(${args[0]}\\right)' + }, + asinh: { + 1: '\\sinh^{-1}\\left(${args[0]}\\right)' + }, + atan: { + 1: '\\tan^{-1}\\left(${args[0]}\\right)' + }, + atan2: { + 2: '\\mathrm{atan2}\\left(${args}\\right)' + }, + atanh: { + 1: '\\tanh^{-1}\\left(${args[0]}\\right)' + }, + cos: { + 1: '\\cos\\left(${args[0]}\\right)' + }, + cosh: { + 1: '\\cosh\\left(${args[0]}\\right)' + }, + cot: { + 1: '\\cot\\left(${args[0]}\\right)' + }, + coth: { + 1: '\\coth\\left(${args[0]}\\right)' + }, + csc: { + 1: '\\csc\\left(${args[0]}\\right)' + }, + csch: { + 1: '\\mathrm{csch}\\left(${args[0]}\\right)' + }, + sec: { + 1: '\\sec\\left(${args[0]}\\right)' + }, + sech: { + 1: '\\mathrm{sech}\\left(${args[0]}\\right)' + }, + sin: { + 1: '\\sin\\left(${args[0]}\\right)' + }, + sinh: { + 1: '\\sinh\\left(${args[0]}\\right)' + }, + tan: { + 1: '\\tan\\left(${args[0]}\\right)' + }, + tanh: { + 1: '\\tanh\\left(${args[0]}\\right)' + }, + // unit + to: { + 2: "\\left(${args[0]}".concat(latexOperators.to, "${args[1]}\\right)") + }, + // utils + numeric: function numeric(node, options) { + // Not sure if this is strictly right but should work correctly for the vast majority of use cases. + return node.args[0].toTex(); + }, + // type + number: { + 0: '0', + 1: '\\left(${args[0]}\\right)', + 2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)' + }, + string: { + 0: '\\mathtt{""}', + 1: '\\mathrm{string}\\left(${args[0]}\\right)' + }, + bignumber: { + 0: '0', + 1: '\\left(${args[0]}\\right)' + }, + complex: { + 0: '0', + 1: '\\left(${args[0]}\\right)', + 2: "\\left(\\left(${args[0]}\\right)+".concat(latexSymbols.i, "\\cdot\\left(${args[1]}\\right)\\right)") + }, + matrix: { + 0: '\\begin{bmatrix}\\end{bmatrix}', + 1: '\\left(${args[0]}\\right)', + 2: '\\left(${args[0]}\\right)' + }, + sparse: { + 0: '\\begin{bsparse}\\end{bsparse}', + 1: '\\left(${args[0]}\\right)' + }, + unit: { + 1: '\\left(${args[0]}\\right)', + 2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)' + } +}; +var defaultTemplate = '\\mathrm{${name}}\\left(${args}\\right)'; +var latexUnits = { + deg: '^\\circ' +}; +function escapeLatex(string) { + return dist_default()(string, { + preserveFormatting: true + }); +} // @param {string} name +// @param {boolean} isUnit + +function toSymbol(name, isUnit) { + isUnit = typeof isUnit === 'undefined' ? false : isUnit; + + if (isUnit) { + if (Object(utils_object["f" /* hasOwnProperty */])(latexUnits, name)) { + return latexUnits[name]; + } + + return '\\mathrm{' + escapeLatex(name) + '}'; + } + + if (Object(utils_object["f" /* hasOwnProperty */])(latexSymbols, name)) { + return latexSymbols[name]; + } + + return escapeLatex(name); +} +// CONCATENATED MODULE: ./src/expression/node/ConstantNode.js + + + + +var ConstantNode_name = 'ConstantNode'; +var ConstantNode_dependencies = ['Node']; +var ConstantNode_createConstantNode = /* #__PURE__ */Object(factory["a" /* factory */])(ConstantNode_name, ConstantNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * A ConstantNode holds a constant value like a number or string. + * + * Usage: + * + * new ConstantNode(2.3) + * new ConstantNode('hello') + * + * @param {*} value Value can be any type (number, BigNumber, string, ...) + * @constructor ConstantNode + * @extends {Node} + */ + function ConstantNode(value) { + if (!(this instanceof ConstantNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (arguments.length === 2) { + // TODO: remove deprecation error some day (created 2018-01-23) + throw new SyntaxError('new ConstantNode(valueStr, valueType) is not supported anymore since math v4.0.0. Use new ConstantNode(value) instead, where value is a non-stringified value.'); + } + + this.value = value; + } + + ConstantNode.prototype = new Node(); + ConstantNode.prototype.type = 'ConstantNode'; + ConstantNode.prototype.isConstantNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + ConstantNode.prototype._compile = function (math, argNames) { + var value = this.value; + return function evalConstantNode() { + return value; + }; + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + ConstantNode.prototype.forEach = function (callback) {} // nothing to do, we don't have childs + + /** + * Create a new ConstantNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node) : Node} callback + * @returns {ConstantNode} Returns a clone of the node + */ + ; + + ConstantNode.prototype.map = function (callback) { + return this.clone(); + }; + /** + * Create a clone of this node, a shallow copy + * @return {ConstantNode} + */ + + + ConstantNode.prototype.clone = function () { + return new ConstantNode(this.value); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + */ + + + ConstantNode.prototype._toString = function (options) { + return Object(utils_string["d" /* format */])(this.value, options); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + */ + + + ConstantNode.prototype.toHTML = function (options) { + var value = this._toString(options); + + switch (Object(is["M" /* typeOf */])(this.value)) { + case 'number': + case 'BigNumber': + case 'Fraction': + return '' + value + ''; + + case 'string': + return '' + value + ''; + + case 'boolean': + return '' + value + ''; + + case 'null': + return '' + value + ''; + + case 'undefined': + return '' + value + ''; + + default: + return '' + value + ''; + } + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + ConstantNode.prototype.toJSON = function () { + return { + mathjs: 'ConstantNode', + value: this.value + }; + }; + /** + * Instantiate a ConstantNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "SymbolNode", value: 2.3}`, + * where mathjs is optional + * @returns {ConstantNode} + */ + + + ConstantNode.fromJSON = function (json) { + return new ConstantNode(json.value); + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + ConstantNode.prototype._toTex = function (options) { + var value = this._toString(options); + + switch (Object(is["M" /* typeOf */])(this.value)) { + case 'string': + return '\\mathtt{' + escapeLatex(value) + '}'; + + case 'number': + case 'BigNumber': + { + if (!isFinite(this.value)) { + return this.value.valueOf() < 0 ? '-\\infty' : '\\infty'; + } + + var index = value.toLowerCase().indexOf('e'); + + if (index !== -1) { + return value.substring(0, index) + '\\cdot10^{' + value.substring(index + 1) + '}'; + } + } + return value; + + case 'Fraction': + return this.value.toLatex(); + + default: + return value; + } + }; + + return ConstantNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/FunctionAssignmentNode.js + + + + + + + + +var FunctionAssignmentNode_name = 'FunctionAssignmentNode'; +var FunctionAssignmentNode_dependencies = ['typed', 'Node']; +var createFunctionAssignmentNode = /* #__PURE__ */Object(factory["a" /* factory */])(FunctionAssignmentNode_name, FunctionAssignmentNode_dependencies, function (_ref) { + var typed = _ref.typed, + Node = _ref.Node; + + /** + * @constructor FunctionAssignmentNode + * @extends {Node} + * Function assignment + * + * @param {string} name Function name + * @param {string[] | Array.<{name: string, type: string}>} params + * Array with function parameter names, or an + * array with objects containing the name + * and type of the parameter + * @param {Node} expr The function expression + */ + function FunctionAssignmentNode(name, params, expr) { + if (!(this instanceof FunctionAssignmentNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // validate input + + + if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"'); + if (!Array.isArray(params)) throw new TypeError('Array containing strings or objects expected for parameter "params"'); + if (!Object(is["w" /* isNode */])(expr)) throw new TypeError('Node expected for parameter "expr"'); + if (name in keywords) throw new Error('Illegal function name, "' + name + '" is a reserved keyword'); + this.name = name; + this.params = params.map(function (param) { + return param && param.name || param; + }); + this.types = params.map(function (param) { + return param && param.type || 'any'; + }); + this.expr = expr; + } + + FunctionAssignmentNode.prototype = new Node(); + FunctionAssignmentNode.prototype.type = 'FunctionAssignmentNode'; + FunctionAssignmentNode.prototype.isFunctionAssignmentNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + FunctionAssignmentNode.prototype._compile = function (math, argNames) { + var childArgNames = Object.create(argNames); + Object(utils_array["f" /* forEach */])(this.params, function (param) { + childArgNames[param] = true; + }); // compile the function expression with the child args + + var evalExpr = this.expr._compile(math, childArgNames); + + var name = this.name; + var params = this.params; + var signature = Object(utils_array["k" /* join */])(this.types, ','); + var syntax = name + '(' + Object(utils_array["k" /* join */])(this.params, ', ') + ')'; + return function evalFunctionAssignmentNode(scope, args, context) { + var signatures = {}; + + signatures[signature] = function () { + var childArgs = Object.create(args); + + for (var i = 0; i < params.length; i++) { + childArgs[params[i]] = arguments[i]; + } + + return evalExpr(scope, childArgs, context); + }; + + var fn = typed(name, signatures); + fn.syntax = syntax; + setSafeProperty(scope, name, fn); + return fn; + }; + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + FunctionAssignmentNode.prototype.forEach = function (callback) { + callback(this.expr, 'expr', this); + }; + /** + * Create a new FunctionAssignmentNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {FunctionAssignmentNode} Returns a transformed copy of the node + */ + + + FunctionAssignmentNode.prototype.map = function (callback) { + var expr = this._ifNode(callback(this.expr, 'expr', this)); + + return new FunctionAssignmentNode(this.name, this.params.slice(0), expr); + }; + /** + * Create a clone of this node, a shallow copy + * @return {FunctionAssignmentNode} + */ + + + FunctionAssignmentNode.prototype.clone = function () { + return new FunctionAssignmentNode(this.name, this.params.slice(0), this.expr); + }; + /** + * Is parenthesis needed? + * @param {Node} node + * @param {Object} parenthesis + * @private + */ + + + function needParenthesis(node, parenthesis) { + var precedence = getPrecedence(node, parenthesis); + var exprPrecedence = getPrecedence(node.expr, parenthesis); + return parenthesis === 'all' || exprPrecedence !== null && exprPrecedence <= precedence; + } + /** + * get string representation + * @param {Object} options + * @return {string} str + */ + + + FunctionAssignmentNode.prototype._toString = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var expr = this.expr.toString(options); + + if (needParenthesis(this, parenthesis)) { + expr = '(' + expr + ')'; + } + + return this.name + '(' + this.params.join(', ') + ') = ' + expr; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + FunctionAssignmentNode.prototype.toJSON = function () { + var types = this.types; + return { + mathjs: 'FunctionAssignmentNode', + name: this.name, + params: this.params.map(function (param, index) { + return { + name: param, + type: types[index] + }; + }), + expr: this.expr + }; + }; + /** + * Instantiate an FunctionAssignmentNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "FunctionAssignmentNode", name: ..., params: ..., expr: ...}`, + * where mathjs is optional + * @returns {FunctionAssignmentNode} + */ + + + FunctionAssignmentNode.fromJSON = function (json) { + return new FunctionAssignmentNode(json.name, json.params, json.expr); + }; + /** + * get HTML representation + * @param {Object} options + * @return {string} str + */ + + + FunctionAssignmentNode.prototype.toHTML = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var params = []; + + for (var i = 0; i < this.params.length; i++) { + params.push('' + Object(utils_string["c" /* escape */])(this.params[i]) + ''); + } + + var expr = this.expr.toHTML(options); + + if (needParenthesis(this, parenthesis)) { + expr = '(' + expr + ')'; + } + + return '' + Object(utils_string["c" /* escape */])(this.name) + '' + '(' + params.join(',') + ')=' + expr; + }; + /** + * get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + FunctionAssignmentNode.prototype._toTex = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var expr = this.expr.toTex(options); + + if (needParenthesis(this, parenthesis)) { + expr = "\\left(".concat(expr, "\\right)"); + } + + return '\\mathrm{' + this.name + '}\\left(' + this.params.map(toSymbol).join(',') + '\\right):=' + expr; + }; + + return FunctionAssignmentNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/IndexNode.js +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + + + + + + +var IndexNode_name = 'IndexNode'; +var IndexNode_dependencies = ['Range', 'Node', 'size']; +var createIndexNode = /* #__PURE__ */Object(factory["a" /* factory */])(IndexNode_name, IndexNode_dependencies, function (_ref) { + var Range = _ref.Range, + Node = _ref.Node, + size = _ref.size; + + /** + * @constructor IndexNode + * @extends Node + * + * Describes a subset of a matrix or an object property. + * Cannot be used on its own, needs to be used within an AccessorNode or + * AssignmentNode. + * + * @param {Node[]} dimensions + * @param {boolean} [dotNotation=false] Optional property describing whether + * this index was written using dot + * notation like `a.b`, or using bracket + * notation like `a["b"]` (default). + * Used to stringify an IndexNode. + */ + function IndexNode(dimensions, dotNotation) { + if (!(this instanceof IndexNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.dimensions = dimensions; + this.dotNotation = dotNotation || false; // validate input + + if (!Array.isArray(dimensions) || !dimensions.every(is["w" /* isNode */])) { + throw new TypeError('Array containing Nodes expected for parameter "dimensions"'); + } + + if (this.dotNotation && !this.isObjectProperty()) { + throw new Error('dotNotation only applicable for object properties'); + } // TODO: deprecated since v3, remove some day + + + var deprecated = function deprecated() { + throw new Error('Property `IndexNode.object` is deprecated, use `IndexNode.fn` instead'); + }; + + Object.defineProperty(this, 'object', { + get: deprecated, + set: deprecated + }); + } + + IndexNode.prototype = new Node(); + IndexNode.prototype.type = 'IndexNode'; + IndexNode.prototype.isIndexNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + IndexNode.prototype._compile = function (math, argNames) { + // TODO: implement support for bignumber (currently bignumbers are silently + // reduced to numbers when changing the value to zero-based) + // TODO: Optimization: when the range values are ConstantNodes, + // we can beforehand resolve the zero-based value + // optimization for a simple object property + var evalDimensions = Object(utils_array["m" /* map */])(this.dimensions, function (range, i) { + if (Object(is["E" /* isRangeNode */])(range)) { + if (range.needsEnd()) { + // create a range containing end (like '4:end') + var childArgNames = Object.create(argNames); + childArgNames.end = true; + + var evalStart = range.start._compile(math, childArgNames); + + var evalEnd = range.end._compile(math, childArgNames); + + var evalStep = range.step ? range.step._compile(math, childArgNames) : function () { + return 1; + }; + return function evalDimension(scope, args, context) { + var s = size(context).valueOf(); + var childArgs = Object.create(args); + childArgs.end = s[i]; + return createRange(evalStart(scope, childArgs, context), evalEnd(scope, childArgs, context), evalStep(scope, childArgs, context)); + }; + } else { + // create range + var _evalStart = range.start._compile(math, argNames); + + var _evalEnd = range.end._compile(math, argNames); + + var _evalStep = range.step ? range.step._compile(math, argNames) : function () { + return 1; + }; + + return function evalDimension(scope, args, context) { + return createRange(_evalStart(scope, args, context), _evalEnd(scope, args, context), _evalStep(scope, args, context)); + }; + } + } else if (Object(is["J" /* isSymbolNode */])(range) && range.name === 'end') { + // SymbolNode 'end' + var _childArgNames = Object.create(argNames); + + _childArgNames.end = true; + + var evalRange = range._compile(math, _childArgNames); + + return function evalDimension(scope, args, context) { + var s = size(context).valueOf(); + var childArgs = Object.create(args); + childArgs.end = s[i]; + return evalRange(scope, childArgs, context); + }; + } else { + // ConstantNode + var _evalRange = range._compile(math, argNames); + + return function evalDimension(scope, args, context) { + return _evalRange(scope, args, context); + }; + } + }); + var index = getSafeProperty(math, 'index'); + return function evalIndexNode(scope, args, context) { + var dimensions = Object(utils_array["m" /* map */])(evalDimensions, function (evalDimension) { + return evalDimension(scope, args, context); + }); + return index.apply(void 0, _toConsumableArray(dimensions)); + }; + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + IndexNode.prototype.forEach = function (callback) { + for (var i = 0; i < this.dimensions.length; i++) { + callback(this.dimensions[i], 'dimensions[' + i + ']', this); + } + }; + /** + * Create a new IndexNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {IndexNode} Returns a transformed copy of the node + */ + + + IndexNode.prototype.map = function (callback) { + var dimensions = []; + + for (var i = 0; i < this.dimensions.length; i++) { + dimensions[i] = this._ifNode(callback(this.dimensions[i], 'dimensions[' + i + ']', this)); + } + + return new IndexNode(dimensions, this.dotNotation); + }; + /** + * Create a clone of this node, a shallow copy + * @return {IndexNode} + */ + + + IndexNode.prototype.clone = function () { + return new IndexNode(this.dimensions.slice(0), this.dotNotation); + }; + /** + * Test whether this IndexNode contains a single property name + * @return {boolean} + */ + + + IndexNode.prototype.isObjectProperty = function () { + return this.dimensions.length === 1 && Object(is["l" /* isConstantNode */])(this.dimensions[0]) && typeof this.dimensions[0].value === 'string'; + }; + /** + * Returns the property name if IndexNode contains a property. + * If not, returns null. + * @return {string | null} + */ + + + IndexNode.prototype.getObjectProperty = function () { + return this.isObjectProperty() ? this.dimensions[0].value : null; + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + */ + + + IndexNode.prototype._toString = function (options) { + // format the parameters like "[1, 0:5]" + return this.dotNotation ? '.' + this.getObjectProperty() : '[' + this.dimensions.join(', ') + ']'; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + IndexNode.prototype.toJSON = function () { + return { + mathjs: 'IndexNode', + dimensions: this.dimensions, + dotNotation: this.dotNotation + }; + }; + /** + * Instantiate an IndexNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "IndexNode", dimensions: [...], dotNotation: false}`, + * where mathjs is optional + * @returns {IndexNode} + */ + + + IndexNode.fromJSON = function (json) { + return new IndexNode(json.dimensions, json.dotNotation); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + */ + + + IndexNode.prototype.toHTML = function (options) { + // format the parameters like "[1, 0:5]" + var dimensions = []; + + for (var i = 0; i < this.dimensions.length; i++) { + dimensions[i] = this.dimensions[i].toHTML(); + } + + if (this.dotNotation) { + return '.' + '' + Object(utils_string["c" /* escape */])(this.getObjectProperty()) + ''; + } else { + return '[' + dimensions.join(',') + ']'; + } + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + IndexNode.prototype._toTex = function (options) { + var dimensions = this.dimensions.map(function (range) { + return range.toTex(options); + }); + return this.dotNotation ? '.' + this.getObjectProperty() + '' : '_{' + dimensions.join(',') + '}'; + }; // helper function to create a Range from start, step and end + + + function createRange(start, end, step) { + return new Range(Object(is["e" /* isBigNumber */])(start) ? start.toNumber() : start, Object(is["e" /* isBigNumber */])(end) ? end.toNumber() : end, Object(is["e" /* isBigNumber */])(step) ? step.toNumber() : step); + } + + return IndexNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/ObjectNode.js +function ObjectNode_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { ObjectNode_typeof = function _typeof(obj) { return typeof obj; }; } else { ObjectNode_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return ObjectNode_typeof(obj); } + + + + + + +var ObjectNode_name = 'ObjectNode'; +var ObjectNode_dependencies = ['Node']; +var createObjectNode = /* #__PURE__ */Object(factory["a" /* factory */])(ObjectNode_name, ObjectNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * @constructor ObjectNode + * @extends {Node} + * Holds an object with keys/values + * @param {Object.} [properties] object with key/value pairs + */ + function ObjectNode(properties) { + if (!(this instanceof ObjectNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.properties = properties || {}; // validate input + + if (properties) { + if (!(ObjectNode_typeof(properties) === 'object') || !Object.keys(properties).every(function (key) { + return Object(is["w" /* isNode */])(properties[key]); + })) { + throw new TypeError('Object containing Nodes expected'); + } + } + } + + ObjectNode.prototype = new Node(); + ObjectNode.prototype.type = 'ObjectNode'; + ObjectNode.prototype.isObjectNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + ObjectNode.prototype._compile = function (math, argNames) { + var evalEntries = {}; + + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + // we stringify/parse the key here to resolve unicode characters, + // so you cannot create a key like {"co\\u006Estructor": null} + var stringifiedKey = Object(utils_string["e" /* stringify */])(key); + var parsedKey = JSON.parse(stringifiedKey); + + if (!isSafeProperty(this.properties, parsedKey)) { + throw new Error('No access to property "' + parsedKey + '"'); + } + + evalEntries[parsedKey] = this.properties[key]._compile(math, argNames); + } + } + + return function evalObjectNode(scope, args, context) { + var obj = {}; + + for (var _key in evalEntries) { + if (Object(utils_object["f" /* hasOwnProperty */])(evalEntries, _key)) { + obj[_key] = evalEntries[_key](scope, args, context); + } + } + + return obj; + }; + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + ObjectNode.prototype.forEach = function (callback) { + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + callback(this.properties[key], 'properties[' + Object(utils_string["e" /* stringify */])(key) + ']', this); + } + } + }; + /** + * Create a new ObjectNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {ObjectNode} Returns a transformed copy of the node + */ + + + ObjectNode.prototype.map = function (callback) { + var properties = {}; + + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + properties[key] = this._ifNode(callback(this.properties[key], 'properties[' + Object(utils_string["e" /* stringify */])(key) + ']', this)); + } + } + + return new ObjectNode(properties); + }; + /** + * Create a clone of this node, a shallow copy + * @return {ObjectNode} + */ + + + ObjectNode.prototype.clone = function () { + var properties = {}; + + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + properties[key] = this.properties[key]; + } + } + + return new ObjectNode(properties); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ObjectNode.prototype._toString = function (options) { + var entries = []; + + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + entries.push(Object(utils_string["e" /* stringify */])(key) + ': ' + this.properties[key].toString(options)); + } + } + + return '{' + entries.join(', ') + '}'; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + ObjectNode.prototype.toJSON = function () { + return { + mathjs: 'ObjectNode', + properties: this.properties + }; + }; + /** + * Instantiate an OperatorNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "ObjectNode", "properties": {...}}`, + * where mathjs is optional + * @returns {ObjectNode} + */ + + + ObjectNode.fromJSON = function (json) { + return new ObjectNode(json.properties); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ObjectNode.prototype.toHTML = function (options) { + var entries = []; + + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + entries.push('' + Object(utils_string["c" /* escape */])(key) + '' + ':' + this.properties[key].toHTML(options)); + } + } + + return '{' + entries.join(',') + '}'; + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + ObjectNode.prototype._toTex = function (options) { + var entries = []; + + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + entries.push('\\mathbf{' + key + ':} & ' + this.properties[key].toTex(options) + '\\\\'); + } + } + + return "\\left\\{\\begin{array}{ll}".concat(entries.join('\n'), "\\end{array}\\right\\}"); + }; + + return ObjectNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/OperatorNode.js + + + + + + + +var OperatorNode_name = 'OperatorNode'; +var OperatorNode_dependencies = ['Node']; +var createOperatorNode = /* #__PURE__ */Object(factory["a" /* factory */])(OperatorNode_name, OperatorNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * @constructor OperatorNode + * @extends {Node} + * An operator with two arguments, like 2+3 + * + * @param {string} op Operator name, for example '+' + * @param {string} fn Function name, for example 'add' + * @param {Node[]} args Operator arguments + * @param {boolean} [implicit] Is this an implicit multiplication? + */ + function OperatorNode(op, fn, args, implicit) { + if (!(this instanceof OperatorNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // validate input + + + if (typeof op !== 'string') { + throw new TypeError('string expected for parameter "op"'); + } + + if (typeof fn !== 'string') { + throw new TypeError('string expected for parameter "fn"'); + } + + if (!Array.isArray(args) || !args.every(is["w" /* isNode */])) { + throw new TypeError('Array containing Nodes expected for parameter "args"'); + } + + this.implicit = implicit === true; + this.op = op; + this.fn = fn; + this.args = args || []; + } + + OperatorNode.prototype = new Node(); + OperatorNode.prototype.type = 'OperatorNode'; + OperatorNode.prototype.isOperatorNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + OperatorNode.prototype._compile = function (math, argNames) { + // validate fn + if (typeof this.fn !== 'string' || !isSafeMethod(math, this.fn)) { + if (!math[this.fn]) { + throw new Error('Function ' + this.fn + ' missing in provided namespace "math"'); + } else { + throw new Error('No access to function "' + this.fn + '"'); + } + } + + var fn = getSafeProperty(math, this.fn); + var evalArgs = Object(utils_array["m" /* map */])(this.args, function (arg) { + return arg._compile(math, argNames); + }); + + if (evalArgs.length === 1) { + var evalArg0 = evalArgs[0]; + return function evalOperatorNode(scope, args, context) { + return fn(evalArg0(scope, args, context)); + }; + } else if (evalArgs.length === 2) { + var _evalArg = evalArgs[0]; + var evalArg1 = evalArgs[1]; + return function evalOperatorNode(scope, args, context) { + return fn(_evalArg(scope, args, context), evalArg1(scope, args, context)); + }; + } else { + return function evalOperatorNode(scope, args, context) { + return fn.apply(null, Object(utils_array["m" /* map */])(evalArgs, function (evalArg) { + return evalArg(scope, args, context); + })); + }; + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + OperatorNode.prototype.forEach = function (callback) { + for (var i = 0; i < this.args.length; i++) { + callback(this.args[i], 'args[' + i + ']', this); + } + }; + /** + * Create a new OperatorNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {OperatorNode} Returns a transformed copy of the node + */ + + + OperatorNode.prototype.map = function (callback) { + var args = []; + + for (var i = 0; i < this.args.length; i++) { + args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this)); + } + + return new OperatorNode(this.op, this.fn, args, this.implicit); + }; + /** + * Create a clone of this node, a shallow copy + * @return {OperatorNode} + */ + + + OperatorNode.prototype.clone = function () { + return new OperatorNode(this.op, this.fn, this.args.slice(0), this.implicit); + }; + /** + * Check whether this is an unary OperatorNode: + * has exactly one argument, like `-a`. + * @return {boolean} Returns true when an unary operator node, false otherwise. + */ + + + OperatorNode.prototype.isUnary = function () { + return this.args.length === 1; + }; + /** + * Check whether this is a binary OperatorNode: + * has exactly two arguments, like `a + b`. + * @return {boolean} Returns true when a binary operator node, false otherwise. + */ + + + OperatorNode.prototype.isBinary = function () { + return this.args.length === 2; + }; + /** + * Calculate which parentheses are necessary. Gets an OperatorNode + * (which is the root of the tree) and an Array of Nodes + * (this.args) and returns an array where 'true' means that an argument + * has to be enclosed in parentheses whereas 'false' means the opposite. + * + * @param {OperatorNode} root + * @param {string} parenthesis + * @param {Node[]} args + * @param {boolean} latex + * @return {boolean[]} + * @private + */ + + + function calculateNecessaryParentheses(root, parenthesis, implicit, args, latex) { + // precedence of the root OperatorNode + var precedence = getPrecedence(root, parenthesis); + var associativity = getAssociativity(root, parenthesis); + + if (parenthesis === 'all' || args.length > 2 && root.getIdentifier() !== 'OperatorNode:add' && root.getIdentifier() !== 'OperatorNode:multiply') { + return args.map(function (arg) { + switch (arg.getContent().type) { + // Nodes that don't need extra parentheses + case 'ArrayNode': + case 'ConstantNode': + case 'SymbolNode': + case 'ParenthesisNode': + return false; + + default: + return true; + } + }); + } + + var result; + + switch (args.length) { + case 0: + result = []; + break; + + case 1: + // unary operators + { + // precedence of the operand + var operandPrecedence = getPrecedence(args[0], parenthesis); // handle special cases for LaTeX, where some of the parentheses aren't needed + + if (latex && operandPrecedence !== null) { + var operandIdentifier; + var rootIdentifier; + + if (parenthesis === 'keep') { + operandIdentifier = args[0].getIdentifier(); + rootIdentifier = root.getIdentifier(); + } else { + // Ignore Parenthesis Nodes when not in 'keep' mode + operandIdentifier = args[0].getContent().getIdentifier(); + rootIdentifier = root.getContent().getIdentifier(); + } + + if (operators_properties[precedence][rootIdentifier].latexLeftParens === false) { + result = [false]; + break; + } + + if (operators_properties[operandPrecedence][operandIdentifier].latexParens === false) { + result = [false]; + break; + } + } + + if (operandPrecedence === null) { + // if the operand has no defined precedence, no parens are needed + result = [false]; + break; + } + + if (operandPrecedence <= precedence) { + // if the operands precedence is lower, parens are needed + result = [true]; + break; + } // otherwise, no parens needed + + + result = [false]; + } + break; + + case 2: + // binary operators + { + var lhsParens; // left hand side needs parenthesis? + // precedence of the left hand side + + var lhsPrecedence = getPrecedence(args[0], parenthesis); // is the root node associative with the left hand side + + var assocWithLhs = isAssociativeWith(root, args[0], parenthesis); + + if (lhsPrecedence === null) { + // if the left hand side has no defined precedence, no parens are needed + // FunctionNode for example + lhsParens = false; + } else if (lhsPrecedence === precedence && associativity === 'right' && !assocWithLhs) { + // In case of equal precedence, if the root node is left associative + // parens are **never** necessary for the left hand side. + // If it is right associative however, parens are necessary + // if the root node isn't associative with the left hand side + lhsParens = true; + } else if (lhsPrecedence < precedence) { + lhsParens = true; + } else { + lhsParens = false; + } + + var rhsParens; // right hand side needs parenthesis? + // precedence of the right hand side + + var rhsPrecedence = getPrecedence(args[1], parenthesis); // is the root node associative with the right hand side? + + var assocWithRhs = isAssociativeWith(root, args[1], parenthesis); + + if (rhsPrecedence === null) { + // if the right hand side has no defined precedence, no parens are needed + // FunctionNode for example + rhsParens = false; + } else if (rhsPrecedence === precedence && associativity === 'left' && !assocWithRhs) { + // In case of equal precedence, if the root node is right associative + // parens are **never** necessary for the right hand side. + // If it is left associative however, parens are necessary + // if the root node isn't associative with the right hand side + rhsParens = true; + } else if (rhsPrecedence < precedence) { + rhsParens = true; + } else { + rhsParens = false; + } // handle special cases for LaTeX, where some of the parentheses aren't needed + + + if (latex) { + var _rootIdentifier; + + var lhsIdentifier; + var rhsIdentifier; + + if (parenthesis === 'keep') { + _rootIdentifier = root.getIdentifier(); + lhsIdentifier = root.args[0].getIdentifier(); + rhsIdentifier = root.args[1].getIdentifier(); + } else { + // Ignore ParenthesisNodes when not in 'keep' mode + _rootIdentifier = root.getContent().getIdentifier(); + lhsIdentifier = root.args[0].getContent().getIdentifier(); + rhsIdentifier = root.args[1].getContent().getIdentifier(); + } + + if (lhsPrecedence !== null) { + if (operators_properties[precedence][_rootIdentifier].latexLeftParens === false) { + lhsParens = false; + } + + if (operators_properties[lhsPrecedence][lhsIdentifier].latexParens === false) { + lhsParens = false; + } + } + + if (rhsPrecedence !== null) { + if (operators_properties[precedence][_rootIdentifier].latexRightParens === false) { + rhsParens = false; + } + + if (operators_properties[rhsPrecedence][rhsIdentifier].latexParens === false) { + rhsParens = false; + } + } + } + + result = [lhsParens, rhsParens]; + } + break; + + default: + if (root.getIdentifier() === 'OperatorNode:add' || root.getIdentifier() === 'OperatorNode:multiply') { + result = args.map(function (arg) { + var argPrecedence = getPrecedence(arg, parenthesis); + var assocWithArg = isAssociativeWith(root, arg, parenthesis); + var argAssociativity = getAssociativity(arg, parenthesis); + + if (argPrecedence === null) { + // if the argument has no defined precedence, no parens are needed + return false; + } else if (precedence === argPrecedence && associativity === argAssociativity && !assocWithArg) { + return true; + } else if (argPrecedence < precedence) { + return true; + } + + return false; + }); + } + + break; + } // handles an edge case of 'auto' parentheses with implicit multiplication of ConstantNode + // In that case print parentheses for ParenthesisNodes even though they normally wouldn't be + // printed. + + + if (args.length >= 2 && root.getIdentifier() === 'OperatorNode:multiply' && root.implicit && parenthesis === 'auto' && implicit === 'hide') { + result = args.map(function (arg, index) { + var isParenthesisNode = arg.getIdentifier() === 'ParenthesisNode'; + + if (result[index] || isParenthesisNode) { + // put in parenthesis? + return true; + } + + return false; + }); + } + + return result; + } + /** + * Get string representation. + * @param {Object} options + * @return {string} str + */ + + + OperatorNode.prototype._toString = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var implicit = options && options.implicit ? options.implicit : 'hide'; + var args = this.args; + var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, false); + + if (args.length === 1) { + // unary operators + var assoc = getAssociativity(this, parenthesis); + var operand = args[0].toString(options); + + if (parens[0]) { + operand = '(' + operand + ')'; + } // for example for "not", we want a space between operand and argument + + + var opIsNamed = /[a-zA-Z]+/.test(this.op); + + if (assoc === 'right') { + // prefix operator + return this.op + (opIsNamed ? ' ' : '') + operand; + } else if (assoc === 'left') { + // postfix + return operand + (opIsNamed ? ' ' : '') + this.op; + } // fall back to postfix + + + return operand + this.op; + } else if (args.length === 2) { + var lhs = args[0].toString(options); // left hand side + + var rhs = args[1].toString(options); // right hand side + + if (parens[0]) { + // left hand side in parenthesis? + lhs = '(' + lhs + ')'; + } + + if (parens[1]) { + // right hand side in parenthesis? + rhs = '(' + rhs + ')'; + } + + if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') { + return lhs + ' ' + rhs; + } + + return lhs + ' ' + this.op + ' ' + rhs; + } else if (args.length > 2 && (this.getIdentifier() === 'OperatorNode:add' || this.getIdentifier() === 'OperatorNode:multiply')) { + var stringifiedArgs = args.map(function (arg, index) { + arg = arg.toString(options); + + if (parens[index]) { + // put in parenthesis? + arg = '(' + arg + ')'; + } + + return arg; + }); + + if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') { + return stringifiedArgs.join(' '); + } + + return stringifiedArgs.join(' ' + this.op + ' '); + } else { + // fallback to formatting as a function call + return this.fn + '(' + this.args.join(', ') + ')'; + } + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + OperatorNode.prototype.toJSON = function () { + return { + mathjs: 'OperatorNode', + op: this.op, + fn: this.fn, + args: this.args, + implicit: this.implicit + }; + }; + /** + * Instantiate an OperatorNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "OperatorNode", "op": "+", "fn": "add", "args": [...], "implicit": false}`, + * where mathjs is optional + * @returns {OperatorNode} + */ + + + OperatorNode.fromJSON = function (json) { + return new OperatorNode(json.op, json.fn, json.args, json.implicit); + }; + /** + * Get HTML representation. + * @param {Object} options + * @return {string} str + */ + + + OperatorNode.prototype.toHTML = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var implicit = options && options.implicit ? options.implicit : 'hide'; + var args = this.args; + var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, false); + + if (args.length === 1) { + // unary operators + var assoc = getAssociativity(this, parenthesis); + var operand = args[0].toHTML(options); + + if (parens[0]) { + operand = '(' + operand + ')'; + } + + if (assoc === 'right') { + // prefix operator + return '' + Object(utils_string["c" /* escape */])(this.op) + '' + operand; + } else { + // postfix when assoc === 'left' or undefined + return operand + '' + Object(utils_string["c" /* escape */])(this.op) + ''; + } + } else if (args.length === 2) { + // binary operatoes + var lhs = args[0].toHTML(options); // left hand side + + var rhs = args[1].toHTML(options); // right hand side + + if (parens[0]) { + // left hand side in parenthesis? + lhs = '(' + lhs + ')'; + } + + if (parens[1]) { + // right hand side in parenthesis? + rhs = '(' + rhs + ')'; + } + + if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') { + return lhs + '' + rhs; + } + + return lhs + '' + Object(utils_string["c" /* escape */])(this.op) + '' + rhs; + } else { + var stringifiedArgs = args.map(function (arg, index) { + arg = arg.toHTML(options); + + if (parens[index]) { + // put in parenthesis? + arg = '(' + arg + ')'; + } + + return arg; + }); + + if (args.length > 2 && (this.getIdentifier() === 'OperatorNode:add' || this.getIdentifier() === 'OperatorNode:multiply')) { + if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') { + return stringifiedArgs.join(''); + } + + return stringifiedArgs.join('' + Object(utils_string["c" /* escape */])(this.op) + ''); + } else { + // fallback to formatting as a function call + return '' + Object(utils_string["c" /* escape */])(this.fn) + '(' + stringifiedArgs.join(',') + ')'; + } + } + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + OperatorNode.prototype._toTex = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var implicit = options && options.implicit ? options.implicit : 'hide'; + var args = this.args; + var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, true); + var op = latexOperators[this.fn]; + op = typeof op === 'undefined' ? this.op : op; // fall back to using this.op + + if (args.length === 1) { + // unary operators + var assoc = getAssociativity(this, parenthesis); + var operand = args[0].toTex(options); + + if (parens[0]) { + operand = "\\left(".concat(operand, "\\right)"); + } + + if (assoc === 'right') { + // prefix operator + return op + operand; + } else if (assoc === 'left') { + // postfix operator + return operand + op; + } // fall back to postfix + + + return operand + op; + } else if (args.length === 2) { + // binary operators + var lhs = args[0]; // left hand side + + var lhsTex = lhs.toTex(options); + + if (parens[0]) { + lhsTex = "\\left(".concat(lhsTex, "\\right)"); + } + + var rhs = args[1]; // right hand side + + var rhsTex = rhs.toTex(options); + + if (parens[1]) { + rhsTex = "\\left(".concat(rhsTex, "\\right)"); + } // handle some exceptions (due to the way LaTeX works) + + + var lhsIdentifier; + + if (parenthesis === 'keep') { + lhsIdentifier = lhs.getIdentifier(); + } else { + // Ignore ParenthesisNodes if in 'keep' mode + lhsIdentifier = lhs.getContent().getIdentifier(); + } + + switch (this.getIdentifier()) { + case 'OperatorNode:divide': + // op contains '\\frac' at this point + return op + '{' + lhsTex + '}' + '{' + rhsTex + '}'; + + case 'OperatorNode:pow': + lhsTex = '{' + lhsTex + '}'; + rhsTex = '{' + rhsTex + '}'; + + switch (lhsIdentifier) { + case 'ConditionalNode': // + + case 'OperatorNode:divide': + lhsTex = "\\left(".concat(lhsTex, "\\right)"); + } + + break; + + case 'OperatorNode:multiply': + if (this.implicit && implicit === 'hide') { + return lhsTex + '~' + rhsTex; + } + + } + + return lhsTex + op + rhsTex; + } else if (args.length > 2 && (this.getIdentifier() === 'OperatorNode:add' || this.getIdentifier() === 'OperatorNode:multiply')) { + var texifiedArgs = args.map(function (arg, index) { + arg = arg.toTex(options); + + if (parens[index]) { + arg = "\\left(".concat(arg, "\\right)"); + } + + return arg; + }); + + if (this.getIdentifier() === 'OperatorNode:multiply' && this.implicit) { + return texifiedArgs.join('~'); + } + + return texifiedArgs.join(op); + } else { + // fall back to formatting as a function call + // as this is a fallback, it doesn't use + // fancy function names + return '\\mathrm{' + this.fn + '}\\left(' + args.map(function (arg) { + return arg.toTex(options); + }).join(',') + '\\right)'; + } + }; + /** + * Get identifier. + * @return {string} + */ + + + OperatorNode.prototype.getIdentifier = function () { + return this.type + ':' + this.fn; + }; + + return OperatorNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/ParenthesisNode.js + + +var ParenthesisNode_name = 'ParenthesisNode'; +var ParenthesisNode_dependencies = ['Node']; +var createParenthesisNode = /* #__PURE__ */Object(factory["a" /* factory */])(ParenthesisNode_name, ParenthesisNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * @constructor ParenthesisNode + * @extends {Node} + * A parenthesis node describes manual parenthesis from the user input + * @param {Node} content + * @extends {Node} + */ + function ParenthesisNode(content) { + if (!(this instanceof ParenthesisNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // validate input + + + if (!Object(is["w" /* isNode */])(content)) { + throw new TypeError('Node expected for parameter "content"'); + } + + this.content = content; + } + + ParenthesisNode.prototype = new Node(); + ParenthesisNode.prototype.type = 'ParenthesisNode'; + ParenthesisNode.prototype.isParenthesisNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + ParenthesisNode.prototype._compile = function (math, argNames) { + return this.content._compile(math, argNames); + }; + /** + * Get the content of the current Node. + * @return {Node} content + * @override + **/ + + + ParenthesisNode.prototype.getContent = function () { + return this.content.getContent(); + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + ParenthesisNode.prototype.forEach = function (callback) { + callback(this.content, 'content', this); + }; + /** + * Create a new ParenthesisNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node) : Node} callback + * @returns {ParenthesisNode} Returns a clone of the node + */ + + + ParenthesisNode.prototype.map = function (callback) { + var content = callback(this.content, 'content', this); + return new ParenthesisNode(content); + }; + /** + * Create a clone of this node, a shallow copy + * @return {ParenthesisNode} + */ + + + ParenthesisNode.prototype.clone = function () { + return new ParenthesisNode(this.content); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ParenthesisNode.prototype._toString = function (options) { + if (!options || options && !options.parenthesis || options && options.parenthesis === 'keep') { + return '(' + this.content.toString(options) + ')'; + } + + return this.content.toString(options); + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + ParenthesisNode.prototype.toJSON = function () { + return { + mathjs: 'ParenthesisNode', + content: this.content + }; + }; + /** + * Instantiate an ParenthesisNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "ParenthesisNode", "content": ...}`, + * where mathjs is optional + * @returns {ParenthesisNode} + */ + + + ParenthesisNode.fromJSON = function (json) { + return new ParenthesisNode(json.content); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ParenthesisNode.prototype.toHTML = function (options) { + if (!options || options && !options.parenthesis || options && options.parenthesis === 'keep') { + return '(' + this.content.toHTML(options) + ')'; + } + + return this.content.toHTML(options); + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ParenthesisNode.prototype._toTex = function (options) { + if (!options || options && !options.parenthesis || options && options.parenthesis === 'keep') { + return "\\left(".concat(this.content.toTex(options), "\\right)"); + } + + return this.content.toTex(options); + }; + + return ParenthesisNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/RangeNode.js + + + +var RangeNode_name = 'RangeNode'; +var RangeNode_dependencies = ['Node']; +var createRangeNode = /* #__PURE__ */Object(factory["a" /* factory */])(RangeNode_name, RangeNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * @constructor RangeNode + * @extends {Node} + * create a range + * @param {Node} start included lower-bound + * @param {Node} end included upper-bound + * @param {Node} [step] optional step + */ + function RangeNode(start, end, step) { + if (!(this instanceof RangeNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // validate inputs + + + if (!Object(is["w" /* isNode */])(start)) throw new TypeError('Node expected'); + if (!Object(is["w" /* isNode */])(end)) throw new TypeError('Node expected'); + if (step && !Object(is["w" /* isNode */])(step)) throw new TypeError('Node expected'); + if (arguments.length > 3) throw new Error('Too many arguments'); + this.start = start; // included lower-bound + + this.end = end; // included upper-bound + + this.step = step || null; // optional step + } + + RangeNode.prototype = new Node(); + RangeNode.prototype.type = 'RangeNode'; + RangeNode.prototype.isRangeNode = true; + /** + * Check whether the RangeNode needs the `end` symbol to be defined. + * This end is the size of the Matrix in current dimension. + * @return {boolean} + */ + + RangeNode.prototype.needsEnd = function () { + // find all `end` symbols in this RangeNode + var endSymbols = this.filter(function (node) { + return Object(is["J" /* isSymbolNode */])(node) && node.name === 'end'; + }); + return endSymbols.length > 0; + }; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + + RangeNode.prototype._compile = function (math, argNames) { + var range = math.range; + + var evalStart = this.start._compile(math, argNames); + + var evalEnd = this.end._compile(math, argNames); + + if (this.step) { + var evalStep = this.step._compile(math, argNames); + + return function evalRangeNode(scope, args, context) { + return range(evalStart(scope, args, context), evalEnd(scope, args, context), evalStep(scope, args, context)); + }; + } else { + return function evalRangeNode(scope, args, context) { + return range(evalStart(scope, args, context), evalEnd(scope, args, context)); + }; + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + RangeNode.prototype.forEach = function (callback) { + callback(this.start, 'start', this); + callback(this.end, 'end', this); + + if (this.step) { + callback(this.step, 'step', this); + } + }; + /** + * Create a new RangeNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {RangeNode} Returns a transformed copy of the node + */ + + + RangeNode.prototype.map = function (callback) { + return new RangeNode(this._ifNode(callback(this.start, 'start', this)), this._ifNode(callback(this.end, 'end', this)), this.step && this._ifNode(callback(this.step, 'step', this))); + }; + /** + * Create a clone of this node, a shallow copy + * @return {RangeNode} + */ + + + RangeNode.prototype.clone = function () { + return new RangeNode(this.start, this.end, this.step && this.step); + }; + /** + * Calculate the necessary parentheses + * @param {Node} node + * @param {string} parenthesis + * @return {Object} parentheses + * @private + */ + + + function calculateNecessaryParentheses(node, parenthesis) { + var precedence = getPrecedence(node, parenthesis); + var parens = {}; + var startPrecedence = getPrecedence(node.start, parenthesis); + parens.start = startPrecedence !== null && startPrecedence <= precedence || parenthesis === 'all'; + + if (node.step) { + var stepPrecedence = getPrecedence(node.step, parenthesis); + parens.step = stepPrecedence !== null && stepPrecedence <= precedence || parenthesis === 'all'; + } + + var endPrecedence = getPrecedence(node.end, parenthesis); + parens.end = endPrecedence !== null && endPrecedence <= precedence || parenthesis === 'all'; + return parens; + } + /** + * Get string representation + * @param {Object} options + * @return {string} str + */ + + + RangeNode.prototype._toString = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var parens = calculateNecessaryParentheses(this, parenthesis); // format string as start:step:stop + + var str; + var start = this.start.toString(options); + + if (parens.start) { + start = '(' + start + ')'; + } + + str = start; + + if (this.step) { + var step = this.step.toString(options); + + if (parens.step) { + step = '(' + step + ')'; + } + + str += ':' + step; + } + + var end = this.end.toString(options); + + if (parens.end) { + end = '(' + end + ')'; + } + + str += ':' + end; + return str; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + RangeNode.prototype.toJSON = function () { + return { + mathjs: 'RangeNode', + start: this.start, + end: this.end, + step: this.step + }; + }; + /** + * Instantiate an RangeNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "RangeNode", "start": ..., "end": ..., "step": ...}`, + * where mathjs is optional + * @returns {RangeNode} + */ + + + RangeNode.fromJSON = function (json) { + return new RangeNode(json.start, json.end, json.step); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + */ + + + RangeNode.prototype.toHTML = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var parens = calculateNecessaryParentheses(this, parenthesis); // format string as start:step:stop + + var str; + var start = this.start.toHTML(options); + + if (parens.start) { + start = '(' + start + ')'; + } + + str = start; + + if (this.step) { + var step = this.step.toHTML(options); + + if (parens.step) { + step = '(' + step + ')'; + } + + str += ':' + step; + } + + var end = this.end.toHTML(options); + + if (parens.end) { + end = '(' + end + ')'; + } + + str += ':' + end; + return str; + }; + /** + * Get LaTeX representation + * @params {Object} options + * @return {string} str + */ + + + RangeNode.prototype._toTex = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var parens = calculateNecessaryParentheses(this, parenthesis); + var str = this.start.toTex(options); + + if (parens.start) { + str = "\\left(".concat(str, "\\right)"); + } + + if (this.step) { + var step = this.step.toTex(options); + + if (parens.step) { + step = "\\left(".concat(step, "\\right)"); + } + + str += ':' + step; + } + + var end = this.end.toTex(options); + + if (parens.end) { + end = "\\left(".concat(end, "\\right)"); + } + + str += ':' + end; + return str; + }; + + return RangeNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/RelationalNode.js + + + + + +var RelationalNode_name = 'RelationalNode'; +var RelationalNode_dependencies = ['Node']; +var createRelationalNode = /* #__PURE__ */Object(factory["a" /* factory */])(RelationalNode_name, RelationalNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * A node representing a chained conditional expression, such as 'x > y > z' + * + * @param {String[]} conditionals An array of conditional operators used to compare the parameters + * @param {Node[]} params The parameters that will be compared + * + * @constructor RelationalNode + * @extends {Node} + */ + function RelationalNode(conditionals, params) { + if (!(this instanceof RelationalNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (!Array.isArray(conditionals)) throw new TypeError('Parameter conditionals must be an array'); + if (!Array.isArray(params)) throw new TypeError('Parameter params must be an array'); + if (conditionals.length !== params.length - 1) throw new TypeError('Parameter params must contain exactly one more element than parameter conditionals'); + this.conditionals = conditionals; + this.params = params; + } + + RelationalNode.prototype = new Node(); + RelationalNode.prototype.type = 'RelationalNode'; + RelationalNode.prototype.isRelationalNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + RelationalNode.prototype._compile = function (math, argNames) { + var self = this; + var compiled = this.params.map(function (p) { + return p._compile(math, argNames); + }); + return function evalRelationalNode(scope, args, context) { + var evalLhs; + var evalRhs = compiled[0](scope, args, context); + + for (var i = 0; i < self.conditionals.length; i++) { + evalLhs = evalRhs; + evalRhs = compiled[i + 1](scope, args, context); + var condFn = getSafeProperty(math, self.conditionals[i]); + + if (!condFn(evalLhs, evalRhs)) { + return false; + } + } + + return true; + }; + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + RelationalNode.prototype.forEach = function (callback) { + var _this = this; + + this.params.forEach(function (n, i) { + return callback(n, 'params[' + i + ']', _this); + }, this); + }; + /** + * Create a new RelationalNode having its childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {RelationalNode} Returns a transformed copy of the node + */ + + + RelationalNode.prototype.map = function (callback) { + var _this2 = this; + + return new RelationalNode(this.conditionals.slice(), this.params.map(function (n, i) { + return _this2._ifNode(callback(n, 'params[' + i + ']', _this2)); + }, this)); + }; + /** + * Create a clone of this node, a shallow copy + * @return {RelationalNode} + */ + + + RelationalNode.prototype.clone = function () { + return new RelationalNode(this.conditionals, this.params); + }; + /** + * Get string representation. + * @param {Object} options + * @return {string} str + */ + + + RelationalNode.prototype._toString = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var precedence = getPrecedence(this, parenthesis); + var paramStrings = this.params.map(function (p, index) { + var paramPrecedence = getPrecedence(p, parenthesis); + return parenthesis === 'all' || paramPrecedence !== null && paramPrecedence <= precedence ? '(' + p.toString(options) + ')' : p.toString(options); + }); + var operatorMap = { + equal: '==', + unequal: '!=', + smaller: '<', + larger: '>', + smallerEq: '<=', + largerEq: '>=' + }; + var ret = paramStrings[0]; + + for (var i = 0; i < this.conditionals.length; i++) { + ret += ' ' + operatorMap[this.conditionals[i]] + ' ' + paramStrings[i + 1]; + } + + return ret; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + RelationalNode.prototype.toJSON = function () { + return { + mathjs: 'RelationalNode', + conditionals: this.conditionals, + params: this.params + }; + }; + /** + * Instantiate a RelationalNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "RelationalNode", "condition": ..., "trueExpr": ..., "falseExpr": ...}`, + * where mathjs is optional + * @returns {RelationalNode} + */ + + + RelationalNode.fromJSON = function (json) { + return new RelationalNode(json.conditionals, json.params); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + */ + + + RelationalNode.prototype.toHTML = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var precedence = getPrecedence(this, parenthesis); + var paramStrings = this.params.map(function (p, index) { + var paramPrecedence = getPrecedence(p, parenthesis); + return parenthesis === 'all' || paramPrecedence !== null && paramPrecedence <= precedence ? '(' + p.toHTML(options) + ')' : p.toHTML(options); + }); + var operatorMap = { + equal: '==', + unequal: '!=', + smaller: '<', + larger: '>', + smallerEq: '<=', + largerEq: '>=' + }; + var ret = paramStrings[0]; + + for (var i = 0; i < this.conditionals.length; i++) { + ret += '' + Object(utils_string["c" /* escape */])(operatorMap[this.conditionals[i]]) + '' + paramStrings[i + 1]; + } + + return ret; + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + RelationalNode.prototype._toTex = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var precedence = getPrecedence(this, parenthesis); + var paramStrings = this.params.map(function (p, index) { + var paramPrecedence = getPrecedence(p, parenthesis); + return parenthesis === 'all' || paramPrecedence !== null && paramPrecedence <= precedence ? '\\left(' + p.toTex(options) + '\right)' : p.toTex(options); + }); + var ret = paramStrings[0]; + + for (var i = 0; i < this.conditionals.length; i++) { + ret += latexOperators[this.conditionals[i]] + paramStrings[i + 1]; + } + + return ret; + }; + + return RelationalNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/SymbolNode.js + + + + +var SymbolNode_name = 'SymbolNode'; +var SymbolNode_dependencies = ['math', '?Unit', 'Node']; +var createSymbolNode = /* #__PURE__ */Object(factory["a" /* factory */])(SymbolNode_name, SymbolNode_dependencies, function (_ref) { + var math = _ref.math, + Unit = _ref.Unit, + Node = _ref.Node; + + /** + * Check whether some name is a valueless unit like "inch". + * @param {string} name + * @return {boolean} + */ + function isValuelessUnit(name) { + return Unit ? Unit.isValuelessUnit(name) : false; + } + /** + * @constructor SymbolNode + * @extends {Node} + * A symbol node can hold and resolve a symbol + * @param {string} name + * @extends {Node} + */ + + + function SymbolNode(name) { + if (!(this instanceof SymbolNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // validate input + + + if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"'); + this.name = name; + } + + SymbolNode.prototype = new Node(); + SymbolNode.prototype.type = 'SymbolNode'; + SymbolNode.prototype.isSymbolNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + SymbolNode.prototype._compile = function (math, argNames) { + var name = this.name; + + if (argNames[name] === true) { + // this is a FunctionAssignment argument + // (like an x when inside the expression of a function assignment `f(x) = ...`) + return function (scope, args, context) { + return args[name]; + }; + } else if (name in math) { + return function (scope, args, context) { + return name in scope ? getSafeProperty(scope, name) : getSafeProperty(math, name); + }; + } else { + var isUnit = isValuelessUnit(name); + return function (scope, args, context) { + return name in scope ? getSafeProperty(scope, name) : isUnit ? new Unit(null, name) : undef(name); + }; + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + SymbolNode.prototype.forEach = function (callback) {} // nothing to do, we don't have childs + + /** + * Create a new SymbolNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node) : Node} callback + * @returns {SymbolNode} Returns a clone of the node + */ + ; + + SymbolNode.prototype.map = function (callback) { + return this.clone(); + }; + /** + * Throws an error 'Undefined symbol {name}' + * @param {string} name + */ + + + function undef(name) { + throw new Error('Undefined symbol ' + name); + } + /** + * Create a clone of this node, a shallow copy + * @return {SymbolNode} + */ + + + SymbolNode.prototype.clone = function () { + return new SymbolNode(this.name); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + * @override + */ + + + SymbolNode.prototype._toString = function (options) { + return this.name; + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + * @override + */ + + + SymbolNode.prototype.toHTML = function (options) { + var name = Object(utils_string["c" /* escape */])(this.name); + + if (name === 'true' || name === 'false') { + return '' + name + ''; + } else if (name === 'i') { + return '' + name + ''; + } else if (name === 'Infinity') { + return '' + name + ''; + } else if (name === 'NaN') { + return '' + name + ''; + } else if (name === 'null') { + return '' + name + ''; + } else if (name === 'undefined') { + return '' + name + ''; + } + + return '' + name + ''; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + SymbolNode.prototype.toJSON = function () { + return { + mathjs: 'SymbolNode', + name: this.name + }; + }; + /** + * Instantiate a SymbolNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "SymbolNode", name: "x"}`, + * where mathjs is optional + * @returns {SymbolNode} + */ + + + SymbolNode.fromJSON = function (json) { + return new SymbolNode(json.name); + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + * @override + */ + + + SymbolNode.prototype._toTex = function (options) { + var isUnit = false; + + if (typeof math[this.name] === 'undefined' && isValuelessUnit(this.name)) { + isUnit = true; + } + + var symbol = toSymbol(this.name, isUnit); + + if (symbol[0] === '\\') { + // no space needed if the symbol starts with '\' + return symbol; + } // the space prevents symbols from breaking stuff like '\cdot' if it's written right before the symbol + + + return ' ' + symbol; + }; + + return SymbolNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/FunctionNode.js +function FunctionNode_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { FunctionNode_typeof = function _typeof(obj) { return typeof obj; }; } else { FunctionNode_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return FunctionNode_typeof(obj); } + +function FunctionNode_extends() { FunctionNode_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return FunctionNode_extends.apply(this, arguments); } + + + + + + + + +var FunctionNode_name = 'FunctionNode'; +var FunctionNode_dependencies = ['math', 'Node', 'SymbolNode']; +var createFunctionNode = /* #__PURE__ */Object(factory["a" /* factory */])(FunctionNode_name, FunctionNode_dependencies, function (_ref) { + var math = _ref.math, + Node = _ref.Node, + SymbolNode = _ref.SymbolNode; + + /** + * @constructor FunctionNode + * @extends {./Node} + * invoke a list with arguments on a node + * @param {./Node | string} fn Node resolving with a function on which to invoke + * the arguments, typically a SymboNode or AccessorNode + * @param {./Node[]} args + */ + function FunctionNode(fn, args) { + if (!(this instanceof FunctionNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (typeof fn === 'string') { + fn = new SymbolNode(fn); + } // validate input + + + if (!Object(is["w" /* isNode */])(fn)) throw new TypeError('Node expected as parameter "fn"'); + + if (!Array.isArray(args) || !args.every(is["w" /* isNode */])) { + throw new TypeError('Array containing Nodes expected for parameter "args"'); + } + + this.fn = fn; + this.args = args || []; // readonly property name + + Object.defineProperty(this, 'name', { + get: function () { + return this.fn.name || ''; + }.bind(this), + set: function set() { + throw new Error('Cannot assign a new name, name is read-only'); + } + }); // TODO: deprecated since v3, remove some day + + var deprecated = function deprecated() { + throw new Error('Property `FunctionNode.object` is deprecated, use `FunctionNode.fn` instead'); + }; + + Object.defineProperty(this, 'object', { + get: deprecated, + set: deprecated + }); + } + + FunctionNode.prototype = new Node(); + FunctionNode.prototype.type = 'FunctionNode'; + FunctionNode.prototype.isFunctionNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + FunctionNode.prototype._compile = function (math, argNames) { + if (!(this instanceof FunctionNode)) { + throw new TypeError('No valid FunctionNode'); + } // compile arguments + + + var evalArgs = Object(utils_array["m" /* map */])(this.args, function (arg) { + return arg._compile(math, argNames); + }); + + if (Object(is["J" /* isSymbolNode */])(this.fn)) { + // we can statically determine whether the function has an rawArgs property + var _name = this.fn.name; + var fn = _name in math ? getSafeProperty(math, _name) : undefined; + var isRaw = typeof fn === 'function' && fn.rawArgs === true; + + if (isRaw) { + // pass unevaluated parameters (nodes) to the function + // "raw" evaluation + var rawArgs = this.args; + return function evalFunctionNode(scope, args, context) { + return (_name in scope ? getSafeProperty(scope, _name) : fn)(rawArgs, math, FunctionNode_extends({}, scope, args)); + }; + } else { + // "regular" evaluation + if (evalArgs.length === 1) { + var evalArg0 = evalArgs[0]; + return function evalFunctionNode(scope, args, context) { + return (_name in scope ? getSafeProperty(scope, _name) : fn)(evalArg0(scope, args, context)); + }; + } else if (evalArgs.length === 2) { + var _evalArg = evalArgs[0]; + var evalArg1 = evalArgs[1]; + return function evalFunctionNode(scope, args, context) { + return (_name in scope ? getSafeProperty(scope, _name) : fn)(_evalArg(scope, args, context), evalArg1(scope, args, context)); + }; + } else { + return function evalFunctionNode(scope, args, context) { + return (_name in scope ? getSafeProperty(scope, _name) : fn).apply(null, Object(utils_array["m" /* map */])(evalArgs, function (evalArg) { + return evalArg(scope, args, context); + })); + }; + } + } + } else if (Object(is["a" /* isAccessorNode */])(this.fn) && Object(is["u" /* isIndexNode */])(this.fn.index) && this.fn.index.isObjectProperty()) { + // execute the function with the right context: the object of the AccessorNode + var evalObject = this.fn.object._compile(math, argNames); + + var prop = this.fn.index.getObjectProperty(); + var _rawArgs = this.args; + return function evalFunctionNode(scope, args, context) { + var object = evalObject(scope, args, context); + validateSafeMethod(object, prop); + var isRaw = object[prop] && object[prop].rawArgs; + return isRaw ? object[prop](_rawArgs, math, FunctionNode_extends({}, scope, args)) // "raw" evaluation + : object[prop].apply(object, Object(utils_array["m" /* map */])(evalArgs, function (evalArg) { + // "regular" evaluation + return evalArg(scope, args, context); + })); + }; + } else { + // node.fn.isAccessorNode && !node.fn.index.isObjectProperty() + // we have to dynamically determine whether the function has a rawArgs property + var evalFn = this.fn._compile(math, argNames); + + var _rawArgs2 = this.args; + return function evalFunctionNode(scope, args, context) { + var fn = evalFn(scope, args, context); + var isRaw = fn && fn.rawArgs; + return isRaw ? fn(_rawArgs2, math, FunctionNode_extends({}, scope, args)) // "raw" evaluation + : fn.apply(fn, Object(utils_array["m" /* map */])(evalArgs, function (evalArg) { + // "regular" evaluation + return evalArg(scope, args, context); + })); + }; + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + FunctionNode.prototype.forEach = function (callback) { + callback(this.fn, 'fn', this); + + for (var i = 0; i < this.args.length; i++) { + callback(this.args[i], 'args[' + i + ']', this); + } + }; + /** + * Create a new FunctionNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {FunctionNode} Returns a transformed copy of the node + */ + + + FunctionNode.prototype.map = function (callback) { + var fn = this._ifNode(callback(this.fn, 'fn', this)); + + var args = []; + + for (var i = 0; i < this.args.length; i++) { + args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this)); + } + + return new FunctionNode(fn, args); + }; + /** + * Create a clone of this node, a shallow copy + * @return {FunctionNode} + */ + + + FunctionNode.prototype.clone = function () { + return new FunctionNode(this.fn, this.args.slice(0)); + }; // backup Node's toString function + // @private + + + var nodeToString = FunctionNode.prototype.toString; + /** + * Get string representation. (wrapper function) + * This overrides parts of Node's toString function. + * If callback is an object containing callbacks, it + * calls the correct callback for the current node, + * otherwise it falls back to calling Node's toString + * function. + * + * @param {Object} options + * @return {string} str + * @override + */ + + FunctionNode.prototype.toString = function (options) { + var customString; + var name = this.fn.toString(options); + + if (options && FunctionNode_typeof(options.handler) === 'object' && Object(utils_object["f" /* hasOwnProperty */])(options.handler, name)) { + // callback is a map of callback functions + customString = options.handler[name](this, options); + } + + if (typeof customString !== 'undefined') { + return customString; + } // fall back to Node's toString + + + return nodeToString.call(this, options); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + */ + + + FunctionNode.prototype._toString = function (options) { + var args = this.args.map(function (arg) { + return arg.toString(options); + }); + var fn = Object(is["q" /* isFunctionAssignmentNode */])(this.fn) ? '(' + this.fn.toString(options) + ')' : this.fn.toString(options); // format the arguments like "add(2, 4.2)" + + return fn + '(' + args.join(', ') + ')'; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + FunctionNode.prototype.toJSON = function () { + return { + mathjs: 'FunctionNode', + fn: this.fn, + args: this.args + }; + }; + /** + * Instantiate an AssignmentNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "FunctionNode", fn: ..., args: ...}`, + * where mathjs is optional + * @returns {FunctionNode} + */ + + + FunctionNode.fromJSON = function (json) { + return new FunctionNode(json.fn, json.args); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + */ + + + FunctionNode.prototype.toHTML = function (options) { + var args = this.args.map(function (arg) { + return arg.toHTML(options); + }); // format the arguments like "add(2, 4.2)" + + return '' + Object(utils_string["c" /* escape */])(this.fn) + '(' + args.join(',') + ')'; + }; + /* + * Expand a LaTeX template + * + * @param {string} template + * @param {Node} node + * @param {Object} options + * @private + **/ + + + function expandTemplate(template, node, options) { + var latex = ''; // Match everything of the form ${identifier} or ${identifier[2]} or $$ + // while submatching identifier and 2 (in the second case) + + var regex = new RegExp('\\$(?:\\{([a-z_][a-z_0-9]*)(?:\\[([0-9]+)\\])?\\}|\\$)', 'ig'); + var inputPos = 0; // position in the input string + + var match; + + while ((match = regex.exec(template)) !== null) { + // go through all matches + // add everything in front of the match to the LaTeX string + latex += template.substring(inputPos, match.index); + inputPos = match.index; + + if (match[0] === '$$') { + // escaped dollar sign + latex += '$'; + inputPos++; + } else { + // template parameter + inputPos += match[0].length; + var property = node[match[1]]; + + if (!property) { + throw new ReferenceError('Template: Property ' + match[1] + ' does not exist.'); + } + + if (match[2] === undefined) { + // no square brackets + switch (FunctionNode_typeof(property)) { + case 'string': + latex += property; + break; + + case 'object': + if (Object(is["w" /* isNode */])(property)) { + latex += property.toTex(options); + } else if (Array.isArray(property)) { + // make array of Nodes into comma separated list + latex += property.map(function (arg, index) { + if (Object(is["w" /* isNode */])(arg)) { + return arg.toTex(options); + } + + throw new TypeError('Template: ' + match[1] + '[' + index + '] is not a Node.'); + }).join(','); + } else { + throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes'); + } + + break; + + default: + throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes'); + } + } else { + // with square brackets + if (Object(is["w" /* isNode */])(property[match[2]] && property[match[2]])) { + latex += property[match[2]].toTex(options); + } else { + throw new TypeError('Template: ' + match[1] + '[' + match[2] + '] is not a Node.'); + } + } + } + } + + latex += template.slice(inputPos); // append rest of the template + + return latex; + } // backup Node's toTex function + // @private + + + var nodeToTex = FunctionNode.prototype.toTex; + /** + * Get LaTeX representation. (wrapper function) + * This overrides parts of Node's toTex function. + * If callback is an object containing callbacks, it + * calls the correct callback for the current node, + * otherwise it falls back to calling Node's toTex + * function. + * + * @param {Object} options + * @return {string} + */ + + FunctionNode.prototype.toTex = function (options) { + var customTex; + + if (options && FunctionNode_typeof(options.handler) === 'object' && Object(utils_object["f" /* hasOwnProperty */])(options.handler, this.name)) { + // callback is a map of callback functions + customTex = options.handler[this.name](this, options); + } + + if (typeof customTex !== 'undefined') { + return customTex; + } // fall back to Node's toTex + + + return nodeToTex.call(this, options); + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + FunctionNode.prototype._toTex = function (options) { + var args = this.args.map(function (arg) { + // get LaTeX of the arguments + return arg.toTex(options); + }); + var latexConverter; + + if (latexFunctions[this.name]) { + latexConverter = latexFunctions[this.name]; + } // toTex property on the function itself + + + if (math[this.name] && (typeof math[this.name].toTex === 'function' || FunctionNode_typeof(math[this.name].toTex) === 'object' || typeof math[this.name].toTex === 'string')) { + // .toTex is a callback function + latexConverter = math[this.name].toTex; + } + + var customToTex; + + switch (FunctionNode_typeof(latexConverter)) { + case 'function': + // a callback function + customToTex = latexConverter(this, options); + break; + + case 'string': + // a template string + customToTex = expandTemplate(latexConverter, this, options); + break; + + case 'object': + // an object with different "converters" for different numbers of arguments + switch (FunctionNode_typeof(latexConverter[args.length])) { + case 'function': + customToTex = latexConverter[args.length](this, options); + break; + + case 'string': + customToTex = expandTemplate(latexConverter[args.length], this, options); + break; + } + + } + + if (typeof customToTex !== 'undefined') { + return customToTex; + } + + return expandTemplate(defaultTemplate, this, options); + }; + /** + * Get identifier. + * @return {string} + */ + + + FunctionNode.prototype.getIdentifier = function () { + return this.type + ':' + this.name; + }; + + return FunctionNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/parse.js +function parse_extends() { parse_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return parse_extends.apply(this, arguments); } + + + + + +var parse_name = 'parse'; +var parse_dependencies = ['typed', 'numeric', 'config', 'AccessorNode', 'ArrayNode', 'AssignmentNode', 'BlockNode', 'ConditionalNode', 'ConstantNode', 'FunctionAssignmentNode', 'FunctionNode', 'IndexNode', 'ObjectNode', 'OperatorNode', 'ParenthesisNode', 'RangeNode', 'RelationalNode', 'SymbolNode']; +var createParse = /* #__PURE__ */Object(factory["a" /* factory */])(parse_name, parse_dependencies, function (_ref) { + var typed = _ref.typed, + numeric = _ref.numeric, + config = _ref.config, + AccessorNode = _ref.AccessorNode, + ArrayNode = _ref.ArrayNode, + AssignmentNode = _ref.AssignmentNode, + BlockNode = _ref.BlockNode, + ConditionalNode = _ref.ConditionalNode, + ConstantNode = _ref.ConstantNode, + FunctionAssignmentNode = _ref.FunctionAssignmentNode, + FunctionNode = _ref.FunctionNode, + IndexNode = _ref.IndexNode, + ObjectNode = _ref.ObjectNode, + OperatorNode = _ref.OperatorNode, + ParenthesisNode = _ref.ParenthesisNode, + RangeNode = _ref.RangeNode, + RelationalNode = _ref.RelationalNode, + SymbolNode = _ref.SymbolNode; + + /** + * Parse an expression. Returns a node tree, which can be evaluated by + * invoking node.evaluate(). + * + * Note the evaluating arbitrary expressions may involve security risks, + * see [https://mathjs.org/docs/expressions/security.html](https://mathjs.org/docs/expressions/security.html) for more information. + * + * Syntax: + * + * math.parse(expr) + * math.parse(expr, options) + * math.parse([expr1, expr2, expr3, ...]) + * math.parse([expr1, expr2, expr3, ...], options) + * + * Example: + * + * const node1 = math.parse('sqrt(3^2 + 4^2)') + * node1.compile().evaluate() // 5 + * + * let scope = {a:3, b:4} + * const node2 = math.parse('a * b') // 12 + * const code2 = node2.compile() + * code2.evaluate(scope) // 12 + * scope.a = 5 + * code2.evaluate(scope) // 20 + * + * const nodes = math.parse(['a = 3', 'b = 4', 'a * b']) + * nodes[2].compile().evaluate() // 12 + * + * See also: + * + * evaluate, compile + * + * @param {string | string[] | Matrix} expr Expression to be parsed + * @param {{nodes: Object}} [options] Available options: + * - `nodes` a set of custom nodes + * @return {Node | Node[]} node + * @throws {Error} + */ + var parse = typed(parse_name, { + string: function string(expression) { + return parseStart(expression, {}); + }, + 'Array | Matrix': function ArrayMatrix(expressions) { + return parseMultiple(expressions, {}); + }, + 'string, Object': function stringObject(expression, options) { + var extraNodes = options.nodes !== undefined ? options.nodes : {}; + return parseStart(expression, extraNodes); + }, + 'Array | Matrix, Object': parseMultiple + }); + + function parseMultiple(expressions) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var extraNodes = options.nodes !== undefined ? options.nodes : {}; // parse an array or matrix with expressions + + return deepMap(expressions, function (elem) { + if (typeof elem !== 'string') throw new TypeError('String expected'); + return parseStart(elem, extraNodes); + }); + } // token types enumeration + + + var TOKENTYPE = { + NULL: 0, + DELIMITER: 1, + NUMBER: 2, + SYMBOL: 3, + UNKNOWN: 4 + }; // map with all delimiters + + var DELIMITERS = { + ',': true, + '(': true, + ')': true, + '[': true, + ']': true, + '{': true, + '}': true, + '"': true, + '\'': true, + ';': true, + '+': true, + '-': true, + '*': true, + '.*': true, + '/': true, + './': true, + '%': true, + '^': true, + '.^': true, + '~': true, + '!': true, + '&': true, + '|': true, + '^|': true, + '=': true, + ':': true, + '?': true, + '==': true, + '!=': true, + '<': true, + '>': true, + '<=': true, + '>=': true, + '<<': true, + '>>': true, + '>>>': true + }; // map with all named delimiters + + var NAMED_DELIMITERS = { + mod: true, + to: true, + "in": true, + and: true, + xor: true, + or: true, + not: true + }; + var CONSTANTS = { + "true": true, + "false": false, + "null": null, + undefined: undefined + }; + var NUMERIC_CONSTANTS = ['NaN', 'Infinity']; + + function initialState() { + return { + extraNodes: {}, + // current extra nodes, must be careful not to mutate + expression: '', + // current expression + comment: '', + // last parsed comment + index: 0, + // current index in expr + token: '', + // current token + tokenType: TOKENTYPE.NULL, + // type of the token + nestingLevel: 0, + // level of nesting inside parameters, used to ignore newline characters + conditionalLevel: null // when a conditional is being parsed, the level of the conditional is stored here + + }; + } + /** + * View upto `length` characters of the expression starting at the current character. + * + * @param {Object} state + * @param {number} [length=1] Number of characters to view + * @returns {string} + * @private + */ + + + function currentString(state, length) { + return state.expression.substr(state.index, length); + } + /** + * View the current character. Returns '' if end of expression is reached. + * + * @param {Object} state + * @returns {string} + * @private + */ + + + function currentCharacter(state) { + return currentString(state, 1); + } + /** + * Get the next character from the expression. + * The character is stored into the char c. If the end of the expression is + * reached, the function puts an empty string in c. + * @private + */ + + + function next(state) { + state.index++; + } + /** + * Preview the previous character from the expression. + * @return {string} cNext + * @private + */ + + + function prevCharacter(state) { + return state.expression.charAt(state.index - 1); + } + /** + * Preview the next character from the expression. + * @return {string} cNext + * @private + */ + + + function nextCharacter(state) { + return state.expression.charAt(state.index + 1); + } + /** + * Get next token in the current string expr. + * The token and token type are available as token and tokenType + * @private + */ + + + function getToken(state) { + state.tokenType = TOKENTYPE.NULL; + state.token = ''; + state.comment = ''; // skip over whitespaces + // space, tab, and newline when inside parameters + + while (parse.isWhitespace(currentCharacter(state), state.nestingLevel)) { + next(state); + } // skip comment + + + if (currentCharacter(state) === '#') { + while (currentCharacter(state) !== '\n' && currentCharacter(state) !== '') { + state.comment += currentCharacter(state); + next(state); + } + } // check for end of expression + + + if (currentCharacter(state) === '') { + // token is still empty + state.tokenType = TOKENTYPE.DELIMITER; + return; + } // check for new line character + + + if (currentCharacter(state) === '\n' && !state.nestingLevel) { + state.tokenType = TOKENTYPE.DELIMITER; + state.token = currentCharacter(state); + next(state); + return; + } + + var c1 = currentCharacter(state); + var c2 = currentString(state, 2); + var c3 = currentString(state, 3); + + if (c3.length === 3 && DELIMITERS[c3]) { + state.tokenType = TOKENTYPE.DELIMITER; + state.token = c3; + next(state); + next(state); + next(state); + return; + } // check for delimiters consisting of 2 characters + + + if (c2.length === 2 && DELIMITERS[c2]) { + state.tokenType = TOKENTYPE.DELIMITER; + state.token = c2; + next(state); + next(state); + return; + } // check for delimiters consisting of 1 character + + + if (DELIMITERS[c1]) { + state.tokenType = TOKENTYPE.DELIMITER; + state.token = c1; + next(state); + return; + } // check for a number + + + if (parse.isDigitDot(c1)) { + state.tokenType = TOKENTYPE.NUMBER; // get number, can have a single dot + + if (currentCharacter(state) === '.') { + state.token += currentCharacter(state); + next(state); + + if (!parse.isDigit(currentCharacter(state))) { + // this is no number, it is just a dot (can be dot notation) + state.tokenType = TOKENTYPE.DELIMITER; + } + } else { + while (parse.isDigit(currentCharacter(state))) { + state.token += currentCharacter(state); + next(state); + } + + if (parse.isDecimalMark(currentCharacter(state), nextCharacter(state))) { + state.token += currentCharacter(state); + next(state); + } + } + + while (parse.isDigit(currentCharacter(state))) { + state.token += currentCharacter(state); + next(state); + } // check for exponential notation like "2.3e-4", "1.23e50" or "2e+4" + + + if (currentCharacter(state) === 'E' || currentCharacter(state) === 'e') { + if (parse.isDigit(nextCharacter(state)) || nextCharacter(state) === '-' || nextCharacter(state) === '+') { + state.token += currentCharacter(state); + next(state); + + if (currentCharacter(state) === '+' || currentCharacter(state) === '-') { + state.token += currentCharacter(state); + next(state); + } // Scientific notation MUST be followed by an exponent + + + if (!parse.isDigit(currentCharacter(state))) { + throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"'); + } + + while (parse.isDigit(currentCharacter(state))) { + state.token += currentCharacter(state); + next(state); + } + + if (parse.isDecimalMark(currentCharacter(state), nextCharacter(state))) { + throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"'); + } + } else if (nextCharacter(state) === '.') { + next(state); + throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"'); + } + } + + return; + } // check for variables, functions, named operators + + + if (parse.isAlpha(currentCharacter(state), prevCharacter(state), nextCharacter(state))) { + while (parse.isAlpha(currentCharacter(state), prevCharacter(state), nextCharacter(state)) || parse.isDigit(currentCharacter(state))) { + state.token += currentCharacter(state); + next(state); + } + + if (Object(utils_object["f" /* hasOwnProperty */])(NAMED_DELIMITERS, state.token)) { + state.tokenType = TOKENTYPE.DELIMITER; + } else { + state.tokenType = TOKENTYPE.SYMBOL; + } + + return; + } // something unknown is found, wrong characters -> a syntax error + + + state.tokenType = TOKENTYPE.UNKNOWN; + + while (currentCharacter(state) !== '') { + state.token += currentCharacter(state); + next(state); + } + + throw createSyntaxError(state, 'Syntax error in part "' + state.token + '"'); + } + /** + * Get next token and skip newline tokens + */ + + + function getTokenSkipNewline(state) { + do { + getToken(state); + } while (state.token === '\n'); // eslint-disable-line no-unmodified-loop-condition + + } + /** + * Open parameters. + * New line characters will be ignored until closeParams(state) is called + */ + + + function openParams(state) { + state.nestingLevel++; + } + /** + * Close parameters. + * New line characters will no longer be ignored + */ + + + function closeParams(state) { + state.nestingLevel--; + } + /** + * Checks whether the current character `c` is a valid alpha character: + * + * - A latin letter (upper or lower case) Ascii: a-z, A-Z + * - An underscore Ascii: _ + * - A dollar sign Ascii: $ + * - A latin letter with accents Unicode: \u00C0 - \u02AF + * - A greek letter Unicode: \u0370 - \u03FF + * - A mathematical alphanumeric symbol Unicode: \u{1D400} - \u{1D7FF} excluding invalid code points + * + * The previous and next characters are needed to determine whether + * this character is part of a unicode surrogate pair. + * + * @param {string} c Current character in the expression + * @param {string} cPrev Previous character + * @param {string} cNext Next character + * @return {boolean} + */ + + + parse.isAlpha = function isAlpha(c, cPrev, cNext) { + return parse.isValidLatinOrGreek(c) || parse.isValidMathSymbol(c, cNext) || parse.isValidMathSymbol(cPrev, c); + }; + /** + * Test whether a character is a valid latin, greek, or letter-like character + * @param {string} c + * @return {boolean} + */ + + + parse.isValidLatinOrGreek = function isValidLatinOrGreek(c) { + return /^[a-zA-Z_$\u00C0-\u02AF\u0370-\u03FF\u2100-\u214F]$/.test(c); + }; + /** + * Test whether two given 16 bit characters form a surrogate pair of a + * unicode math symbol. + * + * https://unicode-table.com/en/ + * https://www.wikiwand.com/en/Mathematical_operators_and_symbols_in_Unicode + * + * Note: In ES6 will be unicode aware: + * https://stackoverflow.com/questions/280712/javascript-unicode-regexes + * https://mathiasbynens.be/notes/es6-unicode-regex + * + * @param {string} high + * @param {string} low + * @return {boolean} + */ + + + parse.isValidMathSymbol = function isValidMathSymbol(high, low) { + return /^[\uD835]$/.test(high) && /^[\uDC00-\uDFFF]$/.test(low) && /^[^\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDFCC\uDFCD]$/.test(low); + }; + /** + * Check whether given character c is a white space character: space, tab, or enter + * @param {string} c + * @param {number} nestingLevel + * @return {boolean} + */ + + + parse.isWhitespace = function isWhitespace(c, nestingLevel) { + // TODO: also take '\r' carriage return as newline? Or does that give problems on mac? + return c === ' ' || c === '\t' || c === '\n' && nestingLevel > 0; + }; + /** + * Test whether the character c is a decimal mark (dot). + * This is the case when it's not the start of a delimiter '.*', './', or '.^' + * @param {string} c + * @param {string} cNext + * @return {boolean} + */ + + + parse.isDecimalMark = function isDecimalMark(c, cNext) { + return c === '.' && cNext !== '/' && cNext !== '*' && cNext !== '^'; + }; + /** + * checks if the given char c is a digit or dot + * @param {string} c a string with one character + * @return {boolean} + */ + + + parse.isDigitDot = function isDigitDot(c) { + return c >= '0' && c <= '9' || c === '.'; + }; + /** + * checks if the given char c is a digit + * @param {string} c a string with one character + * @return {boolean} + */ + + + parse.isDigit = function isDigit(c) { + return c >= '0' && c <= '9'; + }; + /** + * Start of the parse levels below, in order of precedence + * @return {Node} node + * @private + */ + + + function parseStart(expression, extraNodes) { + var state = initialState(); + + parse_extends(state, { + expression: expression, + extraNodes: extraNodes + }); + + getToken(state); + var node = parseBlock(state); // check for garbage at the end of the expression + // an expression ends with a empty character '' and tokenType DELIMITER + + if (state.token !== '') { + if (state.tokenType === TOKENTYPE.DELIMITER) { + // user entered a not existing operator like "//" + // TODO: give hints for aliases, for example with "<>" give as hint " did you mean !== ?" + throw createError(state, 'Unexpected operator ' + state.token); + } else { + throw createSyntaxError(state, 'Unexpected part "' + state.token + '"'); + } + } + + return node; + } + /** + * Parse a block with expressions. Expressions can be separated by a newline + * character '\n', or by a semicolon ';'. In case of a semicolon, no output + * of the preceding line is returned. + * @return {Node} node + * @private + */ + + + function parseBlock(state) { + var node; + var blocks = []; + var visible; + + if (state.token !== '' && state.token !== '\n' && state.token !== ';') { + node = parseAssignment(state); + node.comment = state.comment; + } // TODO: simplify this loop + + + while (state.token === '\n' || state.token === ';') { + // eslint-disable-line no-unmodified-loop-condition + if (blocks.length === 0 && node) { + visible = state.token !== ';'; + blocks.push({ + node: node, + visible: visible + }); + } + + getToken(state); + + if (state.token !== '\n' && state.token !== ';' && state.token !== '') { + node = parseAssignment(state); + node.comment = state.comment; + visible = state.token !== ';'; + blocks.push({ + node: node, + visible: visible + }); + } + } + + if (blocks.length > 0) { + return new BlockNode(blocks); + } else { + if (!node) { + node = new ConstantNode(undefined); + node.comment = state.comment; + } + + return node; + } + } + /** + * Assignment of a function or variable, + * - can be a variable like 'a=2.3' + * - or a updating an existing variable like 'matrix(2,3:5)=[6,7,8]' + * - defining a function like 'f(x) = x^2' + * @return {Node} node + * @private + */ + + + function parseAssignment(state) { + var name, args, value, valid; + var node = parseConditional(state); + + if (state.token === '=') { + if (Object(is["J" /* isSymbolNode */])(node)) { + // parse a variable assignment like 'a = 2/3' + name = node.name; + getTokenSkipNewline(state); + value = parseAssignment(state); + return new AssignmentNode(new SymbolNode(name), value); + } else if (Object(is["a" /* isAccessorNode */])(node)) { + // parse a matrix subset assignment like 'A[1,2] = 4' + getTokenSkipNewline(state); + value = parseAssignment(state); + return new AssignmentNode(node.object, node.index, value); + } else if (Object(is["r" /* isFunctionNode */])(node) && Object(is["J" /* isSymbolNode */])(node.fn)) { + // parse function assignment like 'f(x) = x^2' + valid = true; + args = []; + name = node.name; + node.args.forEach(function (arg, index) { + if (Object(is["J" /* isSymbolNode */])(arg)) { + args[index] = arg.name; + } else { + valid = false; + } + }); + + if (valid) { + getTokenSkipNewline(state); + value = parseAssignment(state); + return new FunctionAssignmentNode(name, args, value); + } + } + + throw createSyntaxError(state, 'Invalid left hand side of assignment operator ='); + } + + return node; + } + /** + * conditional operation + * + * condition ? truePart : falsePart + * + * Note: conditional operator is right-associative + * + * @return {Node} node + * @private + */ + + + function parseConditional(state) { + var node = parseLogicalOr(state); + + while (state.token === '?') { + // eslint-disable-line no-unmodified-loop-condition + // set a conditional level, the range operator will be ignored as long + // as conditionalLevel === state.nestingLevel. + var prev = state.conditionalLevel; + state.conditionalLevel = state.nestingLevel; + getTokenSkipNewline(state); + var condition = node; + var trueExpr = parseAssignment(state); + if (state.token !== ':') throw createSyntaxError(state, 'False part of conditional expression expected'); + state.conditionalLevel = null; + getTokenSkipNewline(state); + var falseExpr = parseAssignment(state); // Note: check for conditional operator again, right associativity + + node = new ConditionalNode(condition, trueExpr, falseExpr); // restore the previous conditional level + + state.conditionalLevel = prev; + } + + return node; + } + /** + * logical or, 'x or y' + * @return {Node} node + * @private + */ + + + function parseLogicalOr(state) { + var node = parseLogicalXor(state); + + while (state.token === 'or') { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + node = new OperatorNode('or', 'or', [node, parseLogicalXor(state)]); + } + + return node; + } + /** + * logical exclusive or, 'x xor y' + * @return {Node} node + * @private + */ + + + function parseLogicalXor(state) { + var node = parseLogicalAnd(state); + + while (state.token === 'xor') { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + node = new OperatorNode('xor', 'xor', [node, parseLogicalAnd(state)]); + } + + return node; + } + /** + * logical and, 'x and y' + * @return {Node} node + * @private + */ + + + function parseLogicalAnd(state) { + var node = parseBitwiseOr(state); + + while (state.token === 'and') { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + node = new OperatorNode('and', 'and', [node, parseBitwiseOr(state)]); + } + + return node; + } + /** + * bitwise or, 'x | y' + * @return {Node} node + * @private + */ + + + function parseBitwiseOr(state) { + var node = parseBitwiseXor(state); + + while (state.token === '|') { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + node = new OperatorNode('|', 'bitOr', [node, parseBitwiseXor(state)]); + } + + return node; + } + /** + * bitwise exclusive or (xor), 'x ^| y' + * @return {Node} node + * @private + */ + + + function parseBitwiseXor(state) { + var node = parseBitwiseAnd(state); + + while (state.token === '^|') { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + node = new OperatorNode('^|', 'bitXor', [node, parseBitwiseAnd(state)]); + } + + return node; + } + /** + * bitwise and, 'x & y' + * @return {Node} node + * @private + */ + + + function parseBitwiseAnd(state) { + var node = parseRelational(state); + + while (state.token === '&') { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + node = new OperatorNode('&', 'bitAnd', [node, parseRelational(state)]); + } + + return node; + } + /** + * Parse a chained conditional, like 'a > b >= c' + * @return {Node} node + */ + + + function parseRelational(state) { + var params = [parseShift(state)]; + var conditionals = []; + var operators = { + '==': 'equal', + '!=': 'unequal', + '<': 'smaller', + '>': 'larger', + '<=': 'smallerEq', + '>=': 'largerEq' + }; + + while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + // eslint-disable-line no-unmodified-loop-condition + var cond = { + name: state.token, + fn: operators[state.token] + }; + conditionals.push(cond); + getTokenSkipNewline(state); + params.push(parseShift(state)); + } + + if (params.length === 1) { + return params[0]; + } else if (params.length === 2) { + return new OperatorNode(conditionals[0].name, conditionals[0].fn, params); + } else { + return new RelationalNode(conditionals.map(function (c) { + return c.fn; + }), params); + } + } + /** + * Bitwise left shift, bitwise right arithmetic shift, bitwise right logical shift + * @return {Node} node + * @private + */ + + + function parseShift(state) { + var node, name, fn, params; + node = parseConversion(state); + var operators = { + '<<': 'leftShift', + '>>': 'rightArithShift', + '>>>': 'rightLogShift' + }; + + while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + name = state.token; + fn = operators[name]; + getTokenSkipNewline(state); + params = [node, parseConversion(state)]; + node = new OperatorNode(name, fn, params); + } + + return node; + } + /** + * conversion operators 'to' and 'in' + * @return {Node} node + * @private + */ + + + function parseConversion(state) { + var node, name, fn, params; + node = parseRange(state); + var operators = { + to: 'to', + "in": 'to' // alias of 'to' + + }; + + while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + name = state.token; + fn = operators[name]; + getTokenSkipNewline(state); + + if (name === 'in' && state.token === '') { + // end of expression -> this is the unit 'in' ('inch') + node = new OperatorNode('*', 'multiply', [node, new SymbolNode('in')], true); + } else { + // operator 'a to b' or 'a in b' + params = [node, parseRange(state)]; + node = new OperatorNode(name, fn, params); + } + } + + return node; + } + /** + * parse range, "start:end", "start:step:end", ":", "start:", ":end", etc + * @return {Node} node + * @private + */ + + + function parseRange(state) { + var node; + var params = []; + + if (state.token === ':') { + // implicit start=1 (one-based) + node = new ConstantNode(1); + } else { + // explicit start + node = parseAddSubtract(state); + } + + if (state.token === ':' && state.conditionalLevel !== state.nestingLevel) { + // we ignore the range operator when a conditional operator is being processed on the same level + params.push(node); // parse step and end + + while (state.token === ':' && params.length < 3) { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + + if (state.token === ')' || state.token === ']' || state.token === ',' || state.token === '') { + // implicit end + params.push(new SymbolNode('end')); + } else { + // explicit end + params.push(parseAddSubtract(state)); + } + } + + if (params.length === 3) { + // params = [start, step, end] + node = new RangeNode(params[0], params[2], params[1]); // start, end, step + } else { + // length === 2 + // params = [start, end] + node = new RangeNode(params[0], params[1]); // start, end + } + } + + return node; + } + /** + * add or subtract + * @return {Node} node + * @private + */ + + + function parseAddSubtract(state) { + var node, name, fn, params; + node = parseMultiplyDivide(state); + var operators = { + '+': 'add', + '-': 'subtract' + }; + + while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + name = state.token; + fn = operators[name]; + getTokenSkipNewline(state); + params = [node, parseMultiplyDivide(state)]; + node = new OperatorNode(name, fn, params); + } + + return node; + } + /** + * multiply, divide, modulus + * @return {Node} node + * @private + */ + + + function parseMultiplyDivide(state) { + var node, last, name, fn; + node = parseImplicitMultiplication(state); + last = node; + var operators = { + '*': 'multiply', + '.*': 'dotMultiply', + '/': 'divide', + './': 'dotDivide', + '%': 'mod', + mod: 'mod' + }; + + while (true) { + if (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + // explicit operators + name = state.token; + fn = operators[name]; + getTokenSkipNewline(state); + last = parseImplicitMultiplication(state); + node = new OperatorNode(name, fn, [node, last]); + } else { + break; + } + } + + return node; + } + /** + * implicit multiplication + * @return {Node} node + * @private + */ + + + function parseImplicitMultiplication(state) { + var node, last; + node = parseRule2(state); + last = node; + + while (true) { + if (state.tokenType === TOKENTYPE.SYMBOL || state.token === 'in' && Object(is["l" /* isConstantNode */])(node) || state.tokenType === TOKENTYPE.NUMBER && !Object(is["l" /* isConstantNode */])(last) && (!Object(is["B" /* isOperatorNode */])(last) || last.op === '!') || state.token === '(') { + // parse implicit multiplication + // + // symbol: implicit multiplication like '2a', '(2+3)a', 'a b' + // number: implicit multiplication like '(2+3)2' + // parenthesis: implicit multiplication like '2(3+4)', '(3+4)(1+2)' + last = parseRule2(state); + node = new OperatorNode('*', 'multiply', [node, last], true + /* implicit */ + ); + } else { + break; + } + } + + return node; + } + /** + * Infamous "rule 2" as described in https://github.com/josdejong/mathjs/issues/792#issuecomment-361065370 + * Explicit division gets higher precedence than implicit multiplication + * when the division matches this pattern: [number] / [number] [symbol] + * @return {Node} node + * @private + */ + + + function parseRule2(state) { + var node = parseUnary(state); + var last = node; + var tokenStates = []; + + while (true) { + // Match the "number /" part of the pattern "number / number symbol" + if (state.token === '/' && Object(is["l" /* isConstantNode */])(last)) { + // Look ahead to see if the next token is a number + tokenStates.push(parse_extends({}, state)); + getTokenSkipNewline(state); // Match the "number / number" part of the pattern + + if (state.tokenType === TOKENTYPE.NUMBER) { + // Look ahead again + tokenStates.push(parse_extends({}, state)); + getTokenSkipNewline(state); // Match the "symbol" part of the pattern, or a left parenthesis + + if (state.tokenType === TOKENTYPE.SYMBOL || state.token === '(') { + // We've matched the pattern "number / number symbol". + // Rewind once and build the "number / number" node; the symbol will be consumed later + parse_extends(state, tokenStates.pop()); + + tokenStates.pop(); + last = parseUnary(state); + node = new OperatorNode('/', 'divide', [node, last]); + } else { + // Not a match, so rewind + tokenStates.pop(); + + parse_extends(state, tokenStates.pop()); + + break; + } + } else { + // Not a match, so rewind + parse_extends(state, tokenStates.pop()); + + break; + } + } else { + break; + } + } + + return node; + } + /** + * Unary plus and minus, and logical and bitwise not + * @return {Node} node + * @private + */ + + + function parseUnary(state) { + var name, params, fn; + var operators = { + '-': 'unaryMinus', + '+': 'unaryPlus', + '~': 'bitNot', + not: 'not' + }; + + if (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + fn = operators[state.token]; + name = state.token; + getTokenSkipNewline(state); + params = [parseUnary(state)]; + return new OperatorNode(name, fn, params); + } + + return parsePow(state); + } + /** + * power + * Note: power operator is right associative + * @return {Node} node + * @private + */ + + + function parsePow(state) { + var node, name, fn, params; + node = parseLeftHandOperators(state); + + if (state.token === '^' || state.token === '.^') { + name = state.token; + fn = name === '^' ? 'pow' : 'dotPow'; + getTokenSkipNewline(state); + params = [node, parseUnary(state)]; // Go back to unary, we can have '2^-3' + + node = new OperatorNode(name, fn, params); + } + + return node; + } + /** + * Left hand operators: factorial x!, ctranspose x' + * @return {Node} node + * @private + */ + + + function parseLeftHandOperators(state) { + var node, name, fn, params; + node = parseCustomNodes(state); + var operators = { + '!': 'factorial', + '\'': 'ctranspose' + }; + + while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + name = state.token; + fn = operators[name]; + getToken(state); + params = [node]; + node = new OperatorNode(name, fn, params); + node = parseAccessors(state, node); + } + + return node; + } + /** + * Parse a custom node handler. A node handler can be used to process + * nodes in a custom way, for example for handling a plot. + * + * A handler must be passed as second argument of the parse function. + * - must extend math.expression.node.Node + * - must contain a function _compile(defs: Object) : string + * - must contain a function find(filter: Object) : Node[] + * - must contain a function toString() : string + * - the constructor is called with a single argument containing all parameters + * + * For example: + * + * nodes = { + * 'plot': PlotHandler + * } + * + * The constructor of the handler is called as: + * + * node = new PlotHandler(params) + * + * The handler will be invoked when evaluating an expression like: + * + * node = math.parse('plot(sin(x), x)', nodes) + * + * @return {Node} node + * @private + */ + + + function parseCustomNodes(state) { + var params = []; + + if (state.tokenType === TOKENTYPE.SYMBOL && Object(utils_object["f" /* hasOwnProperty */])(state.extraNodes, state.token)) { + var CustomNode = state.extraNodes[state.token]; + getToken(state); // parse parameters + + if (state.token === '(') { + params = []; + openParams(state); + getToken(state); + + if (state.token !== ')') { + params.push(parseAssignment(state)); // parse a list with parameters + + while (state.token === ',') { + // eslint-disable-line no-unmodified-loop-condition + getToken(state); + params.push(parseAssignment(state)); + } + } + + if (state.token !== ')') { + throw createSyntaxError(state, 'Parenthesis ) expected'); + } + + closeParams(state); + getToken(state); + } // create a new custom node + // noinspection JSValidateTypes + + + return new CustomNode(params); + } + + return parseSymbol(state); + } + /** + * parse symbols: functions, variables, constants, units + * @return {Node} node + * @private + */ + + + function parseSymbol(state) { + var node, name; + + if (state.tokenType === TOKENTYPE.SYMBOL || state.tokenType === TOKENTYPE.DELIMITER && state.token in NAMED_DELIMITERS) { + name = state.token; + getToken(state); + + if (Object(utils_object["f" /* hasOwnProperty */])(CONSTANTS, name)) { + // true, false, null, ... + node = new ConstantNode(CONSTANTS[name]); + } else if (NUMERIC_CONSTANTS.indexOf(name) !== -1) { + // NaN, Infinity + node = new ConstantNode(numeric(name, 'number')); + } else { + node = new SymbolNode(name); + } // parse function parameters and matrix index + + + node = parseAccessors(state, node); + return node; + } + + return parseDoubleQuotesString(state); + } + /** + * parse accessors: + * - function invocation in round brackets (...), for example sqrt(2) + * - index enclosed in square brackets [...], for example A[2,3] + * - dot notation for properties, like foo.bar + * @param {Object} state + * @param {Node} node Node on which to apply the parameters. If there + * are no parameters in the expression, the node + * itself is returned + * @param {string[]} [types] Filter the types of notations + * can be ['(', '[', '.'] + * @return {Node} node + * @private + */ + + + function parseAccessors(state, node, types) { + var params; + + while ((state.token === '(' || state.token === '[' || state.token === '.') && (!types || types.indexOf(state.token) !== -1)) { + // eslint-disable-line no-unmodified-loop-condition + params = []; + + if (state.token === '(') { + if (Object(is["J" /* isSymbolNode */])(node) || Object(is["a" /* isAccessorNode */])(node)) { + // function invocation like fn(2, 3) or obj.fn(2, 3) + openParams(state); + getToken(state); + + if (state.token !== ')') { + params.push(parseAssignment(state)); // parse a list with parameters + + while (state.token === ',') { + // eslint-disable-line no-unmodified-loop-condition + getToken(state); + params.push(parseAssignment(state)); + } + } + + if (state.token !== ')') { + throw createSyntaxError(state, 'Parenthesis ) expected'); + } + + closeParams(state); + getToken(state); + node = new FunctionNode(node, params); + } else { + // implicit multiplication like (2+3)(4+5) or sqrt(2)(1+2) + // don't parse it here but let it be handled by parseImplicitMultiplication + // with correct precedence + return node; + } + } else if (state.token === '[') { + // index notation like variable[2, 3] + openParams(state); + getToken(state); + + if (state.token !== ']') { + params.push(parseAssignment(state)); // parse a list with parameters + + while (state.token === ',') { + // eslint-disable-line no-unmodified-loop-condition + getToken(state); + params.push(parseAssignment(state)); + } + } + + if (state.token !== ']') { + throw createSyntaxError(state, 'Parenthesis ] expected'); + } + + closeParams(state); + getToken(state); + node = new AccessorNode(node, new IndexNode(params)); + } else { + // dot notation like variable.prop + getToken(state); + + if (state.tokenType !== TOKENTYPE.SYMBOL) { + throw createSyntaxError(state, 'Property name expected after dot'); + } + + params.push(new ConstantNode(state.token)); + getToken(state); + var dotNotation = true; + node = new AccessorNode(node, new IndexNode(params, dotNotation)); + } + } + + return node; + } + /** + * Parse a double quotes string. + * @return {Node} node + * @private + */ + + + function parseDoubleQuotesString(state) { + var node, str; + + if (state.token === '"') { + str = parseDoubleQuotesStringToken(state); // create constant + + node = new ConstantNode(str); // parse index parameters + + node = parseAccessors(state, node); + return node; + } + + return parseSingleQuotesString(state); + } + /** + * Parse a string surrounded by double quotes "..." + * @return {string} + */ + + + function parseDoubleQuotesStringToken(state) { + var str = ''; + + while (currentCharacter(state) !== '' && currentCharacter(state) !== '"') { + if (currentCharacter(state) === '\\') { + // escape character, immediately process the next + // character to prevent stopping at a next '\"' + str += currentCharacter(state); + next(state); + } + + str += currentCharacter(state); + next(state); + } + + getToken(state); + + if (state.token !== '"') { + throw createSyntaxError(state, 'End of string " expected'); + } + + getToken(state); + return JSON.parse('"' + str + '"'); // unescape escaped characters + } + /** + * Parse a single quotes string. + * @return {Node} node + * @private + */ + + + function parseSingleQuotesString(state) { + var node, str; + + if (state.token === '\'') { + str = parseSingleQuotesStringToken(state); // create constant + + node = new ConstantNode(str); // parse index parameters + + node = parseAccessors(state, node); + return node; + } + + return parseMatrix(state); + } + /** + * Parse a string surrounded by single quotes '...' + * @return {string} + */ + + + function parseSingleQuotesStringToken(state) { + var str = ''; + + while (currentCharacter(state) !== '' && currentCharacter(state) !== '\'') { + if (currentCharacter(state) === '\\') { + // escape character, immediately process the next + // character to prevent stopping at a next '\'' + str += currentCharacter(state); + next(state); + } + + str += currentCharacter(state); + next(state); + } + + getToken(state); + + if (state.token !== '\'') { + throw createSyntaxError(state, 'End of string \' expected'); + } + + getToken(state); + return JSON.parse('"' + str + '"'); // unescape escaped characters + } + /** + * parse the matrix + * @return {Node} node + * @private + */ + + + function parseMatrix(state) { + var array, params, rows, cols; + + if (state.token === '[') { + // matrix [...] + openParams(state); + getToken(state); + + if (state.token !== ']') { + // this is a non-empty matrix + var row = parseRow(state); + + if (state.token === ';') { + // 2 dimensional array + rows = 1; + params = [row]; // the rows of the matrix are separated by dot-comma's + + while (state.token === ';') { + // eslint-disable-line no-unmodified-loop-condition + getToken(state); + params[rows] = parseRow(state); + rows++; + } + + if (state.token !== ']') { + throw createSyntaxError(state, 'End of matrix ] expected'); + } + + closeParams(state); + getToken(state); // check if the number of columns matches in all rows + + cols = params[0].items.length; + + for (var r = 1; r < rows; r++) { + if (params[r].items.length !== cols) { + throw createError(state, 'Column dimensions mismatch ' + '(' + params[r].items.length + ' !== ' + cols + ')'); + } + } + + array = new ArrayNode(params); + } else { + // 1 dimensional vector + if (state.token !== ']') { + throw createSyntaxError(state, 'End of matrix ] expected'); + } + + closeParams(state); + getToken(state); + array = row; + } + } else { + // this is an empty matrix "[ ]" + closeParams(state); + getToken(state); + array = new ArrayNode([]); + } + + return parseAccessors(state, array); + } + + return parseObject(state); + } + /** + * Parse a single comma-separated row from a matrix, like 'a, b, c' + * @return {ArrayNode} node + */ + + + function parseRow(state) { + var params = [parseAssignment(state)]; + var len = 1; + + while (state.token === ',') { + // eslint-disable-line no-unmodified-loop-condition + getToken(state); // parse expression + + params[len] = parseAssignment(state); + len++; + } + + return new ArrayNode(params); + } + /** + * parse an object, enclosed in angle brackets{...}, for example {value: 2} + * @return {Node} node + * @private + */ + + + function parseObject(state) { + if (state.token === '{') { + openParams(state); + var key; + var properties = {}; + + do { + getToken(state); + + if (state.token !== '}') { + // parse key + if (state.token === '"') { + key = parseDoubleQuotesStringToken(state); + } else if (state.token === '\'') { + key = parseSingleQuotesStringToken(state); + } else if (state.tokenType === TOKENTYPE.SYMBOL || state.tokenType === TOKENTYPE.DELIMITER && state.token in NAMED_DELIMITERS) { + key = state.token; + getToken(state); + } else { + throw createSyntaxError(state, 'Symbol or string expected as object key'); + } // parse key/value separator + + + if (state.token !== ':') { + throw createSyntaxError(state, 'Colon : expected after object key'); + } + + getToken(state); // parse key + + properties[key] = parseAssignment(state); + } + } while (state.token === ','); // eslint-disable-line no-unmodified-loop-condition + + + if (state.token !== '}') { + throw createSyntaxError(state, 'Comma , or bracket } expected after object value'); + } + + closeParams(state); + getToken(state); + var node = new ObjectNode(properties); // parse index parameters + + node = parseAccessors(state, node); + return node; + } + + return parseNumber(state); + } + /** + * parse a number + * @return {Node} node + * @private + */ + + + function parseNumber(state) { + var numberStr; + + if (state.tokenType === TOKENTYPE.NUMBER) { + // this is a number + numberStr = state.token; + getToken(state); + return new ConstantNode(numeric(numberStr, config.number)); + } + + return parseParentheses(state); + } + /** + * parentheses + * @return {Node} node + * @private + */ + + + function parseParentheses(state) { + var node; // check if it is a parenthesized expression + + if (state.token === '(') { + // parentheses (...) + openParams(state); + getToken(state); + node = parseAssignment(state); // start again + + if (state.token !== ')') { + throw createSyntaxError(state, 'Parenthesis ) expected'); + } + + closeParams(state); + getToken(state); + node = new ParenthesisNode(node); + node = parseAccessors(state, node); + return node; + } + + return parseEnd(state); + } + /** + * Evaluated when the expression is not yet ended but expected to end + * @return {Node} res + * @private + */ + + + function parseEnd(state) { + if (state.token === '') { + // syntax error or unexpected end of expression + throw createSyntaxError(state, 'Unexpected end of expression'); + } else { + throw createSyntaxError(state, 'Value expected'); + } + } + /** + * Shortcut for getting the current row value (one based) + * Returns the line of the currently handled expression + * @private + */ + + /* TODO: implement keeping track on the row number + function row () { + return null + } + */ + + /** + * Shortcut for getting the current col value (one based) + * Returns the column (position) where the last state.token starts + * @private + */ + + + function col(state) { + return state.index - state.token.length + 1; + } + /** + * Create an error + * @param {Object} state + * @param {string} message + * @return {SyntaxError} instantiated error + * @private + */ + + + function createSyntaxError(state, message) { + var c = col(state); + var error = new SyntaxError(message + ' (char ' + c + ')'); + error["char"] = c; + return error; + } + /** + * Create an error + * @param {Object} state + * @param {string} message + * @return {Error} instantiated error + * @private + */ + + + function createError(state, message) { + var c = col(state); + var error = new SyntaxError(message + ' (char ' + c + ')'); + error["char"] = c; + return error; + } + + return parse; +}); +// CONCATENATED MODULE: ./src/expression/function/compile.js + + +var compile_name = 'compile'; +var compile_dependencies = ['typed', 'parse']; +var createCompile = /* #__PURE__ */Object(factory["a" /* factory */])(compile_name, compile_dependencies, function (_ref) { + var typed = _ref.typed, + parse = _ref.parse; + + /** + * Parse and compile an expression. + * Returns a an object with a function `evaluate([scope])` to evaluate the + * compiled expression. + * + * Syntax: + * + * math.compile(expr) // returns one node + * math.compile([expr1, expr2, expr3, ...]) // returns an array with nodes + * + * Examples: + * + * const code1 = math.compile('sqrt(3^2 + 4^2)') + * code1.evaluate() // 5 + * + * let scope = {a: 3, b: 4} + * const code2 = math.compile('a * b') // 12 + * code2.evaluate(scope) // 12 + * scope.a = 5 + * code2.evaluate(scope) // 20 + * + * const nodes = math.compile(['a = 3', 'b = 4', 'a * b']) + * nodes[2].evaluate() // 12 + * + * See also: + * + * parse, evaluate + * + * @param {string | string[] | Array | Matrix} expr + * The expression to be compiled + * @return {{evaluate: Function} | Array.<{evaluate: Function}>} code + * An object with the compiled expression + * @throws {Error} + */ + return typed(compile_name, { + string: function string(expr) { + return parse(expr).compile(); + }, + 'Array | Matrix': function ArrayMatrix(expr) { + return deepMap(expr, function (entry) { + return parse(entry).compile(); + }); + } + }); +}); +// CONCATENATED MODULE: ./src/expression/function/evaluate.js + + +var evaluate_name = 'evaluate'; +var evaluate_dependencies = ['typed', 'parse']; +var createEvaluate = /* #__PURE__ */Object(factory["a" /* factory */])(evaluate_name, evaluate_dependencies, function (_ref) { + var typed = _ref.typed, + parse = _ref.parse; + + /** + * Evaluate an expression. + * + * Note the evaluating arbitrary expressions may involve security risks, + * see [https://mathjs.org/docs/expressions/security.html](https://mathjs.org/docs/expressions/security.html) for more information. + * + * Syntax: + * + * math.evaluate(expr) + * math.evaluate(expr, scope) + * math.evaluate([expr1, expr2, expr3, ...]) + * math.evaluate([expr1, expr2, expr3, ...], scope) + * + * Example: + * + * math.evaluate('(2+3)/4') // 1.25 + * math.evaluate('sqrt(3^2 + 4^2)') // 5 + * math.evaluate('sqrt(-4)') // 2i + * math.evaluate(['a=3', 'b=4', 'a*b']) // [3, 4, 12] + * + * let scope = {a:3, b:4} + * math.evaluate('a * b', scope) // 12 + * + * See also: + * + * parse, compile + * + * @param {string | string[] | Matrix} expr The expression to be evaluated + * @param {Object} [scope] Scope to read/write variables + * @return {*} The result of the expression + * @throws {Error} + */ + return typed(evaluate_name, { + string: function string(expr) { + var scope = {}; + return parse(expr).compile().evaluate(scope); + }, + 'string, Object': function stringObject(expr, scope) { + return parse(expr).compile().evaluate(scope); + }, + 'Array | Matrix': function ArrayMatrix(expr) { + var scope = {}; + return deepMap(expr, function (entry) { + return parse(entry).compile().evaluate(scope); + }); + }, + 'Array | Matrix, Object': function ArrayMatrixObject(expr, scope) { + return deepMap(expr, function (entry) { + return parse(entry).compile().evaluate(scope); + }); + } + }); +}); +// CONCATENATED MODULE: ./src/expression/function/eval.js +// For backward compatibility, deprecated since version 6.0.0. Date: 2018-12-05 + + +var createDeprecatedEval = /* #__PURE__ */Object(factory["a" /* factory */])('eval', ['evaluate'], function (_ref) { + var evaluate = _ref.evaluate; + return function () { + Object(utils_log["a" /* warnOnce */])('Function "eval" has been renamed to "evaluate" in v6.0.0, please use the new function instead.'); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return evaluate.apply(evaluate, args); + }; +}); +// CONCATENATED MODULE: ./src/expression/Parser.js + + + + +var Parser_name = 'Parser'; +var Parser_dependencies = ['parse']; +var createParserClass = /* #__PURE__ */Object(factory["a" /* factory */])(Parser_name, Parser_dependencies, function (_ref) { + var parse = _ref.parse; + + /** + * @constructor Parser + * Parser contains methods to evaluate or parse expressions, and has a number + * of convenience methods to get, set, and remove variables from memory. Parser + * keeps a scope containing variables in memory, which is used for all + * evaluations. + * + * Methods: + * const result = parser.evaluate(expr) // evaluate an expression + * const value = parser.get(name) // retrieve a variable from the parser + * const values = parser.getAll() // retrieve all defined variables + * parser.set(name, value) // set a variable in the parser + * parser.remove(name) // clear a variable from the + * // parsers scope + * parser.clear() // clear the parsers scope + * + * Example usage: + * const parser = new Parser() + * // Note: there is a convenience method which can be used instead: + * // const parser = new math.parser() + * + * // evaluate expressions + * parser.evaluate('sqrt(3^2 + 4^2)') // 5 + * parser.evaluate('sqrt(-4)') // 2i + * parser.evaluate('2 inch in cm') // 5.08 cm + * parser.evaluate('cos(45 deg)') // 0.7071067811865476 + * + * // define variables and functions + * parser.evaluate('x = 7 / 2') // 3.5 + * parser.evaluate('x + 3') // 6.5 + * parser.evaluate('function f(x, y) = x^y') // f(x, y) + * parser.evaluate('f(2, 3)') // 8 + * + * // get and set variables and functions + * const x = parser.get('x') // 7 + * const f = parser.get('f') // function + * const g = f(3, 2) // 9 + * parser.set('h', 500) + * const i = parser.evaluate('h / 2') // 250 + * parser.set('hello', function (name) { + * return 'hello, ' + name + '!' + * }) + * parser.evaluate('hello("user")') // "hello, user!" + * + * // clear defined functions and variables + * parser.clear() + * + */ + function Parser() { + if (!(this instanceof Parser)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.scope = {}; + } + /** + * Attach type information + */ + + + Parser.prototype.type = 'Parser'; + Parser.prototype.isParser = true; + /** + * Parse an expression and return the parsed function node. + * The node tree can be compiled via `code = node.compile(math)`, + * and the compiled code can be executed as `code.evaluate([scope])` + * @param {string} expr + * @return {Node} node + * @throws {Error} + */ + + Parser.prototype.parse = function (expr) { + throw new Error('Parser.parse is deprecated. Use math.parse instead.'); + }; + /** + * Parse and compile an expression, return the compiled javascript code. + * The node can be evaluated via code.evaluate([scope]) + * @param {string} expr + * @return {{evaluate: function}} code + * @throws {Error} + */ + + + Parser.prototype.compile = function (expr) { + throw new Error('Parser.compile is deprecated. Use math.compile instead.'); + }; + /** + * Parse and evaluate the given expression + * @param {string} expr A string containing an expression, for example "2+3" + * @return {*} result The result, or undefined when the expression was empty + * @throws {Error} + */ + + + Parser.prototype.evaluate = function (expr) { + // TODO: validate arguments + return parse(expr).compile().evaluate(this.scope); + }; + /** + * Parse and evaluate the given expression + * @param {string} expr A string containing an expression, for example "2+3" + * @return {*} result The result, or undefined when the expression was empty + * @throws {Error} + */ + // TODO: Deprecated since v6.0.0. Clean up some day + + + Parser.prototype.eval = function (expr) { + Object(utils_log["a" /* warnOnce */])('Method Parser.eval is renamed to Parser.evaluate. Please use the new method name.'); + return this.evaluate(expr); + }; + /** + * Get a variable (a function or variable) by name from the parsers scope. + * Returns undefined when not found + * @param {string} name + * @return {* | undefined} value + */ + + + Parser.prototype.get = function (name) { + // TODO: validate arguments + return name in this.scope ? getSafeProperty(this.scope, name) : undefined; + }; + /** + * Get a map with all defined variables + * @return {Object} values + */ + + + Parser.prototype.getAll = function () { + return Object(utils_object["e" /* extend */])({}, this.scope); + }; + /** + * Set a symbol (a function or variable) by name from the parsers scope. + * @param {string} name + * @param {* | undefined} value + */ + + + Parser.prototype.set = function (name, value) { + // TODO: validate arguments + return setSafeProperty(this.scope, name, value); + }; + /** + * Remove a variable from the parsers scope + * @param {string} name + */ + + + Parser.prototype.remove = function (name) { + // TODO: validate arguments + delete this.scope[name]; + }; + /** + * Clear the scope with variables and functions + */ + + + Parser.prototype.clear = function () { + for (var _name in this.scope) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.scope, _name)) { + delete this.scope[_name]; + } + } + }; + + return Parser; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/expression/function/parser.js + +var parser_name = 'parser'; +var parser_dependencies = ['typed', 'Parser']; +var createParser = /* #__PURE__ */Object(factory["a" /* factory */])(parser_name, parser_dependencies, function (_ref) { + var typed = _ref.typed, + Parser = _ref.Parser; + + /** + * Create a parser. The function creates a new `math.Parser` object. + * + * Syntax: + * + * math.parser() + * + * Examples: + * + * const parser = new math.parser() + * + * // evaluate expressions + * const a = parser.evaluate('sqrt(3^2 + 4^2)') // 5 + * const b = parser.evaluate('sqrt(-4)') // 2i + * const c = parser.evaluate('2 inch in cm') // 5.08 cm + * const d = parser.evaluate('cos(45 deg)') // 0.7071067811865476 + * + * // define variables and functions + * parser.evaluate('x = 7 / 2') // 3.5 + * parser.evaluate('x + 3') // 6.5 + * parser.evaluate('function f(x, y) = x^y') // f(x, y) + * parser.evaluate('f(2, 3)') // 8 + * + * // get and set variables and functions + * const x = parser.get('x') // 7 + * const f = parser.get('f') // function + * const g = f(3, 2) // 9 + * parser.set('h', 500) + * const i = parser.evaluate('h / 2') // 250 + * parser.set('hello', function (name) { + * return 'hello, ' + name + '!' + * }) + * parser.evaluate('hello("user")') // "hello, user!" + * + * // clear defined functions and variables + * parser.clear() + * + * See also: + * + * evaluate, compile, parse + * + * @return {Parser} Parser + */ + return typed(parser_name, { + '': function _() { + return new Parser(); + } + }); +}); +// CONCATENATED MODULE: ./src/function/algebra/decomposition/lup.js + + +var lup_name = 'lup'; +var lup_dependencies = ['typed', 'matrix', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtract', 'larger', 'equalScalar', 'unaryMinus', 'DenseMatrix', 'SparseMatrix', 'Spa']; +var createLup = /* #__PURE__ */Object(factory["a" /* factory */])(lup_name, lup_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + abs = _ref.abs, + addScalar = _ref.addScalar, + divideScalar = _ref.divideScalar, + multiplyScalar = _ref.multiplyScalar, + subtract = _ref.subtract, + larger = _ref.larger, + equalScalar = _ref.equalScalar, + unaryMinus = _ref.unaryMinus, + DenseMatrix = _ref.DenseMatrix, + SparseMatrix = _ref.SparseMatrix, + Spa = _ref.Spa; + + /** + * Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a + * row permutation vector `p` where `A[p,:] = L * U` + * + * Syntax: + * + * math.lup(A) + * + * Example: + * + * const m = [[2, 1], [1, 4]] + * const r = math.lup(m) + * // r = { + * // L: [[1, 0], [0.5, 1]], + * // U: [[2, 1], [0, 3.5]], + * // P: [0, 1] + * // } + * + * See also: + * + * slu, lsolve, lusolve, usolve + * + * @param {Matrix | Array} A A two dimensional matrix or array for which to get the LUP decomposition. + * + * @return {{L: Array | Matrix, U: Array | Matrix, P: Array.}} The lower triangular matrix, the upper triangular matrix and the permutation matrix. + */ + return typed(lup_name, { + DenseMatrix: function DenseMatrix(m) { + return _denseLUP(m); + }, + SparseMatrix: function SparseMatrix(m) { + return _sparseLUP(m); + }, + Array: function Array(a) { + // create dense matrix from array + var m = matrix(a); // lup, use matrix implementation + + var r = _denseLUP(m); // result + + + return { + L: r.L.valueOf(), + U: r.U.valueOf(), + p: r.p + }; + } + }); + + function _denseLUP(m) { + // rows & columns + var rows = m._size[0]; + var columns = m._size[1]; // minimum rows and columns + + var n = Math.min(rows, columns); // matrix array, clone original data + + var data = Object(utils_object["a" /* clone */])(m._data); // l matrix arrays + + var ldata = []; + var lsize = [rows, n]; // u matrix arrays + + var udata = []; + var usize = [n, columns]; // vars + + var i, j, k; // permutation vector + + var p = []; + + for (i = 0; i < rows; i++) { + p[i] = i; + } // loop columns + + + for (j = 0; j < columns; j++) { + // skip first column in upper triangular matrix + if (j > 0) { + // loop rows + for (i = 0; i < rows; i++) { + // min i,j + var min = Math.min(i, j); // v[i, j] + + var s = 0; // loop up to min + + for (k = 0; k < min; k++) { + // s = l[i, k] - data[k, j] + s = addScalar(s, multiplyScalar(data[i][k], data[k][j])); + } + + data[i][j] = subtract(data[i][j], s); + } + } // row with larger value in cvector, row >= j + + + var pi = j; + var pabsv = 0; + var vjj = 0; // loop rows + + for (i = j; i < rows; i++) { + // data @ i, j + var v = data[i][j]; // absolute value + + var absv = abs(v); // value is greater than pivote value + + if (larger(absv, pabsv)) { + // store row + pi = i; // update max value + + pabsv = absv; // value @ [j, j] + + vjj = v; + } + } // swap rows (j <-> pi) + + + if (j !== pi) { + // swap values j <-> pi in p + p[j] = [p[pi], p[pi] = p[j]][0]; // swap j <-> pi in data + + DenseMatrix._swapRows(j, pi, data); + } // check column is in lower triangular matrix + + + if (j < rows) { + // loop rows (lower triangular matrix) + for (i = j + 1; i < rows; i++) { + // value @ i, j + var vij = data[i][j]; + + if (!equalScalar(vij, 0)) { + // update data + data[i][j] = divideScalar(data[i][j], vjj); + } + } + } + } // loop columns + + + for (j = 0; j < columns; j++) { + // loop rows + for (i = 0; i < rows; i++) { + // initialize row in arrays + if (j === 0) { + // check row exists in upper triangular matrix + if (i < columns) { + // U + udata[i] = []; + } // L + + + ldata[i] = []; + } // check we are in the upper triangular matrix + + + if (i < j) { + // check row exists in upper triangular matrix + if (i < columns) { + // U + udata[i][j] = data[i][j]; + } // check column exists in lower triangular matrix + + + if (j < rows) { + // L + ldata[i][j] = 0; + } + + continue; + } // diagonal value + + + if (i === j) { + // check row exists in upper triangular matrix + if (i < columns) { + // U + udata[i][j] = data[i][j]; + } // check column exists in lower triangular matrix + + + if (j < rows) { + // L + ldata[i][j] = 1; + } + + continue; + } // check row exists in upper triangular matrix + + + if (i < columns) { + // U + udata[i][j] = 0; + } // check column exists in lower triangular matrix + + + if (j < rows) { + // L + ldata[i][j] = data[i][j]; + } + } + } // l matrix + + + var l = new DenseMatrix({ + data: ldata, + size: lsize + }); // u matrix + + var u = new DenseMatrix({ + data: udata, + size: usize + }); // p vector + + var pv = []; + + for (i = 0, n = p.length; i < n; i++) { + pv[p[i]] = i; + } // return matrices + + + return { + L: l, + U: u, + p: pv, + toString: function toString() { + return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p; + } + }; + } + + function _sparseLUP(m) { + // rows & columns + var rows = m._size[0]; + var columns = m._size[1]; // minimum rows and columns + + var n = Math.min(rows, columns); // matrix arrays (will not be modified, thanks to permutation vector) + + var values = m._values; + var index = m._index; + var ptr = m._ptr; // l matrix arrays + + var lvalues = []; + var lindex = []; + var lptr = []; + var lsize = [rows, n]; // u matrix arrays + + var uvalues = []; + var uindex = []; + var uptr = []; + var usize = [n, columns]; // vars + + var i, j, k; // permutation vectors, (current index -> original index) and (original index -> current index) + + var pvCo = []; + var pvOc = []; + + for (i = 0; i < rows; i++) { + pvCo[i] = i; + pvOc[i] = i; + } // swap indices in permutation vectors (condition x < y)! + + + var swapIndeces = function swapIndeces(x, y) { + // find pv indeces getting data from x and y + var kx = pvOc[x]; + var ky = pvOc[y]; // update permutation vector current -> original + + pvCo[kx] = y; + pvCo[ky] = x; // update permutation vector original -> current + + pvOc[x] = ky; + pvOc[y] = kx; + }; // loop columns + + + var _loop = function _loop() { + // sparse accumulator + var spa = new Spa(); // check lower triangular matrix has a value @ column j + + if (j < rows) { + // update ptr + lptr.push(lvalues.length); // first value in j column for lower triangular matrix + + lvalues.push(1); + lindex.push(j); + } // update ptr + + + uptr.push(uvalues.length); // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + + var k0 = ptr[j]; + var k1 = ptr[j + 1]; // copy column j into sparse accumulator + + for (k = k0; k < k1; k++) { + // row + i = index[k]; // copy column values into sparse accumulator (use permutation vector) + + spa.set(pvCo[i], values[k]); + } // skip first column in upper triangular matrix + + + if (j > 0) { + // loop rows in column j (above diagonal) + spa.forEach(0, j - 1, function (k, vkj) { + // loop rows in column k (L) + SparseMatrix._forEachRow(k, lvalues, lindex, lptr, function (i, vik) { + // check row is below k + if (i > k) { + // update spa value + spa.accumulate(i, unaryMinus(multiplyScalar(vik, vkj))); + } + }); + }); + } // row with larger value in spa, row >= j + + + var pi = j; + var vjj = spa.get(j); + var pabsv = abs(vjj); // loop values in spa (order by row, below diagonal) + + spa.forEach(j + 1, rows - 1, function (x, v) { + // absolute value + var absv = abs(v); // value is greater than pivote value + + if (larger(absv, pabsv)) { + // store row + pi = x; // update max value + + pabsv = absv; // value @ [j, j] + + vjj = v; + } + }); // swap rows (j <-> pi) + + if (j !== pi) { + // swap values j <-> pi in L + SparseMatrix._swapRows(j, pi, lsize[1], lvalues, lindex, lptr); // swap values j <-> pi in U + + + SparseMatrix._swapRows(j, pi, usize[1], uvalues, uindex, uptr); // swap values in spa + + + spa.swap(j, pi); // update permutation vector (swap values @ j, pi) + + swapIndeces(j, pi); + } // loop values in spa (order by row) + + + spa.forEach(0, rows - 1, function (x, v) { + // check we are above diagonal + if (x <= j) { + // update upper triangular matrix + uvalues.push(v); + uindex.push(x); + } else { + // update value + v = divideScalar(v, vjj); // check value is non zero + + if (!equalScalar(v, 0)) { + // update lower triangular matrix + lvalues.push(v); + lindex.push(x); + } + } + }); + }; + + for (j = 0; j < columns; j++) { + _loop(); + } // update ptrs + + + uptr.push(uvalues.length); + lptr.push(lvalues.length); // return matrices + + return { + L: new SparseMatrix({ + values: lvalues, + index: lindex, + ptr: lptr, + size: lsize + }), + U: new SparseMatrix({ + values: uvalues, + index: uindex, + ptr: uptr, + size: usize + }), + p: pvCo, + toString: function toString() { + return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p; + } + }; + } +}); +// CONCATENATED MODULE: ./src/function/algebra/decomposition/qr.js +function qr_extends() { qr_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return qr_extends.apply(this, arguments); } + + +var qr_name = 'qr'; +var qr_dependencies = ['typed', 'matrix', 'zeros', 'identity', 'isZero', 'equal', 'sign', 'sqrt', 'conj', 'unaryMinus', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtract', 'complex']; +var createQr = /* #__PURE__ */Object(factory["a" /* factory */])(qr_name, qr_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + zeros = _ref.zeros, + identity = _ref.identity, + isZero = _ref.isZero, + equal = _ref.equal, + sign = _ref.sign, + sqrt = _ref.sqrt, + conj = _ref.conj, + unaryMinus = _ref.unaryMinus, + addScalar = _ref.addScalar, + divideScalar = _ref.divideScalar, + multiplyScalar = _ref.multiplyScalar, + subtract = _ref.subtract, + complex = _ref.complex; + + /** + * Calculate the Matrix QR decomposition. Matrix `A` is decomposed in + * two matrices (`Q`, `R`) where `Q` is an + * orthogonal matrix and `R` is an upper triangular matrix. + * + * Syntax: + * + * math.qr(A) + * + * Example: + * + * const m = [ + * [1, -1, 4], + * [1, 4, -2], + * [1, 4, 2], + * [1, -1, 0] + * ] + * const result = math.qr(m) + * // r = { + * // Q: [ + * // [0.5, -0.5, 0.5], + * // [0.5, 0.5, -0.5], + * // [0.5, 0.5, 0.5], + * // [0.5, -0.5, -0.5], + * // ], + * // R: [ + * // [2, 3, 2], + * // [0, 5, -2], + * // [0, 0, 4], + * // [0, 0, 0] + * // ] + * // } + * + * See also: + * + * lup, lusolve + * + * @param {Matrix | Array} A A two dimensional matrix or array + * for which to get the QR decomposition. + * + * @return {{Q: Array | Matrix, R: Array | Matrix}} Q: the orthogonal + * matrix and R: the upper triangular matrix + */ + return qr_extends(typed(qr_name, { + DenseMatrix: function DenseMatrix(m) { + return _denseQR(m); + }, + SparseMatrix: function SparseMatrix(m) { + return _sparseQR(m); + }, + Array: function Array(a) { + // create dense matrix from array + var m = matrix(a); // lup, use matrix implementation + + var r = _denseQR(m); // result + + + return { + Q: r.Q.valueOf(), + R: r.R.valueOf() + }; + } + }), { + _denseQRimpl: _denseQRimpl + }); + + function _denseQRimpl(m) { + // rows & columns (m x n) + var rows = m._size[0]; // m + + var cols = m._size[1]; // n + + var Q = identity([rows], 'dense'); + var Qdata = Q._data; + var R = m.clone(); + var Rdata = R._data; // vars + + var i, j, k; + var w = zeros([rows], ''); + + for (k = 0; k < Math.min(cols, rows); ++k) { + /* + * **k-th Household matrix** + * + * The matrix I - 2*v*transpose(v) + * x = first column of A + * x1 = first element of x + * alpha = x1 / |x1| * |x| + * e1 = tranpose([1, 0, 0, ...]) + * u = x - alpha * e1 + * v = u / |u| + * + * Household matrix = I - 2 * v * tranpose(v) + * + * * Initially Q = I and R = A. + * * Household matrix is a reflection in a plane normal to v which + * will zero out all but the top right element in R. + * * Appplying reflection to both Q and R will not change product. + * * Repeat this process on the (1,1) minor to get R as an upper + * triangular matrix. + * * Reflections leave the magnitude of the columns of Q unchanged + * so Q remains othoganal. + * + */ + var pivot = Rdata[k][k]; + var sgn = unaryMinus(equal(pivot, 0) ? 1 : sign(pivot)); + var conjSgn = conj(sgn); + var alphaSquared = 0; + + for (i = k; i < rows; i++) { + alphaSquared = addScalar(alphaSquared, multiplyScalar(Rdata[i][k], conj(Rdata[i][k]))); + } + + var alpha = multiplyScalar(sgn, sqrt(alphaSquared)); + + if (!isZero(alpha)) { + // first element in vector u + var u1 = subtract(pivot, alpha); // w = v * u1 / |u| (only elements k to (rows-1) are used) + + w[k] = 1; + + for (i = k + 1; i < rows; i++) { + w[i] = divideScalar(Rdata[i][k], u1); + } // tau = - conj(u1 / alpha) + + + var tau = unaryMinus(conj(divideScalar(u1, alpha))); + var s = void 0; + /* + * tau and w have been choosen so that + * + * 2 * v * tranpose(v) = tau * w * tranpose(w) + */ + + /* + * -- calculate R = R - tau * w * tranpose(w) * R -- + * Only do calculation with rows k to (rows-1) + * Additionally columns 0 to (k-1) will not be changed by this + * multiplication so do not bother recalculating them + */ + + for (j = k; j < cols; j++) { + s = 0.0; // calculate jth element of [tranpose(w) * R] + + for (i = k; i < rows; i++) { + s = addScalar(s, multiplyScalar(conj(w[i]), Rdata[i][j])); + } // calculate the jth element of [tau * transpose(w) * R] + + + s = multiplyScalar(s, tau); + + for (i = k; i < rows; i++) { + Rdata[i][j] = multiplyScalar(subtract(Rdata[i][j], multiplyScalar(w[i], s)), conjSgn); + } + } + /* + * -- calculate Q = Q - tau * Q * w * transpose(w) -- + * Q is a square matrix (rows x rows) + * Only do calculation with columns k to (rows-1) + * Additionally rows 0 to (k-1) will not be changed by this + * multiplication so do not bother recalculating them + */ + + + for (i = 0; i < rows; i++) { + s = 0.0; // calculate ith element of [Q * w] + + for (j = k; j < rows; j++) { + s = addScalar(s, multiplyScalar(Qdata[i][j], w[j])); + } // calculate the ith element of [tau * Q * w] + + + s = multiplyScalar(s, tau); + + for (j = k; j < rows; ++j) { + Qdata[i][j] = divideScalar(subtract(Qdata[i][j], multiplyScalar(s, conj(w[j]))), conjSgn); + } + } + } + } // return matrices + + + return { + Q: Q, + R: R, + toString: function toString() { + return 'Q: ' + this.Q.toString() + '\nR: ' + this.R.toString(); + } + }; + } + + function _denseQR(m) { + var ret = _denseQRimpl(m); + + var Rdata = ret.R._data; + + if (m._data.length > 0) { + var zero = Rdata[0][0].type === 'Complex' ? complex(0) : 0; + + for (var i = 0; i < Rdata.length; ++i) { + for (var j = 0; j < i && j < (Rdata[0] || []).length; ++j) { + Rdata[i][j] = zero; + } + } + } + + return ret; + } + + function _sparseQR(m) { + throw new Error('qr not implemented for sparse matrices yet'); + } +}); +// CONCATENATED MODULE: ./src/function/algebra/sparse/csPermute.js +/** + * Permutes a sparse matrix C = P * A * Q + * + * @param {SparseMatrix} a The Matrix A + * @param {Array} pinv The row permutation vector + * @param {Array} q The column permutation vector + * @param {boolean} values Create a pattern matrix (false), values and pattern otherwise + * + * @return {Matrix} C = P * A * Q, null on error + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csPermute(a, pinv, q, values) { + // a arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; + var adt = a._datatype; // rows & columns + + var m = asize[0]; + var n = asize[1]; // c arrays + + var cvalues = values && a._values ? [] : null; + var cindex = []; // (aptr[n]) + + var cptr = []; // (n + 1) + // initialize vars + + var nz = 0; // loop columns + + for (var k = 0; k < n; k++) { + // column k of C is column q[k] of A + cptr[k] = nz; // apply column permutation + + var j = q ? q[k] : k; // loop values in column j of A + + for (var t0 = aptr[j], t1 = aptr[j + 1], t = t0; t < t1; t++) { + // row i of A is row pinv[i] of C + var r = pinv ? pinv[aindex[t]] : aindex[t]; // index + + cindex[nz] = r; // check we need to populate values + + if (cvalues) { + cvalues[nz] = avalues[t]; + } // increment number of nonzero elements + + + nz++; + } + } // finalize the last column of C + + + cptr[n] = nz; // return C matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [m, n], + datatype: adt + }); +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csTdfs.js +/** + * Depth-first search and postorder of a tree rooted at node j + * + * @param {Number} j The tree node + * @param {Number} k + * @param {Array} w The workspace array + * @param {Number} head The index offset within the workspace for the head array + * @param {Number} next The index offset within the workspace for the next array + * @param {Array} post The post ordering array + * @param {Number} stack The index offset within the workspace for the stack array + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csTdfs(j, k, w, head, next, post, stack) { + // variables + var top = 0; // place j on the stack + + w[stack] = j; // while (stack is not empty) + + while (top >= 0) { + // p = top of stack + var p = w[stack + top]; // i = youngest child of p + + var i = w[head + p]; + + if (i === -1) { + // p has no unordered children left + top--; // node p is the kth postordered node + + post[k++] = p; + } else { + // remove i from children of p + w[head + p] = w[next + i]; // increment top + + ++top; // start dfs on child node i + + w[stack + top] = i; + } + } + + return k; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csPost.js + +/** + * Post order a tree of forest + * + * @param {Array} parent The tree or forest + * @param {Number} n Number of columns + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + +function csPost(parent, n) { + // check inputs + if (!parent) { + return null; + } // vars + + + var k = 0; + var j; // allocate result + + var post = []; // (n) + // workspace, head: first n entries, next: next n entries, stack: last n entries + + var w = []; // (3 * n) + + var head = 0; + var next = n; + var stack = 2 * n; // initialize workspace + + for (j = 0; j < n; j++) { + // empty linked lists + w[head + j] = -1; + } // traverse nodes in reverse order + + + for (j = n - 1; j >= 0; j--) { + // check j is a root + if (parent[j] === -1) { + continue; + } // add j to list of its parent + + + w[next + j] = w[head + parent[j]]; + w[head + parent[j]] = j; + } // loop nodes + + + for (j = 0; j < n; j++) { + // skip j if it is not a root + if (parent[j] !== -1) { + continue; + } // depth-first search + + + k = csTdfs(j, k, w, head, next, post, stack); + } + + return post; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csEtree.js +/** + * Computes the elimination tree of Matrix A (using triu(A)) or the + * elimination tree of A'A without forming A'A. + * + * @param {Matrix} a The A Matrix + * @param {boolean} ata A value of true the function computes the etree of A'A + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csEtree(a, ata) { + // check inputs + if (!a) { + return null; + } // a arrays + + + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; // rows & columns + + var m = asize[0]; + var n = asize[1]; // allocate result + + var parent = []; // (n) + // allocate workspace + + var w = []; // (n + (ata ? m : 0)) + + var ancestor = 0; // first n entries in w + + var prev = n; // last m entries (ata = true) + + var i, inext; // check we are calculating A'A + + if (ata) { + // initialize workspace + for (i = 0; i < m; i++) { + w[prev + i] = -1; + } + } // loop columns + + + for (var k = 0; k < n; k++) { + // node k has no parent yet + parent[k] = -1; // nor does k have an ancestor + + w[ancestor + k] = -1; // values in column k + + for (var p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) { + // row + var r = aindex[p]; // node + + i = ata ? w[prev + r] : r; // traverse from i to k + + for (; i !== -1 && i < k; i = inext) { + // inext = ancestor of i + inext = w[ancestor + i]; // path compression + + w[ancestor + i] = k; // check no anc., parent is k + + if (inext === -1) { + parent[i] = k; + } + } + + if (ata) { + w[prev + r] = k; + } + } + } + + return parent; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csFkeep.js +/** + * Keeps entries in the matrix when the callback function returns true, removes the entry otherwise + * + * @param {Matrix} a The sparse matrix + * @param {function} callback The callback function, function will be invoked with the following args: + * - The entry row + * - The entry column + * - The entry value + * - The state parameter + * @param {any} other The state + * + * @return The number of nonzero elements in the matrix + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csFkeep(a, callback, other) { + // a arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; // columns + + var n = asize[1]; // nonzero items + + var nz = 0; // loop columns + + for (var j = 0; j < n; j++) { + // get current location of col j + var p = aptr[j]; // record new location of col j + + aptr[j] = nz; + + for (; p < aptr[j + 1]; p++) { + // check we need to keep this item + if (callback(aindex[p], j, avalues ? avalues[p] : 1, other)) { + // keep A(i,j) + aindex[nz] = aindex[p]; // check we need to process values (pattern only) + + if (avalues) { + avalues[nz] = avalues[p]; + } // increment nonzero items + + + nz++; + } + } + } // finalize A + + + aptr[n] = nz; // trim arrays + + aindex.splice(nz, aindex.length - nz); // check we need to process values (pattern only) + + if (avalues) { + avalues.splice(nz, avalues.length - nz); + } // return number of nonzero items + + + return nz; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csFlip.js +/** + * This function "flips" its input about the integer -1. + * + * @param {Number} i The value to flip + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csFlip(i) { + // flip the value + return -i - 2; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csAmd.js + + + + +var csAmd_name = 'csAmd'; +var csAmd_dependencies = ['add', 'multiply', 'transpose']; +var createCsAmd = /* #__PURE__ */Object(factory["a" /* factory */])(csAmd_name, csAmd_dependencies, function (_ref) { + var add = _ref.add, + multiply = _ref.multiply, + transpose = _ref.transpose; + + /** + * Approximate minimum degree ordering. The minimum degree algorithm is a widely used + * heuristic for finding a permutation P so that P*A*P' has fewer nonzeros in its factorization + * than A. It is a gready method that selects the sparsest pivot row and column during the course + * of a right looking sparse Cholesky factorization. + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + * + * @param {Number} order 0: Natural, 1: Cholesky, 2: LU, 3: QR + * @param {Matrix} m Sparse Matrix + */ + return function csAmd(order, a) { + // check input parameters + if (!a || order <= 0 || order > 3) { + return null; + } // a matrix arrays + + + var asize = a._size; // rows and columns + + var m = asize[0]; + var n = asize[1]; // initialize vars + + var lemax = 0; // dense threshold + + var dense = Math.max(16, 10 * Math.sqrt(n)); + dense = Math.min(n - 2, dense); // create target matrix C + + var cm = _createTargetMatrix(order, a, m, n, dense); // drop diagonal entries + + + csFkeep(cm, _diag, null); // C matrix arrays + + var cindex = cm._index; + var cptr = cm._ptr; // number of nonzero elements in C + + var cnz = cptr[n]; // allocate result (n+1) + + var P = []; // create workspace (8 * (n + 1)) + + var W = []; + var len = 0; // first n + 1 entries + + var nv = n + 1; // next n + 1 entries + + var next = 2 * (n + 1); // next n + 1 entries + + var head = 3 * (n + 1); // next n + 1 entries + + var elen = 4 * (n + 1); // next n + 1 entries + + var degree = 5 * (n + 1); // next n + 1 entries + + var w = 6 * (n + 1); // next n + 1 entries + + var hhead = 7 * (n + 1); // last n + 1 entries + // use P as workspace for last + + var last = P; // initialize quotient graph + + var mark = _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree); // initialize degree lists + + + var nel = _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next); // minimum degree node + + + var mindeg = 0; // vars + + var i, j, k, k1, k2, e, pj, ln, nvi, pk, eln, p1, p2, pn, h, d; // while (selecting pivots) do + + while (nel < n) { + // select node of minimum approximate degree. amd() is now ready to start eliminating the graph. It first + // finds a node k of minimum degree and removes it from its degree list. The variable nel keeps track of thow + // many nodes have been eliminated. + for (k = -1; mindeg < n && (k = W[head + mindeg]) === -1; mindeg++) { + ; + } + + if (W[next + k] !== -1) { + last[W[next + k]] = -1; + } // remove k from degree list + + + W[head + mindeg] = W[next + k]; // elenk = |Ek| + + var elenk = W[elen + k]; // # of nodes k represents + + var nvk = W[nv + k]; // W[nv + k] nodes of A eliminated + + nel += nvk; // Construct a new element. The new element Lk is constructed in place if |Ek| = 0. nv[i] is + // negated for all nodes i in Lk to flag them as members of this set. Each node i is removed from the + // degree lists. All elements e in Ek are absorved into element k. + + var dk = 0; // flag k as in Lk + + W[nv + k] = -nvk; + var p = cptr[k]; // do in place if W[elen + k] === 0 + + var pk1 = elenk === 0 ? p : cnz; + var pk2 = pk1; + + for (k1 = 1; k1 <= elenk + 1; k1++) { + if (k1 > elenk) { + // search the nodes in k + e = k; // list of nodes starts at cindex[pj] + + pj = p; // length of list of nodes in k + + ln = W[len + k] - elenk; + } else { + // search the nodes in e + e = cindex[p++]; + pj = cptr[e]; // length of list of nodes in e + + ln = W[len + e]; + } + + for (k2 = 1; k2 <= ln; k2++) { + i = cindex[pj++]; // check node i dead, or seen + + if ((nvi = W[nv + i]) <= 0) { + continue; + } // W[degree + Lk] += size of node i + + + dk += nvi; // negate W[nv + i] to denote i in Lk + + W[nv + i] = -nvi; // place i in Lk + + cindex[pk2++] = i; + + if (W[next + i] !== -1) { + last[W[next + i]] = last[i]; + } // check we need to remove i from degree list + + + if (last[i] !== -1) { + W[next + last[i]] = W[next + i]; + } else { + W[head + W[degree + i]] = W[next + i]; + } + } + + if (e !== k) { + // absorb e into k + cptr[e] = csFlip(k); // e is now a dead element + + W[w + e] = 0; + } + } // cindex[cnz...nzmax] is free + + + if (elenk !== 0) { + cnz = pk2; + } // external degree of k - |Lk\i| + + + W[degree + k] = dk; // element k is in cindex[pk1..pk2-1] + + cptr[k] = pk1; + W[len + k] = pk2 - pk1; // k is now an element + + W[elen + k] = -2; // Find set differences. The scan1 function now computes the set differences |Le \ Lk| for all elements e. At the start of the + // scan, no entry in the w array is greater than or equal to mark. + // clear w if necessary + + mark = _wclear(mark, lemax, W, w, n); // scan 1: find |Le\Lk| + + for (pk = pk1; pk < pk2; pk++) { + i = cindex[pk]; // check if W[elen + i] empty, skip it + + if ((eln = W[elen + i]) <= 0) { + continue; + } // W[nv + i] was negated + + + nvi = -W[nv + i]; + var wnvi = mark - nvi; // scan Ei + + for (p = cptr[i], p1 = cptr[i] + eln - 1; p <= p1; p++) { + e = cindex[p]; + + if (W[w + e] >= mark) { + // decrement |Le\Lk| + W[w + e] -= nvi; + } else if (W[w + e] !== 0) { + // ensure e is a live element, 1st time e seen in scan 1 + W[w + e] = W[degree + e] + wnvi; + } + } + } // degree update + // The second pass computes the approximate degree di, prunes the sets Ei and Ai, and computes a hash + // function h(i) for all nodes in Lk. + // scan2: degree update + + + for (pk = pk1; pk < pk2; pk++) { + // consider node i in Lk + i = cindex[pk]; + p1 = cptr[i]; + p2 = p1 + W[elen + i] - 1; + pn = p1; // scan Ei + + for (h = 0, d = 0, p = p1; p <= p2; p++) { + e = cindex[p]; // check e is an unabsorbed element + + if (W[w + e] !== 0) { + // dext = |Le\Lk| + var dext = W[w + e] - mark; + + if (dext > 0) { + // sum up the set differences + d += dext; // keep e in Ei + + cindex[pn++] = e; // compute the hash of node i + + h += e; + } else { + // aggressive absorb. e->k + cptr[e] = csFlip(k); // e is a dead element + + W[w + e] = 0; + } + } + } // W[elen + i] = |Ei| + + + W[elen + i] = pn - p1 + 1; + var p3 = pn; + var p4 = p1 + W[len + i]; // prune edges in Ai + + for (p = p2 + 1; p < p4; p++) { + j = cindex[p]; // check node j dead or in Lk + + var nvj = W[nv + j]; + + if (nvj <= 0) { + continue; + } // degree(i) += |j| + + + d += nvj; // place j in node list of i + + cindex[pn++] = j; // compute hash for node i + + h += j; + } // check for mass elimination + + + if (d === 0) { + // absorb i into k + cptr[i] = csFlip(k); + nvi = -W[nv + i]; // |Lk| -= |i| + + dk -= nvi; // |k| += W[nv + i] + + nvk += nvi; + nel += nvi; + W[nv + i] = 0; // node i is dead + + W[elen + i] = -1; + } else { + // update degree(i) + W[degree + i] = Math.min(W[degree + i], d); // move first node to end + + cindex[pn] = cindex[p3]; // move 1st el. to end of Ei + + cindex[p3] = cindex[p1]; // add k as 1st element in of Ei + + cindex[p1] = k; // new len of adj. list of node i + + W[len + i] = pn - p1 + 1; // finalize hash of i + + h = (h < 0 ? -h : h) % n; // place i in hash bucket + + W[next + i] = W[hhead + h]; + W[hhead + h] = i; // save hash of i in last[i] + + last[i] = h; + } + } // finalize |Lk| + + + W[degree + k] = dk; + lemax = Math.max(lemax, dk); // clear w + + mark = _wclear(mark + lemax, lemax, W, w, n); // Supernode detection. Supernode detection relies on the hash function h(i) computed for each node i. + // If two nodes have identical adjacency lists, their hash functions wil be identical. + + for (pk = pk1; pk < pk2; pk++) { + i = cindex[pk]; // check i is dead, skip it + + if (W[nv + i] >= 0) { + continue; + } // scan hash bucket of node i + + + h = last[i]; + i = W[hhead + h]; // hash bucket will be empty + + W[hhead + h] = -1; + + for (; i !== -1 && W[next + i] !== -1; i = W[next + i], mark++) { + ln = W[len + i]; + eln = W[elen + i]; + + for (p = cptr[i] + 1; p <= cptr[i] + ln - 1; p++) { + W[w + cindex[p]] = mark; + } + + var jlast = i; // compare i with all j + + for (j = W[next + i]; j !== -1;) { + var ok = W[len + j] === ln && W[elen + j] === eln; + + for (p = cptr[j] + 1; ok && p <= cptr[j] + ln - 1; p++) { + // compare i and j + if (W[w + cindex[p]] !== mark) { + ok = 0; + } + } // check i and j are identical + + + if (ok) { + // absorb j into i + cptr[j] = csFlip(i); + W[nv + i] += W[nv + j]; + W[nv + j] = 0; // node j is dead + + W[elen + j] = -1; // delete j from hash bucket + + j = W[next + j]; + W[next + jlast] = j; + } else { + // j and i are different + jlast = j; + j = W[next + j]; + } + } + } + } // Finalize new element. The elimination of node k is nearly complete. All nodes i in Lk are scanned one last time. + // Node i is removed from Lk if it is dead. The flagged status of nv[i] is cleared. + + + for (p = pk1, pk = pk1; pk < pk2; pk++) { + i = cindex[pk]; // check i is dead, skip it + + if ((nvi = -W[nv + i]) <= 0) { + continue; + } // restore W[nv + i] + + + W[nv + i] = nvi; // compute external degree(i) + + d = W[degree + i] + dk - nvi; + d = Math.min(d, n - nel - nvi); + + if (W[head + d] !== -1) { + last[W[head + d]] = i; + } // put i back in degree list + + + W[next + i] = W[head + d]; + last[i] = -1; + W[head + d] = i; // find new minimum degree + + mindeg = Math.min(mindeg, d); + W[degree + i] = d; // place i in Lk + + cindex[p++] = i; + } // # nodes absorbed into k + + + W[nv + k] = nvk; // length of adj list of element k + + if ((W[len + k] = p - pk1) === 0) { + // k is a root of the tree + cptr[k] = -1; // k is now a dead element + + W[w + k] = 0; + } + + if (elenk !== 0) { + // free unused space in Lk + cnz = p; + } + } // Postordering. The elimination is complete, but no permutation has been computed. All that is left + // of the graph is the assembly tree (ptr) and a set of dead nodes and elements (i is a dead node if + // nv[i] is zero and a dead element if nv[i] > 0). It is from this information only that the final permutation + // is computed. The tree is restored by unflipping all of ptr. + // fix assembly tree + + + for (i = 0; i < n; i++) { + cptr[i] = csFlip(cptr[i]); + } + + for (j = 0; j <= n; j++) { + W[head + j] = -1; + } // place unordered nodes in lists + + + for (j = n; j >= 0; j--) { + // skip if j is an element + if (W[nv + j] > 0) { + continue; + } // place j in list of its parent + + + W[next + j] = W[head + cptr[j]]; + W[head + cptr[j]] = j; + } // place elements in lists + + + for (e = n; e >= 0; e--) { + // skip unless e is an element + if (W[nv + e] <= 0) { + continue; + } + + if (cptr[e] !== -1) { + // place e in list of its parent + W[next + e] = W[head + cptr[e]]; + W[head + cptr[e]] = e; + } + } // postorder the assembly tree + + + for (k = 0, i = 0; i <= n; i++) { + if (cptr[i] === -1) { + k = csTdfs(i, k, W, head, next, P, w); + } + } // remove last item in array + + + P.splice(P.length - 1, 1); // return P + + return P; + }; + /** + * Creates the matrix that will be used by the approximate minimum degree ordering algorithm. The function accepts the matrix M as input and returns a permutation + * vector P. The amd algorithm operates on a symmetrix matrix, so one of three symmetric matrices is formed. + * + * Order: 0 + * A natural ordering P=null matrix is returned. + * + * Order: 1 + * Matrix must be square. This is appropriate for a Cholesky or LU factorization. + * P = M + M' + * + * Order: 2 + * Dense columns from M' are dropped, M recreated from M'. This is appropriatefor LU factorization of unsymmetric matrices. + * P = M' * M + * + * Order: 3 + * This is best used for QR factorization or LU factorization is matrix M has no dense rows. A dense row is a row with more than 10*sqr(columns) entries. + * P = M' * M + */ + + function _createTargetMatrix(order, a, m, n, dense) { + // compute A' + var at = transpose(a); // check order = 1, matrix must be square + + if (order === 1 && n === m) { + // C = A + A' + return add(a, at); + } // check order = 2, drop dense columns from M' + + + if (order === 2) { + // transpose arrays + var tindex = at._index; + var tptr = at._ptr; // new column index + + var p2 = 0; // loop A' columns (rows) + + for (var j = 0; j < m; j++) { + // column j of AT starts here + var p = tptr[j]; // new column j starts here + + tptr[j] = p2; // skip dense col j + + if (tptr[j + 1] - p > dense) { + continue; + } // map rows in column j of A + + + for (var p1 = tptr[j + 1]; p < p1; p++) { + tindex[p2++] = tindex[p]; + } + } // finalize AT + + + tptr[m] = p2; // recreate A from new transpose matrix + + a = transpose(at); // use A' * A + + return multiply(at, a); + } // use A' * A, square or rectangular matrix + + + return multiply(at, a); + } + /** + * Initialize quotient graph. There are four kind of nodes and elements that must be represented: + * + * - A live node is a node i (or a supernode) that has not been selected as a pivot nad has not been merged into another supernode. + * - A dead node i is one that has been removed from the graph, having been absorved into r = flip(ptr[i]). + * - A live element e is one that is in the graph, having been formed when node e was selected as the pivot. + * - A dead element e is one that has benn absorved into a subsequent element s = flip(ptr[e]). + */ + + + function _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree) { + // Initialize quotient graph + for (var k = 0; k < n; k++) { + W[len + k] = cptr[k + 1] - cptr[k]; + } + + W[len + n] = 0; // initialize workspace + + for (var i = 0; i <= n; i++) { + // degree list i is empty + W[head + i] = -1; + last[i] = -1; + W[next + i] = -1; // hash list i is empty + + W[hhead + i] = -1; // node i is just one node + + W[nv + i] = 1; // node i is alive + + W[w + i] = 1; // Ek of node i is empty + + W[elen + i] = 0; // degree of node i + + W[degree + i] = W[len + i]; + } // clear w + + + var mark = _wclear(0, 0, W, w, n); // n is a dead element + + + W[elen + n] = -2; // n is a root of assembly tree + + cptr[n] = -1; // n is a dead element + + W[w + n] = 0; // return mark + + return mark; + } + /** + * Initialize degree lists. Each node is placed in its degree lists. Nodes of zero degree are eliminated immediately. Nodes with + * degree >= dense are alsol eliminated and merged into a placeholder node n, a dead element. Thes nodes will appera last in the + * output permutation p. + */ + + + function _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next) { + // result + var nel = 0; // loop columns + + for (var i = 0; i < n; i++) { + // degree @ i + var d = W[degree + i]; // check node i is empty + + if (d === 0) { + // element i is dead + W[elen + i] = -2; + nel++; // i is a root of assembly tree + + cptr[i] = -1; + W[w + i] = 0; + } else if (d > dense) { + // absorb i into element n + W[nv + i] = 0; // node i is dead + + W[elen + i] = -1; + nel++; + cptr[i] = csFlip(n); + W[nv + n]++; + } else { + var h = W[head + d]; + + if (h !== -1) { + last[h] = i; + } // put node i in degree list d + + + W[next + i] = W[head + d]; + W[head + d] = i; + } + } + + return nel; + } + + function _wclear(mark, lemax, W, w, n) { + if (mark < 2 || mark + lemax < 0) { + for (var k = 0; k < n; k++) { + if (W[w + k] !== 0) { + W[w + k] = 1; + } + } + + mark = 2; + } // at this point, W [0..n-1] < mark holds + + + return mark; + } + + function _diag(i, j) { + return i !== j; + } +}); +// CONCATENATED MODULE: ./src/function/algebra/sparse/csLeaf.js +/** + * This function determines if j is a leaf of the ith row subtree. + * Consider A(i,j), node j in ith row subtree and return lca(jprev,j) + * + * @param {Number} i The ith row subtree + * @param {Number} j The node to test + * @param {Array} w The workspace array + * @param {Number} first The index offset within the workspace for the first array + * @param {Number} maxfirst The index offset within the workspace for the maxfirst array + * @param {Number} prevleaf The index offset within the workspace for the prevleaf array + * @param {Number} ancestor The index offset within the workspace for the ancestor array + * + * @return {Object} + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor) { + var s, sparent; // our result + + var jleaf = 0; + var q; // check j is a leaf + + if (i <= j || w[first + j] <= w[maxfirst + i]) { + return -1; + } // update max first[j] seen so far + + + w[maxfirst + i] = w[first + j]; // jprev = previous leaf of ith subtree + + var jprev = w[prevleaf + i]; + w[prevleaf + i] = j; // check j is first or subsequent leaf + + if (jprev === -1) { + // 1st leaf, q = root of ith subtree + jleaf = 1; + q = i; + } else { + // update jleaf + jleaf = 2; // q = least common ancester (jprev,j) + + for (q = jprev; q !== w[ancestor + q]; q = w[ancestor + q]) { + ; + } + + for (s = jprev; s !== q; s = sparent) { + // path compression + sparent = w[ancestor + s]; + w[ancestor + s] = q; + } + } + + return { + jleaf: jleaf, + q: q + }; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csCounts.js + + +var csCounts_name = 'csCounts'; +var csCounts_dependencies = ['transpose']; +var createCsCounts = /* #__PURE__ */Object(factory["a" /* factory */])(csCounts_name, csCounts_dependencies, function (_ref) { + var transpose = _ref.transpose; + + /** + * Computes the column counts using the upper triangular part of A. + * It transposes A internally, none of the input parameters are modified. + * + * @param {Matrix} a The sparse matrix A + * + * @param {Matrix} ata Count the columns of A'A instead + * + * @return An array of size n of the column counts or null on error + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + return function (a, parent, post, ata) { + // check inputs + if (!a || !parent || !post) { + return null; + } // a matrix arrays + + + var asize = a._size; // rows and columns + + var m = asize[0]; + var n = asize[1]; // variables + + var i, j, k, J, p, p0, p1; // workspace size + + var s = 4 * n + (ata ? n + m + 1 : 0); // allocate workspace + + var w = []; // (s) + + var ancestor = 0; // first n entries + + var maxfirst = n; // next n entries + + var prevleaf = 2 * n; // next n entries + + var first = 3 * n; // next n entries + + var head = 4 * n; // next n + 1 entries (used when ata is true) + + var next = 5 * n + 1; // last entries in workspace + // clear workspace w[0..s-1] + + for (k = 0; k < s; k++) { + w[k] = -1; + } // allocate result + + + var colcount = []; // (n) + // AT = A' + + var at = transpose(a); // at arrays + + var tindex = at._index; + var tptr = at._ptr; // find w[first + j] + + for (k = 0; k < n; k++) { + j = post[k]; // colcount[j]=1 if j is a leaf + + colcount[j] = w[first + j] === -1 ? 1 : 0; + + for (; j !== -1 && w[first + j] === -1; j = parent[j]) { + w[first + j] = k; + } + } // initialize ata if needed + + + if (ata) { + // invert post + for (k = 0; k < n; k++) { + w[post[k]] = k; + } // loop rows (columns in AT) + + + for (i = 0; i < m; i++) { + // values in column i of AT + for (k = n, p0 = tptr[i], p1 = tptr[i + 1], p = p0; p < p1; p++) { + k = Math.min(k, w[tindex[p]]); + } // place row i in linked list k + + + w[next + i] = w[head + k]; + w[head + k] = i; + } + } // each node in its own set + + + for (i = 0; i < n; i++) { + w[ancestor + i] = i; + } + + for (k = 0; k < n; k++) { + // j is the kth node in postordered etree + j = post[k]; // check j is not a root + + if (parent[j] !== -1) { + colcount[parent[j]]--; + } // J=j for LL'=A case + + + for (J = ata ? w[head + k] : j; J !== -1; J = ata ? w[next + J] : -1) { + for (p = tptr[J]; p < tptr[J + 1]; p++) { + i = tindex[p]; + var r = csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor); // check A(i,j) is in skeleton + + if (r.jleaf >= 1) { + colcount[j]++; + } // check account for overlap in q + + + if (r.jleaf === 2) { + colcount[r.q]--; + } + } + } + + if (parent[j] !== -1) { + w[ancestor + j] = parent[j]; + } + } // sum up colcount's of each child + + + for (j = 0; j < n; j++) { + if (parent[j] !== -1) { + colcount[parent[j]] += colcount[j]; + } + } + + return colcount; + }; +}); +// CONCATENATED MODULE: ./src/function/algebra/sparse/csSqr.js + + + + + + +var csSqr_name = 'csSqr'; +var csSqr_dependencies = ['add', 'multiply', 'transpose']; +var createCsSqr = /* #__PURE__ */Object(factory["a" /* factory */])(csSqr_name, csSqr_dependencies, function (_ref) { + var add = _ref.add, + multiply = _ref.multiply, + transpose = _ref.transpose; + var csAmd = createCsAmd({ + add: add, + multiply: multiply, + transpose: transpose + }); + var csCounts = createCsCounts({ + transpose: transpose + }); + /** + * Symbolic ordering and analysis for QR and LU decompositions. + * + * @param {Number} order The ordering strategy (see csAmd for more details) + * @param {Matrix} a The A matrix + * @param {boolean} qr Symbolic ordering and analysis for QR decomposition (true) or + * symbolic ordering and analysis for LU decomposition (false) + * + * @return {Object} The Symbolic ordering and analysis for matrix A + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + + return function csSqr(order, a, qr) { + // a arrays + var aptr = a._ptr; + var asize = a._size; // columns + + var n = asize[1]; // vars + + var k; // symbolic analysis result + + var s = {}; // fill-reducing ordering + + s.q = csAmd(order, a); // validate results + + if (order && !s.q) { + return null; + } // QR symbolic analysis + + + if (qr) { + // apply permutations if needed + var c = order ? csPermute(a, null, s.q, 0) : a; // etree of C'*C, where C=A(:,q) + + s.parent = csEtree(c, 1); // post order elimination tree + + var post = csPost(s.parent, n); // col counts chol(C'*C) + + s.cp = csCounts(c, s.parent, post, 1); // check we have everything needed to calculate number of nonzero elements + + if (c && s.parent && s.cp && _vcount(c, s)) { + // calculate number of nonzero elements + for (s.unz = 0, k = 0; k < n; k++) { + s.unz += s.cp[k]; + } + } + } else { + // for LU factorization only, guess nnz(L) and nnz(U) + s.unz = 4 * aptr[n] + n; + s.lnz = s.unz; + } // return result S + + + return s; + }; + /** + * Compute nnz(V) = s.lnz, s.pinv, s.leftmost, s.m2 from A and s.parent + */ + + function _vcount(a, s) { + // a arrays + var aptr = a._ptr; + var aindex = a._index; + var asize = a._size; // rows & columns + + var m = asize[0]; + var n = asize[1]; // initialize s arrays + + s.pinv = []; // (m + n) + + s.leftmost = []; // (m) + // vars + + var parent = s.parent; + var pinv = s.pinv; + var leftmost = s.leftmost; // workspace, next: first m entries, head: next n entries, tail: next n entries, nque: next n entries + + var w = []; // (m + 3 * n) + + var next = 0; + var head = m; + var tail = m + n; + var nque = m + 2 * n; // vars + + var i, k, p, p0, p1; // initialize w + + for (k = 0; k < n; k++) { + // queue k is empty + w[head + k] = -1; + w[tail + k] = -1; + w[nque + k] = 0; + } // initialize row arrays + + + for (i = 0; i < m; i++) { + leftmost[i] = -1; + } // loop columns backwards + + + for (k = n - 1; k >= 0; k--) { + // values & index for column k + for (p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) { + // leftmost[i] = min(find(A(i,:))) + leftmost[aindex[p]] = k; + } + } // scan rows in reverse order + + + for (i = m - 1; i >= 0; i--) { + // row i is not yet ordered + pinv[i] = -1; + k = leftmost[i]; // check row i is empty + + if (k === -1) { + continue; + } // first row in queue k + + + if (w[nque + k]++ === 0) { + w[tail + k] = i; + } // put i at head of queue k + + + w[next + i] = w[head + k]; + w[head + k] = i; + } + + s.lnz = 0; + s.m2 = m; // find row permutation and nnz(V) + + for (k = 0; k < n; k++) { + // remove row i from queue k + i = w[head + k]; // count V(k,k) as nonzero + + s.lnz++; // add a fictitious row + + if (i < 0) { + i = s.m2++; + } // associate row i with V(:,k) + + + pinv[i] = k; // skip if V(k+1:m,k) is empty + + if (--nque[k] <= 0) { + continue; + } // nque[k] is nnz (V(k+1:m,k)) + + + s.lnz += w[nque + k]; // move all rows to parent of k + + var pa = parent[k]; + + if (pa !== -1) { + if (w[nque + pa] === 0) { + w[tail + pa] = w[tail + k]; + } + + w[next + w[tail + k]] = w[head + pa]; + w[head + pa] = w[next + i]; + w[nque + pa] += w[nque + k]; + } + } + + for (i = 0; i < m; i++) { + if (pinv[i] < 0) { + pinv[i] = k++; + } + } + + return true; + } +}); +// CONCATENATED MODULE: ./src/function/algebra/sparse/csMarked.js +/** + * Checks if the node at w[j] is marked + * + * @param {Array} w The array + * @param {Number} j The array index + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csMarked(w, j) { + // check node is marked + return w[j] < 0; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csMark.js + +/** + * Marks the node at w[j] + * + * @param {Array} w The array + * @param {Number} j The array index + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + +function csMark(w, j) { + // mark w[j] + w[j] = csFlip(w[j]); +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csUnflip.js + +/** + * Flips the value if it is negative of returns the same value otherwise. + * + * @param {Number} i The value to flip + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + +function csUnflip(i) { + // flip the value if it is negative + return i < 0 ? csFlip(i) : i; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csDfs.js + + + +/** + * Depth-first search computes the nonzero pattern xi of the directed graph G (Matrix) starting + * at nodes in B (see csReach()). + * + * @param {Number} j The starting node for the DFS algorithm + * @param {Matrix} g The G matrix to search, ptr array modified, then restored + * @param {Number} top Start index in stack xi[top..n-1] + * @param {Number} k The kth column in B + * @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n + * The first n entries is the nonzero pattern, the last n entries is the stack + * @param {Array} pinv The inverse row permutation vector, must be null for L * x = b + * + * @return {Number} New value of top + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + +function csDfs(j, g, top, xi, pinv) { + // g arrays + var index = g._index; + var ptr = g._ptr; + var size = g._size; // columns + + var n = size[1]; // vars + + var i, p, p2; // initialize head + + var head = 0; // initialize the recursion stack + + xi[0] = j; // loop + + while (head >= 0) { + // get j from the top of the recursion stack + j = xi[head]; // apply permutation vector + + var jnew = pinv ? pinv[j] : j; // check node j is marked + + if (!csMarked(ptr, j)) { + // mark node j as visited + csMark(ptr, j); // update stack (last n entries in xi) + + xi[n + head] = jnew < 0 ? 0 : csUnflip(ptr[jnew]); + } // node j done if no unvisited neighbors + + + var done = 1; // examine all neighbors of j, stack (last n entries in xi) + + for (p = xi[n + head], p2 = jnew < 0 ? 0 : csUnflip(ptr[jnew + 1]); p < p2; p++) { + // consider neighbor node i + i = index[p]; // check we have visited node i, skip it + + if (csMarked(ptr, i)) { + continue; + } // pause depth-first search of node j, update stack (last n entries in xi) + + + xi[n + head] = p; // start dfs at node i + + xi[++head] = i; // node j is not done + + done = 0; // break, to start dfs(i) + + break; + } // check depth-first search at node j is done + + + if (done) { + // remove j from the recursion stack + head--; // and place in the output stack + + xi[--top] = j; + } + } + + return top; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csReach.js + + + +/** + * The csReach function computes X = Reach(B), where B is the nonzero pattern of the n-by-1 + * sparse column of vector b. The function returns the set of nodes reachable from any node in B. The + * nonzero pattern xi of the solution x to the sparse linear system Lx=b is given by X=Reach(B). + * + * @param {Matrix} g The G matrix + * @param {Matrix} b The B matrix + * @param {Number} k The kth column in B + * @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n + * The first n entries is the nonzero pattern, the last n entries is the stack + * @param {Array} pinv The inverse row permutation vector + * + * @return {Number} The index for the nonzero pattern + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + +function csReach(g, b, k, xi, pinv) { + // g arrays + var gptr = g._ptr; + var gsize = g._size; // b arrays + + var bindex = b._index; + var bptr = b._ptr; // columns + + var n = gsize[1]; // vars + + var p, p0, p1; // initialize top + + var top = n; // loop column indeces in B + + for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) { + // node i + var i = bindex[p]; // check node i is marked + + if (!csMarked(gptr, i)) { + // start a dfs at unmarked node i + top = csDfs(i, g, top, xi, pinv); + } + } // loop columns from top -> n - 1 + + + for (p = top; p < n; p++) { + // restore G + csMark(gptr, xi[p]); + } + + return top; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csSpsolve.js + + +var csSpsolve_name = 'csSpsolve'; +var csSpsolve_dependencies = ['divideScalar', 'multiply', 'subtract']; +var createCsSpsolve = /* #__PURE__ */Object(factory["a" /* factory */])(csSpsolve_name, csSpsolve_dependencies, function (_ref) { + var divideScalar = _ref.divideScalar, + multiply = _ref.multiply, + subtract = _ref.subtract; + + /** + * The function csSpsolve() computes the solution to G * x = bk, where bk is the + * kth column of B. When lo is true, the function assumes G = L is lower triangular with the + * diagonal entry as the first entry in each column. When lo is true, the function assumes G = U + * is upper triangular with the diagonal entry as the last entry in each column. + * + * @param {Matrix} g The G matrix + * @param {Matrix} b The B matrix + * @param {Number} k The kth column in B + * @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n + * The first n entries is the nonzero pattern, the last n entries is the stack + * @param {Array} x The soluton to the linear system G * x = b + * @param {Array} pinv The inverse row permutation vector, must be null for L * x = b + * @param {boolean} lo The lower (true) upper triangular (false) flag + * + * @return {Number} The index for the nonzero pattern + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + return function csSpsolve(g, b, k, xi, x, pinv, lo) { + // g arrays + var gvalues = g._values; + var gindex = g._index; + var gptr = g._ptr; + var gsize = g._size; // columns + + var n = gsize[1]; // b arrays + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; // vars + + var p, p0, p1, q; // xi[top..n-1] = csReach(B(:,k)) + + var top = csReach(g, b, k, xi, pinv); // clear x + + for (p = top; p < n; p++) { + x[xi[p]] = 0; + } // scatter b + + + for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) { + x[bindex[p]] = bvalues[p]; + } // loop columns + + + for (var px = top; px < n; px++) { + // x array index for px + var j = xi[px]; // apply permutation vector (U x = b), j maps to column J of G + + var J = pinv ? pinv[j] : j; // check column J is empty + + if (J < 0) { + continue; + } // column value indeces in G, p0 <= p < p1 + + + p0 = gptr[J]; + p1 = gptr[J + 1]; // x(j) /= G(j,j) + + x[j] = divideScalar(x[j], gvalues[lo ? p0 : p1 - 1]); // first entry L(j,j) + + p = lo ? p0 + 1 : p0; + q = lo ? p1 : p1 - 1; // loop + + for (; p < q; p++) { + // row + var i = gindex[p]; // x(i) -= G(i,j) * x(j) + + x[i] = subtract(x[i], multiply(gvalues[p], x[j])); + } + } // return top of stack + + + return top; + }; +}); +// CONCATENATED MODULE: ./src/function/algebra/sparse/csLu.js + + +var csLu_name = 'csLu'; +var csLu_dependencies = ['abs', 'divideScalar', 'multiply', 'subtract', 'larger', 'largerEq', 'SparseMatrix']; +var createCsLu = /* #__PURE__ */Object(factory["a" /* factory */])(csLu_name, csLu_dependencies, function (_ref) { + var abs = _ref.abs, + divideScalar = _ref.divideScalar, + multiply = _ref.multiply, + subtract = _ref.subtract, + larger = _ref.larger, + largerEq = _ref.largerEq, + SparseMatrix = _ref.SparseMatrix; + var csSpsolve = createCsSpsolve({ + divideScalar: divideScalar, + multiply: multiply, + subtract: subtract + }); + /** + * Computes the numeric LU factorization of the sparse matrix A. Implements a Left-looking LU factorization + * algorithm that computes L and U one column at a tume. At the kth step, it access columns 1 to k-1 of L + * and column k of A. Given the fill-reducing column ordering q (see parameter s) computes L, U and pinv so + * L * U = A(p, q), where p is the inverse of pinv. + * + * @param {Matrix} m The A Matrix to factorize + * @param {Object} s The symbolic analysis from csSqr(). Provides the fill-reducing + * column ordering q + * @param {Number} tol Partial pivoting threshold (1 for partial pivoting) + * + * @return {Number} The numeric LU factorization of A or null + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + + return function csLu(m, s, tol) { + // validate input + if (!m) { + return null; + } // m arrays + + + var size = m._size; // columns + + var n = size[1]; // symbolic analysis result + + var q; + var lnz = 100; + var unz = 100; // update symbolic analysis parameters + + if (s) { + q = s.q; + lnz = s.lnz || lnz; + unz = s.unz || unz; + } // L arrays + + + var lvalues = []; // (lnz) + + var lindex = []; // (lnz) + + var lptr = []; // (n + 1) + // L + + var L = new SparseMatrix({ + values: lvalues, + index: lindex, + ptr: lptr, + size: [n, n] + }); // U arrays + + var uvalues = []; // (unz) + + var uindex = []; // (unz) + + var uptr = []; // (n + 1) + // U + + var U = new SparseMatrix({ + values: uvalues, + index: uindex, + ptr: uptr, + size: [n, n] + }); // inverse of permutation vector + + var pinv = []; // (n) + // vars + + var i, p; // allocate arrays + + var x = []; // (n) + + var xi = []; // (2 * n) + // initialize variables + + for (i = 0; i < n; i++) { + // clear workspace + x[i] = 0; // no rows pivotal yet + + pinv[i] = -1; // no cols of L yet + + lptr[i + 1] = 0; + } // reset number of nonzero elements in L and U + + + lnz = 0; + unz = 0; // compute L(:,k) and U(:,k) + + for (var k = 0; k < n; k++) { + // update ptr + lptr[k] = lnz; + uptr[k] = unz; // apply column permutations if needed + + var col = q ? q[k] : k; // solve triangular system, x = L\A(:,col) + + var top = csSpsolve(L, m, col, xi, x, pinv, 1); // find pivot + + var ipiv = -1; + var a = -1; // loop xi[] from top -> n + + for (p = top; p < n; p++) { + // x[i] is nonzero + i = xi[p]; // check row i is not yet pivotal + + if (pinv[i] < 0) { + // absolute value of x[i] + var xabs = abs(x[i]); // check absoulte value is greater than pivot value + + if (larger(xabs, a)) { + // largest pivot candidate so far + a = xabs; + ipiv = i; + } + } else { + // x(i) is the entry U(pinv[i],k) + uindex[unz] = pinv[i]; + uvalues[unz++] = x[i]; + } + } // validate we found a valid pivot + + + if (ipiv === -1 || a <= 0) { + return null; + } // update actual pivot column, give preference to diagonal value + + + if (pinv[col] < 0 && largerEq(abs(x[col]), multiply(a, tol))) { + ipiv = col; + } // the chosen pivot + + + var pivot = x[ipiv]; // last entry in U(:,k) is U(k,k) + + uindex[unz] = k; + uvalues[unz++] = pivot; // ipiv is the kth pivot row + + pinv[ipiv] = k; // first entry in L(:,k) is L(k,k) = 1 + + lindex[lnz] = ipiv; + lvalues[lnz++] = 1; // L(k+1:n,k) = x / pivot + + for (p = top; p < n; p++) { + // row + i = xi[p]; // check x(i) is an entry in L(:,k) + + if (pinv[i] < 0) { + // save unpermuted row in L + lindex[lnz] = i; // scale pivot column + + lvalues[lnz++] = divideScalar(x[i], pivot); + } // x[0..n-1] = 0 for next k + + + x[i] = 0; + } + } // update ptr + + + lptr[n] = lnz; + uptr[n] = unz; // fix row indices of L for final pinv + + for (p = 0; p < lnz; p++) { + lindex[p] = pinv[lindex[p]]; + } // trim arrays + + + lvalues.splice(lnz, lvalues.length - lnz); + lindex.splice(lnz, lindex.length - lnz); + uvalues.splice(unz, uvalues.length - unz); + uindex.splice(unz, uindex.length - unz); // return LU factor + + return { + L: L, + U: U, + pinv: pinv + }; + }; +}); +// CONCATENATED MODULE: ./src/function/algebra/decomposition/slu.js + + + + +var slu_name = 'slu'; +var slu_dependencies = ['typed', 'abs', 'add', 'multiply', 'transpose', 'divideScalar', 'subtract', 'larger', 'largerEq', 'SparseMatrix']; +var createSlu = /* #__PURE__ */Object(factory["a" /* factory */])(slu_name, slu_dependencies, function (_ref) { + var typed = _ref.typed, + abs = _ref.abs, + add = _ref.add, + multiply = _ref.multiply, + transpose = _ref.transpose, + divideScalar = _ref.divideScalar, + subtract = _ref.subtract, + larger = _ref.larger, + largerEq = _ref.largerEq, + SparseMatrix = _ref.SparseMatrix; + var csSqr = createCsSqr({ + add: add, + multiply: multiply, + transpose: transpose + }); + var csLu = createCsLu({ + abs: abs, + divideScalar: divideScalar, + multiply: multiply, + subtract: subtract, + larger: larger, + largerEq: largerEq, + SparseMatrix: SparseMatrix + }); + /** + * Calculate the Sparse Matrix LU decomposition with full pivoting. Sparse Matrix `A` is decomposed in two matrices (`L`, `U`) and two permutation vectors (`pinv`, `q`) where + * + * `P * A * Q = L * U` + * + * Syntax: + * + * math.slu(A, order, threshold) + * + * Examples: + * + * const A = math.sparse([[4,3], [6, 3]]) + * math.slu(A, 1, 0.001) + * // returns: + * // { + * // L: [[1, 0], [1.5, 1]] + * // U: [[4, 3], [0, -1.5]] + * // p: [0, 1] + * // q: [0, 1] + * // } + * + * See also: + * + * lup, lsolve, usolve, lusolve + * + * @param {SparseMatrix} A A two dimensional sparse matrix for which to get the LU decomposition. + * @param {Number} order The Symbolic Ordering and Analysis order: + * 0 - Natural ordering, no permutation vector q is returned + * 1 - Matrix must be square, symbolic ordering and analisis is performed on M = A + A' + * 2 - Symbolic ordering and analisis is performed on M = A' * A. Dense columns from A' are dropped, A recreated from A'. + * This is appropriatefor LU factorization of unsymmetric matrices. + * 3 - Symbolic ordering and analisis is performed on M = A' * A. This is best used for LU factorization is matrix M has no dense rows. + * A dense row is a row with more than 10*sqr(columns) entries. + * @param {Number} threshold Partial pivoting threshold (1 for partial pivoting) + * + * @return {Object} The lower triangular matrix, the upper triangular matrix and the permutation vectors. + */ + + return typed(slu_name, { + 'SparseMatrix, number, number': function SparseMatrixNumberNumber(a, order, threshold) { + // verify order + if (!Object(utils_number["i" /* isInteger */])(order) || order < 0 || order > 3) { + throw new Error('Symbolic Ordering and Analysis order must be an integer number in the interval [0, 3]'); + } // verify threshold + + + if (threshold < 0 || threshold > 1) { + throw new Error('Partial pivoting threshold must be a number from 0 to 1'); + } // perform symbolic ordering and analysis + + + var s = csSqr(order, a, false); // perform lu decomposition + + var f = csLu(a, s, threshold); // return decomposition + + return { + L: f.L, + U: f.U, + p: f.pinv, + q: s.q, + toString: function toString() { + return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\np: ' + this.p.toString() + (this.q ? '\nq: ' + this.q.toString() : '') + '\n'; + } + }; + } + }); +}); +// CONCATENATED MODULE: ./src/function/algebra/sparse/csIpvec.js +/** + * Permutes a vector; x = P'b. In MATLAB notation, x(p)=b. + * + * @param {Array} p The permutation vector of length n. null value denotes identity + * @param {Array} b The input vector + * + * @return {Array} The output vector x = P'b + */ +function csIpvec(p, b) { + // vars + var k; + var n = b.length; + var x = []; // check permutation vector was provided, p = null denotes identity + + if (p) { + // loop vector + for (k = 0; k < n; k++) { + // apply permutation + x[p[k]] = b[k]; + } + } else { + // loop vector + for (k = 0; k < n; k++) { + // x[i] = b[i] + x[k] = b[k]; + } + } + + return x; +} +// CONCATENATED MODULE: ./src/function/algebra/solver/lusolve.js + + + + +var lusolve_name = 'lusolve'; +var lusolve_dependencies = ['typed', 'matrix', 'lup', 'slu', 'usolve', 'lsolve', 'DenseMatrix']; +var createLusolve = /* #__PURE__ */Object(factory["a" /* factory */])(lusolve_name, lusolve_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + lup = _ref.lup, + slu = _ref.slu, + usolve = _ref.usolve, + lsolve = _ref.lsolve, + DenseMatrix = _ref.DenseMatrix; + var solveValidation = createSolveValidation({ + DenseMatrix: DenseMatrix + }); + /** + * Solves the linear system `A * x = b` where `A` is an [n x n] matrix and `b` is a [n] column vector. + * + * Syntax: + * + * math.lusolve(A, b) // returns column vector with the solution to the linear system A * x = b + * math.lusolve(lup, b) // returns column vector with the solution to the linear system A * x = b, lup = math.lup(A) + * + * Examples: + * + * const m = [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]] + * + * const x = math.lusolve(m, [-1, -1, -1, -1]) // x = [[-1], [-0.5], [-1/3], [-0.25]] + * + * const f = math.lup(m) + * const x1 = math.lusolve(f, [-1, -1, -1, -1]) // x1 = [[-1], [-0.5], [-1/3], [-0.25]] + * const x2 = math.lusolve(f, [1, 2, 1, -1]) // x2 = [[1], [1], [1/3], [-0.25]] + * + * const a = [[-2, 3], [2, 1]] + * const b = [11, 9] + * const x = math.lusolve(a, b) // [[2], [5]] + * + * See also: + * + * lup, slu, lsolve, usolve + * + * @param {Matrix | Array | Object} A Invertible Matrix or the Matrix LU decomposition + * @param {Matrix | Array} b Column Vector + * @param {number} [order] The Symbolic Ordering and Analysis order, see slu for details. Matrix must be a SparseMatrix + * @param {Number} [threshold] Partial pivoting threshold (1 for partial pivoting), see slu for details. Matrix must be a SparseMatrix. + * + * @return {DenseMatrix | Array} Column vector with the solution to the linear system A * x = b + */ + + return typed(lusolve_name, { + 'Array, Array | Matrix': function ArrayArrayMatrix(a, b) { + // convert a to matrix + a = matrix(a); // matrix lup decomposition + + var d = lup(a); // solve + + var x = _lusolve(d.L, d.U, d.p, null, b); // convert result to array + + + return x.valueOf(); + }, + 'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(a, b) { + // matrix lup decomposition + var d = lup(a); // solve + + return _lusolve(d.L, d.U, d.p, null, b); + }, + 'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(a, b) { + // matrix lup decomposition + var d = lup(a); // solve + + return _lusolve(d.L, d.U, d.p, null, b); + }, + 'SparseMatrix, Array | Matrix, number, number': function SparseMatrixArrayMatrixNumberNumber(a, b, order, threshold) { + // matrix lu decomposition + var d = slu(a, order, threshold); // solve + + return _lusolve(d.L, d.U, d.p, d.q, b); + }, + 'Object, Array | Matrix': function ObjectArrayMatrix(d, b) { + // solve + return _lusolve(d.L, d.U, d.p, d.q, b); + } + }); + + function _toMatrix(a) { + // check it is a matrix + if (Object(is["v" /* isMatrix */])(a)) { + return a; + } // check array + + + if (Object(is["b" /* isArray */])(a)) { + return matrix(a); + } // throw + + + throw new TypeError('Invalid Matrix LU decomposition'); + } + + function _lusolve(l, u, p, q, b) { + // verify L, U, P + l = _toMatrix(l); + u = _toMatrix(u); // validate matrix and vector + + b = solveValidation(l, b, false); // apply row permutations if needed (b is a DenseMatrix) + + if (p) { + b._data = csIpvec(p, b._data); + } // use forward substitution to resolve L * y = b + + + var y = lsolve(l, b); // use backward substitution to resolve U * x = y + + var x = usolve(u, y); // apply column permutations if needed (x is a DenseMatrix) + + if (q) { + x._data = csIpvec(q, x._data); + } // return solution + + + return x; + } +}); +// CONCATENATED MODULE: ./src/expression/Help.js + + + + +var Help_name = 'Help'; +var Help_dependencies = ['parse']; +var createHelpClass = /* #__PURE__ */Object(factory["a" /* factory */])(Help_name, Help_dependencies, function (_ref) { + var parse = _ref.parse; + + /** + * Documentation object + * @param {Object} doc Object containing properties: + * {string} name + * {string} category + * {string} description + * {string[]} syntax + * {string[]} examples + * {string[]} seealso + * @constructor + */ + function Help(doc) { + if (!(this instanceof Help)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (!doc) throw new Error('Argument "doc" missing'); + this.doc = doc; + } + /** + * Attach type information + */ + + + Help.prototype.type = 'Help'; + Help.prototype.isHelp = true; + /** + * Generate a string representation of the Help object + * @return {string} Returns a string + * @private + */ + + Help.prototype.toString = function () { + var doc = this.doc || {}; + var desc = '\n'; + + if (doc.name) { + desc += 'Name: ' + doc.name + '\n\n'; + } + + if (doc.category) { + desc += 'Category: ' + doc.category + '\n\n'; + } + + if (doc.description) { + desc += 'Description:\n ' + doc.description + '\n\n'; + } + + if (doc.syntax) { + desc += 'Syntax:\n ' + doc.syntax.join('\n ') + '\n\n'; + } + + if (doc.examples) { + desc += 'Examples:\n'; + var scope = {}; + + for (var i = 0; i < doc.examples.length; i++) { + var expr = doc.examples[i]; + desc += ' ' + expr + '\n'; + var res = void 0; + + try { + // note: res can be undefined when `expr` is an empty string + res = parse(expr).compile().evaluate(scope); + } catch (e) { + res = e; + } + + if (res !== undefined && !Object(is["s" /* isHelp */])(res)) { + desc += ' ' + Object(utils_string["d" /* format */])(res, { + precision: 14 + }) + '\n'; + } + } + + desc += '\n'; + } + + if (doc.seealso && doc.seealso.length) { + desc += 'See also: ' + doc.seealso.join(', ') + '\n'; + } + + return desc; + }; + /** + * Export the help object to JSON + */ + + + Help.prototype.toJSON = function () { + var obj = Object(utils_object["a" /* clone */])(this.doc); + obj.mathjs = 'Help'; + return obj; + }; + /** + * Instantiate a Help object from a JSON object + * @param {Object} json + * @returns {Help} Returns a new Help object + */ + + + Help.fromJSON = function (json) { + var doc = {}; + + for (var prop in json) { + if (prop !== 'mathjs') { + // ignore mathjs field + doc[prop] = json[prop]; + } + } + + return new Help(doc); + }; + /** + * Returns a string representation of the Help object + */ + + + Help.prototype.valueOf = Help.prototype.toString; + return Help; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/chain/Chain.js + + + + +var Chain_name = 'Chain'; +var Chain_dependencies = ['?on', 'math']; +var createChainClass = /* #__PURE__ */Object(factory["a" /* factory */])(Chain_name, Chain_dependencies, function (_ref) { + var on = _ref.on, + math = _ref.math; + + /** + * @constructor Chain + * Wrap any value in a chain, allowing to perform chained operations on + * the value. + * + * All methods available in the math.js library can be called upon the chain, + * and then will be evaluated with the value itself as first argument. + * The chain can be closed by executing chain.done(), which will return + * the final value. + * + * The Chain has a number of special functions: + * - done() Finalize the chained operation and return the + * chain's value. + * - valueOf() The same as done() + * - toString() Returns a string representation of the chain's value. + * + * @param {*} [value] + */ + function Chain(value) { + if (!(this instanceof Chain)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (Object(is["h" /* isChain */])(value)) { + this.value = value.value; + } else { + this.value = value; + } + } + /** + * Attach type information + */ + + + Chain.prototype.type = 'Chain'; + Chain.prototype.isChain = true; + /** + * Close the chain. Returns the final value. + * Does the same as method valueOf() + * @returns {*} value + */ + + Chain.prototype.done = function () { + return this.value; + }; + /** + * Close the chain. Returns the final value. + * Does the same as method done() + * @returns {*} value + */ + + + Chain.prototype.valueOf = function () { + return this.value; + }; + /** + * Get a string representation of the value in the chain + * @returns {string} + */ + + + Chain.prototype.toString = function () { + return Object(utils_string["d" /* format */])(this.value); + }; + /** + * Get a JSON representation of the chain + * @returns {Object} + */ + + + Chain.prototype.toJSON = function () { + return { + mathjs: 'Chain', + value: this.value + }; + }; + /** + * Instantiate a Chain from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "Chain", value: ...}`, + * where mathjs is optional + * @returns {Chain} + */ + + + Chain.fromJSON = function (json) { + return new Chain(json.value); + }; + /** + * Create a proxy method for the chain + * @param {string} name + * @param {Function} fn The function to be proxied + * If fn is no function, it is silently ignored. + * @private + */ + + + function createProxy(name, fn) { + if (typeof fn === 'function') { + Chain.prototype[name] = chainify(fn); + } + } + /** + * Create a proxy method for the chain + * @param {string} name + * @param {function} resolver The function resolving with the + * function to be proxied + * @private + */ + + + function createLazyProxy(name, resolver) { + Object(utils_object["h" /* lazy */])(Chain.prototype, name, function outerResolver() { + var fn = resolver(); + + if (typeof fn === 'function') { + return chainify(fn); + } + + return undefined; // if not a function, ignore + }); + } + /** + * Make a function chainable + * @param {function} fn + * @return {Function} chain function + * @private + */ + + + function chainify(fn) { + return function () { + var args = [this.value]; // `this` will be the context of a Chain instance + + for (var i = 0; i < arguments.length; i++) { + args[i + 1] = arguments[i]; + } + + return new Chain(fn.apply(fn, args)); + }; + } + /** + * Create a proxy for a single method, or an object with multiple methods. + * Example usage: + * + * Chain.createProxy('add', function add (x, y) {...}) + * Chain.createProxy({ + * add: function add (x, y) {...}, + * subtract: function subtract (x, y) {...} + * } + * + * @param {string | Object} arg0 A name (string), or an object with + * functions + * @param {*} [arg1] A function, when arg0 is a name + */ + + + Chain.createProxy = function (arg0, arg1) { + if (typeof arg0 === 'string') { + // createProxy(name, value) + createProxy(arg0, arg1); + } else { + var _loop = function _loop(_name) { + if (Object(utils_object["f" /* hasOwnProperty */])(arg0, _name) && excludedNames[_name] === undefined) { + createLazyProxy(_name, function () { + return arg0[_name]; + }); + } + }; + + // createProxy(values) + for (var _name in arg0) { + _loop(_name); + } + } + }; + + var excludedNames = { + expression: true, + docs: true, + type: true, + classes: true, + json: true, + error: true, + isChain: true // conflicts with the property isChain of a Chain instance + + }; // create proxy for everything that is in math.js + + Chain.createProxy(math); // register on the import event, automatically add a proxy for every imported function. + + if (on) { + on('import', function (name, resolver, path) { + if (!path) { + // an imported function (not a data type or something special) + createLazyProxy(name, resolver); + } + }); + } + + return Chain; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/bignumber.js +var bignumberDocs = { + name: 'bignumber', + category: 'Construction', + syntax: ['bignumber(x)'], + description: 'Create a big number from a number or string.', + examples: ['0.1 + 0.2', 'bignumber(0.1) + bignumber(0.2)', 'bignumber("7.2")', 'bignumber("7.2e500")', 'bignumber([0.1, 0.2, 0.3])'], + seealso: ['boolean', 'complex', 'fraction', 'index', 'matrix', 'string', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/typeOf.js +var typeOfDocs = { + name: 'typeOf', + category: 'Utils', + syntax: ['typeOf(x)'], + description: 'Get the type of a variable.', + examples: ['typeOf(3.5)', 'typeOf(2 - 4i)', 'typeOf(45 deg)', 'typeOf("hello world")'], + seealso: ['getMatrixDataType'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isZero.js +var isZeroDocs = { + name: 'isZero', + category: 'Utils', + syntax: ['isZero(x)'], + description: 'Test whether a value is zero.', + examples: ['isZero(2)', 'isZero(0)', 'isZero(-4)', 'isZero([3, 0, -2, 0])'], + seealso: ['isInteger', 'isNumeric', 'isNegative', 'isPositive'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isPrime.js +var isPrimeDocs = { + name: 'isPrime', + category: 'Utils', + syntax: ['isPrime(x)'], + description: 'Test whether a value is prime: has no divisors other than itself and one.', + examples: ['isPrime(3)', 'isPrime(-2)', 'isPrime([2, 17, 100])'], + seealso: ['isInteger', 'isNumeric', 'isNegative', 'isZero'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isPositive.js +var isPositiveDocs = { + name: 'isPositive', + category: 'Utils', + syntax: ['isPositive(x)'], + description: 'Test whether a value is positive: larger than zero.', + examples: ['isPositive(2)', 'isPositive(0)', 'isPositive(-4)', 'isPositive([3, 0.5, -2])'], + seealso: ['isInteger', 'isNumeric', 'isNegative', 'isZero'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isNumeric.js +var isNumericDocs = { + name: 'isNumeric', + category: 'Utils', + syntax: ['isNumeric(x)'], + description: 'Test whether a value is a numeric value. ' + 'Returns true when the input is a number, BigNumber, Fraction, or boolean.', + examples: ['isNumeric(2)', 'isNumeric("2")', 'hasNumericValue("2")', 'isNumeric(0)', 'isNumeric(bignumber(500))', 'isNumeric(fraction(0.125))', 'isNumeric(2 + 3i)', 'isNumeric([2.3, "foo", false])'], + seealso: ['isInteger', 'isZero', 'isNegative', 'isPositive', 'isNaN', 'hasNumericValue'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/hasNumericValue.js +var hasNumericValueDocs = { + name: 'hasNumericValue', + category: 'Utils', + syntax: ['hasNumericValue(x)'], + description: 'Test whether a value is an numeric value. ' + 'In case of a string, true is returned if the string contains a numeric value.', + examples: ['hasNumericValue(2)', 'hasNumericValue("2")', 'isNumeric("2")', 'hasNumericValue(0)', 'hasNumericValue(bignumber(500))', 'hasNumericValue(fraction(0.125))', 'hasNumericValue(2 + 3i)', 'hasNumericValue([2.3, "foo", false])'], + seealso: ['isInteger', 'isZero', 'isNegative', 'isPositive', 'isNaN', 'isNumeric'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isNegative.js +var isNegativeDocs = { + name: 'isNegative', + category: 'Utils', + syntax: ['isNegative(x)'], + description: 'Test whether a value is negative: smaller than zero.', + examples: ['isNegative(2)', 'isNegative(0)', 'isNegative(-4)', 'isNegative([3, 0.5, -2])'], + seealso: ['isInteger', 'isNumeric', 'isPositive', 'isZero'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isInteger.js +var isIntegerDocs = { + name: 'isInteger', + category: 'Utils', + syntax: ['isInteger(x)'], + description: 'Test whether a value is an integer number.', + examples: ['isInteger(2)', 'isInteger(3.5)', 'isInteger([3, 0.5, -2])'], + seealso: ['isNegative', 'isNumeric', 'isPositive', 'isZero'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isNaN.js +var isNaNDocs = { + name: 'isNaN', + category: 'Utils', + syntax: ['isNaN(x)'], + description: 'Test whether a value is NaN (not a number)', + examples: ['isNaN(2)', 'isNaN(0 / 0)', 'isNaN(NaN)', 'isNaN(Infinity)'], + seealso: ['isNegative', 'isNumeric', 'isPositive', 'isZero'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/format.js +var formatDocs = { + name: 'format', + category: 'Utils', + syntax: ['format(value)', 'format(value, precision)'], + description: 'Format a value of any type as string.', + examples: ['format(2.3)', 'format(3 - 4i)', 'format([])', 'format(pi, 3)'], + seealso: ['print'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/clone.js +var cloneDocs = { + name: 'clone', + category: 'Utils', + syntax: ['clone(x)'], + description: 'Clone a variable. Creates a copy of primitive variables,and a deep copy of matrices', + examples: ['clone(3.5)', 'clone(2 - 4i)', 'clone(45 deg)', 'clone([1, 2; 3, 4])', 'clone("hello world")'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/units/to.js +var toDocs = { + name: 'to', + category: 'Units', + syntax: ['x to unit', 'to(x, unit)'], + description: 'Change the unit of a value.', + examples: ['5 inch to cm', '3.2kg to g', '16 bytes in bits'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/tanh.js +var tanhDocs = { + name: 'tanh', + category: 'Trigonometry', + syntax: ['tanh(x)'], + description: 'Compute the hyperbolic tangent of x in radians.', + examples: ['tanh(0.5)', 'sinh(0.5) / cosh(0.5)'], + seealso: ['sinh', 'cosh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/tan.js +var tanDocs = { + name: 'tan', + category: 'Trigonometry', + syntax: ['tan(x)'], + description: 'Compute the tangent of x in radians.', + examples: ['tan(0.5)', 'sin(0.5) / cos(0.5)', 'tan(pi / 4)', 'tan(45 deg)'], + seealso: ['atan', 'sin', 'cos'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/sinh.js +var sinhDocs = { + name: 'sinh', + category: 'Trigonometry', + syntax: ['sinh(x)'], + description: 'Compute the hyperbolic sine of x in radians.', + examples: ['sinh(0.5)'], + seealso: ['cosh', 'tanh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/sech.js +var sechDocs = { + name: 'sech', + category: 'Trigonometry', + syntax: ['sech(x)'], + description: 'Compute the hyperbolic secant of x in radians. Defined as 1/cosh(x)', + examples: ['sech(2)', '1 / cosh(2)'], + seealso: ['coth', 'csch', 'cosh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/sec.js +var secDocs = { + name: 'sec', + category: 'Trigonometry', + syntax: ['sec(x)'], + description: 'Compute the secant of x in radians. Defined as 1/cos(x)', + examples: ['sec(2)', '1 / cos(2)'], + seealso: ['cot', 'csc', 'cos'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/csch.js +var cschDocs = { + name: 'csch', + category: 'Trigonometry', + syntax: ['csch(x)'], + description: 'Compute the hyperbolic cosecant of x in radians. Defined as 1/sinh(x)', + examples: ['csch(2)', '1 / sinh(2)'], + seealso: ['sech', 'coth', 'sinh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/csc.js +var cscDocs = { + name: 'csc', + category: 'Trigonometry', + syntax: ['csc(x)'], + description: 'Compute the cosecant of x in radians. Defined as 1/sin(x)', + examples: ['csc(2)', '1 / sin(2)'], + seealso: ['sec', 'cot', 'sin'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/coth.js +var cothDocs = { + name: 'coth', + category: 'Trigonometry', + syntax: ['coth(x)'], + description: 'Compute the hyperbolic cotangent of x in radians.', + examples: ['coth(2)', '1 / tanh(2)'], + seealso: ['sech', 'csch', 'tanh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/cot.js +var cotDocs = { + name: 'cot', + category: 'Trigonometry', + syntax: ['cot(x)'], + description: 'Compute the cotangent of x in radians. Defined as 1/tan(x)', + examples: ['cot(2)', '1 / tan(2)'], + seealso: ['sec', 'csc', 'tan'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/cosh.js +var coshDocs = { + name: 'cosh', + category: 'Trigonometry', + syntax: ['cosh(x)'], + description: 'Compute the hyperbolic cosine of x in radians.', + examples: ['cosh(0.5)'], + seealso: ['sinh', 'tanh', 'coth'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/cos.js +var cosDocs = { + name: 'cos', + category: 'Trigonometry', + syntax: ['cos(x)'], + description: 'Compute the cosine of x in radians.', + examples: ['cos(2)', 'cos(pi / 4) ^ 2', 'cos(180 deg)', 'cos(60 deg)', 'sin(0.2)^2 + cos(0.2)^2'], + seealso: ['acos', 'sin', 'tan'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/atan2.js +var atan2Docs = { + name: 'atan2', + category: 'Trigonometry', + syntax: ['atan2(y, x)'], + description: 'Computes the principal value of the arc tangent of y/x in radians.', + examples: ['atan2(2, 2) / pi', 'angle = 60 deg in rad', 'x = cos(angle)', 'y = sin(angle)', 'atan2(y, x)'], + seealso: ['sin', 'cos', 'tan'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/atanh.js +var atanhDocs = { + name: 'atanh', + category: 'Trigonometry', + syntax: ['atanh(x)'], + description: 'Calculate the hyperbolic arctangent of a value, defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.', + examples: ['atanh(0.5)'], + seealso: ['acosh', 'asinh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/atan.js +var atanDocs = { + name: 'atan', + category: 'Trigonometry', + syntax: ['atan(x)'], + description: 'Compute the inverse tangent of a value in radians.', + examples: ['atan(0.5)', 'atan(tan(0.5))'], + seealso: ['tan', 'acos', 'asin'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/asinh.js +var asinhDocs = { + name: 'asinh', + category: 'Trigonometry', + syntax: ['asinh(x)'], + description: 'Calculate the hyperbolic arcsine of a value, defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.', + examples: ['asinh(0.5)'], + seealso: ['acosh', 'atanh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/asin.js +var asinDocs = { + name: 'asin', + category: 'Trigonometry', + syntax: ['asin(x)'], + description: 'Compute the inverse sine of a value in radians.', + examples: ['asin(0.5)', 'asin(sin(0.5))'], + seealso: ['sin', 'acos', 'atan'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/asech.js +var asechDocs = { + name: 'asech', + category: 'Trigonometry', + syntax: ['asech(x)'], + description: 'Calculate the inverse secant of a value.', + examples: ['asech(0.5)'], + seealso: ['acsch', 'acoth'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/asec.js +var asecDocs = { + name: 'asec', + category: 'Trigonometry', + syntax: ['asec(x)'], + description: 'Calculate the inverse secant of a value.', + examples: ['asec(0.5)', 'asec(sec(0.5))', 'asec(2)'], + seealso: ['acos', 'acot', 'acsc'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acsch.js +var acschDocs = { + name: 'acsch', + category: 'Trigonometry', + syntax: ['acsch(x)'], + description: 'Calculate the hyperbolic arccosecant of a value, defined as `acsch(x) = ln(1/x + sqrt(1/x^2 + 1))`.', + examples: ['acsch(0.5)'], + seealso: ['asech', 'acoth'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acsc.js +var acscDocs = { + name: 'acsc', + category: 'Trigonometry', + syntax: ['acsc(x)'], + description: 'Calculate the inverse cotangent of a value.', + examples: ['acsc(2)', 'acsc(csc(0.5))', 'acsc(0.5)'], + seealso: ['csc', 'asin', 'asec'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acoth.js +var acothDocs = { + name: 'acoth', + category: 'Trigonometry', + syntax: ['acoth(x)'], + description: 'Calculate the hyperbolic arccotangent of a value, defined as `acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.', + examples: ['acoth(2)', 'acoth(0.5)'], + seealso: ['acsch', 'asech'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acot.js +var acotDocs = { + name: 'acot', + category: 'Trigonometry', + syntax: ['acot(x)'], + description: 'Calculate the inverse cotangent of a value.', + examples: ['acot(0.5)', 'acot(cot(0.5))', 'acot(2)'], + seealso: ['cot', 'atan'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acosh.js +var acoshDocs = { + name: 'acosh', + category: 'Trigonometry', + syntax: ['acosh(x)'], + description: 'Calculate the hyperbolic arccos of a value, defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.', + examples: ['acosh(1.5)'], + seealso: ['cosh', 'asinh', 'atanh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acos.js +var acosDocs = { + name: 'acos', + category: 'Trigonometry', + syntax: ['acos(x)'], + description: 'Compute the inverse cosine of a value in radians.', + examples: ['acos(0.5)', 'acos(cos(2.3))'], + seealso: ['cos', 'atan', 'asin'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/sum.js +var sumDocs = { + name: 'sum', + category: 'Statistics', + syntax: ['sum(a, b, c, ...)', 'sum(A)'], + description: 'Compute the sum of all values.', + examples: ['sum(2, 3, 4, 1)', 'sum([2, 3, 4, 1])', 'sum([2, 5; 4, 3])'], + seealso: ['max', 'mean', 'median', 'min', 'prod', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/std.js +var stdDocs = { + name: 'std', + category: 'Statistics', + syntax: ['std(a, b, c, ...)', 'std(A)', 'std(A, normalization)'], + description: 'Compute the standard deviation of all values, defined as std(A) = sqrt(variance(A)). Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".', + examples: ['std(2, 4, 6)', 'std([2, 4, 6, 8])', 'std([2, 4, 6, 8], "uncorrected")', 'std([2, 4, 6, 8], "biased")', 'std([1, 2, 3; 4, 5, 6])'], + seealso: ['max', 'mean', 'min', 'median', 'prod', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/quantileSeq.js +var quantileSeqDocs = { + name: 'quantileSeq', + category: 'Statistics', + syntax: ['quantileSeq(A, prob[, sorted])', 'quantileSeq(A, [prob1, prob2, ...][, sorted])', 'quantileSeq(A, N[, sorted])'], + description: 'Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. Supported types of sequence values are: Number, BigNumber, Unit Supported types of probablity are: Number, BigNumber. \n\nIn case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated.', + examples: ['quantileSeq([3, -1, 5, 7], 0.5)', 'quantileSeq([3, -1, 5, 7], [1/3, 2/3])', 'quantileSeq([3, -1, 5, 7], 2)', 'quantileSeq([-1, 3, 5, 7], 0.5, true)'], + seealso: ['mean', 'median', 'min', 'max', 'prod', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/prod.js +var prodDocs = { + name: 'prod', + category: 'Statistics', + syntax: ['prod(a, b, c, ...)', 'prod(A)'], + description: 'Compute the product of all values.', + examples: ['prod(2, 3, 4)', 'prod([2, 3, 4])', 'prod([2, 5; 4, 3])'], + seealso: ['max', 'mean', 'min', 'median', 'min', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/mode.js +var modeDocs = { + name: 'mode', + category: 'Statistics', + syntax: ['mode(a, b, c, ...)', 'mode(A)', 'mode(A, a, b, B, c, ...)'], + description: 'Computes the mode of all values as an array. In case mode being more than one, multiple values are returned in an array.', + examples: ['mode(2, 1, 4, 3, 1)', 'mode([1, 2.7, 3.2, 4, 2.7])', 'mode(1, 4, 6, 1, 6)'], + seealso: ['max', 'mean', 'min', 'median', 'prod', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/min.js +var minDocs = { + name: 'min', + category: 'Statistics', + syntax: ['min(a, b, c, ...)', 'min(A)', 'min(A, dim)'], + description: 'Compute the minimum value of a list of values.', + examples: ['min(2, 3, 4, 1)', 'min([2, 3, 4, 1])', 'min([2, 5; 4, 3])', 'min([2, 5; 4, 3], 1)', 'min([2, 5; 4, 3], 2)', 'min(2.7, 7.1, -4.5, 2.0, 4.1)', 'max(2.7, 7.1, -4.5, 2.0, 4.1)'], + seealso: ['max', 'mean', 'median', 'prod', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/median.js +var medianDocs = { + name: 'median', + category: 'Statistics', + syntax: ['median(a, b, c, ...)', 'median(A)'], + description: 'Compute the median of all values. The values are sorted and the middle value is returned. In case of an even number of values, the average of the two middle values is returned.', + examples: ['median(5, 2, 7)', 'median([3, -1, 5, 7])'], + seealso: ['max', 'mean', 'min', 'prod', 'std', 'sum', 'variance', 'quantileSeq'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/mean.js +var meanDocs = { + name: 'mean', + category: 'Statistics', + syntax: ['mean(a, b, c, ...)', 'mean(A)', 'mean(A, dim)'], + description: 'Compute the arithmetic mean of a list of values.', + examples: ['mean(2, 3, 4, 1)', 'mean([2, 3, 4, 1])', 'mean([2, 5; 4, 3])', 'mean([2, 5; 4, 3], 1)', 'mean([2, 5; 4, 3], 2)', 'mean([1.0, 2.7, 3.2, 4.0])'], + seealso: ['max', 'median', 'min', 'prod', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/max.js +var maxDocs = { + name: 'max', + category: 'Statistics', + syntax: ['max(a, b, c, ...)', 'max(A)', 'max(A, dim)'], + description: 'Compute the maximum value of a list of values.', + examples: ['max(2, 3, 4, 1)', 'max([2, 3, 4, 1])', 'max([2, 5; 4, 3])', 'max([2, 5; 4, 3], 1)', 'max([2, 5; 4, 3], 2)', 'max(2.7, 7.1, -4.5, 2.0, 4.1)', 'min(2.7, 7.1, -4.5, 2.0, 4.1)'], + seealso: ['mean', 'median', 'min', 'prod', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/mad.js +var madDocs = { + name: 'mad', + category: 'Statistics', + syntax: ['mad(a, b, c, ...)', 'mad(A)'], + description: 'Compute the median absolute deviation of a matrix or a list with values. The median absolute deviation is defined as the median of the absolute deviations from the median.', + examples: ['mad(10, 20, 30)', 'mad([1, 2, 3])'], + seealso: ['mean', 'median', 'std', 'abs'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/special/erf.js +var erfDocs = { + name: 'erf', + category: 'Special', + syntax: ['erf(x)'], + description: 'Compute the erf function of a value using a rational Chebyshev approximations for different intervals of x', + examples: ['erf(0.2)', 'erf(-0.5)', 'erf(4)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setUnion.js +var setUnionDocs = { + name: 'setUnion', + category: 'Set', + syntax: ['setUnion(set1, set2)'], + description: 'Create the union of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.', + examples: ['setUnion([1, 2, 3, 4], [3, 4, 5, 6])', 'setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]])'], + seealso: ['setIntersect', 'setDifference'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setSymDifference.js +var setSymDifferenceDocs = { + name: 'setSymDifference', + category: 'Set', + syntax: ['setSymDifference(set1, set2)'], + description: 'Create the symmetric difference of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.', + examples: ['setSymDifference([1, 2, 3, 4], [3, 4, 5, 6])', 'setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])'], + seealso: ['setUnion', 'setIntersect', 'setDifference'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setSize.js +var setSizeDocs = { + name: 'setSize', + category: 'Set', + syntax: ['setSize(set)', 'setSize(set, unique)'], + description: 'Count the number of elements of a (multi)set. When the second parameter "unique" is true, count only the unique values. A multi-dimension array will be converted to a single-dimension array before the operation.', + examples: ['setSize([1, 2, 2, 4])', 'setSize([1, 2, 2, 4], true)'], + seealso: ['setUnion', 'setIntersect', 'setDifference'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setPowerset.js +var setPowersetDocs = { + name: 'setPowerset', + category: 'Set', + syntax: ['setPowerset(set)'], + description: 'Create the powerset of a (multi)set: the powerset contains very possible subsets of a (multi)set. A multi-dimension array will be converted to a single-dimension array before the operation.', + examples: ['setPowerset([1, 2, 3])'], + seealso: ['setCartesian'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setMultiplicity.js +var setMultiplicityDocs = { + name: 'setMultiplicity', + category: 'Set', + syntax: ['setMultiplicity(element, set)'], + description: 'Count the multiplicity of an element in a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.', + examples: ['setMultiplicity(1, [1, 2, 2, 4])', 'setMultiplicity(2, [1, 2, 2, 4])'], + seealso: ['setDistinct', 'setSize'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setIsSubset.js +var setIsSubsetDocs = { + name: 'setIsSubset', + category: 'Set', + syntax: ['setIsSubset(set1, set2)'], + description: 'Check whether a (multi)set is a subset of another (multi)set: every element of set1 is the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.', + examples: ['setIsSubset([1, 2], [3, 4, 5, 6])', 'setIsSubset([3, 4], [3, 4, 5, 6])'], + seealso: ['setUnion', 'setIntersect', 'setDifference'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setIntersect.js +var setIntersectDocs = { + name: 'setIntersect', + category: 'Set', + syntax: ['setIntersect(set1, set2)'], + description: 'Create the intersection of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.', + examples: ['setIntersect([1, 2, 3, 4], [3, 4, 5, 6])', 'setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]])'], + seealso: ['setUnion', 'setDifference'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setDistinct.js +var setDistinctDocs = { + name: 'setDistinct', + category: 'Set', + syntax: ['setDistinct(set)'], + description: 'Collect the distinct elements of a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.', + examples: ['setDistinct([1, 1, 1, 2, 2, 3])'], + seealso: ['setMultiplicity'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setDifference.js +var setDifferenceDocs = { + name: 'setDifference', + category: 'Set', + syntax: ['setDifference(set1, set2)'], + description: 'Create the difference of two (multi)sets: every element of set1, that is not the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.', + examples: ['setDifference([1, 2, 3, 4], [3, 4, 5, 6])', 'setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])'], + seealso: ['setUnion', 'setIntersect', 'setSymDifference'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setCartesian.js +var setCartesianDocs = { + name: 'setCartesian', + category: 'Set', + syntax: ['setCartesian(set1, set2)'], + description: 'Create the cartesian product of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.', + examples: ['setCartesian([1, 2], [3, 4])'], + seealso: ['setUnion', 'setIntersect', 'setDifference', 'setPowerset'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/unequal.js +var unequalDocs = { + name: 'unequal', + category: 'Relational', + syntax: ['x != y', 'unequal(x, y)'], + description: 'Check unequality of two values. Returns true if the values are unequal, and false if they are equal.', + examples: ['2+2 != 3', '2+2 != 4', 'a = 3.2', 'b = 6-2.8', 'a != b', '50cm != 0.5m', '5 cm != 2 inch'], + seealso: ['equal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare', 'deepEqual'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/smallerEq.js +var smallerEqDocs = { + name: 'smallerEq', + category: 'Relational', + syntax: ['x <= y', 'smallerEq(x, y)'], + description: 'Check if value x is smaller or equal to value y. Returns true if x is smaller than y, and false if not.', + examples: ['2 <= 1+1', '2 < 1+1', 'a = 3.2', 'b = 6-2.8', '(a <= b)'], + seealso: ['equal', 'unequal', 'larger', 'smaller', 'largerEq', 'compare'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/smaller.js +var smallerDocs = { + name: 'smaller', + category: 'Relational', + syntax: ['x < y', 'smaller(x, y)'], + description: 'Check if value x is smaller than value y. Returns true if x is smaller than y, and false if not.', + examples: ['2 < 3', '5 < 2*2', 'a = 3.3', 'b = 6-2.8', '(a < b)', '5 cm < 2 inch'], + seealso: ['equal', 'unequal', 'larger', 'smallerEq', 'largerEq', 'compare'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/largerEq.js +var largerEqDocs = { + name: 'largerEq', + category: 'Relational', + syntax: ['x >= y', 'largerEq(x, y)'], + description: 'Check if value x is larger or equal to y. Returns true if x is larger or equal to y, and false if not.', + examples: ['2 >= 1+1', '2 > 1+1', 'a = 3.2', 'b = 6-2.8', '(a >= b)'], + seealso: ['equal', 'unequal', 'smallerEq', 'smaller', 'compare'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/larger.js +var largerDocs = { + name: 'larger', + category: 'Relational', + syntax: ['x > y', 'larger(x, y)'], + description: 'Check if value x is larger than y. Returns true if x is larger than y, and false if not.', + examples: ['2 > 3', '5 > 2*2', 'a = 3.3', 'b = 6-2.8', '(a > b)', '(b < a)', '5 cm > 2 inch'], + seealso: ['equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compare'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/equalText.js +var equalTextDocs = { + name: 'equalText', + category: 'Relational', + syntax: ['equalText(x, y)'], + description: 'Check equality of two strings. Comparison is case sensitive. Returns true if the values are equal, and false if not.', + examples: ['equalText("Hello", "Hello")', 'equalText("a", "A")', 'equal("2e3", "2000")', 'equalText("2e3", "2000")', 'equalText("B", ["A", "B", "C"])'], + seealso: ['compare', 'compareNatural', 'compareText', 'equal'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/equal.js +var equalDocs = { + name: 'equal', + category: 'Relational', + syntax: ['x == y', 'equal(x, y)'], + description: 'Check equality of two values. Returns true if the values are equal, and false if not.', + examples: ['2+2 == 3', '2+2 == 4', 'a = 3.2', 'b = 6-2.8', 'a == b', '50cm == 0.5m'], + seealso: ['unequal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare', 'deepEqual', 'equalText'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/deepEqual.js +var deepEqualDocs = { + name: 'deepEqual', + category: 'Relational', + syntax: ['deepEqual(x, y)'], + description: 'Check equality of two matrices element wise. Returns true if the size of both matrices is equal and when and each of the elements are equal.', + examples: ['deepEqual([1,3,4], [1,3,4])', 'deepEqual([1,3,4], [1,3])'], + seealso: ['equal', 'unequal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/compareText.js +var compareTextDocs = { + name: 'compareText', + category: 'Relational', + syntax: ['compareText(x, y)'], + description: 'Compare two strings lexically. Comparison is case sensitive. ' + 'Returns 1 when x > y, -1 when x < y, and 0 when x == y.', + examples: ['compareText("B", "A")', 'compareText("A", "B")', 'compareText("A", "A")', 'compareText("2", "10")', 'compare("2", "10")', 'compare(2, 10)', 'compareNatural("2", "10")', 'compareText("B", ["A", "B", "C"])'], + seealso: ['compare', 'compareNatural'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/compareNatural.js +var compareNaturalDocs = { + name: 'compareNatural', + category: 'Relational', + syntax: ['compareNatural(x, y)'], + description: 'Compare two values of any type in a deterministic, natural way. ' + 'Returns 1 when x > y, -1 when x < y, and 0 when x == y.', + examples: ['compareNatural(2, 3)', 'compareNatural(3, 2)', 'compareNatural(2, 2)', 'compareNatural(5cm, 40mm)', 'compareNatural("2", "10")', 'compareNatural(2 + 3i, 2 + 4i)', 'compareNatural([1, 2, 4], [1, 2, 3])', 'compareNatural([1, 5], [1, 2, 3])', 'compareNatural([1, 2], [1, 2])', 'compareNatural({a: 2}, {a: 4})'], + seealso: ['equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compare', 'compareText'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/compare.js +var compareDocs = { + name: 'compare', + category: 'Relational', + syntax: ['compare(x, y)'], + description: 'Compare two values. ' + 'Returns 1 when x > y, -1 when x < y, and 0 when x == y.', + examples: ['compare(2, 3)', 'compare(3, 2)', 'compare(2, 2)', 'compare(5cm, 40mm)', 'compare(2, [1, 2, 3])'], + seealso: ['equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compareNatural', 'compareText'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/randomInt.js +var randomIntDocs = { + name: 'randomInt', + category: 'Probability', + syntax: ['randomInt(max)', 'randomInt(min, max)', 'randomInt(size)', 'randomInt(size, max)', 'randomInt(size, min, max)'], + description: 'Return a random integer number', + examples: ['randomInt(10, 20)', 'randomInt([2, 3], 10)'], + seealso: ['pickRandom', 'random'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/random.js +var randomDocs = { + name: 'random', + category: 'Probability', + syntax: ['random()', 'random(max)', 'random(min, max)', 'random(size)', 'random(size, max)', 'random(size, min, max)'], + description: 'Return a random number.', + examples: ['random()', 'random(10, 20)', 'random([2, 3])'], + seealso: ['pickRandom', 'randomInt'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/pickRandom.js +var pickRandomDocs = { + name: 'pickRandom', + category: 'Probability', + syntax: ['pickRandom(array)', 'pickRandom(array, number)', 'pickRandom(array, weights)', 'pickRandom(array, number, weights)', 'pickRandom(array, weights, number)'], + description: 'Pick a random entry from a given array.', + examples: ['pickRandom(0:10)', 'pickRandom([1, 3, 1, 6])', 'pickRandom([1, 3, 1, 6], 2)', 'pickRandom([1, 3, 1, 6], [2, 3, 2, 1])', 'pickRandom([1, 3, 1, 6], 2, [2, 3, 2, 1])', 'pickRandom([1, 3, 1, 6], [2, 3, 2, 1], 2)'], + seealso: ['random', 'randomInt'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/permutations.js +var permutationsDocs = { + name: 'permutations', + category: 'Probability', + syntax: ['permutations(n)', 'permutations(n, k)'], + description: 'Compute the number of permutations of n items taken k at a time', + examples: ['permutations(5)', 'permutations(5, 3)'], + seealso: ['combinations', 'combinationsWithRep', 'factorial'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/multinomial.js +var multinomialDocs = { + name: 'multinomial', + category: 'Probability', + syntax: ['multinomial(A)'], + description: 'Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities. multinomial takes one array of integers as an argument. The following condition must be enforced: every ai > 0.', + examples: ['multinomial([1, 2, 1])'], + seealso: ['combinations', 'factorial'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/kldivergence.js +var kldivergenceDocs = { + name: 'kldivergence', + category: 'Probability', + syntax: ['kldivergence(x, y)'], + description: 'Calculate the Kullback-Leibler (KL) divergence between two distributions.', + examples: ['kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5])'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/gamma.js +var gammaDocs = { + name: 'gamma', + category: 'Probability', + syntax: ['gamma(n)'], + description: 'Compute the gamma function. For small values, the Lanczos approximation is used, and for large values the extended Stirling approximation.', + examples: ['gamma(4)', '3!', 'gamma(1/2)', 'sqrt(pi)'], + seealso: ['factorial'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/factorial.js +var factorialDocs = { + name: 'factorial', + category: 'Probability', + syntax: ['n!', 'factorial(n)'], + description: 'Compute the factorial of a value', + examples: ['5!', '5 * 4 * 3 * 2 * 1', '3!'], + seealso: ['combinations', 'combinationsWithRep', 'permutations', 'gamma'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/combinations.js +var combinationsDocs = { + name: 'combinations', + category: 'Probability', + syntax: ['combinations(n, k)'], + description: 'Compute the number of combinations of n items taken k at a time', + examples: ['combinations(7, 5)'], + seealso: ['combinationsWithRep', 'permutations', 'factorial'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/combinationsWithRep.js +var combinationsWithRepDocs = { + name: 'combinationsWithRep', + category: 'Probability', + syntax: ['combinationsWithRep(n, k)'], + description: 'Compute the number of combinations of n items taken k at a time with replacements.', + examples: ['combinationsWithRep(7, 5)'], + seealso: ['combinations', 'permutations', 'factorial'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/zeros.js +var zerosDocs = { + name: 'zeros', + category: 'Matrix', + syntax: ['zeros(m)', 'zeros(m, n)', 'zeros(m, n, p, ...)', 'zeros([m])', 'zeros([m, n])', 'zeros([m, n, p, ...])'], + description: 'Create a matrix containing zeros.', + examples: ['zeros(3)', 'zeros(3, 5)', 'a = [1, 2, 3; 4, 5, 6]', 'zeros(size(a))'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/transpose.js +var transposeDocs = { + name: 'transpose', + category: 'Matrix', + syntax: ['x\'', 'transpose(x)'], + description: 'Transpose a matrix', + examples: ['a = [1, 2, 3; 4, 5, 6]', 'a\'', 'transpose(a)'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/trace.js +var traceDocs = { + name: 'trace', + category: 'Matrix', + syntax: ['trace(A)'], + description: 'Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.', + examples: ['A = [1, 2, 3; -1, 2, 3; 2, 0, 3]', 'trace(A)'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/subset.js +var subsetDocs = { + name: 'subset', + category: 'Matrix', + syntax: ['value(index)', 'value(index) = replacement', 'subset(value, [index])', 'subset(value, [index], replacement)'], + description: 'Get or set a subset of a matrix or string. ' + 'Indexes are one-based. ' + 'Both the ranges lower-bound and upper-bound are included.', + examples: ['d = [1, 2; 3, 4]', 'e = []', 'e[1, 1:2] = [5, 6]', 'e[2, :] = [7, 8]', 'f = d * e', 'f[2, 1]', 'f[:, 1]'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/squeeze.js +var squeezeDocs = { + name: 'squeeze', + category: 'Matrix', + syntax: ['squeeze(x)'], + description: 'Remove inner and outer singleton dimensions from a matrix.', + examples: ['a = zeros(3,2,1)', 'size(squeeze(a))', 'b = zeros(1,1,3)', 'size(squeeze(b))'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/sort.js +var sortDocs = { + name: 'sort', + category: 'Matrix', + syntax: ['sort(x)', 'sort(x, compare)'], + description: 'Sort the items in a matrix. Compare can be a string "asc", "desc", "natural", or a custom sort function.', + examples: ['sort([5, 10, 1])', 'sort(["C", "B", "A", "D"])', 'sortByLength(a, b) = size(a)[1] - size(b)[1]', 'sort(["Langdon", "Tom", "Sara"], sortByLength)', 'sort(["10", "1", "2"], "natural")'], + seealso: ['map', 'filter', 'forEach'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/size.js +var sizeDocs = { + name: 'size', + category: 'Matrix', + syntax: ['size(x)'], + description: 'Calculate the size of a matrix.', + examples: ['size(2.3)', 'size("hello world")', 'a = [1, 2; 3, 4; 5, 6]', 'size(a)', 'size(1:6)'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/reshape.js +var reshapeDocs = { + name: 'reshape', + category: 'Matrix', + syntax: ['reshape(x, sizes)'], + description: 'Reshape a multi dimensional array to fit the specified dimensions.', + examples: ['reshape([1, 2, 3, 4, 5, 6], [2, 3])', 'reshape([[1, 2], [3, 4]], [1, 4])', 'reshape([[1, 2], [3, 4]], [4])'], + seealso: ['size', 'squeeze', 'resize'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/resize.js +var resizeDocs = { + name: 'resize', + category: 'Matrix', + syntax: ['resize(x, size)', 'resize(x, size, defaultValue)'], + description: 'Resize a matrix.', + examples: ['resize([1,2,3,4,5], [3])', 'resize([1,2,3], [5])', 'resize([1,2,3], [5], -1)', 'resize(2, [2, 3])', 'resize("hello", [8], "!")'], + seealso: ['size', 'subset', 'squeeze', 'reshape'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/range.js +var rangeDocs = { + name: 'range', + category: 'Type', + syntax: ['start:end', 'start:step:end', 'range(start, end)', 'range(start, end, step)', 'range(string)'], + description: 'Create a range. Lower bound of the range is included, upper bound is excluded.', + examples: ['1:5', '3:-1:-3', 'range(3, 7)', 'range(0, 12, 2)', 'range("4:10")', 'a = [1, 2, 3, 4; 5, 6, 7, 8]', 'a[1:2, 1:2]'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/partitionSelect.js +var partitionSelectDocs = { + name: 'partitionSelect', + category: 'Matrix', + syntax: ['partitionSelect(x, k)', 'partitionSelect(x, k, compare)'], + description: 'Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect.', + examples: ['partitionSelect([5, 10, 1], 2)', 'partitionSelect(["C", "B", "A", "D"], 1)'], + seealso: ['sort'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/ones.js +var onesDocs = { + name: 'ones', + category: 'Matrix', + syntax: ['ones(m)', 'ones(m, n)', 'ones(m, n, p, ...)', 'ones([m])', 'ones([m, n])', 'ones([m, n, p, ...])'], + description: 'Create a matrix containing ones.', + examples: ['ones(3)', 'ones(3, 5)', 'ones([2,3]) * 4.5', 'a = [1, 2, 3; 4, 5, 6]', 'ones(size(a))'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/map.js +var mapDocs = { + name: 'map', + category: 'Matrix', + syntax: ['map(x, callback)'], + description: 'Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.', + examples: ['map([1, 2, 3], square)'], + seealso: ['filter', 'forEach'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/kron.js +var kronDocs = { + name: 'kron', + category: 'Matrix', + syntax: ['kron(x, y)'], + description: 'Calculates the kronecker product of 2 matrices or vectors.', + examples: ['kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])', 'kron([1,1], [2,3,4])'], + seealso: ['multiply', 'dot', 'cross'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/inv.js +var invDocs = { + name: 'inv', + category: 'Matrix', + syntax: ['inv(x)'], + description: 'Calculate the inverse of a matrix', + examples: ['inv([1, 2; 3, 4])', 'inv(4)', '1 / 4'], + seealso: ['concat', 'det', 'diag', 'identity', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/forEach.js +var forEachDocs = { + name: 'forEach', + category: 'Matrix', + syntax: ['forEach(x, callback)'], + description: 'Iterates over all elements of a matrix/array, and executes the given callback function.', + examples: ['forEach([1, 2, 3], function(val) { console.log(val) })'], + seealso: ['map', 'sort', 'filter'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/flatten.js +var flattenDocs = { + name: 'flatten', + category: 'Matrix', + syntax: ['flatten(x)'], + description: 'Flatten a multi dimensional matrix into a single dimensional matrix.', + examples: ['a = [1, 2, 3; 4, 5, 6]', 'size(a)', 'b = flatten(a)', 'size(b)'], + seealso: ['concat', 'resize', 'size', 'squeeze'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/filter.js +var filterDocs = { + name: 'filter', + category: 'Matrix', + syntax: ['filter(x, test)'], + description: 'Filter items in a matrix.', + examples: ['isPositive(x) = x > 0', 'filter([6, -2, -1, 4, 3], isPositive)', 'filter([6, -2, 0, 1, 0], x != 0)'], + seealso: ['sort', 'map', 'forEach'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/identity.js +var identityDocs = { + name: 'identity', + category: 'Matrix', + syntax: ['identity(n)', 'identity(m, n)', 'identity([m, n])'], + description: 'Returns the identity matrix with size m-by-n. The matrix has ones on the diagonal and zeros elsewhere.', + examples: ['identity(3)', 'identity(3, 5)', 'a = [1, 2, 3; 4, 5, 6]', 'identity(size(a))'], + seealso: ['concat', 'det', 'diag', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/getMatrixDataType.js +var getMatrixDataTypeDocs = { + name: 'getMatrixDataType', + category: 'Matrix', + syntax: ['getMatrixDataType(x)'], + description: 'Find the data type of all elements in a matrix or array, ' + 'for example "number" if all items are a number ' + 'and "Complex" if all values are complex numbers. ' + 'If a matrix contains more than one data type, it will return "mixed".', + examples: ['getMatrixDataType([1, 2, 3])', 'getMatrixDataType([[5 cm], [2 inch]])', 'getMatrixDataType([1, "text"])', 'getMatrixDataType([1, bignumber(4)])'], + seealso: ['matrix', 'sparse', 'typeOf'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/dot.js +var dotDocs = { + name: 'dot', + category: 'Matrix', + syntax: ['dot(A, B)', 'A * B'], + description: 'Calculate the dot product of two vectors. ' + 'The dot product of A = [a1, a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] ' + 'is defined as dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn', + examples: ['dot([2, 4, 1], [2, 2, 3])', '[2, 4, 1] * [2, 2, 3]'], + seealso: ['multiply', 'cross'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/diag.js +var diagDocs = { + name: 'diag', + category: 'Matrix', + syntax: ['diag(x)', 'diag(x, k)'], + description: 'Create a diagonal matrix or retrieve the diagonal of a matrix. When x is a vector, a matrix with the vector values on the diagonal will be returned. When x is a matrix, a vector with the diagonal values of the matrix is returned. When k is provided, the k-th diagonal will be filled in or retrieved, if k is positive, the values are placed on the super diagonal. When k is negative, the values are placed on the sub diagonal.', + examples: ['diag(1:3)', 'diag(1:3, 1)', 'a = [1, 2, 3; 4, 5, 6; 7, 8, 9]', 'diag(a)'], + seealso: ['concat', 'det', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/det.js +var detDocs = { + name: 'det', + category: 'Matrix', + syntax: ['det(x)'], + description: 'Calculate the determinant of a matrix', + examples: ['det([1, 2; 3, 4])', 'det([-2, 2, 3; -1, 1, 3; 2, 0, -1])'], + seealso: ['concat', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/ctranspose.js +var ctransposeDocs = { + name: 'ctranspose', + category: 'Matrix', + syntax: ['x\'', 'ctranspose(x)'], + description: 'Complex Conjugate and Transpose a matrix', + examples: ['a = [1, 2, 3; 4, 5, 6]', 'a\'', 'ctranspose(a)'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/cross.js +var crossDocs = { + name: 'cross', + category: 'Matrix', + syntax: ['cross(A, B)'], + description: 'Calculate the cross product for two vectors in three dimensional space.', + examples: ['cross([1, 1, 0], [0, 1, 1])', 'cross([3, -3, 1], [4, 9, 2])', 'cross([2, 3, 4], [5, 6, 7])'], + seealso: ['multiply', 'dot'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/concat.js +var concatDocs = { + name: 'concat', + category: 'Matrix', + syntax: ['concat(A, B, C, ...)', 'concat(A, B, C, ..., dim)'], + description: 'Concatenate matrices. By default, the matrices are concatenated by the last dimension. The dimension on which to concatenate can be provided as last argument.', + examples: ['A = [1, 2; 5, 6]', 'B = [3, 4; 7, 8]', 'concat(A, B)', 'concat(A, B, 1)', 'concat(A, B, 2)'], + seealso: ['det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/logical/xor.js +var xorDocs = { + name: 'xor', + category: 'Logical', + syntax: ['x xor y', 'xor(x, y)'], + description: 'Logical exclusive or, xor. Test whether one and only one value is defined with a nonzero/nonempty value.', + examples: ['true xor false', 'false xor false', 'true xor true', '0 xor 4'], + seealso: ['not', 'and', 'or'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/logical/or.js +var orDocs = { + name: 'or', + category: 'Logical', + syntax: ['x or y', 'or(x, y)'], + description: 'Logical or. Test if at least one value is defined with a nonzero/nonempty value.', + examples: ['true or false', 'false or false', '0 or 4'], + seealso: ['not', 'and', 'xor'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/logical/not.js +var notDocs = { + name: 'not', + category: 'Logical', + syntax: ['not x', 'not(x)'], + description: 'Logical not. Flips the boolean value of given argument.', + examples: ['not true', 'not false', 'not 2', 'not 0'], + seealso: ['and', 'or', 'xor'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/logical/and.js +var andDocs = { + name: 'and', + category: 'Logical', + syntax: ['x and y', 'and(x, y)'], + description: 'Logical and. Test whether two values are both defined with a nonzero/nonempty value.', + examples: ['true and false', 'true and true', '2 and 4'], + seealso: ['not', 'or', 'xor'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/geometry/intersect.js +var intersectDocs = { + name: 'intersect', + category: 'Geometry', + syntax: ['intersect(expr1, expr2, expr3, expr4)', 'intersect(expr1, expr2, expr3)'], + description: 'Computes the intersection point of lines and/or planes.', + examples: ['intersect([0, 0], [10, 10], [10, 0], [0, 10])', 'intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6])'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/geometry/distance.js +var distanceDocs = { + name: 'distance', + category: 'Geometry', + syntax: ['distance([x1, y1], [x2, y2])', 'distance([[x1, y1], [x2, y2]])'], + description: 'Calculates the Euclidean distance between two points.', + examples: ['distance([0,0], [4,4])', 'distance([[0,0], [4,4]])'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/expression/help.js +var helpDocs = { + name: 'help', + category: 'Expression', + syntax: ['help(object)', 'help(string)'], + description: 'Display documentation on a function or data type.', + examples: ['help(sqrt)', 'help("complex")'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/expression/evaluate.js +var evaluateDocs = { + name: 'evaluate', + category: 'Expression', + syntax: ['evaluate(expression)', 'evaluate([expr1, expr2, expr3, ...])'], + description: 'Evaluate an expression or an array with expressions.', + examples: ['evaluate("2 + 3")', 'evaluate("sqrt(" + 4 + ")")'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/complex/im.js +var imDocs = { + name: 'im', + category: 'Complex', + syntax: ['im(x)'], + description: 'Get the imaginary part of a complex number.', + examples: ['im(2 + 3i)', 're(2 + 3i)', 'im(-5.2i)', 'im(2.4)'], + seealso: ['re', 'conj', 'abs', 'arg'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/complex/re.js +var reDocs = { + name: 're', + category: 'Complex', + syntax: ['re(x)'], + description: 'Get the real part of a complex number.', + examples: ['re(2 + 3i)', 'im(2 + 3i)', 're(-5.2i)', 're(2.4)'], + seealso: ['im', 'conj', 'abs', 'arg'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/complex/conj.js +var conjDocs = { + name: 'conj', + category: 'Complex', + syntax: ['conj(x)'], + description: 'Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate is a-bi.', + examples: ['conj(2 + 3i)', 'conj(2 - 3i)', 'conj(-5.2i)'], + seealso: ['re', 'im', 'abs', 'arg'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/complex/arg.js +var argDocs = { + name: 'arg', + category: 'Complex', + syntax: ['arg(x)'], + description: 'Compute the argument of a complex value. If x = a+bi, the argument is computed as atan2(b, a).', + examples: ['arg(2 + 2i)', 'atan2(3, 2)', 'arg(2 + 3i)'], + seealso: ['re', 'im', 'conj', 'abs'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/core/typed.js +var typedDocs = { + name: 'typed', + category: 'Core', + syntax: ['typed(signatures)', 'typed(name, signatures)'], + description: 'Create a typed function.', + examples: ['double = typed({ "number, number": f(x)=x+x })', 'double(2)', 'double("hello")'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/core/import.js +var importDocs = { + name: 'import', + category: 'Core', + syntax: ['import(functions)', 'import(functions, options)'], + description: 'Import functions or constants from an object.', + examples: ['import({myFn: f(x)=x^2, myConstant: 32 })', 'myFn(2)', 'myConstant'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/core/config.js +var configDocs = { + name: 'config', + category: 'Core', + syntax: ['config()', 'config(options)'], + description: 'Get configuration or change configuration.', + examples: ['config()', '1/3 + 1/4', 'config({number: "Fraction"})', '1/3 + 1/4'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/combinatorics/stirlingS2.js +var stirlingS2Docs = { + name: 'stirlingS2', + category: 'Combinatorics', + syntax: ['stirlingS2(n, k)'], + description: 'he Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. `stirlingS2` only takes integer arguments. The following condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = 1.', + examples: ['stirlingS2(5, 3)'], + seealso: ['bellNumbers'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/combinatorics/composition.js +var compositionDocs = { + name: 'composition', + category: 'Combinatorics', + syntax: ['composition(n, k)'], + description: 'The composition counts of n into k parts. composition only takes integer arguments. The following condition must be enforced: k <= n.', + examples: ['composition(5, 3)'], + seealso: ['combinations'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/combinatorics/catalan.js +var catalanDocs = { + name: 'catalan', + category: 'Combinatorics', + syntax: ['catalan(n)'], + description: 'The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0.', + examples: ['catalan(3)', 'catalan(8)'], + seealso: ['bellNumbers'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/combinatorics/bellNumbers.js +var bellNumbersDocs = { + name: 'bellNumbers', + category: 'Combinatorics', + syntax: ['bellNumbers(n)'], + description: 'The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S. `bellNumbers` only takes integer arguments. The following condition must be enforced: n >= 0.', + examples: ['bellNumbers(3)', 'bellNumbers(8)'], + seealso: ['stirlingS2'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/rightLogShift.js +var rightLogShiftDocs = { + name: 'rightLogShift', + category: 'Bitwise', + syntax: ['x >>> y', 'rightLogShift(x, y)'], + description: 'Bitwise right logical shift of a value x by y number of bits.', + examples: ['8 >>> 1', '4 << 1', '-12 >>> 2'], + seealso: ['bitAnd', 'bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/rightArithShift.js +var rightArithShiftDocs = { + name: 'rightArithShift', + category: 'Bitwise', + syntax: ['x >> y', 'rightArithShift(x, y)'], + description: 'Bitwise right arithmetic shift of a value x by y number of bits.', + examples: ['8 >> 1', '4 << 1', '-12 >> 2'], + seealso: ['bitAnd', 'bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightLogShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/leftShift.js +var leftShiftDocs = { + name: 'leftShift', + category: 'Bitwise', + syntax: ['x << y', 'leftShift(x, y)'], + description: 'Bitwise left logical shift of a value x by y number of bits.', + examples: ['4 << 1', '8 >> 1'], + seealso: ['bitAnd', 'bitNot', 'bitOr', 'bitXor', 'rightArithShift', 'rightLogShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/bitXor.js +var bitXorDocs = { + name: 'bitXor', + category: 'Bitwise', + syntax: ['bitXor(x, y)'], + description: 'Bitwise XOR operation, exclusive OR. Performs the logical exclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1.', + examples: ['bitOr(1, 2)', 'bitXor([2, 3, 4], 4)'], + seealso: ['bitAnd', 'bitNot', 'bitOr', 'leftShift', 'rightArithShift', 'rightLogShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/bitOr.js +var bitOrDocs = { + name: 'bitOr', + category: 'Bitwise', + syntax: ['x | y', 'bitOr(x, y)'], + description: 'Bitwise OR operation. Performs the logical inclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if the first bit is 1 or the second bit is 1 or both bits are 1, otherwise, the result is 0.', + examples: ['5 | 3', 'bitOr([1, 2, 3], 4)'], + seealso: ['bitAnd', 'bitNot', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/bitNot.js +var bitNotDocs = { + name: 'bitNot', + category: 'Bitwise', + syntax: ['~x', 'bitNot(x)'], + description: 'Bitwise NOT operation. Performs a logical negation on each bit of the given value. Bits that are 0 become 1, and those that are 1 become 0.', + examples: ['~1', '~2', 'bitNot([2, -3, 4])'], + seealso: ['bitAnd', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/bitAnd.js +var bitAndDocs = { + name: 'bitAnd', + category: 'Bitwise', + syntax: ['x & y', 'bitAnd(x, y)'], + description: 'Bitwise AND operation. Performs the logical AND operation on each pair of the corresponding bits of the two given values by multiplying them. If both bits in the compared position are 1, the bit in the resulting binary representation is 1, otherwise, the result is 0', + examples: ['5 & 3', 'bitAnd(53, 131)', '[1, 12, 31] & 42'], + seealso: ['bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/xgcd.js +var xgcdDocs = { + name: 'xgcd', + category: 'Arithmetic', + syntax: ['xgcd(a, b)'], + description: 'Calculate the extended greatest common divisor for two values. The result is an array [d, x, y] with 3 entries, where d is the greatest common divisor, and d = x * a + y * b.', + examples: ['xgcd(8, 12)', 'gcd(8, 12)', 'xgcd(36163, 21199)'], + seealso: ['gcd', 'lcm'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/unaryPlus.js +var unaryPlusDocs = { + name: 'unaryPlus', + category: 'Operators', + syntax: ['+x', 'unaryPlus(x)'], + description: 'Converts booleans and strings to numbers.', + examples: ['+true', '+"2"'], + seealso: ['add', 'subtract', 'unaryMinus'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/unaryMinus.js +var unaryMinusDocs = { + name: 'unaryMinus', + category: 'Operators', + syntax: ['-x', 'unaryMinus(x)'], + description: 'Inverse the sign of a value. Converts booleans and strings to numbers.', + examples: ['-4.5', '-(-5.6)', '-"22"'], + seealso: ['add', 'subtract', 'unaryPlus'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/square.js +var squareDocs = { + name: 'square', + category: 'Arithmetic', + syntax: ['square(x)'], + description: 'Compute the square of a value. The square of x is x * x.', + examples: ['square(3)', 'sqrt(9)', '3^2', '3 * 3'], + seealso: ['multiply', 'pow', 'sqrt', 'cube'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/sqrtm.js +var sqrtmDocs = { + name: 'sqrtm', + category: 'Arithmetic', + syntax: ['sqrtm(x)'], + description: 'Calculate the principal square root of a square matrix. The principal square root matrix `X` of another matrix `A` is such that `X * X = A`.', + examples: ['sqrtm([[1, 2], [3, 4]])'], + seealso: ['sqrt', 'abs', 'square', 'multiply'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/sqrt.js +var sqrtDocs = { + name: 'sqrt', + category: 'Arithmetic', + syntax: ['sqrt(x)'], + description: 'Compute the square root value. If x = y * y, then y is the square root of x.', + examples: ['sqrt(25)', '5 * 5', 'sqrt(-1)'], + seealso: ['square', 'sqrtm', 'multiply', 'nthRoot', 'nthRoots', 'pow'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/sign.js +var signDocs = { + name: 'sign', + category: 'Arithmetic', + syntax: ['sign(x)'], + description: 'Compute the sign of a value. The sign of a value x is 1 when x>1, -1 when x<0, and 0 when x=0.', + examples: ['sign(3.5)', 'sign(-4.2)', 'sign(0)'], + seealso: ['abs'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/round.js +var roundDocs = { + name: 'round', + category: 'Arithmetic', + syntax: ['round(x)', 'round(x, n)'], + description: 'round a value towards the nearest integer.If x is complex, both real and imaginary part are rounded towards the nearest integer. When n is specified, the value is rounded to n decimals.', + examples: ['round(3.2)', 'round(3.8)', 'round(-4.2)', 'round(-4.8)', 'round(pi, 3)', 'round(123.45678, 2)'], + seealso: ['ceil', 'floor', 'fix'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/pow.js +var powDocs = { + name: 'pow', + category: 'Operators', + syntax: ['x ^ y', 'pow(x, y)'], + description: 'Calculates the power of x to y, x^y.', + examples: ['2^3', '2*2*2', '1 + e ^ (pi * i)'], + seealso: ['multiply', 'nthRoot', 'nthRoots', 'sqrt'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/nthRoots.js +var nthRootsDocs = { + name: 'nthRoots', + category: 'Arithmetic', + syntax: ['nthRoots(A)', 'nthRoots(A, root)'], + description: '' + 'Calculate the nth roots of a value. ' + 'An nth root of a positive real number A, ' + 'is a positive real solution of the equation "x^root = A". ' + 'This function returns an array of complex values.', + examples: ['nthRoots(1)', 'nthRoots(1, 3)'], + seealso: ['sqrt', 'pow', 'nthRoot'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/nthRoot.js +var nthRootDocs = { + name: 'nthRoot', + category: 'Arithmetic', + syntax: ['nthRoot(a)', 'nthRoot(a, root)'], + description: 'Calculate the nth root of a value. ' + 'The principal nth root of a positive real number A, ' + 'is the positive real solution of the equation "x^root = A".', + examples: ['4 ^ 3', 'nthRoot(64, 3)', 'nthRoot(9, 2)', 'sqrt(9)'], + seealso: ['nthRoots', 'pow', 'sqrt'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/norm.js +var normDocs = { + name: 'norm', + category: 'Arithmetic', + syntax: ['norm(x)', 'norm(x, p)'], + description: 'Calculate the norm of a number, vector or matrix.', + examples: ['abs(-3.5)', 'norm(-3.5)', 'norm(3 - 4i)', 'norm([1, 2, -3], Infinity)', 'norm([1, 2, -3], -Infinity)', 'norm([3, 4], 2)', 'norm([[1, 2], [3, 4]], 1)', 'norm([[1, 2], [3, 4]], "inf")', 'norm([[1, 2], [3, 4]], "fro")'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/multiply.js +var multiplyDocs = { + name: 'multiply', + category: 'Operators', + syntax: ['x * y', 'multiply(x, y)'], + description: 'multiply two values.', + examples: ['a = 2.1 * 3.4', 'a / 3.4', '2 * 3 + 4', '2 * (3 + 4)', '3 * 2.1 km'], + seealso: ['divide'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/mod.js +var modDocs = { + name: 'mod', + category: 'Operators', + syntax: ['x % y', 'x mod y', 'mod(x, y)'], + description: 'Calculates the modulus, the remainder of an integer division.', + examples: ['7 % 3', '11 % 2', '10 mod 4', 'isOdd(x) = x % 2', 'isOdd(2)', 'isOdd(3)'], + seealso: ['divide'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/log10.js +var log10Docs = { + name: 'log10', + category: 'Arithmetic', + syntax: ['log10(x)'], + description: 'Compute the 10-base logarithm of a value.', + examples: ['log10(0.00001)', 'log10(10000)', '10 ^ 4', 'log(10000) / log(10)', 'log(10000, 10)'], + seealso: ['exp', 'log'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/log1p.js +var log1pDocs = { + name: 'log1p', + category: 'Arithmetic', + syntax: ['log1p(x)', 'log1p(x, base)'], + description: 'Calculate the logarithm of a `value+1`', + examples: ['log1p(2.5)', 'exp(log1p(1.4))', 'pow(10, 4)', 'log1p(9999, 10)', 'log1p(9999) / log(10)'], + seealso: ['exp', 'log', 'log2', 'log10'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/log2.js +var log2Docs = { + name: 'log2', + category: 'Arithmetic', + syntax: ['log2(x)'], + description: 'Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.', + examples: ['log2(0.03125)', 'log2(16)', 'log2(16) / log2(2)', 'pow(2, 4)'], + seealso: ['exp', 'log1p', 'log', 'log10'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/log.js +var logDocs = { + name: 'log', + category: 'Arithmetic', + syntax: ['log(x)', 'log(x, base)'], + description: 'Compute the logarithm of a value. If no base is provided, the natural logarithm of x is calculated. If base if provided, the logarithm is calculated for the specified base. log(x, base) is defined as log(x) / log(base).', + examples: ['log(3.5)', 'a = log(2.4)', 'exp(a)', '10 ^ 4', 'log(10000, 10)', 'log(10000) / log(10)', 'b = log(1024, 2)', '2 ^ b'], + seealso: ['exp', 'log1p', 'log2', 'log10'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/lcm.js +var lcmDocs = { + name: 'lcm', + category: 'Arithmetic', + syntax: ['lcm(x, y)'], + description: 'Compute the least common multiple.', + examples: ['lcm(4, 6)', 'lcm(6, 21)', 'lcm(6, 21, 5)'], + seealso: ['gcd'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/hypot.js +var hypotDocs = { + name: 'hypot', + category: 'Arithmetic', + syntax: ['hypot(a, b, c, ...)', 'hypot([a, b, c, ...])'], + description: 'Calculate the hypotenusa of a list with values. ', + examples: ['hypot(3, 4)', 'sqrt(3^2 + 4^2)', 'hypot(-2)', 'hypot([3, 4, 5])'], + seealso: ['abs', 'norm'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/gcd.js +var gcdDocs = { + name: 'gcd', + category: 'Arithmetic', + syntax: ['gcd(a, b)', 'gcd(a, b, c, ...)'], + description: 'Compute the greatest common divisor.', + examples: ['gcd(8, 12)', 'gcd(-4, 6)', 'gcd(25, 15, -10)'], + seealso: ['lcm', 'xgcd'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/floor.js +var floorDocs = { + name: 'floor', + category: 'Arithmetic', + syntax: ['floor(x)'], + description: 'Round a value towards minus infinity.If x is complex, both real and imaginary part are rounded towards minus infinity.', + examples: ['floor(3.2)', 'floor(3.8)', 'floor(-4.2)'], + seealso: ['ceil', 'fix', 'round'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/fix.js +var fixDocs = { + name: 'fix', + category: 'Arithmetic', + syntax: ['fix(x)'], + description: 'Round a value towards zero. If x is complex, both real and imaginary part are rounded towards zero.', + examples: ['fix(3.2)', 'fix(3.8)', 'fix(-4.2)', 'fix(-4.8)'], + seealso: ['ceil', 'floor', 'round'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/expm1.js +var expm1Docs = { + name: 'expm1', + category: 'Arithmetic', + syntax: ['expm1(x)'], + description: 'Calculate the value of subtracting 1 from the exponential value.', + examples: ['expm1(2)', 'pow(e, 2) - 1', 'log(expm1(2) + 1)'], + seealso: ['exp', 'pow', 'log'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/expm.js +var expmDocs = { + name: 'expm', + category: 'Arithmetic', + syntax: ['exp(x)'], + description: 'Compute the matrix exponential, expm(A) = e^A. ' + 'The matrix must be square. ' + 'Not to be confused with exp(a), which performs element-wise exponentiation.', + examples: ['expm([[0,2],[0,0]])'], + seealso: ['exp'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/eigs.js +var eigsDocs = { + name: 'eigs', + category: 'Matrix', + syntax: ['eigs(x)'], + description: 'Calculate the eigenvalues and eigenvectors of a real symmetric matrix', + examples: ['eigs([[5, 2.3], [2.3, 1]])'], + seealso: ['inv'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/exp.js +var expDocs = { + name: 'exp', + category: 'Arithmetic', + syntax: ['exp(x)'], + description: 'Calculate the exponent of a value.', + examples: ['exp(1.3)', 'e ^ 1.3', 'log(exp(1.3))', 'x = 2.4', '(exp(i*x) == cos(x) + i*sin(x)) # Euler\'s formula'], + seealso: ['expm', 'expm1', 'pow', 'log'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/dotMultiply.js +var dotMultiplyDocs = { + name: 'dotMultiply', + category: 'Operators', + syntax: ['x .* y', 'dotMultiply(x, y)'], + description: 'Multiply two values element wise.', + examples: ['a = [1, 2, 3; 4, 5, 6]', 'b = [2, 1, 1; 3, 2, 5]', 'a .* b'], + seealso: ['multiply', 'divide', 'dotDivide'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/dotDivide.js +var dotDivideDocs = { + name: 'dotDivide', + category: 'Operators', + syntax: ['x ./ y', 'dotDivide(x, y)'], + description: 'Divide two values element wise.', + examples: ['a = [1, 2, 3; 4, 5, 6]', 'b = [2, 1, 1; 3, 2, 5]', 'a ./ b'], + seealso: ['multiply', 'dotMultiply', 'divide'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/divide.js +var divideDocs = { + name: 'divide', + category: 'Operators', + syntax: ['x / y', 'divide(x, y)'], + description: 'Divide two values.', + examples: ['a = 2 / 3', 'a * 3', '4.5 / 2', '3 + 4 / 2', '(3 + 4) / 2', '18 km / 4.5'], + seealso: ['multiply'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/cube.js +var cubeDocs = { + name: 'cube', + category: 'Arithmetic', + syntax: ['cube(x)'], + description: 'Compute the cube of a value. The cube of x is x * x * x.', + examples: ['cube(2)', '2^3', '2 * 2 * 2'], + seealso: ['multiply', 'square', 'pow'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/ceil.js +var ceilDocs = { + name: 'ceil', + category: 'Arithmetic', + syntax: ['ceil(x)'], + description: 'Round a value towards plus infinity. If x is complex, both real and imaginary part are rounded towards plus infinity.', + examples: ['ceil(3.2)', 'ceil(3.8)', 'ceil(-4.2)'], + seealso: ['floor', 'fix', 'round'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/cbrt.js +var cbrtDocs = { + name: 'cbrt', + category: 'Arithmetic', + syntax: ['cbrt(x)', 'cbrt(x, allRoots)'], + description: 'Compute the cubic root value. If x = y * y * y, then y is the cubic root of x. When `x` is a number or complex number, an optional second argument `allRoots` can be provided to return all three cubic roots. If not provided, the principal root is returned', + examples: ['cbrt(64)', 'cube(4)', 'cbrt(-8)', 'cbrt(2 + 3i)', 'cbrt(8i)', 'cbrt(8i, true)', 'cbrt(27 m^3)'], + seealso: ['square', 'sqrt', 'cube', 'multiply'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/add.js +var addDocs = { + name: 'add', + category: 'Operators', + syntax: ['x + y', 'add(x, y)'], + description: 'Add two values.', + examples: ['a = 2.1 + 3.6', 'a - 3.6', '3 + 2i', '3 cm + 2 inch', '"2.3" + "4"'], + seealso: ['subtract'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/abs.js +var absDocs = { + name: 'abs', + category: 'Arithmetic', + syntax: ['abs(x)'], + description: 'Compute the absolute value.', + examples: ['abs(3.5)', 'abs(-4.2)'], + seealso: ['sign'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/qr.js +var qrDocs = { + name: 'qr', + category: 'Algebra', + syntax: ['qr(A)'], + description: 'Calculates the Matrix QR decomposition. Matrix `A` is decomposed in two matrices (`Q`, `R`) where `Q` is an orthogonal matrix and `R` is an upper triangular matrix.', + examples: ['qr([[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]])'], + seealso: ['lup', 'slu', 'matrix'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/usolve.js +var usolveDocs = { + name: 'usolve', + category: 'Algebra', + syntax: ['x=usolve(U, b)'], + description: 'Solves the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.', + examples: ['x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])'], + seealso: ['lup', 'lusolve', 'lsolve', 'matrix', 'sparse'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/slu.js +var sluDocs = { + name: 'slu', + category: 'Algebra', + syntax: ['slu(A, order, threshold)'], + description: 'Calculate the Matrix LU decomposition with full pivoting. Matrix A is decomposed in two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U', + examples: ['slu(sparse([4.5, 0, 3.2, 0; 3.1, 2.9, 0, 0.9; 0, 1.7, 3, 0; 3.5, 0.4, 0, 1]), 1, 0.001)'], + seealso: ['lusolve', 'lsolve', 'usolve', 'matrix', 'sparse', 'lup', 'qr'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/rationalize.js +var rationalizeDocs = { + name: 'rationalize', + category: 'Algebra', + syntax: ['rationalize(expr)', 'rationalize(expr, scope)', 'rationalize(expr, scope, detailed)'], + description: 'Transform a rationalizable expression in a rational fraction. If rational fraction is one variable polynomial then converts the numerator and denominator in canonical form, with decreasing exponents, returning the coefficients of numerator.', + examples: ['rationalize("2x/y - y/(x+1)")', 'rationalize("2x/y - y/(x+1)", true)'], + seealso: ['simplify'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/simplify.js +var simplifyDocs = { + name: 'simplify', + category: 'Algebra', + syntax: ['simplify(expr)', 'simplify(expr, rules)'], + description: 'Simplify an expression tree.', + examples: ['simplify("3 + 2 / 4")', 'simplify("2x + x")', 'f = parse("x * (x + 2 + x)")', 'simplified = simplify(f)', 'simplified.evaluate({x: 2})'], + seealso: ['derivative', 'parse', 'evaluate'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/lup.js +var lupDocs = { + name: 'lup', + category: 'Algebra', + syntax: ['lup(m)'], + description: 'Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in three matrices (L, U, P) where P * A = L * U', + examples: ['lup([[2, 1], [1, 4]])', 'lup(matrix([[2, 1], [1, 4]]))', 'lup(sparse([[2, 1], [1, 4]]))'], + seealso: ['lusolve', 'lsolve', 'usolve', 'matrix', 'sparse', 'slu', 'qr'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/lsolve.js +var lsolveDocs = { + name: 'lsolve', + category: 'Algebra', + syntax: ['x=lsolve(L, b)'], + description: 'Solves the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.', + examples: ['a = [-2, 3; 2, 1]', 'b = [11, 9]', 'x = lsolve(a, b)'], + seealso: ['lup', 'lusolve', 'usolve', 'matrix', 'sparse'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/derivative.js +var derivativeDocs = { + name: 'derivative', + category: 'Algebra', + syntax: ['derivative(expr, variable)', 'derivative(expr, variable, {simplify: boolean})'], + description: 'Takes the derivative of an expression expressed in parser Nodes. The derivative will be taken over the supplied variable in the second parameter. If there are multiple variables in the expression, it will return a partial derivative.', + examples: ['derivative("2x^3", "x")', 'derivative("2x^3", "x", {simplify: false})', 'derivative("2x^2 + 3x + 4", "x")', 'derivative("sin(2x)", "x")', 'f = parse("x^2 + x")', 'x = parse("x")', 'df = derivative(f, x)', 'df.evaluate({x: 3})'], + seealso: ['simplify', 'parse', 'evaluate'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/version.js +var versionDocs = { + name: 'version', + category: 'Constants', + syntax: ['version'], + description: 'A string with the version number of math.js', + examples: ['version'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/true.js +var trueDocs = { + name: 'true', + category: 'Constants', + syntax: ['true'], + description: 'Boolean value true', + examples: ['true'], + seealso: ['false'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/tau.js +var tauDocs = { + name: 'tau', + category: 'Constants', + syntax: ['tau'], + description: 'Tau is the ratio constant of a circle\'s circumference to radius, equal to 2 * pi, approximately 6.2832.', + examples: ['tau', '2 * pi'], + seealso: ['pi'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/SQRT2.js +var SQRT2Docs = { + name: 'SQRT2', + category: 'Constants', + syntax: ['SQRT2'], + description: 'Returns the square root of 2, approximately equal to 1.414', + examples: ['SQRT2', 'sqrt(2)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/SQRT1_2.js +var SQRT12Docs = { + name: 'SQRT1_2', + category: 'Constants', + syntax: ['SQRT1_2'], + description: 'Returns the square root of 1/2, approximately equal to 0.707', + examples: ['SQRT1_2', 'sqrt(1/2)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/phi.js +var phiDocs = { + name: 'phi', + category: 'Constants', + syntax: ['phi'], + description: 'Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as `(1 + sqrt(5)) / 2` and is approximately 1.618034...', + examples: ['phi'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/pi.js +var piDocs = { + name: 'pi', + category: 'Constants', + syntax: ['pi'], + description: 'The number pi is a mathematical constant that is the ratio of a circle\'s circumference to its diameter, and is approximately equal to 3.14159', + examples: ['pi', 'sin(pi/2)'], + seealso: ['tau'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/null.js +var nullDocs = { + name: 'null', + category: 'Constants', + syntax: ['null'], + description: 'Value null', + examples: ['null'], + seealso: ['true', 'false'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/NaN.js +var NaNDocs = { + name: 'NaN', + category: 'Constants', + syntax: ['NaN'], + description: 'Not a number', + examples: ['NaN', '0 / 0'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/LOG10E.js +var LOG10EDocs = { + name: 'LOG10E', + category: 'Constants', + syntax: ['LOG10E'], + description: 'Returns the base-10 logarithm of E, approximately equal to 0.434', + examples: ['LOG10E', 'log(e, 10)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/LOG2E.js +var LOG2EDocs = { + name: 'LOG2E', + category: 'Constants', + syntax: ['LOG2E'], + description: 'Returns the base-2 logarithm of E, approximately equal to 1.442', + examples: ['LOG2E', 'log(e, 2)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/LN10.js +var LN10Docs = { + name: 'LN10', + category: 'Constants', + syntax: ['LN10'], + description: 'Returns the natural logarithm of 10, approximately equal to 2.302', + examples: ['LN10', 'log(10)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/LN2.js +var LN2Docs = { + name: 'LN2', + category: 'Constants', + syntax: ['LN2'], + description: 'Returns the natural logarithm of 2, approximately equal to 0.693', + examples: ['LN2', 'log(2)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/Infinity.js +var InfinityDocs = { + name: 'Infinity', + category: 'Constants', + syntax: ['Infinity'], + description: 'Infinity, a number which is larger than the maximum number that can be handled by a floating point number.', + examples: ['Infinity', '1 / 0'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/i.js +var iDocs = { + name: 'i', + category: 'Constants', + syntax: ['i'], + description: 'Imaginary unit, defined as i*i=-1. A complex number is described as a + b*i, where a is the real part, and b is the imaginary part.', + examples: ['i', 'i * i', 'sqrt(-1)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/false.js +var falseDocs = { + name: 'false', + category: 'Constants', + syntax: ['false'], + description: 'Boolean value false', + examples: ['false'], + seealso: ['true'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/e.js +var eDocs = { + name: 'e', + category: 'Constants', + syntax: ['e'], + description: 'Euler\'s number, the base of the natural logarithm. Approximately equal to 2.71828', + examples: ['e', 'e ^ 2', 'exp(2)', 'log(e)'], + seealso: ['exp'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/unit.js +var unitDocs = { + name: 'unit', + category: 'Construction', + syntax: ['value unit', 'unit(value, unit)', 'unit(string)'], + description: 'Create a unit.', + examples: ['5.5 mm', '3 inch', 'unit(7.1, "kilogram")', 'unit("23 deg")'], + seealso: ['bignumber', 'boolean', 'complex', 'index', 'matrix', 'number', 'string'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/string.js +var stringDocs = { + name: 'string', + category: 'Construction', + syntax: ['"text"', 'string(x)'], + description: 'Create a string or convert a value to a string', + examples: ['"Hello World!"', 'string(4.2)', 'string(3 + 2i)'], + seealso: ['bignumber', 'boolean', 'complex', 'index', 'matrix', 'number', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/splitUnit.js +var splitUnitDocs = { + name: 'splitUnit', + category: 'Construction', + syntax: ['splitUnit(unit: Unit, parts: Unit[])'], + description: 'Split a unit in an array of units whose sum is equal to the original unit.', + examples: ['splitUnit(1 m, ["feet", "inch"])'], + seealso: ['unit', 'createUnit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/sparse.js +var sparseDocs = { + name: 'sparse', + category: 'Construction', + syntax: ['sparse()', 'sparse([a1, b1, ...; a1, b2, ...])', 'sparse([a1, b1, ...; a1, b2, ...], "number")'], + description: 'Create a sparse matrix.', + examples: ['sparse()', 'sparse([3, 4; 5, 6])', 'sparse([3, 0; 5, 0], "number")'], + seealso: ['bignumber', 'boolean', 'complex', 'index', 'number', 'string', 'unit', 'matrix'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/number.js +var numberDocs = { + name: 'number', + category: 'Construction', + syntax: ['x', 'number(x)', 'number(unit, valuelessUnit)'], + description: 'Create a number or convert a string or boolean into a number.', + examples: ['2', '2e3', '4.05', 'number(2)', 'number("7.2")', 'number(true)', 'number([true, false, true, true])', 'number(unit("52cm"), "m")'], + seealso: ['bignumber', 'boolean', 'complex', 'fraction', 'index', 'matrix', 'string', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/matrix.js +var matrixDocs = { + name: 'matrix', + category: 'Construction', + syntax: ['[]', '[a1, b1, ...; a2, b2, ...]', 'matrix()', 'matrix("dense")', 'matrix([...])'], + description: 'Create a matrix.', + examples: ['[]', '[1, 2, 3]', '[1, 2, 3; 4, 5, 6]', 'matrix()', 'matrix([3, 4])', 'matrix([3, 4; 5, 6], "sparse")', 'matrix([3, 4; 5, 6], "sparse", "number")'], + seealso: ['bignumber', 'boolean', 'complex', 'index', 'number', 'string', 'unit', 'sparse'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/index.js +var indexDocs = { + name: 'index', + category: 'Construction', + syntax: ['[start]', '[start:end]', '[start:step:end]', '[start1, start 2, ...]', '[start1:end1, start2:end2, ...]', '[start1:step1:end1, start2:step2:end2, ...]'], + description: 'Create an index to get or replace a subset of a matrix', + examples: ['[]', '[1, 2, 3]', 'A = [1, 2, 3; 4, 5, 6]', 'A[1, :]', 'A[1, 2] = 50', 'A[0:2, 0:2] = ones(2, 2)'], + seealso: ['bignumber', 'boolean', 'complex', 'matrix,', 'number', 'range', 'string', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/fraction.js +var fractionDocs = { + name: 'fraction', + category: 'Construction', + syntax: ['fraction(num)', 'fraction(num,den)'], + description: 'Create a fraction from a number or from a numerator and denominator.', + examples: ['fraction(0.125)', 'fraction(1, 3) + fraction(2, 5)'], + seealso: ['bignumber', 'boolean', 'complex', 'index', 'matrix', 'string', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/createUnit.js +var createUnitDocs = { + name: 'createUnit', + category: 'Construction', + syntax: ['createUnit(definitions)', 'createUnit(name, definition)'], + description: 'Create a user-defined unit and register it with the Unit type.', + examples: ['createUnit("foo")', 'createUnit("knot", {definition: "0.514444444 m/s", aliases: ["knots", "kt", "kts"]})', 'createUnit("mph", "1 mile/hour")'], + seealso: ['unit', 'splitUnit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/complex.js +var complexDocs = { + name: 'complex', + category: 'Construction', + syntax: ['complex()', 'complex(re, im)', 'complex(string)'], + description: 'Create a complex number.', + examples: ['complex()', 'complex(2, 3)', 'complex("7 - 2i")'], + seealso: ['bignumber', 'boolean', 'index', 'matrix', 'number', 'string', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/boolean.js +var booleanDocs = { + name: 'boolean', + category: 'Construction', + syntax: ['x', 'boolean(x)'], + description: 'Convert a string or number into a boolean.', + examples: ['boolean(0)', 'boolean(1)', 'boolean(3)', 'boolean("true")', 'boolean("false")', 'boolean([1, 0, 1, 1])'], + seealso: ['bignumber', 'complex', 'index', 'matrix', 'number', 'string', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/dotPow.js +var dotPowDocs = { + name: 'dotPow', + category: 'Operators', + syntax: ['x .^ y', 'dotPow(x, y)'], + description: 'Calculates the power of x to y element wise.', + examples: ['a = [1, 2, 3; 4, 5, 6]', 'a .^ 2'], + seealso: ['pow'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/lusolve.js +var lusolveDocs = { + name: 'lusolve', + category: 'Algebra', + syntax: ['x=lusolve(A, b)', 'x=lusolve(lu, b)'], + description: 'Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector.', + examples: ['a = [-2, 3; 2, 1]', 'b = [11, 9]', 'x = lusolve(a, b)'], + seealso: ['lup', 'slu', 'lsolve', 'usolve', 'matrix', 'sparse'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/subtract.js +var subtractDocs = { + name: 'subtract', + category: 'Operators', + syntax: ['x - y', 'subtract(x, y)'], + description: 'subtract two values.', + examples: ['a = 5.3 - 2', 'a + 2', '2/3 - 1/6', '2 * 3 - 3', '2.1 km - 500m'], + seealso: ['add'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/variance.js +var varianceDocs = { + name: 'variance', + category: 'Statistics', + syntax: ['variance(a, b, c, ...)', 'variance(A)', 'variance(A, normalization)'], + description: 'Compute the variance of all values. Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".', + examples: ['variance(2, 4, 6)', 'variance([2, 4, 6, 8])', 'variance([2, 4, 6, 8], "uncorrected")', 'variance([2, 4, 6, 8], "biased")', 'variance([1, 2, 3; 4, 5, 6])'], + seealso: ['max', 'mean', 'min', 'median', 'min', 'prod', 'std', 'sum'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/sin.js +var sinDocs = { + name: 'sin', + category: 'Trigonometry', + syntax: ['sin(x)'], + description: 'Compute the sine of x in radians.', + examples: ['sin(2)', 'sin(pi / 4) ^ 2', 'sin(90 deg)', 'sin(30 deg)', 'sin(0.2)^2 + cos(0.2)^2'], + seealso: ['asin', 'cos', 'tan'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/numeric.js +var numericDocs = { + name: 'numeric', + category: 'Utils', + syntax: ['numeric(x)'], + description: 'Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction.', + examples: ['numeric("4")', 'numeric("4", "number")', 'numeric("4", "BigNumber")', 'numeric("4", "Fraction)', 'numeric(4, "Fraction")', 'numeric(fraction(2, 5), "number)'], + seealso: ['number', 'fraction', 'bignumber', 'string', 'format'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/column.js +var columnDocs = { + name: 'column', + category: 'Matrix', + syntax: ['column(x, index)'], + description: 'Return a column from a matrix or array.', + examples: ['A = [[1, 2], [3, 4]]', 'column(A, 1)', 'column(A, 2)'], + seealso: ['row'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/row.js +var rowDocs = { + name: 'row', + category: 'Matrix', + syntax: ['row(x, index)'], + description: 'Return a row from a matrix or array.', + examples: ['A = [[1, 2], [3, 4]]', 'row(A, 1)', 'row(A, 2)'], + seealso: ['column'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/embeddedDocs.js + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +var embeddedDocs = { + // construction functions + bignumber: bignumberDocs, + "boolean": booleanDocs, + complex: complexDocs, + createUnit: createUnitDocs, + fraction: fractionDocs, + index: indexDocs, + matrix: matrixDocs, + number: numberDocs, + sparse: sparseDocs, + splitUnit: splitUnitDocs, + string: stringDocs, + unit: unitDocs, + // constants + e: eDocs, + E: eDocs, + "false": falseDocs, + i: iDocs, + Infinity: InfinityDocs, + LN2: LN2Docs, + LN10: LN10Docs, + LOG2E: LOG2EDocs, + LOG10E: LOG10EDocs, + NaN: NaNDocs, + "null": nullDocs, + pi: piDocs, + PI: piDocs, + phi: phiDocs, + SQRT1_2: SQRT12Docs, + SQRT2: SQRT2Docs, + tau: tauDocs, + "true": trueDocs, + version: versionDocs, + // physical constants + // TODO: more detailed docs for physical constants + speedOfLight: { + description: 'Speed of light in vacuum', + examples: ['speedOfLight'] + }, + gravitationConstant: { + description: 'Newtonian constant of gravitation', + examples: ['gravitationConstant'] + }, + planckConstant: { + description: 'Planck constant', + examples: ['planckConstant'] + }, + reducedPlanckConstant: { + description: 'Reduced Planck constant', + examples: ['reducedPlanckConstant'] + }, + magneticConstant: { + description: 'Magnetic constant (vacuum permeability)', + examples: ['magneticConstant'] + }, + electricConstant: { + description: 'Electric constant (vacuum permeability)', + examples: ['electricConstant'] + }, + vacuumImpedance: { + description: 'Characteristic impedance of vacuum', + examples: ['vacuumImpedance'] + }, + coulomb: { + description: 'Coulomb\'s constant', + examples: ['coulomb'] + }, + elementaryCharge: { + description: 'Elementary charge', + examples: ['elementaryCharge'] + }, + bohrMagneton: { + description: 'Borh magneton', + examples: ['bohrMagneton'] + }, + conductanceQuantum: { + description: 'Conductance quantum', + examples: ['conductanceQuantum'] + }, + inverseConductanceQuantum: { + description: 'Inverse conductance quantum', + examples: ['inverseConductanceQuantum'] + }, + // josephson: {description: 'Josephson constant', examples: ['josephson']}, + magneticFluxQuantum: { + description: 'Magnetic flux quantum', + examples: ['magneticFluxQuantum'] + }, + nuclearMagneton: { + description: 'Nuclear magneton', + examples: ['nuclearMagneton'] + }, + klitzing: { + description: 'Von Klitzing constant', + examples: ['klitzing'] + }, + bohrRadius: { + description: 'Borh radius', + examples: ['bohrRadius'] + }, + classicalElectronRadius: { + description: 'Classical electron radius', + examples: ['classicalElectronRadius'] + }, + electronMass: { + description: 'Electron mass', + examples: ['electronMass'] + }, + fermiCoupling: { + description: 'Fermi coupling constant', + examples: ['fermiCoupling'] + }, + fineStructure: { + description: 'Fine-structure constant', + examples: ['fineStructure'] + }, + hartreeEnergy: { + description: 'Hartree energy', + examples: ['hartreeEnergy'] + }, + protonMass: { + description: 'Proton mass', + examples: ['protonMass'] + }, + deuteronMass: { + description: 'Deuteron Mass', + examples: ['deuteronMass'] + }, + neutronMass: { + description: 'Neutron mass', + examples: ['neutronMass'] + }, + quantumOfCirculation: { + description: 'Quantum of circulation', + examples: ['quantumOfCirculation'] + }, + rydberg: { + description: 'Rydberg constant', + examples: ['rydberg'] + }, + thomsonCrossSection: { + description: 'Thomson cross section', + examples: ['thomsonCrossSection'] + }, + weakMixingAngle: { + description: 'Weak mixing angle', + examples: ['weakMixingAngle'] + }, + efimovFactor: { + description: 'Efimov factor', + examples: ['efimovFactor'] + }, + atomicMass: { + description: 'Atomic mass constant', + examples: ['atomicMass'] + }, + avogadro: { + description: 'Avogadro\'s number', + examples: ['avogadro'] + }, + boltzmann: { + description: 'Boltzmann constant', + examples: ['boltzmann'] + }, + faraday: { + description: 'Faraday constant', + examples: ['faraday'] + }, + firstRadiation: { + description: 'First radiation constant', + examples: ['firstRadiation'] + }, + loschmidt: { + description: 'Loschmidt constant at T=273.15 K and p=101.325 kPa', + examples: ['loschmidt'] + }, + gasConstant: { + description: 'Gas constant', + examples: ['gasConstant'] + }, + molarPlanckConstant: { + description: 'Molar Planck constant', + examples: ['molarPlanckConstant'] + }, + molarVolume: { + description: 'Molar volume of an ideal gas at T=273.15 K and p=101.325 kPa', + examples: ['molarVolume'] + }, + sackurTetrode: { + description: 'Sackur-Tetrode constant at T=1 K and p=101.325 kPa', + examples: ['sackurTetrode'] + }, + secondRadiation: { + description: 'Second radiation constant', + examples: ['secondRadiation'] + }, + stefanBoltzmann: { + description: 'Stefan-Boltzmann constant', + examples: ['stefanBoltzmann'] + }, + wienDisplacement: { + description: 'Wien displacement law constant', + examples: ['wienDisplacement'] + }, + // spectralRadiance: {description: 'First radiation constant for spectral radiance', examples: ['spectralRadiance']}, + molarMass: { + description: 'Molar mass constant', + examples: ['molarMass'] + }, + molarMassC12: { + description: 'Molar mass constant of carbon-12', + examples: ['molarMassC12'] + }, + gravity: { + description: 'Standard acceleration of gravity (standard acceleration of free-fall on Earth)', + examples: ['gravity'] + }, + planckLength: { + description: 'Planck length', + examples: ['planckLength'] + }, + planckMass: { + description: 'Planck mass', + examples: ['planckMass'] + }, + planckTime: { + description: 'Planck time', + examples: ['planckTime'] + }, + planckCharge: { + description: 'Planck charge', + examples: ['planckCharge'] + }, + planckTemperature: { + description: 'Planck temperature', + examples: ['planckTemperature'] + }, + // functions - algebra + derivative: derivativeDocs, + lsolve: lsolveDocs, + lup: lupDocs, + lusolve: lusolveDocs, + simplify: simplifyDocs, + rationalize: rationalizeDocs, + slu: sluDocs, + usolve: usolveDocs, + qr: qrDocs, + // functions - arithmetic + abs: absDocs, + add: addDocs, + cbrt: cbrtDocs, + ceil: ceilDocs, + cube: cubeDocs, + divide: divideDocs, + dotDivide: dotDivideDocs, + dotMultiply: dotMultiplyDocs, + dotPow: dotPowDocs, + exp: expDocs, + expm: expmDocs, + expm1: expm1Docs, + fix: fixDocs, + floor: floorDocs, + gcd: gcdDocs, + hypot: hypotDocs, + lcm: lcmDocs, + log: logDocs, + log2: log2Docs, + log1p: log1pDocs, + log10: log10Docs, + mod: modDocs, + multiply: multiplyDocs, + norm: normDocs, + nthRoot: nthRootDocs, + nthRoots: nthRootsDocs, + pow: powDocs, + round: roundDocs, + sign: signDocs, + sqrt: sqrtDocs, + sqrtm: sqrtmDocs, + square: squareDocs, + subtract: subtractDocs, + unaryMinus: unaryMinusDocs, + unaryPlus: unaryPlusDocs, + xgcd: xgcdDocs, + // functions - bitwise + bitAnd: bitAndDocs, + bitNot: bitNotDocs, + bitOr: bitOrDocs, + bitXor: bitXorDocs, + leftShift: leftShiftDocs, + rightArithShift: rightArithShiftDocs, + rightLogShift: rightLogShiftDocs, + // functions - combinatorics + bellNumbers: bellNumbersDocs, + catalan: catalanDocs, + composition: compositionDocs, + stirlingS2: stirlingS2Docs, + // functions - core + config: configDocs, + "import": importDocs, + typed: typedDocs, + // functions - complex + arg: argDocs, + conj: conjDocs, + re: reDocs, + im: imDocs, + // functions - expression + evaluate: evaluateDocs, + eval: evaluateDocs, + // TODO: deprecated, cleanup in v7 + help: helpDocs, + // functions - geometry + distance: distanceDocs, + intersect: intersectDocs, + // functions - logical + and: andDocs, + not: notDocs, + or: orDocs, + xor: xorDocs, + // functions - matrix + concat: concatDocs, + cross: crossDocs, + column: columnDocs, + ctranspose: ctransposeDocs, + det: detDocs, + diag: diagDocs, + dot: dotDocs, + getMatrixDataType: getMatrixDataTypeDocs, + identity: identityDocs, + filter: filterDocs, + flatten: flattenDocs, + forEach: forEachDocs, + inv: invDocs, + eigs: eigsDocs, + kron: kronDocs, + map: mapDocs, + ones: onesDocs, + partitionSelect: partitionSelectDocs, + range: rangeDocs, + resize: resizeDocs, + reshape: reshapeDocs, + row: rowDocs, + size: sizeDocs, + sort: sortDocs, + squeeze: squeezeDocs, + subset: subsetDocs, + trace: traceDocs, + transpose: transposeDocs, + zeros: zerosDocs, + // functions - probability + combinations: combinationsDocs, + combinationsWithRep: combinationsWithRepDocs, + // distribution: distributionDocs, + factorial: factorialDocs, + gamma: gammaDocs, + kldivergence: kldivergenceDocs, + multinomial: multinomialDocs, + permutations: permutationsDocs, + pickRandom: pickRandomDocs, + random: randomDocs, + randomInt: randomIntDocs, + // functions - relational + compare: compareDocs, + compareNatural: compareNaturalDocs, + compareText: compareTextDocs, + deepEqual: deepEqualDocs, + equal: equalDocs, + equalText: equalTextDocs, + larger: largerDocs, + largerEq: largerEqDocs, + smaller: smallerDocs, + smallerEq: smallerEqDocs, + unequal: unequalDocs, + // functions - set + setCartesian: setCartesianDocs, + setDifference: setDifferenceDocs, + setDistinct: setDistinctDocs, + setIntersect: setIntersectDocs, + setIsSubset: setIsSubsetDocs, + setMultiplicity: setMultiplicityDocs, + setPowerset: setPowersetDocs, + setSize: setSizeDocs, + setSymDifference: setSymDifferenceDocs, + setUnion: setUnionDocs, + // functions - special + erf: erfDocs, + // functions - statistics + mad: madDocs, + max: maxDocs, + mean: meanDocs, + median: medianDocs, + min: minDocs, + mode: modeDocs, + prod: prodDocs, + quantileSeq: quantileSeqDocs, + std: stdDocs, + sum: sumDocs, + variance: varianceDocs, + "var": varianceDocs, + // TODO: deprecated, cleanup in v7 + // functions - trigonometry + acos: acosDocs, + acosh: acoshDocs, + acot: acotDocs, + acoth: acothDocs, + acsc: acscDocs, + acsch: acschDocs, + asec: asecDocs, + asech: asechDocs, + asin: asinDocs, + asinh: asinhDocs, + atan: atanDocs, + atanh: atanhDocs, + atan2: atan2Docs, + cos: cosDocs, + cosh: coshDocs, + cot: cotDocs, + coth: cothDocs, + csc: cscDocs, + csch: cschDocs, + sec: secDocs, + sech: sechDocs, + sin: sinDocs, + sinh: sinhDocs, + tan: tanDocs, + tanh: tanhDocs, + // functions - units + to: toDocs, + // functions - utils + clone: cloneDocs, + format: formatDocs, + isNaN: isNaNDocs, + isInteger: isIntegerDocs, + isNegative: isNegativeDocs, + isNumeric: isNumericDocs, + hasNumericValue: hasNumericValueDocs, + isPositive: isPositiveDocs, + isPrime: isPrimeDocs, + isZero: isZeroDocs, + // print: printDocs // TODO: add documentation for print as soon as the parser supports objects. + typeOf: typeOfDocs, + "typeof": typeOfDocs, + // TODO: deprecated, cleanup in v7 + numeric: numericDocs +}; +// CONCATENATED MODULE: ./src/expression/function/help.js + + + + +var help_name = 'help'; +var help_dependencies = ['typed', 'mathWithTransform', 'Help']; +var createHelp = /* #__PURE__ */Object(factory["a" /* factory */])(help_name, help_dependencies, function (_ref) { + var typed = _ref.typed, + mathWithTransform = _ref.mathWithTransform, + Help = _ref.Help; + + /** + * Retrieve help on a function or data type. + * Help files are retrieved from the embedded documentation in math.docs. + * + * Syntax: + * + * math.help(search) + * + * Examples: + * + * console.log(math.help('sin').toString()) + * console.log(math.help(math.add).toString()) + * console.log(math.help(math.add).toJSON()) + * + * @param {Function | string | Object} search A function or function name + * for which to get help + * @return {Help} A help object + */ + return typed(help_name, { + any: function any(search) { + var prop; + var searchName = search; + + if (typeof search !== 'string') { + for (prop in mathWithTransform) { + // search in functions and constants + if (Object(utils_object["f" /* hasOwnProperty */])(mathWithTransform, prop) && search === mathWithTransform[prop]) { + searchName = prop; + break; + } + } + /* TODO: implement help for data types + if (!text) { + // search data type + for (prop in math.type) { + if (hasOwnProperty(math, prop)) { + if (search === math.type[prop]) { + text = prop + break + } + } + } + } + */ + + } + + var doc = getSafeProperty(embeddedDocs, searchName); + + if (!doc) { + var searchText = typeof searchName === 'function' ? searchName.name : searchName; + throw new Error('No documentation found on "' + searchText + '"'); + } + + return new Help(doc); + } + }); +}); +// CONCATENATED MODULE: ./src/type/chain/function/chain.js + +var chain_name = 'chain'; +var chain_dependencies = ['typed', 'Chain']; +var createChain = /* #__PURE__ */Object(factory["a" /* factory */])(chain_name, chain_dependencies, function (_ref) { + var typed = _ref.typed, + Chain = _ref.Chain; + + /** + * Wrap any value in a chain, allowing to perform chained operations on + * the value. + * + * All methods available in the math.js library can be called upon the chain, + * and then will be evaluated with the value itself as first argument. + * The chain can be closed by executing `chain.done()`, which returns + * the final value. + * + * The chain has a number of special functions: + * + * - `done()` Finalize the chain and return the chain's value. + * - `valueOf()` The same as `done()` + * - `toString()` Executes `math.format()` onto the chain's value, returning + * a string representation of the value. + * + * Syntax: + * + * math.chain(value) + * + * Examples: + * + * math.chain(3) + * .add(4) + * .subtract(2) + * .done() // 5 + * + * math.chain( [[1, 2], [3, 4]] ) + * .subset(math.index(0, 0), 8) + * .multiply(3) + * .done() // [[24, 6], [9, 12]] + * + * @param {*} [value] A value of any type on which to start a chained operation. + * @return {math.Chain} The created chain + */ + return typed(chain_name, { + '': function _() { + return new Chain(); + }, + any: function any(value) { + return new Chain(value); + } + }); +}); +// CONCATENATED MODULE: ./src/function/matrix/det.js + + + + +var det_name = 'det'; +var det_dependencies = ['typed', 'matrix', 'subtract', 'multiply', 'unaryMinus', 'lup']; +var createDet = /* #__PURE__ */Object(factory["a" /* factory */])(det_name, det_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + subtract = _ref.subtract, + multiply = _ref.multiply, + unaryMinus = _ref.unaryMinus, + lup = _ref.lup; + + /** + * Calculate the determinant of a matrix. + * + * Syntax: + * + * math.det(x) + * + * Examples: + * + * math.det([[1, 2], [3, 4]]) // returns -2 + * + * const A = [ + * [-2, 2, 3], + * [-1, 1, 3], + * [2, 0, -1] + * ] + * math.det(A) // returns 6 + * + * See also: + * + * inv + * + * @param {Array | Matrix} x A matrix + * @return {number} The determinant of `x` + */ + return typed(det_name, { + any: function any(x) { + return Object(utils_object["a" /* clone */])(x); + }, + 'Array | Matrix': function det(x) { + var size; + + if (Object(is["v" /* isMatrix */])(x)) { + size = x.size(); + } else if (Array.isArray(x)) { + x = matrix(x); + size = x.size(); + } else { + // a scalar + size = []; + } + + switch (size.length) { + case 0: + // scalar + return Object(utils_object["a" /* clone */])(x); + + case 1: + // vector + if (size[0] === 1) { + return Object(utils_object["a" /* clone */])(x.valueOf()[0]); + } else { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + + case 2: + { + // two dimensional array + var rows = size[0]; + var cols = size[1]; + + if (rows === cols) { + return _det(x.clone().valueOf(), rows, cols); + } else { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + } + + default: + // multi dimensional array + throw new RangeError('Matrix must be two dimensional ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + } + }); + /** + * Calculate the determinant of a matrix + * @param {Array[]} matrix A square, two dimensional matrix + * @param {number} rows Number of rows of the matrix (zero-based) + * @param {number} cols Number of columns of the matrix (zero-based) + * @returns {number} det + * @private + */ + + function _det(matrix, rows, cols) { + if (rows === 1) { + // this is a 1 x 1 matrix + return Object(utils_object["a" /* clone */])(matrix[0][0]); + } else if (rows === 2) { + // this is a 2 x 2 matrix + // the determinant of [a11,a12;a21,a22] is det = a11*a22-a21*a12 + return subtract(multiply(matrix[0][0], matrix[1][1]), multiply(matrix[1][0], matrix[0][1])); + } else { + // Compute the LU decomposition + var decomp = lup(matrix); // The determinant is the product of the diagonal entries of U (and those of L, but they are all 1) + + var det = decomp.U[0][0]; + + for (var _i = 1; _i < rows; _i++) { + det = multiply(det, decomp.U[_i][_i]); + } // The determinant will be multiplied by 1 or -1 depending on the parity of the permutation matrix. + // This can be determined by counting the cycles. This is roughly a linear time algorithm. + + + var evenCycles = 0; + var i = 0; + var visited = []; + + while (true) { + while (visited[i]) { + i++; + } + + if (i >= rows) break; + var j = i; + var cycleLen = 0; + + while (!visited[decomp.p[j]]) { + visited[decomp.p[j]] = true; + j = decomp.p[j]; + cycleLen++; + } + + if (cycleLen % 2 === 0) { + evenCycles++; + } + } + + return evenCycles % 2 === 0 ? det : unaryMinus(det); + } + } +}); +// CONCATENATED MODULE: ./src/function/matrix/inv.js + + + + +var inv_name = 'inv'; +var inv_dependencies = ['typed', 'matrix', 'divideScalar', 'addScalar', 'multiply', 'unaryMinus', 'det', 'identity', 'abs']; +var createInv = /* #__PURE__ */Object(factory["a" /* factory */])(inv_name, inv_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + divideScalar = _ref.divideScalar, + addScalar = _ref.addScalar, + multiply = _ref.multiply, + unaryMinus = _ref.unaryMinus, + det = _ref.det, + identity = _ref.identity, + abs = _ref.abs; + + /** + * Calculate the inverse of a square matrix. + * + * Syntax: + * + * math.inv(x) + * + * Examples: + * + * math.inv([[1, 2], [3, 4]]) // returns [[-2, 1], [1.5, -0.5]] + * math.inv(4) // returns 0.25 + * 1 / 4 // returns 0.25 + * + * See also: + * + * det, transpose + * + * @param {number | Complex | Array | Matrix} x Matrix to be inversed + * @return {number | Complex | Array | Matrix} The inverse of `x`. + */ + return typed(inv_name, { + 'Array | Matrix': function ArrayMatrix(x) { + var size = Object(is["v" /* isMatrix */])(x) ? x.size() : Object(utils_array["a" /* arraySize */])(x); + + switch (size.length) { + case 1: + // vector + if (size[0] === 1) { + if (Object(is["v" /* isMatrix */])(x)) { + return matrix([divideScalar(1, x.valueOf()[0])]); + } else { + return [divideScalar(1, x[0])]; + } + } else { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + + case 2: + // two dimensional array + { + var rows = size[0]; + var cols = size[1]; + + if (rows === cols) { + if (Object(is["v" /* isMatrix */])(x)) { + return matrix(_inv(x.valueOf(), rows, cols), x.storage()); + } else { + // return an Array + return _inv(x, rows, cols); + } + } else { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + } + + default: + // multi dimensional array + throw new RangeError('Matrix must be two dimensional ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + }, + any: function any(x) { + // scalar + return divideScalar(1, x); // FIXME: create a BigNumber one when configured for bignumbers + } + }); + /** + * Calculate the inverse of a square matrix + * @param {Array[]} mat A square matrix + * @param {number} rows Number of rows + * @param {number} cols Number of columns, must equal rows + * @return {Array[]} inv Inverse matrix + * @private + */ + + function _inv(mat, rows, cols) { + var r, s, f, value, temp; + + if (rows === 1) { + // this is a 1 x 1 matrix + value = mat[0][0]; + + if (value === 0) { + throw Error('Cannot calculate inverse, determinant is zero'); + } + + return [[divideScalar(1, value)]]; + } else if (rows === 2) { + // this is a 2 x 2 matrix + var d = det(mat); + + if (d === 0) { + throw Error('Cannot calculate inverse, determinant is zero'); + } + + return [[divideScalar(mat[1][1], d), divideScalar(unaryMinus(mat[0][1]), d)], [divideScalar(unaryMinus(mat[1][0]), d), divideScalar(mat[0][0], d)]]; + } else { + // this is a matrix of 3 x 3 or larger + // calculate inverse using gauss-jordan elimination + // https://en.wikipedia.org/wiki/Gaussian_elimination + // http://mathworld.wolfram.com/MatrixInverse.html + // http://math.uww.edu/~mcfarlat/inverse.htm + // make a copy of the matrix (only the arrays, not of the elements) + var A = mat.concat(); + + for (r = 0; r < rows; r++) { + A[r] = A[r].concat(); + } // create an identity matrix which in the end will contain the + // matrix inverse + + + var B = identity(rows).valueOf(); // loop over all columns, and perform row reductions + + for (var c = 0; c < cols; c++) { + // Pivoting: Swap row c with row r, where row r contains the largest element A[r][c] + var ABig = abs(A[c][c]); + var rBig = c; + r = c + 1; + + while (r < rows) { + if (abs(A[r][c]) > ABig) { + ABig = abs(A[r][c]); + rBig = r; + } + + r++; + } + + if (ABig === 0) { + throw Error('Cannot calculate inverse, determinant is zero'); + } + + r = rBig; + + if (r !== c) { + temp = A[c]; + A[c] = A[r]; + A[r] = temp; + temp = B[c]; + B[c] = B[r]; + B[r] = temp; + } // eliminate non-zero values on the other rows at column c + + + var Ac = A[c]; + var Bc = B[c]; + + for (r = 0; r < rows; r++) { + var Ar = A[r]; + var Br = B[r]; + + if (r !== c) { + // eliminate value at column c and row r + if (Ar[c] !== 0) { + f = divideScalar(unaryMinus(Ar[c]), Ac[c]); // add (f * row c) to row r to eliminate the value + // at column c + + for (s = c; s < cols; s++) { + Ar[s] = addScalar(Ar[s], multiply(f, Ac[s])); + } + + for (s = 0; s < cols; s++) { + Br[s] = addScalar(Br[s], multiply(f, Bc[s])); + } + } + } else { + // normalize value at Acc to 1, + // divide each value on row r with the value at Acc + f = Ac[c]; + + for (s = c; s < cols; s++) { + Ar[s] = divideScalar(Ar[s], f); + } + + for (s = 0; s < cols; s++) { + Br[s] = divideScalar(Br[s], f); + } + } + } + } + + return B; + } + } +}); +// CONCATENATED MODULE: ./src/function/matrix/eigs.js + + + +var eigs_name = 'eigs'; +var eigs_dependencies = ['config', 'typed', 'matrix', 'addScalar', 'equal', 'subtract', 'abs', 'atan', 'cos', 'sin', 'multiplyScalar', 'inv', 'bignumber', 'multiply', 'add']; +var createEigs = /* #__PURE__ */Object(factory["a" /* factory */])(eigs_name, eigs_dependencies, function (_ref) { + var config = _ref.config, + typed = _ref.typed, + matrix = _ref.matrix, + addScalar = _ref.addScalar, + subtract = _ref.subtract, + equal = _ref.equal, + abs = _ref.abs, + atan = _ref.atan, + cos = _ref.cos, + sin = _ref.sin, + multiplyScalar = _ref.multiplyScalar, + inv = _ref.inv, + bignumber = _ref.bignumber, + multiply = _ref.multiply, + add = _ref.add; + + /** + * Compute eigenvalue and eigenvector of a real symmetric matrix. + * Only applicable to two dimensional symmetric matrices. Uses Jacobi + * Algorithm. Matrix containing mixed type ('number', 'bignumber', 'fraction') + * of elements are not supported. Input matrix or 2D array should contain all elements + * of either 'number', 'bignumber' or 'fraction' type. For 'number' and 'fraction', the + * eigenvalues are of 'number' type. For 'bignumber' the eigenvalues are of ''bignumber' type. + * Eigenvectors are always of 'number' type. + * + * Syntax: + * + * math.eigs(x) + * + * Examples: + * + * const H = [[5, 2.3], [2.3, 1]] + * const ans = math.eigs(H) // returns {values: [E1,E2...sorted], vectors: [v1,v2.... corresponding vectors]} + * const E = ans.values + * const U = ans.vectors + * const UTxHxU = math.multiply(math.transpose(U), H, U) // rotates H to the eigen-representation + * E[0] == UTxHxU[0][0] // returns true + * See also: + * + * inv + * + * @param {Array | Matrix} x Matrix to be diagonalized + * @return {{values: Array, vectors: Array} | {values: Matrix, vectors: Matrix}} Object containing eigenvalues (Array or Matrix) and eigenvectors (2D Array/Matrix). + */ + var eigs = typed('eigs', { + Array: function Array(x) { + // check array size + var mat = matrix(x); + var size = mat.size(); + + if (size.length !== 2 || size[0] !== size[1]) { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } // use dense 2D matrix implementation + + + var ans = checkAndSubmit(mat, size[0]); + return { + values: ans[0], + vectors: ans[1] + }; + }, + Matrix: function Matrix(x) { + // use dense 2D array implementation + // dense matrix + var size = x.size(); + + if (size.length !== 2 || size[0] !== size[1]) { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + + var ans = checkAndSubmit(x, size[0]); + return { + values: matrix(ans[0]), + vectors: matrix(ans[1]) + }; + } + }); // Is the matrix + // symmetric ? + + function isSymmetric(x, n) { + for (var i = 0; i < n; i++) { + for (var j = i; j < n; j++) { + // not symmtric + if (!equal(x[i][j], x[j][i])) { + throw new TypeError('Input matrix is not symmetric'); + } + } + } + } // check input for possible problems + // and perform diagonalization efficiently for + // specific type of number + + + function checkAndSubmit(x, n) { + var type = x.datatype(); // type check + + if (type === undefined) { + type = x.getDataType(); + } + + if (type !== 'number' && type !== 'BigNumber' && type !== 'Fraction') { + if (type === 'mixed') { + throw new TypeError('Mixed matrix element type is not supported'); + } else { + throw new TypeError('Matrix element type not supported (' + type + ')'); + } + } else { + isSymmetric(x.toArray(), n); + } // perform efficient calculation for 'numbers' + + + if (type === 'number') { + return diag(x.toArray()); + } else if (type === 'Fraction') { + var xArr = x.toArray(); // convert fraction to numbers + + for (var i = 0; i < n; i++) { + for (var j = i; j < n; j++) { + xArr[i][j] = xArr[i][j].valueOf(); + xArr[j][i] = xArr[i][j]; + } + } + + return diag(x.toArray()); + } else if (type === 'BigNumber') { + return diagBig(x.toArray()); + } + } // diagonalization implementation for number (efficient) + + + function diag(x) { + var N = x.length; + var e0 = Math.abs(config.epsilon / N); + var psi; + var Sij = new Array(N); // Sij is Identity Matrix + + for (var i = 0; i < N; i++) { + Sij[i] = createArray(N, 0); + Sij[i][i] = 1.0; + } // initial error + + + var Vab = getAij(x); + + while (Math.abs(Vab[1]) >= Math.abs(e0)) { + var _i = Vab[0][0]; + var j = Vab[0][1]; + psi = getTheta(x[_i][_i], x[j][j], x[_i][j]); + x = x1(x, psi, _i, j); + Sij = Sij1(Sij, psi, _i, j); + Vab = getAij(x); + } + + var Ei = createArray(N, 0); // eigenvalues + + for (var _i2 = 0; _i2 < N; _i2++) { + Ei[_i2] = x[_i2][_i2]; + } + + return sorting(Object(utils_object["a" /* clone */])(Ei), Object(utils_object["a" /* clone */])(Sij)); + } // diagonalization implementation for bigNumber + + + function diagBig(x) { + var N = x.length; + var e0 = abs(config.epsilon / N); + var psi; + var Sij = new Array(N); // Sij is Identity Matrix + + for (var i = 0; i < N; i++) { + Sij[i] = createArray(N, 0); + Sij[i][i] = 1.0; + } // initial error + + + var Vab = getAijBig(x); + + while (abs(Vab[1]) >= abs(e0)) { + var _i3 = Vab[0][0]; + var j = Vab[0][1]; + psi = getThetaBig(x[_i3][_i3], x[j][j], x[_i3][j]); + x = x1Big(x, psi, _i3, j); + Sij = Sij1Big(Sij, psi, _i3, j); + Vab = getAijBig(x); + } + + var Ei = createArray(N, 0); // eigenvalues + + for (var _i4 = 0; _i4 < N; _i4++) { + Ei[_i4] = x[_i4][_i4]; + } // return [clone(Ei), clone(Sij)] + + + return sorting(Object(utils_object["a" /* clone */])(Ei), Object(utils_object["a" /* clone */])(Sij)); + } // get angle + + + function getTheta(aii, ajj, aij) { + var denom = ajj - aii; + + if (Math.abs(denom) <= config.epsilon) { + return Math.PI / 4; + } else { + return 0.5 * Math.atan(2 * aij / (ajj - aii)); + } + } // get angle + + + function getThetaBig(aii, ajj, aij) { + var denom = subtract(ajj, aii); + + if (abs(denom) <= config.epsilon) { + return bignumber(-1).acos().div(4); + } else { + return multiplyScalar(0.5, atan(multiply(2, aij, inv(denom)))); + } + } // update eigvec + + + function Sij1(Sij, theta, i, j) { + var N = Sij.length; + var c = Math.cos(theta); + var s = Math.sin(theta); + var Ski = createArray(N, 0); + var Skj = createArray(N, 0); + + for (var k = 0; k < N; k++) { + Ski[k] = c * Sij[k][i] - s * Sij[k][j]; + Skj[k] = s * Sij[k][i] + c * Sij[k][j]; + } + + for (var _k = 0; _k < N; _k++) { + Sij[_k][i] = Ski[_k]; + Sij[_k][j] = Skj[_k]; + } + + return Sij; + } // update eigvec for overlap + + + function Sij1Big(Sij, theta, i, j) { + var N = Sij.length; + var c = cos(theta); + var s = sin(theta); + var Ski = createArray(N, bignumber(0)); + var Skj = createArray(N, bignumber(0)); + + for (var k = 0; k < N; k++) { + Ski[k] = subtract(multiplyScalar(c, Sij[k][i]), multiplyScalar(s, Sij[k][j])); + Skj[k] = addScalar(multiplyScalar(s, Sij[k][i]), multiplyScalar(c, Sij[k][j])); + } + + for (var _k2 = 0; _k2 < N; _k2++) { + Sij[_k2][i] = Ski[_k2]; + Sij[_k2][j] = Skj[_k2]; + } + + return Sij; + } // update matrix + + + function x1Big(Hij, theta, i, j) { + var N = Hij.length; + var c = bignumber(cos(theta)); + var s = bignumber(sin(theta)); + var c2 = multiplyScalar(c, c); + var s2 = multiplyScalar(s, s); + var Aki = createArray(N, bignumber(0)); + var Akj = createArray(N, bignumber(0)); // 2cs Hij + + var csHij = multiply(bignumber(2), c, s, Hij[i][j]); // Aii + + var Aii = addScalar(subtract(multiplyScalar(c2, Hij[i][i]), csHij), multiplyScalar(s2, Hij[j][j])); + var Ajj = add(multiplyScalar(s2, Hij[i][i]), csHij, multiplyScalar(c2, Hij[j][j])); // 0 to i + + for (var k = 0; k < N; k++) { + Aki[k] = subtract(multiplyScalar(c, Hij[i][k]), multiplyScalar(s, Hij[j][k])); + Akj[k] = addScalar(multiplyScalar(s, Hij[i][k]), multiplyScalar(c, Hij[j][k])); + } // Modify Hij + + + Hij[i][i] = Aii; + Hij[j][j] = Ajj; + Hij[i][j] = bignumber(0); + Hij[j][i] = bignumber(0); // 0 to i + + for (var _k3 = 0; _k3 < N; _k3++) { + if (_k3 !== i && _k3 !== j) { + Hij[i][_k3] = Aki[_k3]; + Hij[_k3][i] = Aki[_k3]; + Hij[j][_k3] = Akj[_k3]; + Hij[_k3][j] = Akj[_k3]; + } + } + + return Hij; + } // update matrix + + + function x1(Hij, theta, i, j) { + var N = Hij.length; + var c = Math.cos(theta); + var s = Math.sin(theta); + var c2 = c * c; + var s2 = s * s; + var Aki = createArray(N, 0); + var Akj = createArray(N, 0); // Aii + + var Aii = c2 * Hij[i][i] - 2 * c * s * Hij[i][j] + s2 * Hij[j][j]; + var Ajj = s2 * Hij[i][i] + 2 * c * s * Hij[i][j] + c2 * Hij[j][j]; // 0 to i + + for (var k = 0; k < N; k++) { + Aki[k] = c * Hij[i][k] - s * Hij[j][k]; + Akj[k] = s * Hij[i][k] + c * Hij[j][k]; + } // Modify Hij + + + Hij[i][i] = Aii; + Hij[j][j] = Ajj; + Hij[i][j] = 0; + Hij[j][i] = 0; // 0 to i + + for (var _k4 = 0; _k4 < N; _k4++) { + if (_k4 !== i && _k4 !== j) { + Hij[i][_k4] = Aki[_k4]; + Hij[_k4][i] = Aki[_k4]; + Hij[j][_k4] = Akj[_k4]; + Hij[_k4][j] = Akj[_k4]; + } + } + + return Hij; + } // get max off-diagonal value from Upper Diagonal + + + function getAij(Mij) { + var N = Mij.length; + var maxMij = 0; + var maxIJ = [0, 1]; + + for (var i = 0; i < N; i++) { + for (var j = i + 1; j < N; j++) { + if (Math.abs(maxMij) < Math.abs(Mij[i][j])) { + maxMij = Math.abs(Mij[i][j]); + maxIJ = [i, j]; + } + } + } + + return [maxIJ, maxMij]; + } // get max off-diagonal value from Upper Diagonal + + + function getAijBig(Mij) { + var N = Mij.length; + var maxMij = 0; + var maxIJ = [0, 1]; + + for (var i = 0; i < N; i++) { + for (var j = i + 1; j < N; j++) { + if (abs(maxMij) < abs(Mij[i][j])) { + maxMij = abs(Mij[i][j]); + maxIJ = [i, j]; + } + } + } + + return [maxIJ, maxMij]; + } // sort results + + + function sorting(E, S) { + var N = E.length; + var Ef = Array(N); + var Sf = Array(N); + + for (var k = 0; k < N; k++) { + Sf[k] = Array(N); + } + + for (var i = 0; i < N; i++) { + var minID = 0; + var minE = E[0]; + + for (var j = 0; j < E.length; j++) { + if (E[j] < minE) { + minID = j; + minE = E[minID]; + } + } + + Ef[i] = E.splice(minID, 1)[0]; + + for (var _k5 = 0; _k5 < N; _k5++) { + Sf[_k5][i] = S[_k5][minID]; + + S[_k5].splice(minID, 1); + } + } + + return [Object(utils_object["a" /* clone */])(Ef), Object(utils_object["a" /* clone */])(Sf)]; + } + /** + * Create an array of a certain size and fill all items with an initial value + * @param {number} size + * @param {number} value + * @return {number[]} + */ + + + function createArray(size, value) { + // TODO: as soon as all browsers support Array.fill, use that instead (IE doesn't support it) + var array = new Array(size); + + for (var i = 0; i < size; i++) { + array[i] = value; + } + + return array; + } + + return eigs; +}); +// CONCATENATED MODULE: ./src/function/matrix/expm.js + + + +var expm_name = 'expm'; +var expm_dependencies = ['typed', 'abs', 'add', 'identity', 'inv', 'multiply']; +var createExpm = /* #__PURE__ */Object(factory["a" /* factory */])(expm_name, expm_dependencies, function (_ref) { + var typed = _ref.typed, + abs = _ref.abs, + add = _ref.add, + identity = _ref.identity, + inv = _ref.inv, + multiply = _ref.multiply; + + /** + * Compute the matrix exponential, expm(A) = e^A. The matrix must be square. + * Not to be confused with exp(a), which performs element-wise + * exponentiation. + * + * The exponential is calculated using the Padé approximant with scaling and + * squaring; see "Nineteen Dubious Ways to Compute the Exponential of a + * Matrix," by Moler and Van Loan. + * + * Syntax: + * + * math.expm(x) + * + * Examples: + * + * const A = [[0,2],[0,0]] + * math.expm(A) // returns [[1,2],[0,1]] + * + * See also: + * + * exp + * + * @param {Matrix} x A square Matrix + * @return {Matrix} The exponential of x + */ + return typed(expm_name, { + Matrix: function Matrix(A) { + // Check matrix size + var size = A.size(); + + if (size.length !== 2 || size[0] !== size[1]) { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + + var n = size[0]; // Desired accuracy of the approximant (The actual accuracy + // will be affected by round-off error) + + var eps = 1e-15; // The Padé approximant is not so accurate when the values of A + // are "large", so scale A by powers of two. Then compute the + // exponential, and square the result repeatedly according to + // the identity e^A = (e^(A/m))^m + // Compute infinity-norm of A, ||A||, to see how "big" it is + + var infNorm = infinityNorm(A); // Find the optimal scaling factor and number of terms in the + // Padé approximant to reach the desired accuracy + + var params = findParams(infNorm, eps); + var q = params.q; + var j = params.j; // The Pade approximation to e^A is: + // Rqq(A) = Dqq(A) ^ -1 * Nqq(A) + // where + // Nqq(A) = sum(i=0, q, (2q-i)!p! / [ (2q)!i!(q-i)! ] A^i + // Dqq(A) = sum(i=0, q, (2q-i)!q! / [ (2q)!i!(q-i)! ] (-A)^i + // Scale A by 1 / 2^j + + var Apos = multiply(A, Math.pow(2, -j)); // The i=0 term is just the identity matrix + + var N = identity(n); + var D = identity(n); // Initialization (i=0) + + var factor = 1; // Initialization (i=1) + + var AposToI = Apos; // Cloning not necessary + + var alternate = -1; + + for (var i = 1; i <= q; i++) { + if (i > 1) { + AposToI = multiply(AposToI, Apos); + alternate = -alternate; + } + + factor = factor * (q - i + 1) / ((2 * q - i + 1) * i); + N = add(N, multiply(factor, AposToI)); + D = add(D, multiply(factor * alternate, AposToI)); + } + + var R = multiply(inv(D), N); // Square j times + + for (var _i = 0; _i < j; _i++) { + R = multiply(R, R); + } + + return Object(is["H" /* isSparseMatrix */])(A) ? A.createSparseMatrix(R) : R; + } + }); + + function infinityNorm(A) { + var n = A.size()[0]; + var infNorm = 0; + + for (var i = 0; i < n; i++) { + var rowSum = 0; + + for (var j = 0; j < n; j++) { + rowSum += abs(A.get([i, j])); + } + + infNorm = Math.max(rowSum, infNorm); + } + + return infNorm; + } + /** + * Find the best parameters for the Pade approximant given + * the matrix norm and desired accuracy. Returns the first acceptable + * combination in order of increasing computational load. + */ + + + function findParams(infNorm, eps) { + var maxSearchSize = 30; + + for (var k = 0; k < maxSearchSize; k++) { + for (var q = 0; q <= k; q++) { + var j = k - q; + + if (errorEstimate(infNorm, q, j) < eps) { + return { + q: q, + j: j + }; + } + } + } + + throw new Error('Could not find acceptable parameters to compute the matrix exponential (try increasing maxSearchSize in expm.js)'); + } + /** + * Returns the estimated error of the Pade approximant for the given + * parameters. + */ + + + function errorEstimate(infNorm, q, j) { + var qfac = 1; + + for (var i = 2; i <= q; i++) { + qfac *= i; + } + + var twoqfac = qfac; + + for (var _i2 = q + 1; _i2 <= 2 * q; _i2++) { + twoqfac *= _i2; + } + + var twoqp1fac = twoqfac * (2 * q + 1); + return 8.0 * Math.pow(infNorm / Math.pow(2, j), 2 * q) * qfac * qfac / (twoqfac * twoqp1fac); + } +}); +// CONCATENATED MODULE: ./src/function/matrix/sqrtm.js + + + + +var sqrtm_name = 'sqrtm'; +var sqrtm_dependencies = ['typed', 'abs', 'add', 'multiply', 'sqrt', 'subtract', 'inv', 'size', 'max', 'identity']; +var createSqrtm = /* #__PURE__ */Object(factory["a" /* factory */])(sqrtm_name, sqrtm_dependencies, function (_ref) { + var typed = _ref.typed, + abs = _ref.abs, + add = _ref.add, + multiply = _ref.multiply, + sqrt = _ref.sqrt, + subtract = _ref.subtract, + inv = _ref.inv, + size = _ref.size, + max = _ref.max, + identity = _ref.identity; + + /** + * Calculate the principal square root of a square matrix. + * The principal square root matrix `X` of another matrix `A` is such that `X * X = A`. + * + * https://en.wikipedia.org/wiki/Square_root_of_a_matrix + * + * Syntax: + * + * X = math.sqrtm(A) + * + * Examples: + * + * math.sqrtm([[1, 2], [3, 4]]) // returns [[-2, 1], [1.5, -0.5]] + * + * See also: + * + * sqrt, pow + * + * @param {Array | Matrix} A The square matrix `A` + * @return {Array | Matrix} The principal square root of matrix `A` + */ + var sqrtm = typed(sqrtm_name, { + 'Array | Matrix': function ArrayMatrix(A) { + var size = Object(is["v" /* isMatrix */])(A) ? A.size() : Object(utils_array["a" /* arraySize */])(A); + + switch (size.length) { + case 1: + // Single element Array | Matrix + if (size[0] === 1) { + return sqrt(A); + } else { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + + case 2: + { + // Two-dimensional Array | Matrix + var rows = size[0]; + var cols = size[1]; + + if (rows === cols) { + return _denmanBeavers(A); + } else { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + } + } + } + }); + var _maxIterations = 1e3; + var _tolerance = 1e-6; + /** + * Calculate the principal square root matrix using the Denman–Beavers iterative method + * + * https://en.wikipedia.org/wiki/Square_root_of_a_matrix#By_Denman–Beavers_iteration + * + * @param {Array | Matrix} A The square matrix `A` + * @return {Array | Matrix} The principal square root of matrix `A` + * @private + */ + + function _denmanBeavers(A) { + var error; + var iterations = 0; + var Y = A; + var Z = identity(size(A)); + + do { + var Yk = Y; + Y = multiply(0.5, add(Yk, inv(Z))); + Z = multiply(0.5, add(Z, inv(Yk))); + error = max(abs(subtract(Y, Yk))); + + if (error > _tolerance && ++iterations > _maxIterations) { + throw new Error('computing square root of matrix: iterative method could not converge'); + } + } while (error > _tolerance); + + return Y; + } + + return sqrtm; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/divide.js + + + + +var divide_name = 'divide'; +var divide_dependencies = ['typed', 'matrix', 'multiply', 'equalScalar', 'divideScalar', 'inv']; +var createDivide = /* #__PURE__ */Object(factory["a" /* factory */])(divide_name, divide_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + multiply = _ref.multiply, + equalScalar = _ref.equalScalar, + divideScalar = _ref.divideScalar, + inv = _ref.inv; + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Divide two values, `x / y`. + * To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`. + * + * Syntax: + * + * math.divide(x, y) + * + * Examples: + * + * math.divide(2, 3) // returns number 0.6666666666666666 + * + * const a = math.complex(5, 14) + * const b = math.complex(4, 1) + * math.divide(a, b) // returns Complex 2 + 3i + * + * const c = [[7, -6], [13, -4]] + * const d = [[1, 2], [4, 3]] + * math.divide(c, d) // returns Array [[-9, 4], [-11, 6]] + * + * const e = math.unit('18 km') + * math.divide(e, 4.5) // returns Unit 4 km + * + * See also: + * + * multiply + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator + * @param {number | BigNumber | Fraction | Complex | Array | Matrix} y Denominator + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Quotient, `x / y` + */ + + return typed('divide', Object(utils_object["e" /* extend */])({ + // we extend the signatures of divideScalar with signatures dealing with matrices + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(x, y) { + // TODO: implement matrix right division using pseudo inverse + // https://www.mathworks.nl/help/matlab/ref/mrdivide.html + // https://www.gnu.org/software/octave/doc/interpreter/Arithmetic-Ops.html + // https://stackoverflow.com/questions/12263932/how-does-gnu-octave-matrix-division-work-getting-unexpected-behaviour + return multiply(x, inv(y)); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, divideScalar, false); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, divideScalar, false); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, divideScalar, false).valueOf(); + }, + 'any, Array | Matrix': function anyArrayMatrix(x, y) { + return multiply(x, inv(y)); + } + }, divideScalar.signatures)); +}); +// CONCATENATED MODULE: ./src/function/geometry/distance.js + + +var distance_name = 'distance'; +var distance_dependencies = ['typed', 'addScalar', 'subtract', 'divideScalar', 'multiplyScalar', 'unaryMinus', 'sqrt', 'abs']; +var createDistance = /* #__PURE__ */Object(factory["a" /* factory */])(distance_name, distance_dependencies, function (_ref) { + var typed = _ref.typed, + addScalar = _ref.addScalar, + subtract = _ref.subtract, + multiplyScalar = _ref.multiplyScalar, + divideScalar = _ref.divideScalar, + unaryMinus = _ref.unaryMinus, + sqrt = _ref.sqrt, + abs = _ref.abs; + + /** + * Calculates: + * The eucledian distance between two points in N-dimensional spaces. + * Distance between point and a line in 2 and 3 dimensional spaces. + * Pairwise distance between a set of 2D or 3D points + * NOTE: + * When substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c + * For parametric equation of a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, c) + * + * Syntax: + * math.distance([x1, y1], [x2, y2]) + *- math.distance({pointOneX: 4, pointOneY: 5}, {pointTwoX: 2, pointTwoY: 7}) + * math.distance([x1, y1, z1], [x2, y2, z2]) + * math.distance({pointOneX: 4, pointOneY: 5, pointOneZ: 8}, {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9}) + * math.distance([x1, y1, ... , N1], [x2, y2, ... , N2]) + * math.distance([[A], [B], [C]...]) + * math.distance([x1, y1], [LinePtX1, LinePtY1], [LinePtX2, LinePtY2]) + * math.distance({pointX: 1, pointY: 4}, {lineOnePtX: 6, lineOnePtY: 3}, {lineTwoPtX: 2, lineTwoPtY: 8}) + * math.distance([x1, y1, z1], [LinePtX1, LinePtY1, LinePtZ1], [LinePtX2, LinePtY2, LinePtZ2]) + * math.distance({pointX: 1, pointY: 4, pointZ: 7}, {lineOnePtX: 6, lineOnePtY: 3, lineOnePtZ: 4}, {lineTwoPtX: 2, lineTwoPtY: 8, lineTwoPtZ: 5}) + * math.distance([x1, y1], [xCoeffLine, yCoeffLine, constant]) + * math.distance({pointX: 10, pointY: 10}, {xCoeffLine: 8, yCoeffLine: 1, constant: 3}) + * math.distance([x1, y1, z1], [x0, y0, z0, a-tCoeff, b-tCoeff, c-tCoeff]) point and parametric equation of 3D line + * math.distance([x, y, z], [x0, y0, z0, a, b, c]) + * math.distance({pointX: 2, pointY: 5, pointZ: 9}, {x0: 4, y0: 6, z0: 3, a: 4, b: 2, c: 0}) + * + * Examples: + * math.distance([0,0], [4,4]) // Returns 5.6569 + * math.distance( + * {pointOneX: 0, pointOneY: 0}, + * {pointTwoX: 10, pointTwoY: 10}) // Returns 14.142135623730951 + * math.distance([1, 0, 1], [4, -2, 2]) // Returns 3.74166 + * math.distance( + * {pointOneX: 4, pointOneY: 5, pointOneZ: 8}, + * {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9}) // Returns 3 + * math.distance([1, 0, 1, 0], [0, -1, 0, -1]) // Returns 2 + * math.distance([[1, 2], [1, 2], [1, 3]]) // Returns [0, 1, 1] + * math.distance([[1,2,4], [1,2,6], [8,1,3]]) // Returns [2, 7.14142842854285, 7.681145747868608] + * math.distance([10, 10], [8, 1, 3]) // Returns 11.535230316796387 + * math.distance([10, 10], [2, 3], [-8, 0]) // Returns 8.759953130362847 + * math.distance( + * {pointX: 1, pointY: 4}, + * {lineOnePtX: 6, lineOnePtY: 3}, + * {lineTwoPtX: 2, lineTwoPtY: 8}) // Returns 2.720549372624744 + * math.distance([2, 3, 1], [1, 1, 2, 5, 0, 1]) // Returns 2.3204774044612857 + * math.distance( + * {pointX: 2, pointY: 3, pointZ: 1}, + * {x0: 1, y0: 1, z0: 2, a: 5, b: 0, c: 1} // Returns 2.3204774044612857 + * + * @param {Array | Matrix | Object} x Co-ordinates of first point + * @param {Array | Matrix | Object} y Co-ordinates of second point + * @return {Number | BigNumber} Returns the distance from two/three points + */ + return typed(distance_name, { + 'Array, Array, Array': function ArrayArrayArray(x, y, z) { + // Point to Line 2D (x=Point, y=LinePoint1, z=LinePoint2) + if (x.length === 2 && y.length === 2 && z.length === 2) { + if (!_2d(x)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument'); + } + + if (!_2d(y)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for second argument'); + } + + if (!_2d(z)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for third argument'); + } + + var m = divideScalar(subtract(z[1], z[0]), subtract(y[1], y[0])); + var xCoeff = multiplyScalar(multiplyScalar(m, m), y[0]); + var yCoeff = unaryMinus(multiplyScalar(m, y[0])); + var constant = x[1]; + return _distancePointLine2D(x[0], x[1], xCoeff, yCoeff, constant); + } else { + throw new TypeError('Invalid Arguments: Try again'); + } + }, + 'Object, Object, Object': function ObjectObjectObject(x, y, z) { + if (Object.keys(x).length === 2 && Object.keys(y).length === 2 && Object.keys(z).length === 2) { + if (!_2d(x)) { + throw new TypeError('Values of pointX and pointY should be numbers or BigNumbers'); + } + + if (!_2d(y)) { + throw new TypeError('Values of lineOnePtX and lineOnePtY should be numbers or BigNumbers'); + } + + if (!_2d(z)) { + throw new TypeError('Values of lineTwoPtX and lineTwoPtY should be numbers or BigNumbers'); + } + + if ('pointX' in x && 'pointY' in x && 'lineOnePtX' in y && 'lineOnePtY' in y && 'lineTwoPtX' in z && 'lineTwoPtY' in z) { + var m = divideScalar(subtract(z.lineTwoPtY, z.lineTwoPtX), subtract(y.lineOnePtY, y.lineOnePtX)); + var xCoeff = multiplyScalar(multiplyScalar(m, m), y.lineOnePtX); + var yCoeff = unaryMinus(multiplyScalar(m, y.lineOnePtX)); + var constant = x.pointX; + return _distancePointLine2D(x.pointX, x.pointY, xCoeff, yCoeff, constant); + } else { + throw new TypeError('Key names do not match'); + } + } else { + throw new TypeError('Invalid Arguments: Try again'); + } + }, + 'Array, Array': function ArrayArray(x, y) { + // Point to Line 2D (x=[pointX, pointY], y=[x-coeff, y-coeff, const]) + if (x.length === 2 && y.length === 3) { + if (!_2d(x)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument'); + } + + if (!_3d(y)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument'); + } + + return _distancePointLine2D(x[0], x[1], y[0], y[1], y[2]); + } else if (x.length === 3 && y.length === 6) { + // Point to Line 3D + if (!_3d(x)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument'); + } + + if (!_parametricLine(y)) { + throw new TypeError('Array with 6 numbers or BigNumbers expected for second argument'); + } + + return _distancePointLine3D(x[0], x[1], x[2], y[0], y[1], y[2], y[3], y[4], y[5]); + } else if (x.length === y.length && x.length > 0) { + // Point to Point N-dimensions + if (!_containsOnlyNumbers(x)) { + throw new TypeError('All values of an array should be numbers or BigNumbers'); + } + + if (!_containsOnlyNumbers(y)) { + throw new TypeError('All values of an array should be numbers or BigNumbers'); + } + + return _euclideanDistance(x, y); + } else { + throw new TypeError('Invalid Arguments: Try again'); + } + }, + 'Object, Object': function ObjectObject(x, y) { + if (Object.keys(x).length === 2 && Object.keys(y).length === 3) { + if (!_2d(x)) { + throw new TypeError('Values of pointX and pointY should be numbers or BigNumbers'); + } + + if (!_3d(y)) { + throw new TypeError('Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers'); + } + + if ('pointX' in x && 'pointY' in x && 'xCoeffLine' in y && 'yCoeffLine' in y && 'constant' in y) { + return _distancePointLine2D(x.pointX, x.pointY, y.xCoeffLine, y.yCoeffLine, y.constant); + } else { + throw new TypeError('Key names do not match'); + } + } else if (Object.keys(x).length === 3 && Object.keys(y).length === 6) { + // Point to Line 3D + if (!_3d(x)) { + throw new TypeError('Values of pointX, pointY and pointZ should be numbers or BigNumbers'); + } + + if (!_parametricLine(y)) { + throw new TypeError('Values of x0, y0, z0, a, b and c should be numbers or BigNumbers'); + } + + if ('pointX' in x && 'pointY' in x && 'x0' in y && 'y0' in y && 'z0' in y && 'a' in y && 'b' in y && 'c' in y) { + return _distancePointLine3D(x.pointX, x.pointY, x.pointZ, y.x0, y.y0, y.z0, y.a, y.b, y.c); + } else { + throw new TypeError('Key names do not match'); + } + } else if (Object.keys(x).length === 2 && Object.keys(y).length === 2) { + // Point to Point 2D + if (!_2d(x)) { + throw new TypeError('Values of pointOneX and pointOneY should be numbers or BigNumbers'); + } + + if (!_2d(y)) { + throw new TypeError('Values of pointTwoX and pointTwoY should be numbers or BigNumbers'); + } + + if ('pointOneX' in x && 'pointOneY' in x && 'pointTwoX' in y && 'pointTwoY' in y) { + return _euclideanDistance([x.pointOneX, x.pointOneY], [y.pointTwoX, y.pointTwoY]); + } else { + throw new TypeError('Key names do not match'); + } + } else if (Object.keys(x).length === 3 && Object.keys(y).length === 3) { + // Point to Point 3D + if (!_3d(x)) { + throw new TypeError('Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers'); + } + + if (!_3d(y)) { + throw new TypeError('Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers'); + } + + if ('pointOneX' in x && 'pointOneY' in x && 'pointOneZ' in x && 'pointTwoX' in y && 'pointTwoY' in y && 'pointTwoZ' in y) { + return _euclideanDistance([x.pointOneX, x.pointOneY, x.pointOneZ], [y.pointTwoX, y.pointTwoY, y.pointTwoZ]); + } else { + throw new TypeError('Key names do not match'); + } + } else { + throw new TypeError('Invalid Arguments: Try again'); + } + }, + Array: function Array(arr) { + if (!_pairwise(arr)) { + throw new TypeError('Incorrect array format entered for pairwise distance calculation'); + } + + return _distancePairwise(arr); + } + }); + + function _isNumber(a) { + // distance supports numbers and bignumbers + return typeof a === 'number' || Object(is["e" /* isBigNumber */])(a); + } + + function _2d(a) { + // checks if the number of arguments are correct in count and are valid (should be numbers) + if (a.constructor !== Array) { + a = _objectToArray(a); + } + + return _isNumber(a[0]) && _isNumber(a[1]); + } + + function _3d(a) { + // checks if the number of arguments are correct in count and are valid (should be numbers) + if (a.constructor !== Array) { + a = _objectToArray(a); + } + + return _isNumber(a[0]) && _isNumber(a[1]) && _isNumber(a[2]); + } + + function _containsOnlyNumbers(a) { + // checks if the number of arguments are correct in count and are valid (should be numbers) + if (!Array.isArray(a)) { + a = _objectToArray(a); + } + + return a.every(_isNumber); + } + + function _parametricLine(a) { + if (a.constructor !== Array) { + a = _objectToArray(a); + } + + return _isNumber(a[0]) && _isNumber(a[1]) && _isNumber(a[2]) && _isNumber(a[3]) && _isNumber(a[4]) && _isNumber(a[5]); + } + + function _objectToArray(o) { + var keys = Object.keys(o); + var a = []; + + for (var i = 0; i < keys.length; i++) { + a.push(o[keys[i]]); + } + + return a; + } + + function _pairwise(a) { + // checks for valid arguments passed to _distancePairwise(Array) + if (a[0].length === 2 && _isNumber(a[0][0]) && _isNumber(a[0][1])) { + if (a.some(function (aI) { + return aI.length !== 2 || !_isNumber(aI[0]) || !_isNumber(aI[1]); + })) { + return false; + } + } else if (a[0].length === 3 && _isNumber(a[0][0]) && _isNumber(a[0][1]) && _isNumber(a[0][2])) { + if (a.some(function (aI) { + return aI.length !== 3 || !_isNumber(aI[0]) || !_isNumber(aI[1]) || !_isNumber(aI[2]); + })) { + return false; + } + } else { + return false; + } + + return true; + } + + function _distancePointLine2D(x, y, a, b, c) { + var num = abs(addScalar(addScalar(multiplyScalar(a, x), multiplyScalar(b, y)), c)); + var den = sqrt(addScalar(multiplyScalar(a, a), multiplyScalar(b, b))); + return divideScalar(num, den); + } + + function _distancePointLine3D(x, y, z, x0, y0, z0, a, b, c) { + var num = [subtract(multiplyScalar(subtract(y0, y), c), multiplyScalar(subtract(z0, z), b)), subtract(multiplyScalar(subtract(z0, z), a), multiplyScalar(subtract(x0, x), c)), subtract(multiplyScalar(subtract(x0, x), b), multiplyScalar(subtract(y0, y), a))]; + num = sqrt(addScalar(addScalar(multiplyScalar(num[0], num[0]), multiplyScalar(num[1], num[1])), multiplyScalar(num[2], num[2]))); + var den = sqrt(addScalar(addScalar(multiplyScalar(a, a), multiplyScalar(b, b)), multiplyScalar(c, c))); + return divideScalar(num, den); + } + + function _euclideanDistance(x, y) { + var vectorSize = x.length; + var result = 0; + var diff = 0; + + for (var i = 0; i < vectorSize; i++) { + diff = subtract(x[i], y[i]); + result = addScalar(multiplyScalar(diff, diff), result); + } + + return sqrt(result); + } + + function _distancePairwise(a) { + var result = []; + var pointA = []; + var pointB = []; + + for (var i = 0; i < a.length - 1; i++) { + for (var j = i + 1; j < a.length; j++) { + if (a[0].length === 2) { + pointA = [a[i][0], a[i][1]]; + pointB = [a[j][0], a[j][1]]; + } else if (a[0].length === 3) { + pointA = [a[i][0], a[i][1], a[i][2]]; + pointB = [a[j][0], a[j][1], a[j][2]]; + } + + result.push(_euclideanDistance(pointA, pointB)); + } + } + + return result; + } +}); +// CONCATENATED MODULE: ./src/function/geometry/intersect.js + + +var intersect_name = 'intersect'; +var intersect_dependencies = ['typed', 'config', 'abs', 'add', 'addScalar', 'matrix', 'multiply', 'multiplyScalar', 'divideScalar', 'subtract', 'smaller', 'equalScalar']; +var createIntersect = /* #__PURE__ */Object(factory["a" /* factory */])(intersect_name, intersect_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + abs = _ref.abs, + add = _ref.add, + addScalar = _ref.addScalar, + matrix = _ref.matrix, + multiply = _ref.multiply, + multiplyScalar = _ref.multiplyScalar, + divideScalar = _ref.divideScalar, + subtract = _ref.subtract, + smaller = _ref.smaller, + equalScalar = _ref.equalScalar; + + /** + * Calculates the point of intersection of two lines in two or three dimensions + * and of a line and a plane in three dimensions. The inputs are in the form of + * arrays or 1 dimensional matrices. The line intersection functions return null + * if the lines do not meet. + * + * Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`. + * + * Syntax: + * + * math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2) + * math.intersect(endPoint1, endPoint2, planeCoefficients) + * + * Examples: + * + * math.intersect([0, 0], [10, 10], [10, 0], [0, 10]) // Returns [5, 5] + * math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]) // Returns [5, 5, 0] + * math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]) // Returns [7, -4, 3] + * + * @param {Array | Matrix} w Co-ordinates of first end-point of first line + * @param {Array | Matrix} x Co-ordinates of second end-point of first line + * @param {Array | Matrix} y Co-ordinates of first end-point of second line + * OR Co-efficients of the plane's equation + * @param {Array | Matrix} z Co-ordinates of second end-point of second line + * OR null if the calculation is for line and plane + * @return {Array} Returns the point of intersection of lines/lines-planes + */ + var intersect = typed('intersect', { + 'Array, Array, Array': function ArrayArrayArray(x, y, plane) { + if (!_3d(x)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument'); + } + + if (!_3d(y)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument'); + } + + if (!_4d(plane)) { + throw new TypeError('Array with 4 numbers expected as third argument'); + } + + return _intersectLinePlane(x[0], x[1], x[2], y[0], y[1], y[2], plane[0], plane[1], plane[2], plane[3]); + }, + 'Array, Array, Array, Array': function ArrayArrayArrayArray(w, x, y, z) { + if (w.length === 2) { + if (!_2d(w)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument'); + } + + if (!_2d(x)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for second argument'); + } + + if (!_2d(y)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for third argument'); + } + + if (!_2d(z)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for fourth argument'); + } + + return _intersect2d(w, x, y, z); + } else if (w.length === 3) { + if (!_3d(w)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument'); + } + + if (!_3d(x)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument'); + } + + if (!_3d(y)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for third argument'); + } + + if (!_3d(z)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for fourth argument'); + } + + return _intersect3d(w[0], w[1], w[2], x[0], x[1], x[2], y[0], y[1], y[2], z[0], z[1], z[2]); + } else { + throw new TypeError('Arrays with two or thee dimensional points expected'); + } + }, + 'Matrix, Matrix, Matrix': function MatrixMatrixMatrix(x, y, plane) { + return matrix(intersect(x.valueOf(), y.valueOf(), plane.valueOf())); + }, + 'Matrix, Matrix, Matrix, Matrix': function MatrixMatrixMatrixMatrix(w, x, y, z) { + // TODO: output matrix type should match input matrix type + return matrix(intersect(w.valueOf(), x.valueOf(), y.valueOf(), z.valueOf())); + } + }); + + function _isNumeric(a) { + // intersect supports numbers and bignumbers + return typeof a === 'number' || Object(is["e" /* isBigNumber */])(a); + } + + function _2d(x) { + return x.length === 2 && _isNumeric(x[0]) && _isNumeric(x[1]); + } + + function _3d(x) { + return x.length === 3 && _isNumeric(x[0]) && _isNumeric(x[1]) && _isNumeric(x[2]); + } + + function _4d(x) { + return x.length === 4 && _isNumeric(x[0]) && _isNumeric(x[1]) && _isNumeric(x[2]) && _isNumeric(x[3]); + } + + function _intersect2d(p1a, p1b, p2a, p2b) { + var o1 = p1a; + var o2 = p2a; + var d1 = subtract(o1, p1b); + var d2 = subtract(o2, p2b); + var det = subtract(multiplyScalar(d1[0], d2[1]), multiplyScalar(d2[0], d1[1])); + + if (smaller(abs(det), config.epsilon)) { + return null; + } + + var d20o11 = multiplyScalar(d2[0], o1[1]); + var d21o10 = multiplyScalar(d2[1], o1[0]); + var d20o21 = multiplyScalar(d2[0], o2[1]); + var d21o20 = multiplyScalar(d2[1], o2[0]); + var t = divideScalar(addScalar(subtract(subtract(d20o11, d21o10), d20o21), d21o20), det); + return add(multiply(d1, t), o1); + } + + function _intersect3dHelper(a, b, c, d, e, f, g, h, i, j, k, l) { + // (a - b)*(c - d) + (e - f)*(g - h) + (i - j)*(k - l) + var add1 = multiplyScalar(subtract(a, b), subtract(c, d)); + var add2 = multiplyScalar(subtract(e, f), subtract(g, h)); + var add3 = multiplyScalar(subtract(i, j), subtract(k, l)); + return addScalar(addScalar(add1, add2), add3); + } + + function _intersect3d(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) { + var d1343 = _intersect3dHelper(x1, x3, x4, x3, y1, y3, y4, y3, z1, z3, z4, z3); + + var d4321 = _intersect3dHelper(x4, x3, x2, x1, y4, y3, y2, y1, z4, z3, z2, z1); + + var d1321 = _intersect3dHelper(x1, x3, x2, x1, y1, y3, y2, y1, z1, z3, z2, z1); + + var d4343 = _intersect3dHelper(x4, x3, x4, x3, y4, y3, y4, y3, z4, z3, z4, z3); + + var d2121 = _intersect3dHelper(x2, x1, x2, x1, y2, y1, y2, y1, z2, z1, z2, z1); + + var ta = divideScalar(subtract(multiplyScalar(d1343, d4321), multiplyScalar(d1321, d4343)), subtract(multiplyScalar(d2121, d4343), multiplyScalar(d4321, d4321))); + var tb = divideScalar(addScalar(d1343, multiplyScalar(ta, d4321)), d4343); + var pax = addScalar(x1, multiplyScalar(ta, subtract(x2, x1))); + var pay = addScalar(y1, multiplyScalar(ta, subtract(y2, y1))); + var paz = addScalar(z1, multiplyScalar(ta, subtract(z2, z1))); + var pbx = addScalar(x3, multiplyScalar(tb, subtract(x4, x3))); + var pby = addScalar(y3, multiplyScalar(tb, subtract(y4, y3))); + var pbz = addScalar(z3, multiplyScalar(tb, subtract(z4, z3))); + + if (equalScalar(pax, pbx) && equalScalar(pay, pby) && equalScalar(paz, pbz)) { + return [pax, pay, paz]; + } else { + return null; + } + } + + function _intersectLinePlane(x1, y1, z1, x2, y2, z2, x, y, z, c) { + var x1x = multiplyScalar(x1, x); + var x2x = multiplyScalar(x2, x); + var y1y = multiplyScalar(y1, y); + var y2y = multiplyScalar(y2, y); + var z1z = multiplyScalar(z1, z); + var z2z = multiplyScalar(z2, z); + var t = divideScalar(subtract(subtract(subtract(c, x1x), y1y), z1z), subtract(subtract(subtract(addScalar(addScalar(x2x, y2y), z2z), x1x), y1y), z1z)); + var px = addScalar(x1, multiplyScalar(t, subtract(x2, x1))); + var py = addScalar(y1, multiplyScalar(t, subtract(y2, y1))); + var pz = addScalar(z1, multiplyScalar(t, subtract(z2, z1))); + return [px, py, pz]; // TODO: Add cases when line is parallel to the plane: + // (a) no intersection, + // (b) line contained in plane + } + + return intersect; +}); +// CONCATENATED MODULE: ./src/function/statistics/sum.js + + + + +var sum_name = 'sum'; +var sum_dependencies = ['typed', 'config', 'add', '?bignumber', '?fraction']; +var createSum = /* #__PURE__ */Object(factory["a" /* factory */])(sum_name, sum_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + add = _ref.add, + bignumber = _ref.bignumber, + fraction = _ref.fraction; + + /** + * Compute the sum of a matrix or a list with values. + * In case of a (multi dimensional) array or matrix, the sum of all + * elements will be calculated. + * + * Syntax: + * + * math.sum(a, b, c, ...) + * math.sum(A) + * + * Examples: + * + * math.sum(2, 1, 4, 3) // returns 10 + * math.sum([2, 1, 4, 3]) // returns 10 + * math.sum([[2, 5], [4, 3], [1, 7]]) // returns 22 + * + * See also: + * + * mean, median, min, max, prod, std, variance + * + * @param {... *} args A single matrix or or multiple scalar values + * @return {*} The sum of all values + */ + return typed(sum_name, { + // sum([a, b, c, d, ...]) + 'Array | Matrix': _sum, + // sum([a, b, c, d, ...], dim) + 'Array | Matrix, number | BigNumber': _nsumDim, + // sum(a, b, c, d, ...) + '...': function _(args) { + if (containsCollections(args)) { + throw new TypeError('Scalar values expected in function sum'); + } + + return _sum(args); + } + }); + /** + * Recursively calculate the sum of an n-dimensional array + * @param {Array} array + * @return {number} sum + * @private + */ + + function _sum(array) { + var sum; + deepForEach(array, function (value) { + try { + sum = sum === undefined ? value : add(sum, value); + } catch (err) { + throw improveErrorMessage(err, 'sum', value); + } + }); + + if (sum === undefined) { + switch (config.number) { + case 'number': + return 0; + + case 'BigNumber': + return bignumber ? bignumber(0) : noBignumber(); + + case 'Fraction': + return fraction ? fraction(0) : noFraction(); + + default: + return 0; + } + } + + return sum; + } + + function _nsumDim(array, dim) { + try { + var sum = reduce(array, dim, add); + return sum; + } catch (err) { + throw improveErrorMessage(err, 'sum'); + } + } +}); +// CONCATENATED MODULE: ./src/function/statistics/mean.js + + + + +var mean_name = 'mean'; +var mean_dependencies = ['typed', 'add', 'divide']; +var createMean = /* #__PURE__ */Object(factory["a" /* factory */])(mean_name, mean_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + divide = _ref.divide; + + /** + * Compute the mean value of matrix or a list with values. + * In case of a multi dimensional array, the mean of the flattened array + * will be calculated. When `dim` is provided, the maximum over the selected + * dimension will be calculated. Parameter `dim` is zero-based. + * + * Syntax: + * + * math.mean(a, b, c, ...) + * math.mean(A) + * math.mean(A, dim) + * + * Examples: + * + * math.mean(2, 1, 4, 3) // returns 2.5 + * math.mean([1, 2.7, 3.2, 4]) // returns 2.725 + * + * math.mean([[2, 5], [6, 3], [1, 7]], 0) // returns [3, 5] + * math.mean([[2, 5], [6, 3], [1, 7]], 1) // returns [3.5, 4.5, 4] + * + * See also: + * + * median, min, max, sum, prod, std, variance + * + * @param {... *} args A single matrix or or multiple scalar values + * @return {*} The mean of all values + */ + return typed(mean_name, { + // mean([a, b, c, d, ...]) + 'Array | Matrix': _mean, + // mean([a, b, c, d, ...], dim) + 'Array | Matrix, number | BigNumber': _nmeanDim, + // mean(a, b, c, d, ...) + '...': function _(args) { + if (containsCollections(args)) { + throw new TypeError('Scalar values expected in function mean'); + } + + return _mean(args); + } + }); + /** + * Calculate the mean value in an n-dimensional array, returning a + * n-1 dimensional array + * @param {Array} array + * @param {number} dim + * @return {number} mean + * @private + */ + + function _nmeanDim(array, dim) { + try { + var sum = reduce(array, dim, add); + var s = Array.isArray(array) ? Object(utils_array["a" /* arraySize */])(array) : array.size(); + return divide(sum, s[dim]); + } catch (err) { + throw improveErrorMessage(err, 'mean'); + } + } + /** + * Recursively calculate the mean value in an n-dimensional array + * @param {Array} array + * @return {number} mean + * @private + */ + + + function _mean(array) { + var sum; + var num = 0; + deepForEach(array, function (value) { + try { + sum = sum === undefined ? value : add(sum, value); + num++; + } catch (err) { + throw improveErrorMessage(err, 'mean', value); + } + }); + + if (num === 0) { + throw new Error('Cannot calculate the mean of an empty array'); + } + + return divide(sum, num); + } +}); +// CONCATENATED MODULE: ./src/function/statistics/median.js + + + + +var median_name = 'median'; +var median_dependencies = ['typed', 'add', 'divide', 'compare', 'partitionSelect']; +var createMedian = /* #__PURE__ */Object(factory["a" /* factory */])(median_name, median_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + divide = _ref.divide, + compare = _ref.compare, + partitionSelect = _ref.partitionSelect; + + /** + * Compute the median of a matrix or a list with values. The values are + * sorted and the middle value is returned. In case of an even number of + * values, the average of the two middle values is returned. + * Supported types of values are: Number, BigNumber, Unit + * + * In case of a (multi dimensional) array or matrix, the median of all + * elements will be calculated. + * + * Syntax: + * + * math.median(a, b, c, ...) + * math.median(A) + * + * Examples: + * + * math.median(5, 2, 7) // returns 5 + * math.median([3, -1, 5, 7]) // returns 4 + * + * See also: + * + * mean, min, max, sum, prod, std, variance, quantileSeq + * + * @param {... *} args A single matrix or or multiple scalar values + * @return {*} The median + */ + var median = typed(median_name, { + // median([a, b, c, d, ...]) + 'Array | Matrix': _median, + // median([a, b, c, d, ...], dim) + 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) { + // TODO: implement median(A, dim) + throw new Error('median(A, dim) is not yet supported'); // return reduce(arguments[0], arguments[1], ...) + }, + // median(a, b, c, d, ...) + '...': function _(args) { + if (containsCollections(args)) { + throw new TypeError('Scalar values expected in function median'); + } + + return _median(args); + } + }); + /** + * Recursively calculate the median of an n-dimensional array + * @param {Array} array + * @return {Number} median + * @private + */ + + function _median(array) { + try { + array = Object(utils_array["e" /* flatten */])(array.valueOf()); + var num = array.length; + + if (num === 0) { + throw new Error('Cannot calculate median of an empty array'); + } + + if (num % 2 === 0) { + // even: return the average of the two middle values + var mid = num / 2 - 1; + var right = partitionSelect(array, mid + 1); // array now partitioned at mid + 1, take max of left part + + var left = array[mid]; + + for (var i = 0; i < mid; ++i) { + if (compare(array[i], left) > 0) { + left = array[i]; + } + } + + return middle2(left, right); + } else { + // odd: return the middle value + var m = partitionSelect(array, (num - 1) / 2); + return middle(m); + } + } catch (err) { + throw improveErrorMessage(err, 'median'); + } + } // helper function to type check the middle value of the array + + + var middle = typed({ + 'number | BigNumber | Complex | Unit': function numberBigNumberComplexUnit(value) { + return value; + } + }); // helper function to type check the two middle value of the array + + var middle2 = typed({ + 'number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit': function numberBigNumberComplexUnitNumberBigNumberComplexUnit(left, right) { + return divide(add(left, right), 2); + } + }); + return median; +}); +// CONCATENATED MODULE: ./src/function/statistics/mad.js + + + +var mad_name = 'mad'; +var mad_dependencies = ['typed', 'abs', 'map', 'median', 'subtract']; +var createMad = /* #__PURE__ */Object(factory["a" /* factory */])(mad_name, mad_dependencies, function (_ref) { + var typed = _ref.typed, + abs = _ref.abs, + map = _ref.map, + median = _ref.median, + subtract = _ref.subtract; + + /** + * Compute the median absolute deviation of a matrix or a list with values. + * The median absolute deviation is defined as the median of the absolute + * deviations from the median. + * + * Syntax: + * + * math.mad(a, b, c, ...) + * math.mad(A) + * + * Examples: + * + * math.mad(10, 20, 30) // returns 10 + * math.mad([1, 2, 3]) // returns 1 + * math.mad([[1, 2, 3], [4, 5, 6]]) // returns 1.5 + * + * See also: + * + * median, mean, std, abs + * + * @param {Array | Matrix} array + * A single matrix or multiple scalar values. + * @return {*} The median absolute deviation. + */ + return typed(mad_name, { + // mad([a, b, c, d, ...]) + 'Array | Matrix': _mad, + // mad(a, b, c, d, ...) + '...': function _(args) { + return _mad(args); + } + }); + + function _mad(array) { + array = Object(utils_array["e" /* flatten */])(array.valueOf()); + + if (array.length === 0) { + throw new Error('Cannot calculate median absolute deviation (mad) of an empty array'); + } + + try { + var med = median(array); + return median(map(array, function (value) { + return abs(subtract(value, med)); + })); + } catch (err) { + if (err instanceof TypeError && err.message.indexOf('median') !== -1) { + throw new TypeError(err.message.replace('median', 'mad')); + } else { + throw improveErrorMessage(err, 'mad'); + } + } + } +}); +// CONCATENATED MODULE: ./src/function/statistics/variance.js + + + + + +var DEFAULT_NORMALIZATION = 'unbiased'; +var variance_name = 'variance'; +var variance_dependencies = ['typed', 'add', 'subtract', 'multiply', 'divide', 'apply', 'isNaN']; +var createVariance = /* #__PURE__ */Object(factory["a" /* factory */])(variance_name, variance_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + subtract = _ref.subtract, + multiply = _ref.multiply, + divide = _ref.divide, + apply = _ref.apply, + isNaN = _ref.isNaN; + + /** + * Compute the variance of a matrix or a list with values. + * In case of a (multi dimensional) array or matrix, the variance over all + * elements will be calculated. + * + * Additionally, it is possible to compute the variance along the rows + * or columns of a matrix by specifying the dimension as the second argument. + * + * Optionally, the type of normalization can be specified as the final + * parameter. The parameter `normalization` can be one of the following values: + * + * - 'unbiased' (default) The sum of squared errors is divided by (n - 1) + * - 'uncorrected' The sum of squared errors is divided by n + * - 'biased' The sum of squared errors is divided by (n + 1) + * + * + * Note that older browser may not like the variable name `var`. In that + * case, the function can be called as `math['var'](...)` instead of + * `math.var(...)`. + * + * Syntax: + * + * math.variance(a, b, c, ...) + * math.variance(A) + * math.variance(A, normalization) + * math.variance(A, dimension) + * math.variance(A, dimension, normalization) + * + * Examples: + * + * math.variance(2, 4, 6) // returns 4 + * math.variance([2, 4, 6, 8]) // returns 6.666666666666667 + * math.variance([2, 4, 6, 8], 'uncorrected') // returns 5 + * math.variance([2, 4, 6, 8], 'biased') // returns 4 + * + * math.variance([[1, 2, 3], [4, 5, 6]]) // returns 3.5 + * math.variance([[1, 2, 3], [4, 6, 8]], 0) // returns [4.5, 8, 12.5] + * math.variance([[1, 2, 3], [4, 6, 8]], 1) // returns [1, 4] + * math.variance([[1, 2, 3], [4, 6, 8]], 1, 'biased') // returns [0.5, 2] + * + * See also: + * + * mean, median, max, min, prod, std, sum + * + * @param {Array | Matrix} array + * A single matrix or or multiple scalar values + * @param {string} [normalization='unbiased'] + * Determines how to normalize the variance. + * Choose 'unbiased' (default), 'uncorrected', or 'biased'. + * @param dimension {number | BigNumber} + * Determines the axis to compute the variance for a matrix + * @return {*} The variance + */ + return typed(variance_name, { + // variance([a, b, c, d, ...]) + 'Array | Matrix': function ArrayMatrix(array) { + return _var(array, DEFAULT_NORMALIZATION); + }, + // variance([a, b, c, d, ...], normalization) + 'Array | Matrix, string': _var, + // variance([a, b, c, c, ...], dim) + 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) { + return _varDim(array, dim, DEFAULT_NORMALIZATION); + }, + // variance([a, b, c, c, ...], dim, normalization) + 'Array | Matrix, number | BigNumber, string': _varDim, + // variance(a, b, c, d, ...) + '...': function _(args) { + return _var(args, DEFAULT_NORMALIZATION); + } + }); + /** + * Recursively calculate the variance of an n-dimensional array + * @param {Array} array + * @param {string} normalization + * Determines how to normalize the variance: + * - 'unbiased' The sum of squared errors is divided by (n - 1) + * - 'uncorrected' The sum of squared errors is divided by n + * - 'biased' The sum of squared errors is divided by (n + 1) + * @return {number | BigNumber} variance + * @private + */ + + function _var(array, normalization) { + var sum = 0; + var num = 0; + + if (array.length === 0) { + throw new SyntaxError('Function variance requires one or more parameters (0 provided)'); + } // calculate the mean and number of elements + + + deepForEach(array, function (value) { + try { + sum = add(sum, value); + num++; + } catch (err) { + throw improveErrorMessage(err, 'variance', value); + } + }); + if (num === 0) throw new Error('Cannot calculate variance of an empty array'); + var mean = divide(sum, num); // calculate the variance + + sum = 0; + deepForEach(array, function (value) { + var diff = subtract(value, mean); + sum = add(sum, multiply(diff, diff)); + }); + + if (isNaN(sum)) { + return sum; + } + + switch (normalization) { + case 'uncorrected': + return divide(sum, num); + + case 'biased': + return divide(sum, num + 1); + + case 'unbiased': + { + var zero = Object(is["e" /* isBigNumber */])(sum) ? sum.mul(0) : 0; + return num === 1 ? zero : divide(sum, num - 1); + } + + default: + throw new Error('Unknown normalization "' + normalization + '". ' + 'Choose "unbiased" (default), "uncorrected", or "biased".'); + } + } + + function _varDim(array, dim, normalization) { + try { + if (array.length === 0) { + throw new SyntaxError('Function variance requires one or more parameters (0 provided)'); + } + + return apply(array, dim, function (x) { + return _var(x, normalization); + }); + } catch (err) { + throw improveErrorMessage(err, 'variance'); + } + } +}); // For backward compatibility, deprecated since version 6.0.0. Date: 2018-11-09 + +var createDeprecatedVar = /* #__PURE__ */Object(factory["a" /* factory */])('var', ['variance'], function (_ref2) { + var variance = _ref2.variance; + return function () { + Object(utils_log["a" /* warnOnce */])('Function "var" has been renamed to "variance" in v6.0.0, please use the new function instead.'); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return variance.apply(variance, args); + }; +}); +// CONCATENATED MODULE: ./src/function/statistics/quantileSeq.js + + + + +var quantileSeq_name = 'quantileSeq'; +var quantileSeq_dependencies = ['typed', 'add', 'multiply', 'partitionSelect', 'compare']; +var createQuantileSeq = /* #__PURE__ */Object(factory["a" /* factory */])(quantileSeq_name, quantileSeq_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + multiply = _ref.multiply, + partitionSelect = _ref.partitionSelect, + compare = _ref.compare; + + /** + * Compute the prob order quantile of a matrix or a list with values. + * The sequence is sorted and the middle value is returned. + * Supported types of sequence values are: Number, BigNumber, Unit + * Supported types of probability are: Number, BigNumber + * + * In case of a (multi dimensional) array or matrix, the prob order quantile + * of all elements will be calculated. + * + * Syntax: + * + * math.quantileSeq(A, prob[, sorted]) + * math.quantileSeq(A, [prob1, prob2, ...][, sorted]) + * math.quantileSeq(A, N[, sorted]) + * + * Examples: + * + * math.quantileSeq([3, -1, 5, 7], 0.5) // returns 4 + * math.quantileSeq([3, -1, 5, 7], [1/3, 2/3]) // returns [3, 5] + * math.quantileSeq([3, -1, 5, 7], 2) // returns [3, 5] + * math.quantileSeq([-1, 3, 5, 7], 0.5, true) // returns 4 + * + * See also: + * + * median, mean, min, max, sum, prod, std, variance + * + * @param {Array, Matrix} data A single matrix or Array + * @param {Number, BigNumber, Array} probOrN prob is the order of the quantile, while N is + * the amount of evenly distributed steps of + * probabilities; only one of these options can + * be provided + * @param {Boolean} sorted=false is data sorted in ascending order + * @return {Number, BigNumber, Unit, Array} Quantile(s) + */ + function quantileSeq(data, probOrN, sorted) { + var probArr, dataArr, one; + + if (arguments.length < 2 || arguments.length > 3) { + throw new SyntaxError('Function quantileSeq requires two or three parameters'); + } + + if (Object(is["i" /* isCollection */])(data)) { + sorted = sorted || false; + + if (typeof sorted === 'boolean') { + dataArr = data.valueOf(); + + if (Object(is["y" /* isNumber */])(probOrN)) { + if (probOrN < 0) { + throw new Error('N/prob must be non-negative'); + } + + if (probOrN <= 1) { + // quantileSeq([a, b, c, d, ...], prob[,sorted]) + return _quantileSeq(dataArr, probOrN, sorted); + } + + if (probOrN > 1) { + // quantileSeq([a, b, c, d, ...], N[,sorted]) + if (!Object(utils_number["i" /* isInteger */])(probOrN)) { + throw new Error('N must be a positive integer'); + } + + var nPlusOne = probOrN + 1; + probArr = new Array(probOrN); + + for (var i = 0; i < probOrN;) { + probArr[i] = _quantileSeq(dataArr, ++i / nPlusOne, sorted); + } + + return probArr; + } + } + + if (Object(is["e" /* isBigNumber */])(probOrN)) { + var BigNumber = probOrN.constructor; + + if (probOrN.isNegative()) { + throw new Error('N/prob must be non-negative'); + } + + one = new BigNumber(1); + + if (probOrN.lte(one)) { + // quantileSeq([a, b, c, d, ...], prob[,sorted]) + return new BigNumber(_quantileSeq(dataArr, probOrN, sorted)); + } + + if (probOrN.gt(one)) { + // quantileSeq([a, b, c, d, ...], N[,sorted]) + if (!probOrN.isInteger()) { + throw new Error('N must be a positive integer'); + } // largest possible Array length is 2^32-1 + // 2^32 < 10^15, thus safe conversion guaranteed + + + var intN = probOrN.toNumber(); + + if (intN > 4294967295) { + throw new Error('N must be less than or equal to 2^32-1, as that is the maximum length of an Array'); + } + + var _nPlusOne = new BigNumber(intN + 1); + + probArr = new Array(intN); + + for (var _i = 0; _i < intN;) { + probArr[_i] = new BigNumber(_quantileSeq(dataArr, new BigNumber(++_i).div(_nPlusOne), sorted)); + } + + return probArr; + } + } + + if (Array.isArray(probOrN)) { + // quantileSeq([a, b, c, d, ...], [prob1, prob2, ...][,sorted]) + probArr = new Array(probOrN.length); + + for (var _i2 = 0; _i2 < probArr.length; ++_i2) { + var currProb = probOrN[_i2]; + + if (Object(is["y" /* isNumber */])(currProb)) { + if (currProb < 0 || currProb > 1) { + throw new Error('Probability must be between 0 and 1, inclusive'); + } + } else if (Object(is["e" /* isBigNumber */])(currProb)) { + one = new currProb.constructor(1); + + if (currProb.isNegative() || currProb.gt(one)) { + throw new Error('Probability must be between 0 and 1, inclusive'); + } + } else { + throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function + } + + probArr[_i2] = _quantileSeq(dataArr, currProb, sorted); + } + + return probArr; + } + + throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function + } + + throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function + } + + throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function + } + /** + * Calculate the prob order quantile of an n-dimensional array. + * + * @param {Array} array + * @param {Number, BigNumber} prob + * @param {Boolean} sorted + * @return {Number, BigNumber, Unit} prob order quantile + * @private + */ + + + function _quantileSeq(array, prob, sorted) { + var flat = Object(utils_array["e" /* flatten */])(array); + var len = flat.length; + + if (len === 0) { + throw new Error('Cannot calculate quantile of an empty sequence'); + } + + if (Object(is["y" /* isNumber */])(prob)) { + var _index = prob * (len - 1); + + var _fracPart = _index % 1; + + if (_fracPart === 0) { + var value = sorted ? flat[_index] : partitionSelect(flat, _index); + validate(value); + return value; + } + + var _integerPart = Math.floor(_index); + + var _left; + + var _right; + + if (sorted) { + _left = flat[_integerPart]; + _right = flat[_integerPart + 1]; + } else { + _right = partitionSelect(flat, _integerPart + 1); // max of partition is kth largest + + _left = flat[_integerPart]; + + for (var i = 0; i < _integerPart; ++i) { + if (compare(flat[i], _left) > 0) { + _left = flat[i]; + } + } + } + + validate(_left); + validate(_right); // Q(prob) = (1-f)*A[floor(index)] + f*A[floor(index)+1] + + return add(multiply(_left, 1 - _fracPart), multiply(_right, _fracPart)); + } // If prob is a BigNumber + + + var index = prob.times(len - 1); + + if (index.isInteger()) { + index = index.toNumber(); + + var _value = sorted ? flat[index] : partitionSelect(flat, index); + + validate(_value); + return _value; + } + + var integerPart = index.floor(); + var fracPart = index.minus(integerPart); + var integerPartNumber = integerPart.toNumber(); + var left; + var right; + + if (sorted) { + left = flat[integerPartNumber]; + right = flat[integerPartNumber + 1]; + } else { + right = partitionSelect(flat, integerPartNumber + 1); // max of partition is kth largest + + left = flat[integerPartNumber]; + + for (var _i3 = 0; _i3 < integerPartNumber; ++_i3) { + if (compare(flat[_i3], left) > 0) { + left = flat[_i3]; + } + } + } + + validate(left); + validate(right); // Q(prob) = (1-f)*A[floor(index)] + f*A[floor(index)+1] + + var one = new fracPart.constructor(1); + return add(multiply(left, one.minus(fracPart)), multiply(right, fracPart)); + } + /** + * Check if array value types are valid, throw error otherwise. + * @param {number | BigNumber | Unit} x + * @param {number | BigNumber | Unit} x + * @private + */ + + + var validate = typed({ + 'number | BigNumber | Unit': function numberBigNumberUnit(x) { + return x; + } + }); + return quantileSeq; +}); +// CONCATENATED MODULE: ./src/function/statistics/std.js + +var std_name = 'std'; +var std_dependencies = ['typed', 'sqrt', 'variance']; +var createStd = /* #__PURE__ */Object(factory["a" /* factory */])(std_name, std_dependencies, function (_ref) { + var typed = _ref.typed, + sqrt = _ref.sqrt, + variance = _ref.variance; + + /** + * Compute the standard deviation of a matrix or a list with values. + * The standard deviations is defined as the square root of the variance: + * `std(A) = sqrt(variance(A))`. + * In case of a (multi dimensional) array or matrix, the standard deviation + * over all elements will be calculated by default, unless an axis is specified + * in which case the standard deviation will be computed along that axis. + * + * Additionally, it is possible to compute the standard deviation along the rows + * or columns of a matrix by specifying the dimension as the second argument. + * + * Optionally, the type of normalization can be specified as the final + * parameter. The parameter `normalization` can be one of the following values: + * + * - 'unbiased' (default) The sum of squared errors is divided by (n - 1) + * - 'uncorrected' The sum of squared errors is divided by n + * - 'biased' The sum of squared errors is divided by (n + 1) + * + * + * Syntax: + * + * math.std(a, b, c, ...) + * math.std(A) + * math.std(A, normalization) + * math.std(A, dimension) + * math.std(A, dimension, normalization) + * + * Examples: + * + * math.std(2, 4, 6) // returns 2 + * math.std([2, 4, 6, 8]) // returns 2.581988897471611 + * math.std([2, 4, 6, 8], 'uncorrected') // returns 2.23606797749979 + * math.std([2, 4, 6, 8], 'biased') // returns 2 + * + * math.std([[1, 2, 3], [4, 5, 6]]) // returns 1.8708286933869707 + * math.std([[1, 2, 3], [4, 6, 8]], 0) // returns [2.1213203435596424, 2.8284271247461903, 3.5355339059327378] + * math.std([[1, 2, 3], [4, 6, 8]], 1) // returns [1, 2] + * math.std([[1, 2, 3], [4, 6, 8]], 1, 'biased') // returns [0.7071067811865476, 1.4142135623730951] + * + * See also: + * + * mean, median, max, min, prod, sum, variance + * + * @param {Array | Matrix} array + * A single matrix or or multiple scalar values + * @param {string} [normalization='unbiased'] + * Determines how to normalize the variance. + * Choose 'unbiased' (default), 'uncorrected', or 'biased'. + * @param dimension {number | BigNumber} + * Determines the axis to compute the standard deviation for a matrix + * @return {*} The standard deviation + */ + return typed(std_name, { + // std([a, b, c, d, ...]) + 'Array | Matrix': _std, + // std([a, b, c, d, ...], normalization) + 'Array | Matrix, string': _std, + // std([a, b, c, c, ...], dim) + 'Array | Matrix, number | BigNumber': _std, + // std([a, b, c, c, ...], dim, normalization) + 'Array | Matrix, number | BigNumber, string': _std, + // std(a, b, c, d, ...) + '...': function _(args) { + return _std(args); + } + }); + + function _std(array, normalization) { + if (array.length === 0) { + throw new SyntaxError('Function std requires one or more parameters (0 provided)'); + } + + try { + return sqrt(variance.apply(null, arguments)); + } catch (err) { + if (err instanceof TypeError && err.message.indexOf(' variance') !== -1) { + throw new TypeError(err.message.replace(' variance', ' std')); + } else { + throw err; + } + } + } +}); +// CONCATENATED MODULE: ./src/utils/product.js +/** @param {number} i + * @param {number} n + * @returns {number} product of i to n + */ +function product_product(i, n) { + if (n < i) { + return 1; + } + + if (n === i) { + return n; + } + + var half = n + i >> 1; // divide (n + i) by 2 and truncate to integer + + return product_product(i, half) * product_product(half + 1, n); +} +// CONCATENATED MODULE: ./src/plain/number/combinations.js + + +function combinationsNumber(n, k) { + if (!Object(utils_number["i" /* isInteger */])(n) || n < 0) { + throw new TypeError('Positive integer value expected in function combinations'); + } + + if (!Object(utils_number["i" /* isInteger */])(k) || k < 0) { + throw new TypeError('Positive integer value expected in function combinations'); + } + + if (k > n) { + throw new TypeError('k must be less than or equal to n'); + } + + var nMinusk = n - k; + var prodrange; + + if (k < nMinusk) { + prodrange = product_product(nMinusk + 1, n); + return prodrange / product_product(1, k); + } + + prodrange = product_product(k + 1, n); + return prodrange / product_product(1, nMinusk); +} +combinationsNumber.signature = 'number, number'; +// CONCATENATED MODULE: ./src/function/probability/combinations.js + + +var combinations_name = 'combinations'; +var combinations_dependencies = ['typed']; +var createCombinations = /* #__PURE__ */Object(factory["a" /* factory */])(combinations_name, combinations_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the number of ways of picking `k` unordered outcomes from `n` + * possibilities. + * + * Combinations only takes integer arguments. + * The following condition must be enforced: k <= n. + * + * Syntax: + * + * math.combinations(n, k) + * + * Examples: + * + * math.combinations(7, 5) // returns 21 + * + * See also: + * + * combinationsWithRep, permutations, factorial + * + * @param {number | BigNumber} n Total number of objects in the set + * @param {number | BigNumber} k Number of objects in the subset + * @return {number | BigNumber} Number of possible combinations. + */ + return typed(combinations_name, { + 'number, number': combinationsNumber, + 'BigNumber, BigNumber': function BigNumberBigNumber(n, k) { + var BigNumber = n.constructor; + var result, i; + var nMinusk = n.minus(k); + var one = new BigNumber(1); + + if (!isPositiveInteger(n) || !isPositiveInteger(k)) { + throw new TypeError('Positive integer value expected in function combinations'); + } + + if (k.gt(n)) { + throw new TypeError('k must be less than n in function combinations'); + } + + result = one; + + if (k.lt(nMinusk)) { + for (i = one; i.lte(nMinusk); i = i.plus(one)) { + result = result.times(k.plus(i)).dividedBy(i); + } + } else { + for (i = one; i.lte(k); i = i.plus(one)) { + result = result.times(nMinusk.plus(i)).dividedBy(i); + } + } + + return result; + } // TODO: implement support for collection in combinations + + }); +}); +/** + * Test whether BigNumber n is a positive integer + * @param {BigNumber} n + * @returns {boolean} isPositiveInteger + */ + +function isPositiveInteger(n) { + return n.isInteger() && n.gte(0); +} +// CONCATENATED MODULE: ./src/function/probability/combinationsWithRep.js + + + +var combinationsWithRep_name = 'combinationsWithRep'; +var combinationsWithRep_dependencies = ['typed']; +var createCombinationsWithRep = /* #__PURE__ */Object(factory["a" /* factory */])(combinationsWithRep_name, combinationsWithRep_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the number of ways of picking `k` unordered outcomes from `n` + * possibilities, allowing individual outcomes to be repeated more than once. + * + * CombinationsWithRep only takes integer arguments. + * The following condition must be enforced: k <= n + k -1. + * + * Syntax: + * + * math.combinationsWithRep(n, k) + * + * Examples: + * + * math.combinationsWithRep(7, 5) // returns 462 + * + * See also: + * + * combinations, permutations, factorial + * + * @param {number | BigNumber} n Total number of objects in the set + * @param {number | BigNumber} k Number of objects in the subset + * @return {number | BigNumber} Number of possible combinations with replacement. + */ + return typed(combinationsWithRep_name, { + 'number, number': function numberNumber(n, k) { + if (!Object(utils_number["i" /* isInteger */])(n) || n < 0) { + throw new TypeError('Positive integer value expected in function combinationsWithRep'); + } + + if (!Object(utils_number["i" /* isInteger */])(k) || k < 0) { + throw new TypeError('Positive integer value expected in function combinationsWithRep'); + } + + if (n < 1) { + throw new TypeError('k must be less than or equal to n + k - 1'); + } + + if (k < n - 1) { + var _prodrange = product_product(n, n + k - 1); + + return _prodrange / product_product(1, k); + } + + var prodrange = product_product(k + 1, n + k - 1); + return prodrange / product_product(1, n - 1); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(n, k) { + var BigNumber = n.constructor; + var result, i; + var one = new BigNumber(1); + var nMinusOne = n.minus(one); + + if (!combinationsWithRep_isPositiveInteger(n) || !combinationsWithRep_isPositiveInteger(k)) { + throw new TypeError('Positive integer value expected in function combinationsWithRep'); + } + + if (n.lt(one)) { + throw new TypeError('k must be less than or equal to n + k - 1 in function combinationsWithRep'); + } + + result = one; + + if (k.lt(nMinusOne)) { + for (i = one; i.lte(nMinusOne); i = i.plus(one)) { + result = result.times(k.plus(i)).dividedBy(i); + } + } else { + for (i = one; i.lte(k); i = i.plus(one)) { + result = result.times(nMinusOne.plus(i)).dividedBy(i); + } + } + + return result; + } + }); +}); +/** + * Test whether BigNumber n is a positive integer + * @param {BigNumber} n + * @returns {boolean} isPositiveInteger + */ + +function combinationsWithRep_isPositiveInteger(n) { + return n.isInteger() && n.gte(0); +} +// CONCATENATED MODULE: ./src/plain/number/probability.js + + +function gammaNumber(n) { + var x; + + if (Object(utils_number["i" /* isInteger */])(n)) { + if (n <= 0) { + return isFinite(n) ? Infinity : NaN; + } + + if (n > 171) { + return Infinity; // Will overflow + } + + return product_product(1, n - 1); + } + + if (n < 0.5) { + return Math.PI / (Math.sin(Math.PI * n) * gammaNumber(1 - n)); + } + + if (n >= 171.35) { + return Infinity; // will overflow + } + + if (n > 85.0) { + // Extended Stirling Approx + var twoN = n * n; + var threeN = twoN * n; + var fourN = threeN * n; + var fiveN = fourN * n; + return Math.sqrt(2 * Math.PI / n) * Math.pow(n / Math.E, n) * (1 + 1 / (12 * n) + 1 / (288 * twoN) - 139 / (51840 * threeN) - 571 / (2488320 * fourN) + 163879 / (209018880 * fiveN) + 5246819 / (75246796800 * fiveN * n)); + } + + --n; + x = gammaP[0]; + + for (var i = 1; i < gammaP.length; ++i) { + x += gammaP[i] / (n + i); + } + + var t = n + gammaG + 0.5; + return Math.sqrt(2 * Math.PI) * Math.pow(t, n + 0.5) * Math.exp(-t) * x; +} +gammaNumber.signature = 'number'; // TODO: comment on the variables g and p + +var gammaG = 4.7421875; +var gammaP = [0.99999999999999709182, 57.156235665862923517, -59.597960355475491248, 14.136097974741747174, -0.49191381609762019978, 0.33994649984811888699e-4, 0.46523628927048575665e-4, -0.98374475304879564677e-4, 0.15808870322491248884e-3, -0.21026444172410488319e-3, 0.21743961811521264320e-3, -0.16431810653676389022e-3, 0.84418223983852743293e-4, -0.26190838401581408670e-4, 0.36899182659531622704e-5]; +// CONCATENATED MODULE: ./src/function/probability/gamma.js + + + +var gamma_name = 'gamma'; +var gamma_dependencies = ['typed', 'config', 'multiplyScalar', 'pow', 'BigNumber', 'Complex']; +var createGamma = /* #__PURE__ */Object(factory["a" /* factory */])(gamma_name, gamma_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + multiplyScalar = _ref.multiplyScalar, + pow = _ref.pow, + _BigNumber = _ref.BigNumber, + _Complex = _ref.Complex; + + /** + * Compute the gamma function of a value using Lanczos approximation for + * small values, and an extended Stirling approximation for large values. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.gamma(n) + * + * Examples: + * + * math.gamma(5) // returns 24 + * math.gamma(-0.5) // returns -3.5449077018110335 + * math.gamma(math.i) // returns -0.15494982830180973 - 0.49801566811835596i + * + * See also: + * + * combinations, factorial, permutations + * + * @param {number | Array | Matrix} n A real or complex number + * @return {number | Array | Matrix} The gamma of `n` + */ + var gamma = typed(gamma_name, { + number: gammaNumber, + Complex: function Complex(n) { + if (n.im === 0) { + return gamma(n.re); + } + + n = new _Complex(n.re - 1, n.im); + var x = new _Complex(gammaP[0], 0); + + for (var i = 1; i < gammaP.length; ++i) { + var real = n.re + i; // x += p[i]/(n+i) + + var den = real * real + n.im * n.im; + + if (den !== 0) { + x.re += gammaP[i] * real / den; + x.im += -(gammaP[i] * n.im) / den; + } else { + x.re = gammaP[i] < 0 ? -Infinity : Infinity; + } + } + + var t = new _Complex(n.re + gammaG + 0.5, n.im); + var twoPiSqrt = Math.sqrt(2 * Math.PI); + n.re += 0.5; + var result = pow(t, n); + + if (result.im === 0) { + // sqrt(2*PI)*result + result.re *= twoPiSqrt; + } else if (result.re === 0) { + result.im *= twoPiSqrt; + } else { + result.re *= twoPiSqrt; + result.im *= twoPiSqrt; + } + + var r = Math.exp(-t.re); // exp(-t) + + t.re = r * Math.cos(-t.im); + t.im = r * Math.sin(-t.im); + return multiplyScalar(multiplyScalar(result, t), x); + }, + BigNumber: function BigNumber(n) { + if (n.isInteger()) { + return n.isNegative() || n.isZero() ? new _BigNumber(Infinity) : bigFactorial(n.minus(1)); + } + + if (!n.isFinite()) { + return new _BigNumber(n.isNegative() ? NaN : Infinity); + } + + throw new Error('Integer BigNumber expected'); + }, + 'Array | Matrix': function ArrayMatrix(n) { + return deepMap(n, gamma); + } + }); + /** + * Calculate factorial for a BigNumber + * @param {BigNumber} n + * @returns {BigNumber} Returns the factorial of n + */ + + function bigFactorial(n) { + if (n < 8) { + return new _BigNumber([1, 1, 2, 6, 24, 120, 720, 5040][n]); + } + + var precision = config.precision + (Math.log(n.toNumber()) | 0); + + var Big = _BigNumber.clone({ + precision: precision + }); + + if (n % 2 === 1) { + return n.times(bigFactorial(new _BigNumber(n - 1))); + } + + var p = n; + var prod = new Big(n); + var sum = n.toNumber(); + + while (p > 2) { + p -= 2; + sum += p; + prod = prod.times(sum); + } + + return new _BigNumber(prod.toPrecision(_BigNumber.precision)); + } + + return gamma; +}); +// CONCATENATED MODULE: ./src/function/probability/factorial.js + + +var factorial_name = 'factorial'; +var factorial_dependencies = ['typed', 'gamma']; +var createFactorial = /* #__PURE__ */Object(factory["a" /* factory */])(factorial_name, factorial_dependencies, function (_ref) { + var typed = _ref.typed, + gamma = _ref.gamma; + + /** + * Compute the factorial of a value + * + * Factorial only supports an integer value as argument. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.factorial(n) + * + * Examples: + * + * math.factorial(5) // returns 120 + * math.factorial(3) // returns 6 + * + * See also: + * + * combinations, combinationsWithRep, gamma, permutations + * + * @param {number | BigNumber | Array | Matrix} n An integer number + * @return {number | BigNumber | Array | Matrix} The factorial of `n` + */ + var factorial = typed(factorial_name, { + number: function number(n) { + if (n < 0) { + throw new Error('Value must be non-negative'); + } + + return gamma(n + 1); + }, + BigNumber: function BigNumber(n) { + if (n.isNegative()) { + throw new Error('Value must be non-negative'); + } + + return gamma(n.plus(1)); + }, + 'Array | Matrix': function ArrayMatrix(n) { + return deepMap(n, factorial); + } + }); + return factorial; +}); +// CONCATENATED MODULE: ./src/function/probability/kldivergence.js + +var kldivergence_name = 'kldivergence'; +var kldivergence_dependencies = ['typed', 'matrix', 'divide', 'sum', 'multiply', 'dotDivide', 'log', 'isNumeric']; +var createKldivergence = /* #__PURE__ */Object(factory["a" /* factory */])(kldivergence_name, kldivergence_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + divide = _ref.divide, + sum = _ref.sum, + multiply = _ref.multiply, + dotDivide = _ref.dotDivide, + log = _ref.log, + isNumeric = _ref.isNumeric; + + /** + * Calculate the Kullback-Leibler (KL) divergence between two distributions + * + * Syntax: + * + * math.kldivergence(x, y) + * + * Examples: + * + * math.kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5]) //returns 0.24376698773121153 + * + * + * @param {Array | Matrix} q First vector + * @param {Array | Matrix} p Second vector + * @return {number} Returns distance between q and p + */ + return typed(kldivergence_name, { + 'Array, Array': function ArrayArray(q, p) { + return _kldiv(matrix(q), matrix(p)); + }, + 'Matrix, Array': function MatrixArray(q, p) { + return _kldiv(q, matrix(p)); + }, + 'Array, Matrix': function ArrayMatrix(q, p) { + return _kldiv(matrix(q), p); + }, + 'Matrix, Matrix': function MatrixMatrix(q, p) { + return _kldiv(q, p); + } + }); + + function _kldiv(q, p) { + var plength = p.size().length; + var qlength = q.size().length; + + if (plength > 1) { + throw new Error('first object must be one dimensional'); + } + + if (qlength > 1) { + throw new Error('second object must be one dimensional'); + } + + if (plength !== qlength) { + throw new Error('Length of two vectors must be equal'); + } // Before calculation, apply normalization + + + var sumq = sum(q); + + if (sumq === 0) { + throw new Error('Sum of elements in first object must be non zero'); + } + + var sump = sum(p); + + if (sump === 0) { + throw new Error('Sum of elements in second object must be non zero'); + } + + var qnorm = divide(q, sum(q)); + var pnorm = divide(p, sum(p)); + var result = sum(multiply(qnorm, log(dotDivide(qnorm, pnorm)))); + + if (isNumeric(result)) { + return result; + } else { + return Number.NaN; + } + } +}); +// CONCATENATED MODULE: ./src/function/probability/multinomial.js + + +var multinomial_name = 'multinomial'; +var multinomial_dependencies = ['typed', 'add', 'divide', 'multiply', 'factorial', 'isInteger', 'isPositive']; +var createMultinomial = /* #__PURE__ */Object(factory["a" /* factory */])(multinomial_name, multinomial_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + divide = _ref.divide, + multiply = _ref.multiply, + factorial = _ref.factorial, + isInteger = _ref.isInteger, + isPositive = _ref.isPositive; + + /** + * Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities. + * + * multinomial takes one array of integers as an argument. + * The following condition must be enforced: every ai <= 0 + * + * Syntax: + * + * math.multinomial(a) // a is an array type + * + * Examples: + * + * math.multinomial([1,2,1]) // returns 12 + * + * See also: + * + * combinations, factorial + * + * @param {number[] | BigNumber[]} a Integer numbers of objects in the subset + * @return {Number | BigNumber} Multinomial coefficient. + */ + return typed(multinomial_name, { + 'Array | Matrix': function ArrayMatrix(a) { + var sum = 0; + var denom = 1; + deepForEach(a, function (ai) { + if (!isInteger(ai) || !isPositive(ai)) { + throw new TypeError('Positive integer value expected in function multinomial'); + } + + sum = add(sum, ai); + denom = multiply(denom, factorial(ai)); + }); + return divide(factorial(sum), denom); + } + }); +}); +// CONCATENATED MODULE: ./src/function/probability/permutations.js + + + +var permutations_name = 'permutations'; +var permutations_dependencies = ['typed', 'factorial']; +var createPermutations = /* #__PURE__ */Object(factory["a" /* factory */])(permutations_name, permutations_dependencies, function (_ref) { + var typed = _ref.typed, + factorial = _ref.factorial; + + /** + * Compute the number of ways of obtaining an ordered subset of `k` elements + * from a set of `n` elements. + * + * Permutations only takes integer arguments. + * The following condition must be enforced: k <= n. + * + * Syntax: + * + * math.permutations(n) + * math.permutations(n, k) + * + * Examples: + * + * math.permutations(5) // 120 + * math.permutations(5, 3) // 60 + * + * See also: + * + * combinations, combinationsWithRep, factorial + * + * @param {number | BigNumber} n The number of objects in total + * @param {number | BigNumber} [k] The number of objects in the subset + * @return {number | BigNumber} The number of permutations + */ + return typed(permutations_name, { + 'number | BigNumber': factorial, + 'number, number': function numberNumber(n, k) { + if (!Object(utils_number["i" /* isInteger */])(n) || n < 0) { + throw new TypeError('Positive integer value expected in function permutations'); + } + + if (!Object(utils_number["i" /* isInteger */])(k) || k < 0) { + throw new TypeError('Positive integer value expected in function permutations'); + } + + if (k > n) { + throw new TypeError('second argument k must be less than or equal to first argument n'); + } // Permute n objects, k at a time + + + return product_product(n - k + 1, n); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(n, k) { + var result, i; + + if (!permutations_isPositiveInteger(n) || !permutations_isPositiveInteger(k)) { + throw new TypeError('Positive integer value expected in function permutations'); + } + + if (k.gt(n)) { + throw new TypeError('second argument k must be less than or equal to first argument n'); + } + + var one = n.mul(0).add(1); + result = one; + + for (i = n.minus(k).plus(1); i.lte(n); i = i.plus(1)) { + result = result.times(i); + } + + return result; + } // TODO: implement support for collection in permutations + + }); +}); +/** + * Test whether BigNumber n is a positive integer + * @param {BigNumber} n + * @returns {boolean} isPositiveInteger + */ + +function permutations_isPositiveInteger(n) { + return n.isInteger() && n.gte(0); +} +// EXTERNAL MODULE: ./node_modules/seed-random/index.js +var seed_random = __webpack_require__(15); +var seed_random_default = /*#__PURE__*/__webpack_require__.n(seed_random); + +// CONCATENATED MODULE: ./src/function/probability/util/seededRNG.js +// create a random seed here to prevent an infinite loop from seed-random +// inside the factory. Reason is that math.random is defined as a getter/setter +// and seed-random generates a seed from the local entropy by reading every +// defined object including `math` itself. That means that whilst getting +// math.random, it tries to get math.random, etc... an infinite loop. +// See https://github.com/ForbesLindesay/seed-random/issues/6 + +var singletonRandom = /* #__PURE__ */seed_random_default()(); +function createRng(randomSeed) { + var random; // create a new random generator with given seed + + function setSeed(seed) { + random = seed === null ? singletonRandom : seed_random_default()(String(seed)); + } // initialize a seeded pseudo random number generator with config's random seed + + + setSeed(randomSeed); // wrapper function so the rng can be updated via generator + + function rng() { + return random(); + } + + return rng; +} +// CONCATENATED MODULE: ./src/function/probability/pickRandom.js + + + + +var pickRandom_name = 'pickRandom'; +var pickRandom_dependencies = ['typed', 'config', '?on']; +var createPickRandom = /* #__PURE__ */Object(factory["a" /* factory */])(pickRandom_name, pickRandom_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + on = _ref.on; + // seeded pseudo random number generator + var rng = createRng(config.randomSeed); + + if (on) { + on('config', function (curr, prev) { + if (curr.randomSeed !== prev.randomSeed) { + rng = createRng(curr.randomSeed); + } + }); + } + /** + * Random pick one or more values from a one dimensional array. + * Array elements are picked using a random function with uniform or weighted distribution. + * + * Syntax: + * + * math.pickRandom(array) + * math.pickRandom(array, number) + * math.pickRandom(array, weights) + * math.pickRandom(array, number, weights) + * math.pickRandom(array, weights, number) + * + * Examples: + * + * math.pickRandom([3, 6, 12, 2]) // returns one of the values in the array + * math.pickRandom([3, 6, 12, 2], 2) // returns an array of two of the values in the array + * math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1]) // returns one of the values in the array with weighted distribution + * math.pickRandom([3, 6, 12, 2], 2, [1, 3, 2, 1]) // returns an array of two of the values in the array with weighted distribution + * math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1], 2) // returns an array of two of the values in the array with weighted distribution + * + * See also: + * + * random, randomInt + * + * @param {Array | Matrix} array A one dimensional array + * @param {Int} number An int or float + * @param {Array | Matrix} weights An array of ints or floats + * @return {number | Array} Returns a single random value from array when number is 1 or undefined. + * Returns an array with the configured number of elements when number is > 1. + */ + + + return typed({ + 'Array | Matrix': function ArrayMatrix(possibles) { + return _pickRandom(possibles); + }, + 'Array | Matrix, number': function ArrayMatrixNumber(possibles, number) { + return _pickRandom(possibles, number, undefined); + }, + 'Array | Matrix, Array': function ArrayMatrixArray(possibles, weights) { + return _pickRandom(possibles, undefined, weights); + }, + 'Array | Matrix, Array | Matrix, number': function ArrayMatrixArrayMatrixNumber(possibles, weights, number) { + return _pickRandom(possibles, number, weights); + }, + 'Array | Matrix, number, Array | Matrix': function ArrayMatrixNumberArrayMatrix(possibles, number, weights) { + return _pickRandom(possibles, number, weights); + } + }); + + function _pickRandom(possibles, number, weights) { + var single = typeof number === 'undefined'; + + if (single) { + number = 1; + } + + possibles = possibles.valueOf(); // get Array + + if (weights) { + weights = weights.valueOf(); // get Array + } + + if (Object(utils_array["a" /* arraySize */])(possibles).length > 1) { + throw new Error('Only one dimensional vectors supported'); + } + + var totalWeights = 0; + + if (typeof weights !== 'undefined') { + if (weights.length !== possibles.length) { + throw new Error('Weights must have the same length as possibles'); + } + + for (var i = 0, len = weights.length; i < len; i++) { + if (!Object(is["y" /* isNumber */])(weights[i]) || weights[i] < 0) { + throw new Error('Weights must be an array of positive numbers'); + } + + totalWeights += weights[i]; + } + } + + var length = possibles.length; + + if (length === 0) { + return []; + } else if (number >= length) { + return number > 1 ? possibles : possibles[0]; + } + + var result = []; + var pick; + + while (result.length < number) { + if (typeof weights === 'undefined') { + pick = possibles[Math.floor(rng() * length)]; + } else { + var randKey = rng() * totalWeights; + + for (var _i = 0, _len = possibles.length; _i < _len; _i++) { + randKey -= weights[_i]; + + if (randKey < 0) { + pick = possibles[_i]; + break; + } + } + } + + if (result.indexOf(pick) === -1) { + result.push(pick); + } + } + + return single ? result[0] : result; // TODO: return matrix when input was a matrix + // TODO: add support for multi dimensional matrices + } +}); +// CONCATENATED MODULE: ./src/function/probability/util/randomMatrix.js +/** + * This is a util function for generating a random matrix recursively. + * @param {number[]} size + * @param {function} random + * @returns {Array} + */ +function randomMatrix(size, random) { + var data = []; + size = size.slice(0); + + if (size.length > 1) { + for (var i = 0, length = size.shift(); i < length; i++) { + data.push(randomMatrix(size, random)); + } + } else { + for (var _i = 0, _length = size.shift(); _i < _length; _i++) { + data.push(random()); + } + } + + return data; +} +// CONCATENATED MODULE: ./src/function/probability/random.js + + + + +var random_name = 'random'; +var random_dependencies = ['typed', 'config', '?on']; +var createRandom = /* #__PURE__ */Object(factory["a" /* factory */])(random_name, random_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + on = _ref.on; + // seeded pseudo random number generator + var rng = createRng(config.randomSeed); + + if (on) { + on('config', function (curr, prev) { + if (curr.randomSeed !== prev.randomSeed) { + rng = createRng(curr.randomSeed); + } + }); + } + /** + * Return a random number larger or equal to `min` and smaller than `max` + * using a uniform distribution. + * + * Syntax: + * + * math.random() // generate a random number between 0 and 1 + * math.random(max) // generate a random number between 0 and max + * math.random(min, max) // generate a random number between min and max + * math.random(size) // generate a matrix with random numbers between 0 and 1 + * math.random(size, max) // generate a matrix with random numbers between 0 and max + * math.random(size, min, max) // generate a matrix with random numbers between min and max + * + * Examples: + * + * math.random() // returns a random number between 0 and 1 + * math.random(100) // returns a random number between 0 and 100 + * math.random(30, 40) // returns a random number between 30 and 40 + * math.random([2, 3]) // returns a 2x3 matrix with random numbers between 0 and 1 + * + * See also: + * + * randomInt, pickRandom + * + * @param {Array | Matrix} [size] If provided, an array or matrix with given + * size and filled with random values is returned + * @param {number} [min] Minimum boundary for the random value, included + * @param {number} [max] Maximum boundary for the random value, excluded + * @return {number | Array | Matrix} A random number + */ + + + return typed(random_name, { + '': function _() { + return _random(0, 1); + }, + number: function number(max) { + return _random(0, max); + }, + 'number, number': function numberNumber(min, max) { + return _random(min, max); + }, + 'Array | Matrix': function ArrayMatrix(size) { + return _randomMatrix(size, 0, 1); + }, + 'Array | Matrix, number': function ArrayMatrixNumber(size, max) { + return _randomMatrix(size, 0, max); + }, + 'Array | Matrix, number, number': function ArrayMatrixNumberNumber(size, min, max) { + return _randomMatrix(size, min, max); + } + }); + + function _randomMatrix(size, min, max) { + var res = randomMatrix(size.valueOf(), function () { + return _random(min, max); + }); + return Object(is["v" /* isMatrix */])(size) ? size.create(res) : res; + } + + function _random(min, max) { + return min + rng() * (max - min); + } +}); // number only implementation of random, no matrix support +// TODO: there is quite some duplicate code in both createRandom and createRandomNumber, can we improve that? + +var createRandomNumber = /* #__PURE__ */Object(factory["a" /* factory */])(random_name, ['typed', 'config', '?on'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config, + on = _ref2.on, + matrix = _ref2.matrix; + // seeded pseudo random number generator1 + var rng = createRng(config.randomSeed); + + if (on) { + on('config', function (curr, prev) { + if (curr.randomSeed !== prev.randomSeed) { + rng = createRng(curr.randomSeed); + } + }); + } + + return typed(random_name, { + '': function _() { + return _random(0, 1); + }, + number: function number(max) { + return _random(0, max); + }, + 'number, number': function numberNumber(min, max) { + return _random(min, max); + } + }); + + function _random(min, max) { + return min + rng() * (max - min); + } +}); +// CONCATENATED MODULE: ./src/function/probability/randomInt.js + + + + +var randomInt_name = 'randomInt'; +var randomInt_dependencies = ['typed', 'config', '?on']; +var createRandomInt = /* #__PURE__ */Object(factory["a" /* factory */])(randomInt_name, randomInt_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + on = _ref.on; + // seeded pseudo random number generator + var rng = createRng(config.randomSeed); + + if (on) { + on('config', function (curr, prev) { + if (curr.randomSeed !== prev.randomSeed) { + rng = createRng(curr.randomSeed); + } + }); + } + /** + * Return a random integer number larger or equal to `min` and smaller than `max` + * using a uniform distribution. + * + * Syntax: + * + * math.randomInt() // generate a random integer between 0 and 1 + * math.randomInt(max) // generate a random integer between 0 and max + * math.randomInt(min, max) // generate a random integer between min and max + * math.randomInt(size) // generate a matrix with random integer between 0 and 1 + * math.randomInt(size, max) // generate a matrix with random integer between 0 and max + * math.randomInt(size, min, max) // generate a matrix with random integer between min and max + * + * Examples: + * + * math.randomInt(100) // returns a random integer between 0 and 100 + * math.randomInt(30, 40) // returns a random integer between 30 and 40 + * math.randomInt([2, 3]) // returns a 2x3 matrix with random integers between 0 and 1 + * + * See also: + * + * random, pickRandom + * + * @param {Array | Matrix} [size] If provided, an array or matrix with given + * size and filled with random values is returned + * @param {number} [min] Minimum boundary for the random value, included + * @param {number} [max] Maximum boundary for the random value, excluded + * @return {number | Array | Matrix} A random integer value + */ + + + return typed(randomInt_name, { + '': function _() { + return _randomInt(0, 1); + }, + number: function number(max) { + return _randomInt(0, max); + }, + 'number, number': function numberNumber(min, max) { + return _randomInt(min, max); + }, + 'Array | Matrix': function ArrayMatrix(size) { + return _randomIntMatrix(size, 0, 1); + }, + 'Array | Matrix, number': function ArrayMatrixNumber(size, max) { + return _randomIntMatrix(size, 0, max); + }, + 'Array | Matrix, number, number': function ArrayMatrixNumberNumber(size, min, max) { + return _randomIntMatrix(size, min, max); + } + }); + + function _randomIntMatrix(size, min, max) { + var res = randomMatrix(size.valueOf(), function () { + return _randomInt(min, max); + }); + return Object(is["v" /* isMatrix */])(size) ? size.create(res) : res; + } + + function _randomInt(min, max) { + return Math.floor(min + rng() * (max - min)); + } +}); +// CONCATENATED MODULE: ./src/function/combinatorics/stirlingS2.js + +var stirlingS2_name = 'stirlingS2'; +var stirlingS2_dependencies = ['typed', 'addScalar', 'subtract', 'multiplyScalar', 'divideScalar', 'pow', 'factorial', 'combinations', 'isNegative', 'isInteger', 'larger']; +var createStirlingS2 = /* #__PURE__ */Object(factory["a" /* factory */])(stirlingS2_name, stirlingS2_dependencies, function (_ref) { + var typed = _ref.typed, + addScalar = _ref.addScalar, + subtract = _ref.subtract, + multiplyScalar = _ref.multiplyScalar, + divideScalar = _ref.divideScalar, + pow = _ref.pow, + factorial = _ref.factorial, + combinations = _ref.combinations, + isNegative = _ref.isNegative, + isInteger = _ref.isInteger, + larger = _ref.larger; + + /** + * The Stirling numbers of the second kind, counts the number of ways to partition + * a set of n labelled objects into k nonempty unlabelled subsets. + * stirlingS2 only takes integer arguments. + * The following condition must be enforced: k <= n. + * + * If n = k or k = 1, then s(n,k) = 1 + * + * Syntax: + * + * math.stirlingS2(n, k) + * + * Examples: + * + * math.stirlingS2(5, 3) //returns 25 + * + * See also: + * + * bellNumbers + * + * @param {Number | BigNumber} n Total number of objects in the set + * @param {Number | BigNumber} k Number of objects in the subset + * @return {Number | BigNumber} S(n,k) + */ + return typed(stirlingS2_name, { + 'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(n, k) { + if (!isInteger(n) || isNegative(n) || !isInteger(k) || isNegative(k)) { + throw new TypeError('Non-negative integer value expected in function stirlingS2'); + } else if (larger(k, n)) { + throw new TypeError('k must be less than or equal to n in function stirlingS2'); + } // 1/k! Sum(i=0 -> k) [(-1)^(k-i)*C(k,j)* i^n] + + + var kFactorial = factorial(k); + var result = 0; + + for (var i = 0; i <= k; i++) { + var negativeOne = pow(-1, subtract(k, i)); + var kChooseI = combinations(k, i); + var iPower = pow(i, n); + result = addScalar(result, multiplyScalar(multiplyScalar(kChooseI, iPower), negativeOne)); + } + + return divideScalar(result, kFactorial); + } + }); +}); +// CONCATENATED MODULE: ./src/function/combinatorics/bellNumbers.js + +var bellNumbers_name = 'bellNumbers'; +var bellNumbers_dependencies = ['typed', 'addScalar', 'isNegative', 'isInteger', 'stirlingS2']; +var createBellNumbers = /* #__PURE__ */Object(factory["a" /* factory */])(bellNumbers_name, bellNumbers_dependencies, function (_ref) { + var typed = _ref.typed, + addScalar = _ref.addScalar, + isNegative = _ref.isNegative, + isInteger = _ref.isInteger, + stirlingS2 = _ref.stirlingS2; + + /** + * The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S. + * bellNumbers only takes integer arguments. + * The following condition must be enforced: n >= 0 + * + * Syntax: + * + * math.bellNumbers(n) + * + * Examples: + * + * math.bellNumbers(3) // returns 5 + * math.bellNumbers(8) // returns 4140 + * + * See also: + * + * stirlingS2 + * + * @param {Number | BigNumber} n Total number of objects in the set + * @return {Number | BigNumber} B(n) + */ + return typed(bellNumbers_name, { + 'number | BigNumber': function numberBigNumber(n) { + if (!isInteger(n) || isNegative(n)) { + throw new TypeError('Non-negative integer value expected in function bellNumbers'); + } // Sum (k=0, n) S(n,k). + + + var result = 0; + + for (var i = 0; i <= n; i++) { + result = addScalar(result, stirlingS2(n, i)); + } + + return result; + } + }); +}); +// CONCATENATED MODULE: ./src/function/combinatorics/catalan.js + +var catalan_name = 'catalan'; +var catalan_dependencies = ['typed', 'addScalar', 'divideScalar', 'multiplyScalar', 'combinations', 'isNegative', 'isInteger']; +var createCatalan = /* #__PURE__ */Object(factory["a" /* factory */])(catalan_name, catalan_dependencies, function (_ref) { + var typed = _ref.typed, + addScalar = _ref.addScalar, + divideScalar = _ref.divideScalar, + multiplyScalar = _ref.multiplyScalar, + combinations = _ref.combinations, + isNegative = _ref.isNegative, + isInteger = _ref.isInteger; + + /** + * The Catalan Numbers enumerate combinatorial structures of many different types. + * catalan only takes integer arguments. + * The following condition must be enforced: n >= 0 + * + * Syntax: + * + * math.catalan(n) + * + * Examples: + * + * math.catalan(3) // returns 5 + * math.catalan(8) // returns 1430 + * + * See also: + * + * bellNumbers + * + * @param {Number | BigNumber} n nth Catalan number + * @return {Number | BigNumber} Cn(n) + */ + return typed(catalan_name, { + 'number | BigNumber': function numberBigNumber(n) { + if (!isInteger(n) || isNegative(n)) { + throw new TypeError('Non-negative integer value expected in function catalan'); + } + + return divideScalar(combinations(multiplyScalar(n, 2), n), addScalar(n, 1)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/combinatorics/composition.js + +var composition_name = 'composition'; +var composition_dependencies = ['typed', 'addScalar', 'combinations', 'isNegative', 'isPositive', 'isInteger', 'larger']; +var createComposition = /* #__PURE__ */Object(factory["a" /* factory */])(composition_name, composition_dependencies, function (_ref) { + var typed = _ref.typed, + addScalar = _ref.addScalar, + combinations = _ref.combinations, + isPositive = _ref.isPositive, + isNegative = _ref.isNegative, + isInteger = _ref.isInteger, + larger = _ref.larger; + + /** + * The composition counts of n into k parts. + * + * composition only takes integer arguments. + * The following condition must be enforced: k <= n. + * + * Syntax: + * + * math.composition(n, k) + * + * Examples: + * + * math.composition(5, 3) // returns 6 + * + * See also: + * + * combinations + * + * @param {Number | BigNumber} n Total number of objects in the set + * @param {Number | BigNumber} k Number of objects in the subset + * @return {Number | BigNumber} Returns the composition counts of n into k parts. + */ + return typed(composition_name, { + 'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(n, k) { + if (!isInteger(n) || !isPositive(n) || !isInteger(k) || !isPositive(k)) { + throw new TypeError('Positive integer value expected in function composition'); + } else if (larger(k, n)) { + throw new TypeError('k must be less than or equal to n in function composition'); + } + + return combinations(addScalar(n, -1), addScalar(k, -1)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/algebra/simplify/util.js + + + +var util_name = 'simplifyUtil'; +var util_dependencies = ['FunctionNode', 'OperatorNode', 'SymbolNode']; +var createUtil = /* #__PURE__ */Object(factory["a" /* factory */])(util_name, util_dependencies, function (_ref) { + var FunctionNode = _ref.FunctionNode, + OperatorNode = _ref.OperatorNode, + SymbolNode = _ref.SymbolNode; + // TODO commutative/associative properties rely on the arguments + // e.g. multiply is not commutative for matrices + // The properties should be calculated from an argument to simplify, or possibly something in math.config + // the other option is for typed() to specify a return type so that we can evaluate the type of arguments + var commutative = { + add: true, + multiply: true + }; + var associative = { + add: true, + multiply: true + }; + + function isCommutative(node, context) { + if (!Object(is["B" /* isOperatorNode */])(node)) { + return true; + } + + var name = node.fn.toString(); + + if (context && Object(utils_object["f" /* hasOwnProperty */])(context, name) && Object(utils_object["f" /* hasOwnProperty */])(context[name], 'commutative')) { + return context[name].commutative; + } + + return commutative[name] || false; + } + + function isAssociative(node, context) { + if (!Object(is["B" /* isOperatorNode */])(node)) { + return false; + } + + var name = node.fn.toString(); + + if (context && Object(utils_object["f" /* hasOwnProperty */])(context, name) && Object(utils_object["f" /* hasOwnProperty */])(context[name], 'associative')) { + return context[name].associative; + } + + return associative[name] || false; + } + /** + * Flatten all associative operators in an expression tree. + * Assumes parentheses have already been removed. + */ + + + function flatten(node) { + if (!node.args || node.args.length === 0) { + return node; + } + + node.args = allChildren(node); + + for (var i = 0; i < node.args.length; i++) { + flatten(node.args[i]); + } + } + /** + * Get the children of a node as if it has been flattened. + * TODO implement for FunctionNodes + */ + + + function allChildren(node) { + var op; + var children = []; + + var findChildren = function findChildren(node) { + for (var i = 0; i < node.args.length; i++) { + var child = node.args[i]; + + if (Object(is["B" /* isOperatorNode */])(child) && op === child.op) { + findChildren(child); + } else { + children.push(child); + } + } + }; + + if (isAssociative(node)) { + op = node.op; + findChildren(node); + return children; + } else { + return node.args; + } + } + /** + * Unflatten all flattened operators to a right-heavy binary tree. + */ + + + function unflattenr(node) { + if (!node.args || node.args.length === 0) { + return; + } + + var makeNode = createMakeNodeFunction(node); + var l = node.args.length; + + for (var i = 0; i < l; i++) { + unflattenr(node.args[i]); + } + + if (l > 2 && isAssociative(node)) { + var curnode = node.args.pop(); + + while (node.args.length > 0) { + curnode = makeNode([node.args.pop(), curnode]); + } + + node.args = curnode.args; + } + } + /** + * Unflatten all flattened operators to a left-heavy binary tree. + */ + + + function unflattenl(node) { + if (!node.args || node.args.length === 0) { + return; + } + + var makeNode = createMakeNodeFunction(node); + var l = node.args.length; + + for (var i = 0; i < l; i++) { + unflattenl(node.args[i]); + } + + if (l > 2 && isAssociative(node)) { + var curnode = node.args.shift(); + + while (node.args.length > 0) { + curnode = makeNode([curnode, node.args.shift()]); + } + + node.args = curnode.args; + } + } + + function createMakeNodeFunction(node) { + if (Object(is["B" /* isOperatorNode */])(node)) { + return function (args) { + try { + return new OperatorNode(node.op, node.fn, args, node.implicit); + } catch (err) { + console.error(err); + return []; + } + }; + } else { + return function (args) { + return new FunctionNode(new SymbolNode(node.name), args); + }; + } + } + + return { + createMakeNodeFunction: createMakeNodeFunction, + isCommutative: isCommutative, + isAssociative: isAssociative, + flatten: flatten, + allChildren: allChildren, + unflattenr: unflattenr, + unflattenl: unflattenl + }; +}); +// CONCATENATED MODULE: ./src/function/algebra/simplify/simplifyCore.js + + +var simplifyCore_name = 'simplifyCore'; +var simplifyCore_dependencies = ['equal', 'isZero', 'add', 'subtract', 'multiply', 'divide', 'pow', 'ConstantNode', 'OperatorNode', 'FunctionNode', 'ParenthesisNode']; +var createSimplifyCore = /* #__PURE__ */Object(factory["a" /* factory */])(simplifyCore_name, simplifyCore_dependencies, function (_ref) { + var equal = _ref.equal, + isZero = _ref.isZero, + add = _ref.add, + subtract = _ref.subtract, + multiply = _ref.multiply, + divide = _ref.divide, + pow = _ref.pow, + ConstantNode = _ref.ConstantNode, + OperatorNode = _ref.OperatorNode, + FunctionNode = _ref.FunctionNode, + ParenthesisNode = _ref.ParenthesisNode; + var node0 = new ConstantNode(0); + var node1 = new ConstantNode(1); + /** + * simplifyCore() performs single pass simplification suitable for + * applications requiring ultimate performance. In contrast, simplify() + * extends simplifyCore() with additional passes to provide deeper + * simplification. + * + * Syntax: + * + * simplify.simplifyCore(expr) + * + * Examples: + * + * const f = math.parse('2 * 1 * x ^ (2 - 1)') + * math.simplify.simpifyCore(f) // Node {2 * x} + * math.simplify('2 * 1 * x ^ (2 - 1)', [math.simplify.simpifyCore]) // Node {2 * x} + * + * See also: + * + * derivative + * + * @param {Node} node + * The expression to be simplified + */ + + function simplifyCore(node) { + if (Object(is["B" /* isOperatorNode */])(node) && node.isUnary()) { + var a0 = simplifyCore(node.args[0]); + + if (node.op === '+') { + // unary plus + return a0; + } + + if (node.op === '-') { + // unary minus + if (Object(is["B" /* isOperatorNode */])(a0)) { + if (a0.isUnary() && a0.op === '-') { + return a0.args[0]; + } else if (a0.isBinary() && a0.fn === 'subtract') { + return new OperatorNode('-', 'subtract', [a0.args[1], a0.args[0]]); + } + } + + return new OperatorNode(node.op, node.fn, [a0]); + } + } else if (Object(is["B" /* isOperatorNode */])(node) && node.isBinary()) { + var _a = simplifyCore(node.args[0]); + + var a1 = simplifyCore(node.args[1]); + + if (node.op === '+') { + if (Object(is["l" /* isConstantNode */])(_a)) { + if (isZero(_a.value)) { + return a1; + } else if (Object(is["l" /* isConstantNode */])(a1)) { + return new ConstantNode(add(_a.value, a1.value)); + } + } + + if (Object(is["l" /* isConstantNode */])(a1) && isZero(a1.value)) { + return _a; + } + + if (Object(is["B" /* isOperatorNode */])(a1) && a1.isUnary() && a1.op === '-') { + return new OperatorNode('-', 'subtract', [_a, a1.args[0]]); + } + + return new OperatorNode(node.op, node.fn, a1 ? [_a, a1] : [_a]); + } else if (node.op === '-') { + if (Object(is["l" /* isConstantNode */])(_a) && a1) { + if (Object(is["l" /* isConstantNode */])(a1)) { + return new ConstantNode(subtract(_a.value, a1.value)); + } else if (isZero(_a.value)) { + return new OperatorNode('-', 'unaryMinus', [a1]); + } + } // if (node.fn === "subtract" && node.args.length === 2) { + + + if (node.fn === 'subtract') { + if (Object(is["l" /* isConstantNode */])(a1) && isZero(a1.value)) { + return _a; + } + + if (Object(is["B" /* isOperatorNode */])(a1) && a1.isUnary() && a1.op === '-') { + return simplifyCore(new OperatorNode('+', 'add', [_a, a1.args[0]])); + } + + return new OperatorNode(node.op, node.fn, [_a, a1]); + } + } else if (node.op === '*') { + if (Object(is["l" /* isConstantNode */])(_a)) { + if (isZero(_a.value)) { + return node0; + } else if (equal(_a.value, 1)) { + return a1; + } else if (Object(is["l" /* isConstantNode */])(a1)) { + return new ConstantNode(multiply(_a.value, a1.value)); + } + } + + if (Object(is["l" /* isConstantNode */])(a1)) { + if (isZero(a1.value)) { + return node0; + } else if (equal(a1.value, 1)) { + return _a; + } else if (Object(is["B" /* isOperatorNode */])(_a) && _a.isBinary() && _a.op === node.op) { + var a00 = _a.args[0]; + + if (Object(is["l" /* isConstantNode */])(a00)) { + var a00a1 = new ConstantNode(multiply(a00.value, a1.value)); + return new OperatorNode(node.op, node.fn, [a00a1, _a.args[1]], node.implicit); // constants on left + } + } + + return new OperatorNode(node.op, node.fn, [a1, _a], node.implicit); // constants on left + } + + return new OperatorNode(node.op, node.fn, [_a, a1], node.implicit); + } else if (node.op === '/') { + if (Object(is["l" /* isConstantNode */])(_a)) { + if (isZero(_a.value)) { + return node0; + } else if (Object(is["l" /* isConstantNode */])(a1) && (equal(a1.value, 1) || equal(a1.value, 2) || equal(a1.value, 4))) { + return new ConstantNode(divide(_a.value, a1.value)); + } + } + + return new OperatorNode(node.op, node.fn, [_a, a1]); + } else if (node.op === '^') { + if (Object(is["l" /* isConstantNode */])(a1)) { + if (isZero(a1.value)) { + return node1; + } else if (equal(a1.value, 1)) { + return _a; + } else { + if (Object(is["l" /* isConstantNode */])(_a)) { + // fold constant + return new ConstantNode(pow(_a.value, a1.value)); + } else if (Object(is["B" /* isOperatorNode */])(_a) && _a.isBinary() && _a.op === '^') { + var a01 = _a.args[1]; + + if (Object(is["l" /* isConstantNode */])(a01)) { + return new OperatorNode(node.op, node.fn, [_a.args[0], new ConstantNode(multiply(a01.value, a1.value))]); + } + } + } + } + + return new OperatorNode(node.op, node.fn, [_a, a1]); + } + } else if (Object(is["C" /* isParenthesisNode */])(node)) { + var c = simplifyCore(node.content); + + if (Object(is["C" /* isParenthesisNode */])(c) || Object(is["J" /* isSymbolNode */])(c) || Object(is["l" /* isConstantNode */])(c)) { + return c; + } + + return new ParenthesisNode(c); + } else if (Object(is["r" /* isFunctionNode */])(node)) { + var args = node.args.map(simplifyCore).map(function (arg) { + return Object(is["C" /* isParenthesisNode */])(arg) ? arg.content : arg; + }); + return new FunctionNode(simplifyCore(node.fn), args); + } else {// cannot simplify + } + + return node; + } + + return simplifyCore; +}); +// CONCATENATED MODULE: ./src/function/algebra/simplify/simplifyConstant.js +// TODO this could be improved by simplifying seperated constants under associative and commutative operators + + + + +var simplifyConstant_name = 'simplifyConstant'; +var simplifyConstant_dependencies = ['typed', 'config', 'mathWithTransform', '?fraction', '?bignumber', 'ConstantNode', 'OperatorNode', 'FunctionNode', 'SymbolNode']; +var createSimplifyConstant = /* #__PURE__ */Object(factory["a" /* factory */])(simplifyConstant_name, simplifyConstant_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + mathWithTransform = _ref.mathWithTransform, + fraction = _ref.fraction, + bignumber = _ref.bignumber, + ConstantNode = _ref.ConstantNode, + OperatorNode = _ref.OperatorNode, + FunctionNode = _ref.FunctionNode, + SymbolNode = _ref.SymbolNode; + + var _createUtil = createUtil({ + FunctionNode: FunctionNode, + OperatorNode: OperatorNode, + SymbolNode: SymbolNode + }), + isCommutative = _createUtil.isCommutative, + isAssociative = _createUtil.isAssociative, + allChildren = _createUtil.allChildren, + createMakeNodeFunction = _createUtil.createMakeNodeFunction; + + function simplifyConstant(expr, options) { + var res = foldFraction(expr, options); + return Object(is["w" /* isNode */])(res) ? res : _toNode(res); + } + + function _eval(fnname, args, options) { + try { + return _toNumber(mathWithTransform[fnname].apply(null, args), options); + } catch (ignore) { + // sometimes the implicit type conversion causes the evaluation to fail, so we'll try again after removing Fractions + args = args.map(function (x) { + if (Object(is["o" /* isFraction */])(x)) { + return x.valueOf(); + } + + return x; + }); + return _toNumber(mathWithTransform[fnname].apply(null, args), options); + } + } + + var _toNode = typed({ + Fraction: _fractionToNode, + number: function number(n) { + if (n < 0) { + return unaryMinusNode(new ConstantNode(-n)); + } + + return new ConstantNode(n); + }, + BigNumber: function BigNumber(n) { + if (n < 0) { + return unaryMinusNode(new ConstantNode(-n)); + } + + return new ConstantNode(n); // old parameters: (n.toString(), 'number') + }, + Complex: function Complex(s) { + throw new Error('Cannot convert Complex number to Node'); + } + }); // convert a number to a fraction only if it can be expressed exactly + + + function _exactFraction(n, options) { + var exactFractions = options && options.exactFractions !== false; + + if (exactFractions && isFinite(n) && fraction) { + var f = fraction(n); + + if (f.valueOf() === n) { + return f; + } + } + + return n; + } // Convert numbers to a preferred number type in preference order: Fraction, number, Complex + // BigNumbers are left alone + + + var _toNumber = typed({ + 'string, Object': function stringObject(s, options) { + if (config.number === 'BigNumber') { + if (bignumber === undefined) { + noBignumber(); + } + + return bignumber(s); + } else if (config.number === 'Fraction') { + if (fraction === undefined) { + noFraction(); + } + + return fraction(s); + } else { + var n = parseFloat(s); + return _exactFraction(n, options); + } + }, + 'Fraction, Object': function FractionObject(s, options) { + return s; + }, + // we don't need options here + 'BigNumber, Object': function BigNumberObject(s, options) { + return s; + }, + // we don't need options here + 'number, Object': function numberObject(s, options) { + return _exactFraction(s, options); + }, + 'Complex, Object': function ComplexObject(s, options) { + if (s.im !== 0) { + return s; + } + + return _exactFraction(s.re, options); + } + }); + + function unaryMinusNode(n) { + return new OperatorNode('-', 'unaryMinus', [n]); + } + + function _fractionToNode(f) { + var n; + var vn = f.s * f.n; + + if (vn < 0) { + n = new OperatorNode('-', 'unaryMinus', [new ConstantNode(-vn)]); + } else { + n = new ConstantNode(vn); + } + + if (f.d === 1) { + return n; + } + + return new OperatorNode('/', 'divide', [n, new ConstantNode(f.d)]); + } + /* + * Create a binary tree from a list of Fractions and Nodes. + * Tries to fold Fractions by evaluating them until the first Node in the list is hit, so + * `args` should be sorted to have the Fractions at the start (if the operator is commutative). + * @param args - list of Fractions and Nodes + * @param fn - evaluator for the binary operation evaluator that accepts two Fractions + * @param makeNode - creates a binary OperatorNode/FunctionNode from a list of child Nodes + * if args.length is 1, returns args[0] + * @return - Either a Node representing a binary expression or Fraction + */ + + + function foldOp(fn, args, makeNode, options) { + return args.reduce(function (a, b) { + if (!Object(is["w" /* isNode */])(a) && !Object(is["w" /* isNode */])(b)) { + try { + return _eval(fn, [a, b], options); + } catch (ignoreandcontinue) {} + + a = _toNode(a); + b = _toNode(b); + } else if (!Object(is["w" /* isNode */])(a)) { + a = _toNode(a); + } else if (!Object(is["w" /* isNode */])(b)) { + b = _toNode(b); + } + + return makeNode([a, b]); + }); + } // destroys the original node and returns a folded one + + + function foldFraction(node, options) { + switch (node.type) { + case 'SymbolNode': + return node; + + case 'ConstantNode': + if (typeof node.value === 'number' || !isNaN(node.value)) { + return _toNumber(node.value, options); + } + + return node; + + case 'FunctionNode': + if (mathWithTransform[node.name] && mathWithTransform[node.name].rawArgs) { + return node; + } + + { + // Process operators as OperatorNode + var operatorFunctions = ['add', 'multiply']; + + if (operatorFunctions.indexOf(node.name) === -1) { + var args = node.args.map(function (arg) { + return foldFraction(arg, options); + }); // If all args are numbers + + if (!args.some(is["w" /* isNode */])) { + try { + return _eval(node.name, args, options); + } catch (ignoreandcontine) {} + } // Convert all args to nodes and construct a symbolic function call + + + args = args.map(function (arg) { + return Object(is["w" /* isNode */])(arg) ? arg : _toNode(arg); + }); + return new FunctionNode(node.name, args); + } else {// treat as operator + } + } + + /* falls through */ + + case 'OperatorNode': + { + var fn = node.fn.toString(); + + var _args; + + var res; + var makeNode = createMakeNodeFunction(node); + + if (Object(is["B" /* isOperatorNode */])(node) && node.isUnary()) { + _args = [foldFraction(node.args[0], options)]; + + if (!Object(is["w" /* isNode */])(_args[0])) { + res = _eval(fn, _args, options); + } else { + res = makeNode(_args); + } + } else if (isAssociative(node)) { + _args = allChildren(node); + _args = _args.map(function (arg) { + return foldFraction(arg, options); + }); + + if (isCommutative(fn)) { + // commutative binary operator + var consts = []; + var vars = []; + + for (var i = 0; i < _args.length; i++) { + if (!Object(is["w" /* isNode */])(_args[i])) { + consts.push(_args[i]); + } else { + vars.push(_args[i]); + } + } + + if (consts.length > 1) { + res = foldOp(fn, consts, makeNode, options); + vars.unshift(res); + res = foldOp(fn, vars, makeNode, options); + } else { + // we won't change the children order since it's not neccessary + res = foldOp(fn, _args, makeNode, options); + } + } else { + // non-commutative binary operator + res = foldOp(fn, _args, makeNode, options); + } + } else { + // non-associative binary operator + _args = node.args.map(function (arg) { + return foldFraction(arg, options); + }); + res = foldOp(fn, _args, makeNode, options); + } + + return res; + } + + case 'ParenthesisNode': + // remove the uneccessary parenthesis + return foldFraction(node.content, options); + + case 'AccessorNode': + /* falls through */ + + case 'ArrayNode': + /* falls through */ + + case 'AssignmentNode': + /* falls through */ + + case 'BlockNode': + /* falls through */ + + case 'FunctionAssignmentNode': + /* falls through */ + + case 'IndexNode': + /* falls through */ + + case 'ObjectNode': + /* falls through */ + + case 'RangeNode': + /* falls through */ + + case 'ConditionalNode': + /* falls through */ + + default: + throw new Error("Unimplemented node type in simplifyConstant: ".concat(node.type)); + } + } + + return simplifyConstant; +}); +// CONCATENATED MODULE: ./src/function/algebra/simplify/resolve.js + + +var resolve_name = 'resolve'; +var resolve_dependencies = ['parse', 'FunctionNode', 'OperatorNode', 'ParenthesisNode']; +var createResolve = /* #__PURE__ */Object(factory["a" /* factory */])(resolve_name, resolve_dependencies, function (_ref) { + var parse = _ref.parse, + FunctionNode = _ref.FunctionNode, + OperatorNode = _ref.OperatorNode, + ParenthesisNode = _ref.ParenthesisNode; + + /** + * resolve(expr, scope) replaces variable nodes with their scoped values + * + * Syntax: + * + * simplify.resolve(expr, scope) + * + * Examples: + * + * math.simplify.resolve('x + y', {x:1, y:2}) // Node {1 + 2} + * math.simplify.resolve(math.parse('x+y'), {x:1, y:2}) // Node {1 + 2} + * math.simplify('x+y', {x:2, y:'x+x'}).toString() // "6" + * + * @param {Node} node + * The expression tree to be simplified + * @param {Object} scope with variables to be resolved + */ + function resolve(node, scope) { + if (!scope) { + return node; + } + + if (Object(is["J" /* isSymbolNode */])(node)) { + var value = scope[node.name]; + + if (Object(is["w" /* isNode */])(value)) { + return resolve(value, scope); + } else if (typeof value === 'number') { + return parse(String(value)); + } + } else if (Object(is["B" /* isOperatorNode */])(node)) { + var args = node.args.map(function (arg) { + return resolve(arg, scope); + }); + return new OperatorNode(node.op, node.fn, args, node.implicit); + } else if (Object(is["C" /* isParenthesisNode */])(node)) { + return new ParenthesisNode(resolve(node.content, scope)); + } else if (Object(is["r" /* isFunctionNode */])(node)) { + var _args = node.args.map(function (arg) { + return resolve(arg, scope); + }); + + return new FunctionNode(node.name, _args); + } + + return node; + } + + return resolve; +}); +// CONCATENATED MODULE: ./src/function/algebra/simplify.js +function simplify_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { simplify_typeof = function _typeof(obj) { return typeof obj; }; } else { simplify_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return simplify_typeof(obj); } + + + + + + + + +var simplify_name = 'simplify'; +var simplify_dependencies = ['config', 'typed', 'parse', 'add', 'subtract', 'multiply', 'divide', 'pow', 'isZero', 'equal', '?fraction', '?bignumber', 'mathWithTransform', 'ConstantNode', 'FunctionNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode']; +var createSimplify = /* #__PURE__ */Object(factory["a" /* factory */])(simplify_name, simplify_dependencies, function (_ref) { + var config = _ref.config, + typed = _ref.typed, + parse = _ref.parse, + add = _ref.add, + subtract = _ref.subtract, + multiply = _ref.multiply, + divide = _ref.divide, + pow = _ref.pow, + isZero = _ref.isZero, + equal = _ref.equal, + fraction = _ref.fraction, + bignumber = _ref.bignumber, + mathWithTransform = _ref.mathWithTransform, + ConstantNode = _ref.ConstantNode, + FunctionNode = _ref.FunctionNode, + OperatorNode = _ref.OperatorNode, + ParenthesisNode = _ref.ParenthesisNode, + SymbolNode = _ref.SymbolNode; + var simplifyConstant = createSimplifyConstant({ + typed: typed, + config: config, + mathWithTransform: mathWithTransform, + fraction: fraction, + bignumber: bignumber, + ConstantNode: ConstantNode, + OperatorNode: OperatorNode, + FunctionNode: FunctionNode, + SymbolNode: SymbolNode + }); + var simplifyCore = createSimplifyCore({ + equal: equal, + isZero: isZero, + add: add, + subtract: subtract, + multiply: multiply, + divide: divide, + pow: pow, + ConstantNode: ConstantNode, + OperatorNode: OperatorNode, + FunctionNode: FunctionNode, + ParenthesisNode: ParenthesisNode + }); + var resolve = createResolve({ + parse: parse, + FunctionNode: FunctionNode, + OperatorNode: OperatorNode, + ParenthesisNode: ParenthesisNode + }); + + var _createUtil = createUtil({ + FunctionNode: FunctionNode, + OperatorNode: OperatorNode, + SymbolNode: SymbolNode + }), + isCommutative = _createUtil.isCommutative, + isAssociative = _createUtil.isAssociative, + flatten = _createUtil.flatten, + unflattenr = _createUtil.unflattenr, + unflattenl = _createUtil.unflattenl, + createMakeNodeFunction = _createUtil.createMakeNodeFunction; + /** + * Simplify an expression tree. + * + * A list of rules are applied to an expression, repeating over the list until + * no further changes are made. + * It's possible to pass a custom set of rules to the function as second + * argument. A rule can be specified as an object, string, or function: + * + * const rules = [ + * { l: 'n1*n3 + n2*n3', r: '(n1+n2)*n3' }, + * 'n1*n3 + n2*n3 -> (n1+n2)*n3', + * function (node) { + * // ... return a new node or return the node unchanged + * return node + * } + * ] + * + * String and object rules consist of a left and right pattern. The left is + * used to match against the expression and the right determines what matches + * are replaced with. The main difference between a pattern and a normal + * expression is that variables starting with the following characters are + * interpreted as wildcards: + * + * - 'n' - matches any Node + * - 'c' - matches any ConstantNode + * - 'v' - matches any Node that is not a ConstantNode + * + * The default list of rules is exposed on the function as `simplify.rules` + * and can be used as a basis to built a set of custom rules. + * + * For more details on the theory, see: + * + * - [Strategies for simplifying math expressions (Stackoverflow)](https://stackoverflow.com/questions/7540227/strategies-for-simplifying-math-expressions) + * - [Symbolic computation - Simplification (Wikipedia)](https://en.wikipedia.org/wiki/Symbolic_computation#Simplification) + * + * An optional `options` argument can be passed as last argument of `simplify`. + * There is currently one option available: `exactFractions`, a boolean which + * is `true` by default. + * + * Syntax: + * + * simplify(expr) + * simplify(expr, rules) + * simplify(expr, rules) + * simplify(expr, rules, scope) + * simplify(expr, rules, scope, options) + * simplify(expr, scope) + * simplify(expr, scope, options) + * + * Examples: + * + * math.simplify('2 * 1 * x ^ (2 - 1)') // Node "2 * x" + * math.simplify('2 * 3 * x', {x: 4}) // Node "24" + * const f = math.parse('2 * 1 * x ^ (2 - 1)') + * math.simplify(f) // Node "2 * x" + * math.simplify('0.4 * x', {}, {exactFractions: true}) // Node "x * 2 / 5" + * math.simplify('0.4 * x', {}, {exactFractions: false}) // Node "0.4 * x" + * + * See also: + * + * derivative, parse, evaluate, rationalize + * + * @param {Node | string} expr + * The expression to be simplified + * @param {Array<{l:string, r: string} | string | function>} [rules] + * Optional list with custom rules + * @return {Node} Returns the simplified form of `expr` + */ + + + var simplify = typed('simplify', { + string: function string(expr) { + return simplify(parse(expr), simplify.rules, {}, {}); + }, + 'string, Object': function stringObject(expr, scope) { + return simplify(parse(expr), simplify.rules, scope, {}); + }, + 'string, Object, Object': function stringObjectObject(expr, scope, options) { + return simplify(parse(expr), simplify.rules, scope, options); + }, + 'string, Array': function stringArray(expr, rules) { + return simplify(parse(expr), rules, {}, {}); + }, + 'string, Array, Object': function stringArrayObject(expr, rules, scope) { + return simplify(parse(expr), rules, scope, {}); + }, + 'string, Array, Object, Object': function stringArrayObjectObject(expr, rules, scope, options) { + return simplify(parse(expr), rules, scope, options); + }, + 'Node, Object': function NodeObject(expr, scope) { + return simplify(expr, simplify.rules, scope, {}); + }, + 'Node, Object, Object': function NodeObjectObject(expr, scope, options) { + return simplify(expr, simplify.rules, scope, options); + }, + Node: function Node(expr) { + return simplify(expr, simplify.rules, {}, {}); + }, + 'Node, Array': function NodeArray(expr, rules) { + return simplify(expr, rules, {}, {}); + }, + 'Node, Array, Object': function NodeArrayObject(expr, rules, scope) { + return simplify(expr, rules, scope, {}); + }, + 'Node, Array, Object, Object': function NodeArrayObjectObject(expr, rules, scope, options) { + rules = _buildRules(rules); + var res = resolve(expr, scope); + res = removeParens(res); + var visited = {}; + var str = res.toString({ + parenthesis: 'all' + }); + + while (!visited[str]) { + visited[str] = true; + _lastsym = 0; // counter for placeholder symbols + + for (var i = 0; i < rules.length; i++) { + if (typeof rules[i] === 'function') { + res = rules[i](res, options); + } else { + flatten(res); + res = applyRule(res, rules[i]); + } + + unflattenl(res); // using left-heavy binary tree here since custom rule functions may expect it + } + + str = res.toString({ + parenthesis: 'all' + }); + } + + return res; + } + }); + simplify.simplifyCore = simplifyCore; + simplify.resolve = resolve; + + function removeParens(node) { + return node.transform(function (node, path, parent) { + return Object(is["C" /* isParenthesisNode */])(node) ? removeParens(node.content) : node; + }); + } // All constants that are allowed in rules + + + var SUPPORTED_CONSTANTS = { + "true": true, + "false": true, + e: true, + i: true, + Infinity: true, + LN2: true, + LN10: true, + LOG2E: true, + LOG10E: true, + NaN: true, + phi: true, + pi: true, + SQRT1_2: true, + SQRT2: true, + tau: true // null: false, + // undefined: false, + // version: false, + + }; // Array of strings, used to build the ruleSet. + // Each l (left side) and r (right side) are parsed by + // the expression parser into a node tree. + // Left hand sides are matched to subtrees within the + // expression to be parsed and replaced with the right + // hand side. + // TODO: Add support for constraints on constants (either in the form of a '=' expression or a callback [callback allows things like comparing symbols alphabetically]) + // To evaluate lhs constants for rhs constants, use: { l: 'c1+c2', r: 'c3', evaluate: 'c3 = c1 + c2' }. Multiple assignments are separated by ';' in block format. + // It is possible to get into an infinite loop with conflicting rules + + simplify.rules = [simplifyCore, // { l: 'n+0', r: 'n' }, // simplifyCore + // { l: 'n^0', r: '1' }, // simplifyCore + // { l: '0*n', r: '0' }, // simplifyCore + // { l: 'n/n', r: '1'}, // simplifyCore + // { l: 'n^1', r: 'n' }, // simplifyCore + // { l: '+n1', r:'n1' }, // simplifyCore + // { l: 'n--n1', r:'n+n1' }, // simplifyCore + { + l: 'log(e)', + r: '1' + }, // temporary rules + { + l: 'n-n1', + r: 'n+-n1' + }, // temporarily replace 'subtract' so we can further flatten the 'add' operator + { + l: '-(c*v)', + r: '(-c) * v' + }, // make non-constant terms positive + { + l: '-v', + r: '(-1) * v' + }, { + l: 'n/n1^n2', + r: 'n*n1^-n2' + }, // temporarily replace 'divide' so we can further flatten the 'multiply' operator + { + l: 'n/n1', + r: 'n*n1^-1' + }, // expand nested exponentiation + { + l: '(n ^ n1) ^ n2', + r: 'n ^ (n1 * n2)' + }, // collect like factors + { + l: 'n*n', + r: 'n^2' + }, { + l: 'n * n^n1', + r: 'n^(n1+1)' + }, { + l: 'n^n1 * n^n2', + r: 'n^(n1+n2)' + }, // collect like terms + { + l: 'n+n', + r: '2*n' + }, { + l: 'n+-n', + r: '0' + }, { + l: 'n1*n2 + n2', + r: '(n1+1)*n2' + }, { + l: 'n1*n3 + n2*n3', + r: '(n1+n2)*n3' + }, // remove parenthesis in the case of negating a quantitiy + { + l: 'n1 + -1 * (n2 + n3)', + r: 'n1 + -1 * n2 + -1 * n3' + }, simplifyConstant, { + l: '(-n)*n1', + r: '-(n*n1)' + }, // make factors positive (and undo 'make non-constant terms positive') + // ordering of constants + { + l: 'c+v', + r: 'v+c', + context: { + add: { + commutative: false + } + } + }, { + l: 'v*c', + r: 'c*v', + context: { + multiply: { + commutative: false + } + } + }, // undo temporary rules + // { l: '(-1) * n', r: '-n' }, // #811 added test which proved this is redundant + { + l: 'n+-n1', + r: 'n-n1' + }, // undo replace 'subtract' + { + l: 'n*(n1^-1)', + r: 'n/n1' + }, // undo replace 'divide' + { + l: 'n*n1^-n2', + r: 'n/n1^n2' + }, { + l: 'n1^-1', + r: '1/n1' + }, { + l: 'n*(n1/n2)', + r: '(n*n1)/n2' + }, // '*' before '/' + { + l: 'n-(n1+n2)', + r: 'n-n1-n2' + }, // '-' before '+' + // { l: '(n1/n2)/n3', r: 'n1/(n2*n3)' }, + // { l: '(n*n1)/(n*n2)', r: 'n1/n2' }, + { + l: '1*n', + r: 'n' + }, // this pattern can be produced by simplifyConstant + { + l: 'n1/(n2/n3)', + r: '(n1*n3)/n2' + }]; + /** + * Parse the string array of rules into nodes + * + * Example syntax for rules: + * + * Position constants to the left in a product: + * { l: 'n1 * c1', r: 'c1 * n1' } + * n1 is any Node, and c1 is a ConstantNode. + * + * Apply difference of squares formula: + * { l: '(n1 - n2) * (n1 + n2)', r: 'n1^2 - n2^2' } + * n1, n2 mean any Node. + * + * Short hand notation: + * 'n1 * c1 -> c1 * n1' + */ + + function _buildRules(rules) { + // Array of rules to be used to simplify expressions + var ruleSet = []; + + for (var i = 0; i < rules.length; i++) { + var rule = rules[i]; + var newRule = void 0; + + var ruleType = simplify_typeof(rule); + + switch (ruleType) { + case 'string': + { + var lr = rule.split('->'); + + if (lr.length === 2) { + rule = { + l: lr[0], + r: lr[1] + }; + } else { + throw SyntaxError('Could not parse rule: ' + rule); + } + } + + /* falls through */ + + case 'object': + newRule = { + l: removeParens(parse(rule.l)), + r: removeParens(parse(rule.r)) + }; + + if (rule.context) { + newRule.evaluate = rule.context; + } + + if (rule.evaluate) { + newRule.evaluate = parse(rule.evaluate); + } + + if (isAssociative(newRule.l)) { + var makeNode = createMakeNodeFunction(newRule.l); + + var expandsym = _getExpandPlaceholderSymbol(); + + newRule.expanded = {}; + newRule.expanded.l = makeNode([newRule.l.clone(), expandsym]); // Push the expandsym into the deepest possible branch. + // This helps to match the newRule against nodes returned from getSplits() later on. + + flatten(newRule.expanded.l); + unflattenr(newRule.expanded.l); + newRule.expanded.r = makeNode([newRule.r, expandsym]); + } + + break; + + case 'function': + newRule = rule; + break; + + default: + throw TypeError('Unsupported type of rule: ' + ruleType); + } // console.log('Adding rule: ' + rules[i]) + // console.log(newRule) + + + ruleSet.push(newRule); + } + + return ruleSet; + } + + var _lastsym = 0; + + function _getExpandPlaceholderSymbol() { + return new SymbolNode('_p' + _lastsym++); + } + /** + * Returns a simplfied form of node, or the original node if no simplification was possible. + * + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node + * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The simplified form of `expr`, or the original node if no simplification was possible. + */ + + + var applyRule = typed('applyRule', { + 'Node, Object': function NodeObject(node, rule) { + // console.log('Entering applyRule(' + node.toString() + ')') + // Do not clone node unless we find a match + var res = node; // First replace our child nodes with their simplified versions + // If a child could not be simplified, the assignments will have + // no effect since the node is returned unchanged + + if (res instanceof OperatorNode || res instanceof FunctionNode) { + if (res.args) { + for (var i = 0; i < res.args.length; i++) { + res.args[i] = applyRule(res.args[i], rule); + } + } + } else if (res instanceof ParenthesisNode) { + if (res.content) { + res.content = applyRule(res.content, rule); + } + } // Try to match a rule against this node + + + var repl = rule.r; + + var matches = _ruleMatch(rule.l, res)[0]; // If the rule is associative operator, we can try matching it while allowing additional terms. + // This allows us to match rules like 'n+n' to the expression '(1+x)+x' or even 'x+1+x' if the operator is commutative. + + + if (!matches && rule.expanded) { + repl = rule.expanded.r; + matches = _ruleMatch(rule.expanded.l, res)[0]; + } + + if (matches) { + // const before = res.toString({parenthesis: 'all'}) + // Create a new node by cloning the rhs of the matched rule + // we keep any implicit multiplication state if relevant + var implicit = res.implicit; + res = repl.clone(); + + if (implicit && 'implicit' in repl) { + res.implicit = true; + } // Replace placeholders with their respective nodes without traversing deeper into the replaced nodes + + + res = res.transform(function (node) { + if (node.isSymbolNode && Object(utils_object["f" /* hasOwnProperty */])(matches.placeholders, node.name)) { + return matches.placeholders[node.name].clone(); + } else { + return node; + } + }); // const after = res.toString({parenthesis: 'all'}) + // console.log('Simplified ' + before + ' to ' + after) + } + + return res; + } + }); + /** + * Get (binary) combinations of a flattened binary node + * e.g. +(node1, node2, node3) -> [ + * +(node1, +(node2, node3)), + * +(node2, +(node1, node3)), + * +(node3, +(node1, node2))] + * + */ + + function getSplits(node, context) { + var res = []; + var right, rightArgs; + var makeNode = createMakeNodeFunction(node); + + if (isCommutative(node, context)) { + for (var i = 0; i < node.args.length; i++) { + rightArgs = node.args.slice(0); + rightArgs.splice(i, 1); + right = rightArgs.length === 1 ? rightArgs[0] : makeNode(rightArgs); + res.push(makeNode([node.args[i], right])); + } + } else { + rightArgs = node.args.slice(1); + right = rightArgs.length === 1 ? rightArgs[0] : makeNode(rightArgs); + res.push(makeNode([node.args[0], right])); + } + + return res; + } + /** + * Returns the set union of two match-placeholders or null if there is a conflict. + */ + + + function mergeMatch(match1, match2) { + var res = { + placeholders: {} + }; // Some matches may not have placeholders; this is OK + + if (!match1.placeholders && !match2.placeholders) { + return res; + } else if (!match1.placeholders) { + return match2; + } else if (!match2.placeholders) { + return match1; + } // Placeholders with the same key must match exactly + + + for (var key in match1.placeholders) { + res.placeholders[key] = match1.placeholders[key]; + + if (Object(utils_object["f" /* hasOwnProperty */])(match2.placeholders, key)) { + if (!_exactMatch(match1.placeholders[key], match2.placeholders[key])) { + return null; + } + } + } + + for (var _key in match2.placeholders) { + res.placeholders[_key] = match2.placeholders[_key]; + } + + return res; + } + /** + * Combine two lists of matches by applying mergeMatch to the cartesian product of two lists of matches. + * Each list represents matches found in one child of a node. + */ + + + function combineChildMatches(list1, list2) { + var res = []; + + if (list1.length === 0 || list2.length === 0) { + return res; + } + + var merged; + + for (var i1 = 0; i1 < list1.length; i1++) { + for (var i2 = 0; i2 < list2.length; i2++) { + merged = mergeMatch(list1[i1], list2[i2]); + + if (merged) { + res.push(merged); + } + } + } + + return res; + } + /** + * Combine multiple lists of matches by applying mergeMatch to the cartesian product of two lists of matches. + * Each list represents matches found in one child of a node. + * Returns a list of unique matches. + */ + + + function mergeChildMatches(childMatches) { + if (childMatches.length === 0) { + return childMatches; + } + + var sets = childMatches.reduce(combineChildMatches); + var uniqueSets = []; + var unique = {}; + + for (var i = 0; i < sets.length; i++) { + var s = JSON.stringify(sets[i]); + + if (!unique[s]) { + unique[s] = true; + uniqueSets.push(sets[i]); + } + } + + return uniqueSets; + } + /** + * Determines whether node matches rule. + * + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} rule + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node + * @return {Object} Information about the match, if it exists. + */ + + + function _ruleMatch(rule, node, isSplit) { + // console.log('Entering _ruleMatch(' + JSON.stringify(rule) + ', ' + JSON.stringify(node) + ')') + // console.log('rule = ' + rule) + // console.log('node = ' + node) + // console.log('Entering _ruleMatch(' + rule.toString() + ', ' + node.toString() + ')') + var res = [{ + placeholders: {} + }]; + + if (rule instanceof OperatorNode && node instanceof OperatorNode || rule instanceof FunctionNode && node instanceof FunctionNode) { + // If the rule is an OperatorNode or a FunctionNode, then node must match exactly + if (rule instanceof OperatorNode) { + if (rule.op !== node.op || rule.fn !== node.fn) { + return []; + } + } else if (rule instanceof FunctionNode) { + if (rule.name !== node.name) { + return []; + } + } // rule and node match. Search the children of rule and node. + + + if (node.args.length === 1 && rule.args.length === 1 || !isAssociative(node) || isSplit) { + // Expect non-associative operators to match exactly + var childMatches = []; + + for (var i = 0; i < rule.args.length; i++) { + var childMatch = _ruleMatch(rule.args[i], node.args[i]); + + if (childMatch.length === 0) { + // Child did not match, so stop searching immediately + return []; + } // The child matched, so add the information returned from the child to our result + + + childMatches.push(childMatch); + } + + res = mergeChildMatches(childMatches); + } else if (node.args.length >= 2 && rule.args.length === 2) { + // node is flattened, rule is not + // Associative operators/functions can be split in different ways so we check if the rule matches each + // them and return their union. + var splits = getSplits(node, rule.context); + var splitMatches = []; + + for (var _i = 0; _i < splits.length; _i++) { + var matchSet = _ruleMatch(rule, splits[_i], true); // recursing at the same tree depth here + + + splitMatches = splitMatches.concat(matchSet); + } + + return splitMatches; + } else if (rule.args.length > 2) { + throw Error('Unexpected non-binary associative function: ' + rule.toString()); + } else { + // Incorrect number of arguments in rule and node, so no match + return []; + } + } else if (rule instanceof SymbolNode) { + // If the rule is a SymbolNode, then it carries a special meaning + // according to the first character of the symbol node name. + // c.* matches a ConstantNode + // n.* matches any node + if (rule.name.length === 0) { + throw new Error('Symbol in rule has 0 length...!?'); + } + + if (SUPPORTED_CONSTANTS[rule.name]) { + // built-in constant must match exactly + if (rule.name !== node.name) { + return []; + } + } else if (rule.name[0] === 'n' || rule.name.substring(0, 2) === '_p') { + // rule matches _anything_, so assign this node to the rule.name placeholder + // Assign node to the rule.name placeholder. + // Our parent will check for matches among placeholders. + res[0].placeholders[rule.name] = node; + } else if (rule.name[0] === 'v') { + // rule matches any variable thing (not a ConstantNode) + if (!Object(is["l" /* isConstantNode */])(node)) { + res[0].placeholders[rule.name] = node; + } else { + // Mis-match: rule was expecting something other than a ConstantNode + return []; + } + } else if (rule.name[0] === 'c') { + // rule matches any ConstantNode + if (node instanceof ConstantNode) { + res[0].placeholders[rule.name] = node; + } else { + // Mis-match: rule was expecting a ConstantNode + return []; + } + } else { + throw new Error('Invalid symbol in rule: ' + rule.name); + } + } else if (rule instanceof ConstantNode) { + // Literal constant must match exactly + if (!equal(rule.value, node.value)) { + return []; + } + } else { + // Some other node was encountered which we aren't prepared for, so no match + return []; + } // It's a match! + // console.log('_ruleMatch(' + rule.toString() + ', ' + node.toString() + ') found a match') + + + return res; + } + /** + * Determines whether p and q (and all their children nodes) are identical. + * + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} p + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} q + * @return {Object} Information about the match, if it exists. + */ + + + function _exactMatch(p, q) { + if (p instanceof ConstantNode && q instanceof ConstantNode) { + if (!equal(p.value, q.value)) { + return false; + } + } else if (p instanceof SymbolNode && q instanceof SymbolNode) { + if (p.name !== q.name) { + return false; + } + } else if (p instanceof OperatorNode && q instanceof OperatorNode || p instanceof FunctionNode && q instanceof FunctionNode) { + if (p instanceof OperatorNode) { + if (p.op !== q.op || p.fn !== q.fn) { + return false; + } + } else if (p instanceof FunctionNode) { + if (p.name !== q.name) { + return false; + } + } + + if (p.args.length !== q.args.length) { + return false; + } + + for (var i = 0; i < p.args.length; i++) { + if (!_exactMatch(p.args[i], q.args[i])) { + return false; + } + } + } else { + return false; + } + + return true; + } + + return simplify; +}); +// CONCATENATED MODULE: ./src/function/algebra/derivative.js + + +var derivative_name = 'derivative'; +var derivative_dependencies = ['typed', 'config', 'parse', 'simplify', 'equal', 'isZero', 'numeric', 'ConstantNode', 'FunctionNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode']; +var createDerivative = /* #__PURE__ */Object(factory["a" /* factory */])(derivative_name, derivative_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + parse = _ref.parse, + simplify = _ref.simplify, + equal = _ref.equal, + isZero = _ref.isZero, + numeric = _ref.numeric, + ConstantNode = _ref.ConstantNode, + FunctionNode = _ref.FunctionNode, + OperatorNode = _ref.OperatorNode, + ParenthesisNode = _ref.ParenthesisNode, + SymbolNode = _ref.SymbolNode; + + /** + * Takes the derivative of an expression expressed in parser Nodes. + * The derivative will be taken over the supplied variable in the + * second parameter. If there are multiple variables in the expression, + * it will return a partial derivative. + * + * This uses rules of differentiation which can be found here: + * + * - [Differentiation rules (Wikipedia)](https://en.wikipedia.org/wiki/Differentiation_rules) + * + * Syntax: + * + * derivative(expr, variable) + * derivative(expr, variable, options) + * + * Examples: + * + * math.derivative('x^2', 'x') // Node {2 * x} + * math.derivative('x^2', 'x', {simplify: false}) // Node {2 * 1 * x ^ (2 - 1) + * math.derivative('sin(2x)', 'x')) // Node {2 * cos(2 * x)} + * math.derivative('2*x', 'x').evaluate() // number 2 + * math.derivative('x^2', 'x').evaluate({x: 4}) // number 8 + * const f = math.parse('x^2') + * const x = math.parse('x') + * math.derivative(f, x) // Node {2 * x} + * + * See also: + * + * simplify, parse, evaluate + * + * @param {Node | string} expr The expression to differentiate + * @param {SymbolNode | string} variable The variable over which to differentiate + * @param {{simplify: boolean}} [options] + * There is one option available, `simplify`, which + * is true by default. When false, output will not + * be simplified. + * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The derivative of `expr` + */ + var derivative = typed('derivative', { + 'Node, SymbolNode, Object': function NodeSymbolNodeObject(expr, variable, options) { + var constNodes = {}; + constTag(constNodes, expr, variable.name); + + var res = _derivative(expr, constNodes); + + return options.simplify ? simplify(res) : res; + }, + 'Node, SymbolNode': function NodeSymbolNode(expr, variable) { + return derivative(expr, variable, { + simplify: true + }); + }, + 'string, SymbolNode': function stringSymbolNode(expr, variable) { + return derivative(parse(expr), variable); + }, + 'string, SymbolNode, Object': function stringSymbolNodeObject(expr, variable, options) { + return derivative(parse(expr), variable, options); + }, + 'string, string': function stringString(expr, variable) { + return derivative(parse(expr), parse(variable)); + }, + 'string, string, Object': function stringStringObject(expr, variable, options) { + return derivative(parse(expr), parse(variable), options); + }, + 'Node, string': function NodeString(expr, variable) { + return derivative(expr, parse(variable)); + }, + 'Node, string, Object': function NodeStringObject(expr, variable, options) { + return derivative(expr, parse(variable), options); + } // TODO: replace the 8 signatures above with 4 as soon as typed-function supports optional arguments + + /* TODO: implement and test syntax with order of derivatives -> implement as an option {order: number} + 'Node, SymbolNode, ConstantNode': function (expr, variable, {order}) { + let res = expr + for (let i = 0; i < order; i++) { + let constNodes = {} + constTag(constNodes, expr, variable.name) + res = _derivative(res, constNodes) + } + return res + } + */ + + }); + derivative._simplify = true; + + derivative.toTex = function (deriv) { + return _derivTex.apply(null, deriv.args); + }; // FIXME: move the toTex method of derivative to latex.js. Difficulty is that it relies on parse. + // NOTE: the optional "order" parameter here is currently unused + + + var _derivTex = typed('_derivTex', { + 'Node, SymbolNode': function NodeSymbolNode(expr, x) { + if (Object(is["l" /* isConstantNode */])(expr) && Object(is["M" /* typeOf */])(expr.value) === 'string') { + return _derivTex(parse(expr.value).toString(), x.toString(), 1); + } else { + return _derivTex(expr.toString(), x.toString(), 1); + } + }, + 'Node, ConstantNode': function NodeConstantNode(expr, x) { + if (Object(is["M" /* typeOf */])(x.value) === 'string') { + return _derivTex(expr, parse(x.value)); + } else { + throw new Error("The second parameter to 'derivative' is a non-string constant"); + } + }, + 'Node, SymbolNode, ConstantNode': function NodeSymbolNodeConstantNode(expr, x, order) { + return _derivTex(expr.toString(), x.name, order.value); + }, + 'string, string, number': function stringStringNumber(expr, x, order) { + var d; + + if (order === 1) { + d = '{d\\over d' + x + '}'; + } else { + d = '{d^{' + order + '}\\over d' + x + '^{' + order + '}}'; + } + + return d + "\\left[".concat(expr, "\\right]"); + } + }); + /** + * Does a depth-first search on the expression tree to identify what Nodes + * are constants (e.g. 2 + 2), and stores the ones that are constants in + * constNodes. Classification is done as follows: + * + * 1. ConstantNodes are constants. + * 2. If there exists a SymbolNode, of which we are differentiating over, + * in the subtree it is not constant. + * + * @param {Object} constNodes Holds the nodes that are constant + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node + * @param {string} varName Variable that we are differentiating + * @return {boolean} if node is constant + */ + // TODO: can we rewrite constTag into a pure function? + + + var constTag = typed('constTag', { + 'Object, ConstantNode, string': function ObjectConstantNodeString(constNodes, node) { + constNodes[node] = true; + return true; + }, + 'Object, SymbolNode, string': function ObjectSymbolNodeString(constNodes, node, varName) { + // Treat other variables like constants. For reasoning, see: + // https://en.wikipedia.org/wiki/Partial_derivative + if (node.name !== varName) { + constNodes[node] = true; + return true; + } + + return false; + }, + 'Object, ParenthesisNode, string': function ObjectParenthesisNodeString(constNodes, node, varName) { + return constTag(constNodes, node.content, varName); + }, + 'Object, FunctionAssignmentNode, string': function ObjectFunctionAssignmentNodeString(constNodes, node, varName) { + if (node.params.indexOf(varName) === -1) { + constNodes[node] = true; + return true; + } + + return constTag(constNodes, node.expr, varName); + }, + 'Object, FunctionNode | OperatorNode, string': function ObjectFunctionNodeOperatorNodeString(constNodes, node, varName) { + if (node.args.length > 0) { + var isConst = constTag(constNodes, node.args[0], varName); + + for (var i = 1; i < node.args.length; ++i) { + isConst = constTag(constNodes, node.args[i], varName) && isConst; + } + + if (isConst) { + constNodes[node] = true; + return true; + } + } + + return false; + } + }); + /** + * Applies differentiation rules. + * + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node + * @param {Object} constNodes Holds the nodes that are constant + * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The derivative of `expr` + */ + + var _derivative = typed('_derivative', { + 'ConstantNode, Object': function ConstantNodeObject(node) { + return createConstantNode(0); + }, + 'SymbolNode, Object': function SymbolNodeObject(node, constNodes) { + if (constNodes[node] !== undefined) { + return createConstantNode(0); + } + + return createConstantNode(1); + }, + 'ParenthesisNode, Object': function ParenthesisNodeObject(node, constNodes) { + return new ParenthesisNode(_derivative(node.content, constNodes)); + }, + 'FunctionAssignmentNode, Object': function FunctionAssignmentNodeObject(node, constNodes) { + if (constNodes[node] !== undefined) { + return createConstantNode(0); + } + + return _derivative(node.expr, constNodes); + }, + 'FunctionNode, Object': function FunctionNodeObject(node, constNodes) { + if (node.args.length !== 1) { + funcArgsCheck(node); + } + + if (constNodes[node] !== undefined) { + return createConstantNode(0); + } + + var arg0 = node.args[0]; + var arg1; + var div = false; // is output a fraction? + + var negative = false; // is output negative? + + var funcDerivative; + + switch (node.name) { + case 'cbrt': + // d/dx(cbrt(x)) = 1 / (3x^(2/3)) + div = true; + funcDerivative = new OperatorNode('*', 'multiply', [createConstantNode(3), new OperatorNode('^', 'pow', [arg0, new OperatorNode('/', 'divide', [createConstantNode(2), createConstantNode(3)])])]); + break; + + case 'sqrt': + case 'nthRoot': + // d/dx(sqrt(x)) = 1 / (2*sqrt(x)) + if (node.args.length === 1) { + div = true; + funcDerivative = new OperatorNode('*', 'multiply', [createConstantNode(2), new FunctionNode('sqrt', [arg0])]); + } else if (node.args.length === 2) { + // Rearrange from nthRoot(x, a) -> x^(1/a) + arg1 = new OperatorNode('/', 'divide', [createConstantNode(1), node.args[1]]); // Is a variable? + + constNodes[arg1] = constNodes[node.args[1]]; + return _derivative(new OperatorNode('^', 'pow', [arg0, arg1]), constNodes); + } + + break; + + case 'log10': + arg1 = createConstantNode(10); + + /* fall through! */ + + case 'log': + if (!arg1 && node.args.length === 1) { + // d/dx(log(x)) = 1 / x + funcDerivative = arg0.clone(); + div = true; + } else if (node.args.length === 1 && arg1 || node.args.length === 2 && constNodes[node.args[1]] !== undefined) { + // d/dx(log(x, c)) = 1 / (x*ln(c)) + funcDerivative = new OperatorNode('*', 'multiply', [arg0.clone(), new FunctionNode('log', [arg1 || node.args[1]])]); + div = true; + } else if (node.args.length === 2) { + // d/dx(log(f(x), g(x))) = d/dx(log(f(x)) / log(g(x))) + return _derivative(new OperatorNode('/', 'divide', [new FunctionNode('log', [arg0]), new FunctionNode('log', [node.args[1]])]), constNodes); + } + + break; + + case 'pow': + constNodes[arg1] = constNodes[node.args[1]]; // Pass to pow operator node parser + + return _derivative(new OperatorNode('^', 'pow', [arg0, node.args[1]]), constNodes); + + case 'exp': + // d/dx(e^x) = e^x + funcDerivative = new FunctionNode('exp', [arg0.clone()]); + break; + + case 'sin': + // d/dx(sin(x)) = cos(x) + funcDerivative = new FunctionNode('cos', [arg0.clone()]); + break; + + case 'cos': + // d/dx(cos(x)) = -sin(x) + funcDerivative = new OperatorNode('-', 'unaryMinus', [new FunctionNode('sin', [arg0.clone()])]); + break; + + case 'tan': + // d/dx(tan(x)) = sec(x)^2 + funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('sec', [arg0.clone()]), createConstantNode(2)]); + break; + + case 'sec': + // d/dx(sec(x)) = sec(x)tan(x) + funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('tan', [arg0.clone()])]); + break; + + case 'csc': + // d/dx(csc(x)) = -csc(x)cot(x) + negative = true; + funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('cot', [arg0.clone()])]); + break; + + case 'cot': + // d/dx(cot(x)) = -csc(x)^2 + negative = true; + funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('csc', [arg0.clone()]), createConstantNode(2)]); + break; + + case 'asin': + // d/dx(asin(x)) = 1 / sqrt(1 - x^2) + div = true; + funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])]); + break; + + case 'acos': + // d/dx(acos(x)) = -1 / sqrt(1 - x^2) + div = true; + negative = true; + funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])]); + break; + + case 'atan': + // d/dx(atan(x)) = 1 / (x^2 + 1) + div = true; + funcDerivative = new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)]); + break; + + case 'asec': + // d/dx(asec(x)) = 1 / (|x|*sqrt(x^2 - 1)) + div = true; + funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]); + break; + + case 'acsc': + // d/dx(acsc(x)) = -1 / (|x|*sqrt(x^2 - 1)) + div = true; + negative = true; + funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]); + break; + + case 'acot': + // d/dx(acot(x)) = -1 / (x^2 + 1) + div = true; + negative = true; + funcDerivative = new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)]); + break; + + case 'sinh': + // d/dx(sinh(x)) = cosh(x) + funcDerivative = new FunctionNode('cosh', [arg0.clone()]); + break; + + case 'cosh': + // d/dx(cosh(x)) = sinh(x) + funcDerivative = new FunctionNode('sinh', [arg0.clone()]); + break; + + case 'tanh': + // d/dx(tanh(x)) = sech(x)^2 + funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('sech', [arg0.clone()]), createConstantNode(2)]); + break; + + case 'sech': + // d/dx(sech(x)) = -sech(x)tanh(x) + negative = true; + funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('tanh', [arg0.clone()])]); + break; + + case 'csch': + // d/dx(csch(x)) = -csch(x)coth(x) + negative = true; + funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('coth', [arg0.clone()])]); + break; + + case 'coth': + // d/dx(coth(x)) = -csch(x)^2 + negative = true; + funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('csch', [arg0.clone()]), createConstantNode(2)]); + break; + + case 'asinh': + // d/dx(asinh(x)) = 1 / sqrt(x^2 + 1) + div = true; + funcDerivative = new FunctionNode('sqrt', [new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])]); + break; + + case 'acosh': + // d/dx(acosh(x)) = 1 / sqrt(x^2 - 1); XXX potentially only for x >= 1 (the real spectrum) + div = true; + funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])]); + break; + + case 'atanh': + // d/dx(atanh(x)) = 1 / (1 - x^2) + div = true; + funcDerivative = new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])]); + break; + + case 'asech': + // d/dx(asech(x)) = -1 / (x*sqrt(1 - x^2)) + div = true; + negative = true; + funcDerivative = new OperatorNode('*', 'multiply', [arg0.clone(), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])])]); + break; + + case 'acsch': + // d/dx(acsch(x)) = -1 / (|x|*sqrt(x^2 + 1)) + div = true; + negative = true; + funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]); + break; + + case 'acoth': + // d/dx(acoth(x)) = -1 / (1 - x^2) + div = true; + negative = true; + funcDerivative = new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])]); + break; + + case 'abs': + // d/dx(abs(x)) = abs(x)/x + funcDerivative = new OperatorNode('/', 'divide', [new FunctionNode(new SymbolNode('abs'), [arg0.clone()]), arg0.clone()]); + break; + + case 'gamma': // Needs digamma function, d/dx(gamma(x)) = gamma(x)digamma(x) + + default: + throw new Error('Function "' + node.name + '" is not supported by derivative, or a wrong number of arguments is passed'); + } + + var op, func; + + if (div) { + op = '/'; + func = 'divide'; + } else { + op = '*'; + func = 'multiply'; + } + /* Apply chain rule to all functions: + F(x) = f(g(x)) + F'(x) = g'(x)*f'(g(x)) */ + + + var chainDerivative = _derivative(arg0, constNodes); + + if (negative) { + chainDerivative = new OperatorNode('-', 'unaryMinus', [chainDerivative]); + } + + return new OperatorNode(op, func, [chainDerivative, funcDerivative]); + }, + 'OperatorNode, Object': function OperatorNodeObject(node, constNodes) { + if (constNodes[node] !== undefined) { + return createConstantNode(0); + } + + if (node.op === '+') { + // d/dx(sum(f(x)) = sum(f'(x)) + return new OperatorNode(node.op, node.fn, node.args.map(function (arg) { + return _derivative(arg, constNodes); + })); + } + + if (node.op === '-') { + // d/dx(+/-f(x)) = +/-f'(x) + if (node.isUnary()) { + return new OperatorNode(node.op, node.fn, [_derivative(node.args[0], constNodes)]); + } // Linearity of differentiation, d/dx(f(x) +/- g(x)) = f'(x) +/- g'(x) + + + if (node.isBinary()) { + return new OperatorNode(node.op, node.fn, [_derivative(node.args[0], constNodes), _derivative(node.args[1], constNodes)]); + } + } + + if (node.op === '*') { + // d/dx(c*f(x)) = c*f'(x) + var constantTerms = node.args.filter(function (arg) { + return constNodes[arg] !== undefined; + }); + + if (constantTerms.length > 0) { + var nonConstantTerms = node.args.filter(function (arg) { + return constNodes[arg] === undefined; + }); + var nonConstantNode = nonConstantTerms.length === 1 ? nonConstantTerms[0] : new OperatorNode('*', 'multiply', nonConstantTerms); + var newArgs = constantTerms.concat(_derivative(nonConstantNode, constNodes)); + return new OperatorNode('*', 'multiply', newArgs); + } // Product Rule, d/dx(f(x)*g(x)) = f'(x)*g(x) + f(x)*g'(x) + + + return new OperatorNode('+', 'add', node.args.map(function (argOuter) { + return new OperatorNode('*', 'multiply', node.args.map(function (argInner) { + return argInner === argOuter ? _derivative(argInner, constNodes) : argInner.clone(); + })); + })); + } + + if (node.op === '/' && node.isBinary()) { + var arg0 = node.args[0]; + var arg1 = node.args[1]; // d/dx(f(x) / c) = f'(x) / c + + if (constNodes[arg1] !== undefined) { + return new OperatorNode('/', 'divide', [_derivative(arg0, constNodes), arg1]); + } // Reciprocal Rule, d/dx(c / f(x)) = -c(f'(x)/f(x)^2) + + + if (constNodes[arg0] !== undefined) { + return new OperatorNode('*', 'multiply', [new OperatorNode('-', 'unaryMinus', [arg0]), new OperatorNode('/', 'divide', [_derivative(arg1, constNodes), new OperatorNode('^', 'pow', [arg1.clone(), createConstantNode(2)])])]); + } // Quotient rule, d/dx(f(x) / g(x)) = (f'(x)g(x) - f(x)g'(x)) / g(x)^2 + + + return new OperatorNode('/', 'divide', [new OperatorNode('-', 'subtract', [new OperatorNode('*', 'multiply', [_derivative(arg0, constNodes), arg1.clone()]), new OperatorNode('*', 'multiply', [arg0.clone(), _derivative(arg1, constNodes)])]), new OperatorNode('^', 'pow', [arg1.clone(), createConstantNode(2)])]); + } + + if (node.op === '^' && node.isBinary()) { + var _arg = node.args[0]; + var _arg2 = node.args[1]; + + if (constNodes[_arg] !== undefined) { + // If is secretly constant; 0^f(x) = 1 (in JS), 1^f(x) = 1 + if (Object(is["l" /* isConstantNode */])(_arg) && (isZero(_arg.value) || equal(_arg.value, 1))) { + return createConstantNode(0); + } // d/dx(c^f(x)) = c^f(x)*ln(c)*f'(x) + + + return new OperatorNode('*', 'multiply', [node, new OperatorNode('*', 'multiply', [new FunctionNode('log', [_arg.clone()]), _derivative(_arg2.clone(), constNodes)])]); + } + + if (constNodes[_arg2] !== undefined) { + if (Object(is["l" /* isConstantNode */])(_arg2)) { + // If is secretly constant; f(x)^0 = 1 -> d/dx(1) = 0 + if (isZero(_arg2.value)) { + return createConstantNode(0); + } // Ignore exponent; f(x)^1 = f(x) + + + if (equal(_arg2.value, 1)) { + return _derivative(_arg, constNodes); + } + } // Elementary Power Rule, d/dx(f(x)^c) = c*f'(x)*f(x)^(c-1) + + + var powMinusOne = new OperatorNode('^', 'pow', [_arg.clone(), new OperatorNode('-', 'subtract', [_arg2, createConstantNode(1)])]); + return new OperatorNode('*', 'multiply', [_arg2.clone(), new OperatorNode('*', 'multiply', [_derivative(_arg, constNodes), powMinusOne])]); + } // Functional Power Rule, d/dx(f^g) = f^g*[f'*(g/f) + g'ln(f)] + + + return new OperatorNode('*', 'multiply', [new OperatorNode('^', 'pow', [_arg.clone(), _arg2.clone()]), new OperatorNode('+', 'add', [new OperatorNode('*', 'multiply', [_derivative(_arg, constNodes), new OperatorNode('/', 'divide', [_arg2.clone(), _arg.clone()])]), new OperatorNode('*', 'multiply', [_derivative(_arg2, constNodes), new FunctionNode('log', [_arg.clone()])])])]); + } + + throw new Error('Operator "' + node.op + '" is not supported by derivative, or a wrong number of arguments is passed'); + } + }); + /** + * Ensures the number of arguments for a function are correct, + * and will throw an error otherwise. + * + * @param {FunctionNode} node + */ + + + function funcArgsCheck(node) { + // TODO add min, max etc + if ((node.name === 'log' || node.name === 'nthRoot' || node.name === 'pow') && node.args.length === 2) { + return; + } // There should be an incorrect number of arguments if we reach here + // Change all args to constants to avoid unidentified + // symbol error when compiling function + + + for (var i = 0; i < node.args.length; ++i) { + node.args[i] = createConstantNode(0); + } + + node.compile().evaluate(); + throw new Error('Expected TypeError, but none found'); + } + /** + * Helper function to create a constant node with a specific type + * (number, BigNumber, Fraction) + * @param {number} value + * @param {string} [valueType] + * @return {ConstantNode} + */ + + + function createConstantNode(value, valueType) { + return new ConstantNode(numeric(value, valueType || config.number)); + } + + return derivative; +}); +// CONCATENATED MODULE: ./src/function/algebra/rationalize.js + + + + +var rationalize_name = 'rationalize'; +var rationalize_dependencies = ['config', 'typed', 'equal', 'isZero', 'add', 'subtract', 'multiply', 'divide', 'pow', 'parse', 'simplify', '?bignumber', '?fraction', 'mathWithTransform', 'ConstantNode', 'OperatorNode', 'FunctionNode', 'SymbolNode', 'ParenthesisNode']; +var createRationalize = /* #__PURE__ */Object(factory["a" /* factory */])(rationalize_name, rationalize_dependencies, function (_ref) { + var config = _ref.config, + typed = _ref.typed, + equal = _ref.equal, + isZero = _ref.isZero, + add = _ref.add, + subtract = _ref.subtract, + multiply = _ref.multiply, + divide = _ref.divide, + pow = _ref.pow, + parse = _ref.parse, + simplify = _ref.simplify, + fraction = _ref.fraction, + bignumber = _ref.bignumber, + mathWithTransform = _ref.mathWithTransform, + ConstantNode = _ref.ConstantNode, + OperatorNode = _ref.OperatorNode, + FunctionNode = _ref.FunctionNode, + SymbolNode = _ref.SymbolNode, + ParenthesisNode = _ref.ParenthesisNode; + var simplifyConstant = createSimplifyConstant({ + typed: typed, + config: config, + mathWithTransform: mathWithTransform, + fraction: fraction, + bignumber: bignumber, + ConstantNode: ConstantNode, + OperatorNode: OperatorNode, + FunctionNode: FunctionNode, + SymbolNode: SymbolNode + }); + var simplifyCore = createSimplifyCore({ + equal: equal, + isZero: isZero, + add: add, + subtract: subtract, + multiply: multiply, + divide: divide, + pow: pow, + ConstantNode: ConstantNode, + OperatorNode: OperatorNode, + FunctionNode: FunctionNode, + ParenthesisNode: ParenthesisNode + }); + /** + * Transform a rationalizable expression in a rational fraction. + * If rational fraction is one variable polynomial then converts + * the numerator and denominator in canonical form, with decreasing + * exponents, returning the coefficients of numerator. + * + * Syntax: + * + * rationalize(expr) + * rationalize(expr, detailed) + * rationalize(expr, scope) + * rationalize(expr, scope, detailed) + * + * Examples: + * + * math.rationalize('sin(x)+y') + * // Error: There is an unsolved function call + * math.rationalize('2x/y - y/(x+1)') + * // (2*x^2-y^2+2*x)/(x*y+y) + * math.rationalize('(2x+1)^6') + * // 64*x^6+192*x^5+240*x^4+160*x^3+60*x^2+12*x+1 + * math.rationalize('2x/( (2x-1) / (3x+2) ) - 5x/ ( (3x+4) / (2x^2-5) ) + 3') + * // -20*x^4+28*x^3+104*x^2+6*x-12)/(6*x^2+5*x-4) + * math.rationalize('x/(1-x)/(x-2)/(x-3)/(x-4) + 2x/ ( (1-2x)/(2-3x) )/ ((3-4x)/(4-5x) )') = + * // (-30*x^7+344*x^6-1506*x^5+3200*x^4-3472*x^3+1846*x^2-381*x)/ + * // (-8*x^6+90*x^5-383*x^4+780*x^3-797*x^2+390*x-72) + * + * math.rationalize('x+x+x+y',{y:1}) // 3*x+1 + * math.rationalize('x+x+x+y',{}) // 3*x+y + * + * const ret = math.rationalize('x+x+x+y',{},true) + * // ret.expression=3*x+y, ret.variables = ["x","y"] + * const ret = math.rationalize('-2+5x^2',{},true) + * // ret.expression=5*x^2-2, ret.variables = ["x"], ret.coefficients=[-2,0,5] + * + * See also: + * + * simplify + * + * @param {Node|string} expr The expression to check if is a polynomial expression + * @param {Object|boolean} optional scope of expression or true for already evaluated rational expression at input + * @param {Boolean} detailed optional True if return an object, false if return expression node (default) + * + * @return {Object | Node} The rational polynomial of `expr` or na object + * {Object} + * {Expression Node} expression: node simplified expression + * {Expression Node} numerator: simplified numerator of expression + * {Expression Node | boolean} denominator: simplified denominator or false (if there is no denominator) + * {Array} variables: variable names + * {Array} coefficients: coefficients of numerator sorted by increased exponent + * {Expression Node} node simplified expression + * + */ + + var rationalize = typed(rationalize_name, { + string: function string(expr) { + return rationalize(parse(expr), {}, false); + }, + 'string, boolean': function stringBoolean(expr, detailed) { + return rationalize(parse(expr), {}, detailed); + }, + 'string, Object': function stringObject(expr, scope) { + return rationalize(parse(expr), scope, false); + }, + 'string, Object, boolean': function stringObjectBoolean(expr, scope, detailed) { + return rationalize(parse(expr), scope, detailed); + }, + Node: function Node(expr) { + return rationalize(expr, {}, false); + }, + 'Node, boolean': function NodeBoolean(expr, detailed) { + return rationalize(expr, {}, detailed); + }, + 'Node, Object': function NodeObject(expr, scope) { + return rationalize(expr, scope, false); + }, + 'Node, Object, boolean': function NodeObjectBoolean(expr, scope, detailed) { + var setRules = rulesRationalize(); // Rules for change polynomial in near canonical form + + var polyRet = polynomial(expr, scope, true, setRules.firstRules); // Check if expression is a rationalizable polynomial + + var nVars = polyRet.variables.length; + expr = polyRet.expression; + + if (nVars >= 1) { + // If expression in not a constant + expr = expandPower(expr); // First expand power of polynomials (cannot be made from rules!) + + var sBefore; // Previous expression + + var rules; + var eDistrDiv = true; + var redoInic = false; + expr = simplify(expr, setRules.firstRules, {}, { + exactFractions: false + }); // Apply the initial rules, including succ div rules + + var s; + + while (true) { + // Apply alternately successive division rules and distr.div.rules + rules = eDistrDiv ? setRules.distrDivRules : setRules.sucDivRules; + expr = simplify(expr, rules); // until no more changes + + eDistrDiv = !eDistrDiv; // Swap between Distr.Div and Succ. Div. Rules + + s = expr.toString(); + + if (s === sBefore) { + break; // No changes : end of the loop + } + + redoInic = true; + sBefore = s; + } + + if (redoInic) { + // Apply first rules again without succ div rules (if there are changes) + expr = simplify(expr, setRules.firstRulesAgain, {}, { + exactFractions: false + }); + } + + expr = simplify(expr, setRules.finalRules, {}, { + exactFractions: false + }); // Apply final rules + } // NVars >= 1 + + + var coefficients = []; + var retRationalize = {}; + + if (expr.type === 'OperatorNode' && expr.isBinary() && expr.op === '/') { + // Separate numerator from denominator + if (nVars === 1) { + expr.args[0] = polyToCanonical(expr.args[0], coefficients); + expr.args[1] = polyToCanonical(expr.args[1]); + } + + if (detailed) { + retRationalize.numerator = expr.args[0]; + retRationalize.denominator = expr.args[1]; + } + } else { + if (nVars === 1) { + expr = polyToCanonical(expr, coefficients); + } + + if (detailed) { + retRationalize.numerator = expr; + retRationalize.denominator = null; + } + } // nVars + + + if (!detailed) return expr; + retRationalize.coefficients = coefficients; + retRationalize.variables = polyRet.variables; + retRationalize.expression = expr; + return retRationalize; + } // ^^^^^^^ end of rationalize ^^^^^^^^ + + }); // end of typed rationalize + + /** + * Function to simplify an expression using an optional scope and + * return it if the expression is a polynomial expression, i.e. + * an expression with one or more variables and the operators + * +, -, *, and ^, where the exponent can only be a positive integer. + * + * Syntax: + * + * polynomial(expr,scope,extended, rules) + * + * @param {Node | string} expr The expression to simplify and check if is polynomial expression + * @param {object} scope Optional scope for expression simplification + * @param {boolean} extended Optional. Default is false. When true allows divide operator. + * @param {array} rules Optional. Default is no rule. + * + * + * @return {Object} + * {Object} node: node simplified expression + * {Array} variables: variable names + */ + + function polynomial(expr, scope, extended, rules) { + var variables = []; + var node = simplify(expr, rules, scope, { + exactFractions: false + }); // Resolves any variables and functions with all defined parameters + + extended = !!extended; + var oper = '+-*' + (extended ? '/' : ''); + recPoly(node); + var retFunc = {}; + retFunc.expression = node; + retFunc.variables = variables; + return retFunc; // ------------------------------------------------------------------------------------------------------- + + /** + * Function to simplify an expression using an optional scope and + * return it if the expression is a polynomial expression, i.e. + * an expression with one or more variables and the operators + * +, -, *, and ^, where the exponent can only be a positive integer. + * + * Syntax: + * + * recPoly(node) + * + * + * @param {Node} node The current sub tree expression in recursion + * + * @return nothing, throw an exception if error + */ + + function recPoly(node) { + var tp = node.type; // node type + + if (tp === 'FunctionNode') { + // No function call in polynomial expression + throw new Error('There is an unsolved function call'); + } else if (tp === 'OperatorNode') { + if (node.op === '^') { + // TODO: handle negative exponents like in '1/x^(-2)' + if (node.args[1].type !== 'ConstantNode' || !Object(utils_number["i" /* isInteger */])(parseFloat(node.args[1].value))) { + throw new Error('There is a non-integer exponent'); + } else { + recPoly(node.args[0]); + } + } else { + if (oper.indexOf(node.op) === -1) { + throw new Error('Operator ' + node.op + ' invalid in polynomial expression'); + } + + for (var i = 0; i < node.args.length; i++) { + recPoly(node.args[i]); + } + } // type of operator + + } else if (tp === 'SymbolNode') { + var _name = node.name; // variable name + + var pos = variables.indexOf(_name); + + if (pos === -1) { + // new variable in expression + variables.push(_name); + } + } else if (tp === 'ParenthesisNode') { + recPoly(node.content); + } else if (tp !== 'ConstantNode') { + throw new Error('type ' + tp + ' is not allowed in polynomial expression'); + } + } // end of recPoly + + } // end of polynomial + // --------------------------------------------------------------------------------------- + + /** + * Return a rule set to rationalize an polynomial expression in rationalize + * + * Syntax: + * + * rulesRationalize() + * + * @return {array} rule set to rationalize an polynomial expression + */ + + + function rulesRationalize() { + var oldRules = [simplifyCore, // sCore + { + l: 'n+n', + r: '2*n' + }, { + l: 'n+-n', + r: '0' + }, simplifyConstant, // sConstant + { + l: 'n*(n1^-1)', + r: 'n/n1' + }, { + l: 'n*n1^-n2', + r: 'n/n1^n2' + }, { + l: 'n1^-1', + r: '1/n1' + }, { + l: 'n*(n1/n2)', + r: '(n*n1)/n2' + }, { + l: '1*n', + r: 'n' + }]; + var rulesFirst = [{ + l: '(-n1)/(-n2)', + r: 'n1/n2' + }, // Unary division + { + l: '(-n1)*(-n2)', + r: 'n1*n2' + }, // Unary multiplication + { + l: 'n1--n2', + r: 'n1+n2' + }, // '--' elimination + { + l: 'n1-n2', + r: 'n1+(-n2)' + }, // Subtraction turn into add with un�ry minus + { + l: '(n1+n2)*n3', + r: '(n1*n3 + n2*n3)' + }, // Distributive 1 + { + l: 'n1*(n2+n3)', + r: '(n1*n2+n1*n3)' + }, // Distributive 2 + { + l: 'c1*n + c2*n', + r: '(c1+c2)*n' + }, // Joining constants + { + l: 'c1*n + n', + r: '(c1+1)*n' + }, // Joining constants + { + l: 'c1*n - c2*n', + r: '(c1-c2)*n' + }, // Joining constants + { + l: 'c1*n - n', + r: '(c1-1)*n' + }, // Joining constants + { + l: 'v/c', + r: '(1/c)*v' + }, // variable/constant (new!) + { + l: 'v/-c', + r: '-(1/c)*v' + }, // variable/constant (new!) + { + l: '-v*-c', + r: 'c*v' + }, // Inversion constant and variable 1 + { + l: '-v*c', + r: '-c*v' + }, // Inversion constant and variable 2 + { + l: 'v*-c', + r: '-c*v' + }, // Inversion constant and variable 3 + { + l: 'v*c', + r: 'c*v' + }, // Inversion constant and variable 4 + { + l: '-(-n1*n2)', + r: '(n1*n2)' + }, // Unary propagation + { + l: '-(n1*n2)', + r: '(-n1*n2)' + }, // Unary propagation + { + l: '-(-n1+n2)', + r: '(n1-n2)' + }, // Unary propagation + { + l: '-(n1+n2)', + r: '(-n1-n2)' + }, // Unary propagation + { + l: '(n1^n2)^n3', + r: '(n1^(n2*n3))' + }, // Power to Power + { + l: '-(-n1/n2)', + r: '(n1/n2)' + }, // Division and Unary + { + l: '-(n1/n2)', + r: '(-n1/n2)' + }]; // Divisao and Unary + + var rulesDistrDiv = [{ + l: '(n1/n2 + n3/n4)', + r: '((n1*n4 + n3*n2)/(n2*n4))' + }, // Sum of fractions + { + l: '(n1/n2 + n3)', + r: '((n1 + n3*n2)/n2)' + }, // Sum fraction with number 1 + { + l: '(n1 + n2/n3)', + r: '((n1*n3 + n2)/n3)' + }]; // Sum fraction with number 1 + + var rulesSucDiv = [{ + l: '(n1/(n2/n3))', + r: '((n1*n3)/n2)' + }, // Division simplification + { + l: '(n1/n2/n3)', + r: '(n1/(n2*n3))' + }]; + var setRules = {}; // rules set in 4 steps. + // All rules => infinite loop + // setRules.allRules =oldRules.concat(rulesFirst,rulesDistrDiv,rulesSucDiv) + + setRules.firstRules = oldRules.concat(rulesFirst, rulesSucDiv); // First rule set + + setRules.distrDivRules = rulesDistrDiv; // Just distr. div. rules + + setRules.sucDivRules = rulesSucDiv; // Jus succ. div. rules + + setRules.firstRulesAgain = oldRules.concat(rulesFirst); // Last rules set without succ. div. + // Division simplification + // Second rule set. + // There is no aggregate expression with parentesis, but the only variable can be scattered. + + setRules.finalRules = [simplifyCore, // simplify.rules[0] + { + l: 'n*-n', + r: '-n^2' + }, // Joining multiply with power 1 + { + l: 'n*n', + r: 'n^2' + }, // Joining multiply with power 2 + simplifyConstant, // simplify.rules[14] old 3rd index in oldRules + { + l: 'n*-n^n1', + r: '-n^(n1+1)' + }, // Joining multiply with power 3 + { + l: 'n*n^n1', + r: 'n^(n1+1)' + }, // Joining multiply with power 4 + { + l: 'n^n1*-n^n2', + r: '-n^(n1+n2)' + }, // Joining multiply with power 5 + { + l: 'n^n1*n^n2', + r: 'n^(n1+n2)' + }, // Joining multiply with power 6 + { + l: 'n^n1*-n', + r: '-n^(n1+1)' + }, // Joining multiply with power 7 + { + l: 'n^n1*n', + r: 'n^(n1+1)' + }, // Joining multiply with power 8 + { + l: 'n^n1/-n', + r: '-n^(n1-1)' + }, // Joining multiply with power 8 + { + l: 'n^n1/n', + r: 'n^(n1-1)' + }, // Joining division with power 1 + { + l: 'n/-n^n1', + r: '-n^(1-n1)' + }, // Joining division with power 2 + { + l: 'n/n^n1', + r: 'n^(1-n1)' + }, // Joining division with power 3 + { + l: 'n^n1/-n^n2', + r: 'n^(n1-n2)' + }, // Joining division with power 4 + { + l: 'n^n1/n^n2', + r: 'n^(n1-n2)' + }, // Joining division with power 5 + { + l: 'n1+(-n2*n3)', + r: 'n1-n2*n3' + }, // Solving useless parenthesis 1 + { + l: 'v*(-c)', + r: '-c*v' + }, // Solving useless unary 2 + { + l: 'n1+-n2', + r: 'n1-n2' + }, // Solving +- together (new!) + { + l: 'v*c', + r: 'c*v' + }, // inversion constant with variable + { + l: '(n1^n2)^n3', + r: '(n1^(n2*n3))' + } // Power to Power + ]; + return setRules; + } // End rulesRationalize + // --------------------------------------------------------------------------------------- + + /** + * Expand recursively a tree node for handling with expressions with exponents + * (it's not for constants, symbols or functions with exponents) + * PS: The other parameters are internal for recursion + * + * Syntax: + * + * expandPower(node) + * + * @param {Node} node Current expression node + * @param {node} parent Parent current node inside the recursion + * @param (int} Parent number of chid inside the rercursion + * + * @return {node} node expression with all powers expanded. + */ + + + function expandPower(node, parent, indParent) { + var tp = node.type; + var internal = arguments.length > 1; // TRUE in internal calls + + if (tp === 'OperatorNode' && node.isBinary()) { + var does = false; + var val; + + if (node.op === '^') { + // First operator: Parenthesis or UnaryMinus + if ((node.args[0].type === 'ParenthesisNode' || node.args[0].type === 'OperatorNode') && node.args[1].type === 'ConstantNode') { + // Second operator: Constant + val = parseFloat(node.args[1].value); + does = val >= 2 && Object(utils_number["i" /* isInteger */])(val); + } + } + + if (does) { + // Exponent >= 2 + // Before: + // operator A --> Subtree + // parent pow + // constant + // + if (val > 2) { + // Exponent > 2, + // AFTER: (exponent > 2) + // operator A --> Subtree + // parent * + // deep clone (operator A --> Subtree + // pow + // constant - 1 + // + var nEsqTopo = node.args[0]; + var nDirTopo = new OperatorNode('^', 'pow', [node.args[0].cloneDeep(), new ConstantNode(val - 1)]); + node = new OperatorNode('*', 'multiply', [nEsqTopo, nDirTopo]); + } else { + // Expo = 2 - no power + // AFTER: (exponent = 2) + // operator A --> Subtree + // parent oper + // deep clone (operator A --> Subtree) + // + node = new OperatorNode('*', 'multiply', [node.args[0], node.args[0].cloneDeep()]); + } + + if (internal) { + // Change parent references in internal recursive calls + if (indParent === 'content') { + parent.content = node; + } else { + parent.args[indParent] = node; + } + } + } // does + + } // binary OperatorNode + + + if (tp === 'ParenthesisNode') { + // Recursion + expandPower(node.content, node, 'content'); + } else if (tp !== 'ConstantNode' && tp !== 'SymbolNode') { + for (var i = 0; i < node.args.length; i++) { + expandPower(node.args[i], node, i); + } + } + + if (!internal) { + // return the root node + return node; + } + } // End expandPower + // --------------------------------------------------------------------------------------- + + /** + * Auxilary function for rationalize + * Convert near canonical polynomial in one variable in a canonical polynomial + * with one term for each exponent in decreasing order + * + * Syntax: + * + * polyToCanonical(node [, coefficients]) + * + * @param {Node | string} expr The near canonical polynomial expression to convert in a a canonical polynomial expression + * + * The string or tree expression needs to be at below syntax, with free spaces: + * ( (^(-)? | [+-]? )cte (*)? var (^expo)? | cte )+ + * Where 'var' is one variable with any valid name + * 'cte' are real numeric constants with any value. It can be omitted if equal than 1 + * 'expo' are integers greater than 0. It can be omitted if equal than 1. + * + * @param {array} coefficients Optional returns coefficients sorted by increased exponent + * + * + * @return {node} new node tree with one variable polynomial or string error. + */ + + + function polyToCanonical(node, coefficients) { + if (coefficients === undefined) { + coefficients = []; + } // coefficients. + + + coefficients[0] = 0; // index is the exponent + + var o = {}; + o.cte = 1; + o.oper = '+'; // fire: mark with * or ^ when finds * or ^ down tree, reset to "" with + and -. + // It is used to deduce the exponent: 1 for *, 0 for "". + + o.fire = ''; + var maxExpo = 0; // maximum exponent + + var varname = ''; // variable name + + recurPol(node, null, o); + maxExpo = coefficients.length - 1; + var first = true; + var no; + + for (var i = maxExpo; i >= 0; i--) { + if (coefficients[i] === 0) continue; + var n1 = new ConstantNode(first ? coefficients[i] : Math.abs(coefficients[i])); + var op = coefficients[i] < 0 ? '-' : '+'; + + if (i > 0) { + // Is not a constant without variable + var n2 = new SymbolNode(varname); + + if (i > 1) { + var n3 = new ConstantNode(i); + n2 = new OperatorNode('^', 'pow', [n2, n3]); + } + + if (coefficients[i] === -1 && first) { + n1 = new OperatorNode('-', 'unaryMinus', [n2]); + } else if (Math.abs(coefficients[i]) === 1) { + n1 = n2; + } else { + n1 = new OperatorNode('*', 'multiply', [n1, n2]); + } + } + + if (first) { + no = n1; + } else if (op === '+') { + no = new OperatorNode('+', 'add', [no, n1]); + } else { + no = new OperatorNode('-', 'subtract', [no, n1]); + } + + first = false; + } // for + + + if (first) { + return new ConstantNode(0); + } else { + return no; + } + /** + * Recursive auxilary function inside polyToCanonical for + * converting expression in canonical form + * + * Syntax: + * + * recurPol(node, noPai, obj) + * + * @param {Node} node The current subpolynomial expression + * @param {Node | Null} noPai The current parent node + * @param {object} obj Object with many internal flags + * + * @return {} No return. If error, throws an exception + */ + + + function recurPol(node, noPai, o) { + var tp = node.type; + + if (tp === 'FunctionNode') { + // ***** FunctionName ***** + // No function call in polynomial expression + throw new Error('There is an unsolved function call'); + } else if (tp === 'OperatorNode') { + // ***** OperatorName ***** + if ('+-*^'.indexOf(node.op) === -1) throw new Error('Operator ' + node.op + ' invalid'); + + if (noPai !== null) { + // -(unary),^ : children of *,+,- + if ((node.fn === 'unaryMinus' || node.fn === 'pow') && noPai.fn !== 'add' && noPai.fn !== 'subtract' && noPai.fn !== 'multiply') { + throw new Error('Invalid ' + node.op + ' placing'); + } // -,+,* : children of +,- + + + if ((node.fn === 'subtract' || node.fn === 'add' || node.fn === 'multiply') && noPai.fn !== 'add' && noPai.fn !== 'subtract') { + throw new Error('Invalid ' + node.op + ' placing'); + } // -,+ : first child + + + if ((node.fn === 'subtract' || node.fn === 'add' || node.fn === 'unaryMinus') && o.noFil !== 0) { + throw new Error('Invalid ' + node.op + ' placing'); + } + } // Has parent + // Firers: ^,* Old: ^,&,-(unary): firers + + + if (node.op === '^' || node.op === '*') { + o.fire = node.op; + } + + for (var _i = 0; _i < node.args.length; _i++) { + // +,-: reset fire + if (node.fn === 'unaryMinus') o.oper = '-'; + + if (node.op === '+' || node.fn === 'subtract') { + o.fire = ''; + o.cte = 1; // default if there is no constant + + o.oper = _i === 0 ? '+' : node.op; + } + + o.noFil = _i; // number of son + + recurPol(node.args[_i], node, o); + } // for in children + + } else if (tp === 'SymbolNode') { + // ***** SymbolName ***** + if (node.name !== varname && varname !== '') { + throw new Error('There is more than one variable'); + } + + varname = node.name; + + if (noPai === null) { + coefficients[1] = 1; + return; + } // ^: Symbol is First child + + + if (noPai.op === '^' && o.noFil !== 0) { + throw new Error('In power the variable should be the first parameter'); + } // *: Symbol is Second child + + + if (noPai.op === '*' && o.noFil !== 1) { + throw new Error('In multiply the variable should be the second parameter'); + } // Symbol: firers '',* => it means there is no exponent above, so it's 1 (cte * var) + + + if (o.fire === '' || o.fire === '*') { + if (maxExpo < 1) coefficients[1] = 0; + coefficients[1] += o.cte * (o.oper === '+' ? 1 : -1); + maxExpo = Math.max(1, maxExpo); + } + } else if (tp === 'ConstantNode') { + var valor = parseFloat(node.value); + + if (noPai === null) { + coefficients[0] = valor; + return; + } + + if (noPai.op === '^') { + // cte: second child of power + if (o.noFil !== 1) throw new Error('Constant cannot be powered'); + + if (!Object(utils_number["i" /* isInteger */])(valor) || valor <= 0) { + throw new Error('Non-integer exponent is not allowed'); + } + + for (var _i2 = maxExpo + 1; _i2 < valor; _i2++) { + coefficients[_i2] = 0; + } + + if (valor > maxExpo) coefficients[valor] = 0; + coefficients[valor] += o.cte * (o.oper === '+' ? 1 : -1); + maxExpo = Math.max(valor, maxExpo); + return; + } + + o.cte = valor; // Cte: firer '' => There is no exponent and no multiplication, so the exponent is 0. + + if (o.fire === '') { + coefficients[0] += o.cte * (o.oper === '+' ? 1 : -1); + } + } else { + throw new Error('Type ' + tp + ' is not allowed'); + } + } // End of recurPol + + } // End of polyToCanonical + + + return rationalize; +}); +// CONCATENATED MODULE: ./src/json/reviver.js + +var reviver_name = 'reviver'; +var reviver_dependencies = ['classes']; +var createReviver = /* #__PURE__ */Object(factory["a" /* factory */])(reviver_name, reviver_dependencies, function (_ref) { + var classes = _ref.classes; + + /** + * Instantiate mathjs data types from their JSON representation + * @param {string} key + * @param {*} value + * @returns {*} Returns the revived object + */ + return function reviver(key, value) { + var constructor = classes[value && value.mathjs]; + + if (constructor && typeof constructor.fromJSON === 'function') { + return constructor.fromJSON(value); + } + + return value; + }; +}); +// CONCATENATED MODULE: ./src/json/replacer.js + +var replacer_name = 'replacer'; +var replacer_dependencies = []; +var createReplacer = /* #__PURE__ */Object(factory["a" /* factory */])(replacer_name, replacer_dependencies, function () { + /** + * Stringify data types into their JSON representation. + * Most data types can be serialized using their `.toJSON` method, + * but not all, for example the number `Infinity`. For these cases you have + * to use the replacer. Example usage: + * + * JSON.stringify([2, Infinity], math.replacer) + * + * @param {string} key + * @param {*} value + * @returns {*} Returns the replaced object + */ + return function replacer(key, value) { + // the numeric values Infinitiy, -Infinity, and NaN cannot be serialized to JSON + if (typeof value === 'number' && (!isFinite(value) || isNaN(value))) { + return { + mathjs: 'number', + value: String(value) + }; + } + + return value; + }; +}); +// CONCATENATED MODULE: ./src/version.js +var version = '6.6.5'; // Note: This file is automatically generated when building math.js. +// Changes made in this file will be overwritten. +// CONCATENATED MODULE: ./src/plain/number/constants.js +var constants_pi = Math.PI; +var tau = 2 * Math.PI; +var constants_e = Math.E; +var constants_phi = 1.61803398874989484820458683436563811772030917980576286213545; +// CONCATENATED MODULE: ./src/constants.js + + + + +var createTrue = /* #__PURE__ */Object(factory["a" /* factory */])('true', [], function () { + return true; +}); +var createFalse = /* #__PURE__ */Object(factory["a" /* factory */])('false', [], function () { + return false; +}); +var createNull = /* #__PURE__ */Object(factory["a" /* factory */])('null', [], function () { + return null; +}); +var createInfinity = /* #__PURE__ */recreateFactory('Infinity', ['config', '?BigNumber'], function (_ref) { + var config = _ref.config, + BigNumber = _ref.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(Infinity) : Infinity; +}); +var createNaN = /* #__PURE__ */recreateFactory('NaN', ['config', '?BigNumber'], function (_ref2) { + var config = _ref2.config, + BigNumber = _ref2.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(NaN) : NaN; +}); +var createPi = /* #__PURE__ */recreateFactory('pi', ['config', '?BigNumber'], function (_ref3) { + var config = _ref3.config, + BigNumber = _ref3.BigNumber; + return config.number === 'BigNumber' ? createBigNumberPi(BigNumber) : constants_pi; +}); +var createTau = /* #__PURE__ */recreateFactory('tau', ['config', '?BigNumber'], function (_ref4) { + var config = _ref4.config, + BigNumber = _ref4.BigNumber; + return config.number === 'BigNumber' ? createBigNumberTau(BigNumber) : tau; +}); +var createE = /* #__PURE__ */recreateFactory('e', ['config', '?BigNumber'], function (_ref5) { + var config = _ref5.config, + BigNumber = _ref5.BigNumber; + return config.number === 'BigNumber' ? createBigNumberE(BigNumber) : constants_e; +}); // golden ratio, (1+sqrt(5))/2 + +var createPhi = /* #__PURE__ */recreateFactory('phi', ['config', '?BigNumber'], function (_ref6) { + var config = _ref6.config, + BigNumber = _ref6.BigNumber; + return config.number === 'BigNumber' ? createBigNumberPhi(BigNumber) : constants_phi; +}); +var createLN2 = /* #__PURE__ */recreateFactory('LN2', ['config', '?BigNumber'], function (_ref7) { + var config = _ref7.config, + BigNumber = _ref7.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(2).ln() : Math.LN2; +}); +var createLN10 = /* #__PURE__ */recreateFactory('LN10', ['config', '?BigNumber'], function (_ref8) { + var config = _ref8.config, + BigNumber = _ref8.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(10).ln() : Math.LN10; +}); +var createLOG2E = /* #__PURE__ */recreateFactory('LOG2E', ['config', '?BigNumber'], function (_ref9) { + var config = _ref9.config, + BigNumber = _ref9.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(1).div(new BigNumber(2).ln()) : Math.LOG2E; +}); +var createLOG10E = /* #__PURE__ */recreateFactory('LOG10E', ['config', '?BigNumber'], function (_ref10) { + var config = _ref10.config, + BigNumber = _ref10.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(1).div(new BigNumber(10).ln()) : Math.LOG10E; +}); +var createSQRT1_2 = /* #__PURE__ */recreateFactory( // eslint-disable-line camelcase +'SQRT1_2', ['config', '?BigNumber'], function (_ref11) { + var config = _ref11.config, + BigNumber = _ref11.BigNumber; + return config.number === 'BigNumber' ? new BigNumber('0.5').sqrt() : Math.SQRT1_2; +}); +var createSQRT2 = /* #__PURE__ */recreateFactory('SQRT2', ['config', '?BigNumber'], function (_ref12) { + var config = _ref12.config, + BigNumber = _ref12.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(2).sqrt() : Math.SQRT2; +}); +var createI = /* #__PURE__ */recreateFactory('i', ['Complex'], function (_ref13) { + var Complex = _ref13.Complex; + return Complex.I; +}); // for backward compatibility with v5 + +var createUppercasePi = /* #__PURE__ */Object(factory["a" /* factory */])('PI', ['pi'], function (_ref14) { + var pi = _ref14.pi; + return pi; +}); +var createUppercaseE = /* #__PURE__ */Object(factory["a" /* factory */])('E', ['e'], function (_ref15) { + var e = _ref15.e; + return e; +}); +var createVersion = /* #__PURE__ */Object(factory["a" /* factory */])('version', [], function () { + return version; +}); // helper function to create a factory with a flag recreateOnConfigChange +// idea: allow passing optional properties to be attached to the factory function as 4th argument? + +function recreateFactory(name, dependencies, create) { + return Object(factory["a" /* factory */])(name, dependencies, create, { + recreateOnConfigChange: true + }); +} +// CONCATENATED MODULE: ./src/type/unit/physicalConstants.js + // Source: https://en.wikipedia.org/wiki/Physical_constant +// Universal constants + +var createSpeedOfLight = /* #__PURE__ */unitFactory('speedOfLight', '299792458', 'm s^-1'); +var createGravitationConstant = /* #__PURE__ */unitFactory('gravitationConstant', '6.67430e-11', 'm^3 kg^-1 s^-2'); +var createPlanckConstant = /* #__PURE__ */unitFactory('planckConstant', '6.62607015e-34', 'J s'); +var createReducedPlanckConstant = /* #__PURE__ */unitFactory('reducedPlanckConstant', '1.0545718176461565e-34', 'J s'); // Electromagnetic constants + +var createMagneticConstant = /* #__PURE__ */unitFactory('magneticConstant', '1.25663706212e-6', 'N A^-2'); +var createElectricConstant = /* #__PURE__ */unitFactory('electricConstant', '8.8541878128e-12', 'F m^-1'); +var createVacuumImpedance = /* #__PURE__ */unitFactory('vacuumImpedance', '376.730313667', 'ohm'); +var createCoulomb = /* #__PURE__ */unitFactory('coulomb', '8.987551792261171e9', 'N m^2 C^-2'); +var createElementaryCharge = /* #__PURE__ */unitFactory('elementaryCharge', '1.602176634e-19', 'C'); +var createBohrMagneton = /* #__PURE__ */unitFactory('bohrMagneton', '9.2740100783e-24', 'J T^-1'); +var createConductanceQuantum = /* #__PURE__ */unitFactory('conductanceQuantum', '7.748091729863649e-5', 'S'); +var createInverseConductanceQuantum = /* #__PURE__ */unitFactory('inverseConductanceQuantum', '12906.403729652257', 'ohm'); +var createMagneticFluxQuantum = /* #__PURE__ */unitFactory('magneticFluxQuantum', '2.0678338484619295e-15', 'Wb'); +var createNuclearMagneton = /* #__PURE__ */unitFactory('nuclearMagneton', '5.0507837461e-27', 'J T^-1'); +var createKlitzing = /* #__PURE__ */unitFactory('klitzing', '25812.807459304513', 'ohm'); +var createJosephson = /* #__PURE__ */unitFactory('josephson', '4.835978484169836e14 Hz V', 'Hz V^-1'); // TODO: support for Hz needed +// Atomic and nuclear constants + +var createBohrRadius = /* #__PURE__ */unitFactory('bohrRadius', '5.29177210903e-11', 'm'); +var createClassicalElectronRadius = /* #__PURE__ */unitFactory('classicalElectronRadius', '2.8179403262e-15', 'm'); +var createElectronMass = /* #__PURE__ */unitFactory('electronMass', '9.1093837015e-31', 'kg'); +var createFermiCoupling = /* #__PURE__ */unitFactory('fermiCoupling', '1.1663787e-5', 'GeV^-2'); +var createFineStructure = numberFactory('fineStructure', 7.2973525693e-3); +var createHartreeEnergy = /* #__PURE__ */unitFactory('hartreeEnergy', '4.3597447222071e-18', 'J'); +var createProtonMass = /* #__PURE__ */unitFactory('protonMass', '1.67262192369e-27', 'kg'); +var createDeuteronMass = /* #__PURE__ */unitFactory('deuteronMass', '3.3435830926e-27', 'kg'); +var createNeutronMass = /* #__PURE__ */unitFactory('neutronMass', '1.6749271613e-27', 'kg'); +var createQuantumOfCirculation = /* #__PURE__ */unitFactory('quantumOfCirculation', '3.6369475516e-4', 'm^2 s^-1'); +var createRydberg = /* #__PURE__ */unitFactory('rydberg', '10973731.568160', 'm^-1'); +var createThomsonCrossSection = /* #__PURE__ */unitFactory('thomsonCrossSection', '6.6524587321e-29', 'm^2'); +var createWeakMixingAngle = numberFactory('weakMixingAngle', 0.22290); +var createEfimovFactor = numberFactory('efimovFactor', 22.7); // Physico-chemical constants + +var createAtomicMass = /* #__PURE__ */unitFactory('atomicMass', '1.66053906660e-27', 'kg'); +var createAvogadro = /* #__PURE__ */unitFactory('avogadro', '6.02214076e23', 'mol^-1'); +var createBoltzmann = /* #__PURE__ */unitFactory('boltzmann', '1.380649e-23', 'J K^-1'); +var createFaraday = /* #__PURE__ */unitFactory('faraday', '96485.33212331001', 'C mol^-1'); +var createFirstRadiation = /* #__PURE__ */unitFactory('firstRadiation', '3.7417718521927573e-16', 'W m^2'); // export const createSpectralRadiance = /* #__PURE__ */ unitFactory('spectralRadiance', '1.1910429723971881e-16', 'W m^2 sr^-1') // TODO spectralRadiance + +var createLoschmidt = /* #__PURE__ */unitFactory('loschmidt', '2.686780111798444e25', 'm^-3'); +var createGasConstant = /* #__PURE__ */unitFactory('gasConstant', '8.31446261815324', 'J K^-1 mol^-1'); +var createMolarPlanckConstant = /* #__PURE__ */unitFactory('molarPlanckConstant', '3.990312712893431e-10', 'J s mol^-1'); +var createMolarVolume = /* #__PURE__ */unitFactory('molarVolume', '0.022413969545014137', 'm^3 mol^-1'); +var createSackurTetrode = numberFactory('sackurTetrode', -1.16487052358); +var createSecondRadiation = /* #__PURE__ */unitFactory('secondRadiation', '0.014387768775039337', 'm K'); +var createStefanBoltzmann = /* #__PURE__ */unitFactory('stefanBoltzmann', '5.67037441918443e-8', 'W m^-2 K^-4'); +var createWienDisplacement = /* #__PURE__ */unitFactory('wienDisplacement', '2.897771955e-3', 'm K'); // Adopted values + +var createMolarMass = /* #__PURE__ */unitFactory('molarMass', '0.99999999965e-3', 'kg mol^-1'); +var createMolarMassC12 = /* #__PURE__ */unitFactory('molarMassC12', '11.9999999958e-3', 'kg mol^-1'); +var createGravity = /* #__PURE__ */unitFactory('gravity', '9.80665', 'm s^-2'); // atm is defined in Unit.js +// Natural units + +var createPlanckLength = /* #__PURE__ */unitFactory('planckLength', '1.616255e-35', 'm'); +var createPlanckMass = /* #__PURE__ */unitFactory('planckMass', '2.176435e-8', 'kg'); +var createPlanckTime = /* #__PURE__ */unitFactory('planckTime', '5.391245e-44', 's'); +var createPlanckCharge = /* #__PURE__ */unitFactory('planckCharge', '1.87554603778e-18', 'C'); +var createPlanckTemperature = /* #__PURE__ */unitFactory('planckTemperature', '1.416785e+32', 'K'); // helper function to create a factory function which creates a physical constant, +// a Unit with either a number value or a BigNumber value depending on the configuration + +function unitFactory(name, valueStr, unitStr) { + var dependencies = ['config', 'Unit', 'BigNumber']; + return Object(factory["a" /* factory */])(name, dependencies, function (_ref) { + var config = _ref.config, + Unit = _ref.Unit, + BigNumber = _ref.BigNumber; + // Note that we can parse into number or BigNumber. + // We do not parse into Fractions as that doesn't make sense: we would lose precision of the values + // Therefore we dont use Unit.parse() + var value = config.number === 'BigNumber' ? new BigNumber(valueStr) : parseFloat(valueStr); + var unit = new Unit(value, unitStr); + unit.fixPrefix = true; + return unit; + }); +} // helper function to create a factory function which creates a numeric constant, +// either a number or BigNumber depending on the configuration + + +function numberFactory(name, value) { + var dependencies = ['config', 'BigNumber']; + return Object(factory["a" /* factory */])(name, dependencies, function (_ref2) { + var config = _ref2.config, + BigNumber = _ref2.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(value) : value; + }); +} +// CONCATENATED MODULE: ./src/expression/transform/apply.transform.js + + + + +var apply_transform_name = 'apply'; +var apply_transform_dependencies = ['typed', 'isInteger']; +/** + * Attach a transform function to math.apply + * Adds a property transform containing the transform function. + * + * This transform changed the last `dim` parameter of function apply + * from one-based to zero based + */ + +var createApplyTransform = /* #__PURE__ */Object(factory["a" /* factory */])(apply_transform_name, apply_transform_dependencies, function (_ref) { + var typed = _ref.typed, + isInteger = _ref.isInteger; + var apply = createApply({ + typed: typed, + isInteger: isInteger + }); // @see: comment of concat itself + + return typed('apply', { + '...any': function any(args) { + // change dim from one-based to zero-based + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + + try { + return apply.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/column.transform.js + + + + +var column_transform_name = 'column'; +var column_transform_dependencies = ['typed', 'Index', 'matrix', 'range']; +/** + * Attach a transform function to matrix.column + * Adds a property transform containing the transform function. + * + * This transform changed the last `index` parameter of function column + * from zero-based to one-based + */ + +var createColumnTransform = /* #__PURE__ */Object(factory["a" /* factory */])(column_transform_name, column_transform_dependencies, function (_ref) { + var typed = _ref.typed, + Index = _ref.Index, + matrix = _ref.matrix, + range = _ref.range; + var column = createColumn({ + typed: typed, + Index: Index, + matrix: matrix, + range: range + }); // @see: comment of column itself + + return typed('column', { + '...any': function any(args) { + // change last argument from zero-based to one-based + var lastIndex = args.length - 1; + var last = args[lastIndex]; + + if (Object(is["y" /* isNumber */])(last)) { + args[lastIndex] = last - 1; + } + + try { + return column.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/utils/compileInlineExpression.js + +/** + * Compile an inline expression like "x > 0" + * @param {Node} expression + * @param {Object} math + * @param {Object} scope + * @return {function} Returns a function with one argument which fills in the + * undefined variable (like "x") and evaluates the expression + */ + +function compileInlineExpression(expression, math, scope) { + // find an undefined symbol + var symbol = expression.filter(function (node) { + return Object(is["J" /* isSymbolNode */])(node) && !(node.name in math) && !(node.name in scope); + })[0]; + + if (!symbol) { + throw new Error('No undefined variable found in inline expression "' + expression + '"'); + } // create a test function for this equation + + + var name = symbol.name; // variable name + + var subScope = Object.create(scope); + var eq = expression.compile(); + return function inlineExpression(x) { + subScope[name] = x; + return eq.evaluate(subScope); + }; +} +// CONCATENATED MODULE: ./src/expression/transform/filter.transform.js + + + + + +var filter_transform_name = 'filter'; +var filter_transform_dependencies = ['typed']; +var createFilterTransform = /* #__PURE__ */Object(factory["a" /* factory */])(filter_transform_name, filter_transform_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Attach a transform function to math.filter + * Adds a property transform containing the transform function. + * + * This transform adds support for equations as test function for math.filter, + * so you can do something like 'filter([3, -2, 5], x > 0)'. + */ + function filterTransform(args, math, scope) { + var x, callback; + + if (args[0]) { + x = args[0].compile().evaluate(scope); + } + + if (args[1]) { + if (Object(is["J" /* isSymbolNode */])(args[1]) || Object(is["q" /* isFunctionAssignmentNode */])(args[1])) { + // a function pointer, like filter([3, -2, 5], myTestFunction) + callback = args[1].compile().evaluate(scope); + } else { + // an expression like filter([3, -2, 5], x > 0) + callback = compileInlineExpression(args[1], math, scope); + } + } + + return filter(x, callback); + } + + filterTransform.rawArgs = true; // one based version of function filter + + var filter = typed('filter', { + 'Array, function': _filter, + 'Matrix, function': function MatrixFunction(x, test) { + return x.create(_filter(x.toArray(), test)); + }, + 'Array, RegExp': utils_array["d" /* filterRegExp */], + 'Matrix, RegExp': function MatrixRegExp(x, test) { + return x.create(Object(utils_array["d" /* filterRegExp */])(x.toArray(), test)); + } + }); + return filterTransform; +}, { + isTransformFunction: true +}); +/** + * Filter values in a callback given a callback function + * + * !!! Passes a one-based index !!! + * + * @param {Array} x + * @param {Function} callback + * @return {Array} Returns the filtered array + * @private + */ + +function _filter(x, callback) { + // figure out what number of arguments the callback function expects + var args = maxArgumentCount(callback); + return Object(utils_array["c" /* filter */])(x, function (value, index, array) { + // invoke the callback function with the right number of arguments + if (args === 1) { + return callback(value); + } else if (args === 2) { + return callback(value, [index + 1]); + } else { + // 3 or -1 + return callback(value, [index + 1], array); + } + }); +} +// CONCATENATED MODULE: ./src/expression/transform/forEach.transform.js + + + + + +var forEach_transform_name = 'forEach'; +var forEach_transform_dependencies = ['typed']; +var createForEachTransform = /* #__PURE__ */Object(factory["a" /* factory */])(forEach_transform_name, forEach_transform_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Attach a transform function to math.forEach + * Adds a property transform containing the transform function. + * + * This transform creates a one-based index instead of a zero-based index + */ + function forEachTransform(args, math, scope) { + var x, callback; + + if (args[0]) { + x = args[0].compile().evaluate(scope); + } + + if (args[1]) { + if (Object(is["J" /* isSymbolNode */])(args[1]) || Object(is["q" /* isFunctionAssignmentNode */])(args[1])) { + // a function pointer, like forEach([3, -2, 5], myTestFunction) + callback = args[1].compile().evaluate(scope); + } else { + // an expression like forEach([3, -2, 5], x > 0 ? callback1(x) : callback2(x) ) + callback = compileInlineExpression(args[1], math, scope); + } + } + + return _forEach(x, callback); + } + + forEachTransform.rawArgs = true; // one-based version of forEach + + var _forEach = typed('forEach', { + 'Array | Matrix, function': function ArrayMatrixFunction(array, callback) { + // figure out what number of arguments the callback function expects + var args = maxArgumentCount(callback); + + var recurse = function recurse(value, index) { + if (Array.isArray(value)) { + Object(utils_array["f" /* forEach */])(value, function (child, i) { + // we create a copy of the index array and append the new index value + recurse(child, index.concat(i + 1)); // one based index, hence i+1 + }); + } else { + // invoke the callback function with the right number of arguments + if (args === 1) { + callback(value); + } else if (args === 2) { + callback(value, index); + } else { + // 3 or -1 + callback(value, index, array); + } + } + }; + + recurse(array.valueOf(), []); // pass Array + } + }); + + return forEachTransform; +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/index.transform.js + + +var index_transform_name = 'index'; +var index_transform_dependencies = ['Index']; +var createIndexTransform = /* #__PURE__ */Object(factory["a" /* factory */])(index_transform_name, index_transform_dependencies, function (_ref) { + var Index = _ref.Index; + + /** + * Attach a transform function to math.index + * Adds a property transform containing the transform function. + * + * This transform creates a one-based index instead of a zero-based index + */ + return function indexTransform() { + var args = []; + + for (var i = 0, ii = arguments.length; i < ii; i++) { + var arg = arguments[i]; // change from one-based to zero based, and convert BigNumber to number + + if (Object(is["D" /* isRange */])(arg)) { + arg.start--; + arg.end -= arg.step > 0 ? 0 : 2; + } else if (arg && arg.isSet === true) { + arg = arg.map(function (v) { + return v - 1; + }); + } else if (Object(is["b" /* isArray */])(arg) || Object(is["v" /* isMatrix */])(arg)) { + arg = arg.map(function (v) { + return v - 1; + }); + } else if (Object(is["y" /* isNumber */])(arg)) { + arg--; + } else if (Object(is["e" /* isBigNumber */])(arg)) { + arg = arg.toNumber() - 1; + } else if (typeof arg === 'string') {// leave as is + } else { + throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range'); + } + + args[i] = arg; + } + + var res = new Index(); + Index.apply(res, args); + return res; + }; +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/map.transform.js + + + + + +var map_transform_name = 'map'; +var map_transform_dependencies = ['typed']; +var createMapTransform = /* #__PURE__ */Object(factory["a" /* factory */])(map_transform_name, map_transform_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Attach a transform function to math.map + * Adds a property transform containing the transform function. + * + * This transform creates a one-based index instead of a zero-based index + */ + function mapTransform(args, math, scope) { + var x, callback; + + if (args[0]) { + x = args[0].compile().evaluate(scope); + } + + if (args[1]) { + if (Object(is["J" /* isSymbolNode */])(args[1]) || Object(is["q" /* isFunctionAssignmentNode */])(args[1])) { + // a function pointer, like filter([3, -2, 5], myTestFunction) + callback = args[1].compile().evaluate(scope); + } else { + // an expression like filter([3, -2, 5], x > 0) + callback = compileInlineExpression(args[1], math, scope); + } + } + + return map(x, callback); + } + + mapTransform.rawArgs = true; // one-based version of map function + + var map = typed('map', { + 'Array, function': function ArrayFunction(x, callback) { + return map_transform_map(x, callback, x); + }, + 'Matrix, function': function MatrixFunction(x, callback) { + return x.create(map_transform_map(x.valueOf(), callback, x)); + } + }); + return mapTransform; +}, { + isTransformFunction: true +}); +/** + * Map for a multi dimensional array. One-based indexes + * @param {Array} array + * @param {function} callback + * @param {Array} orig + * @return {Array} + * @private + */ + +function map_transform_map(array, callback, orig) { + // figure out what number of arguments the callback function expects + var argsCount = maxArgumentCount(callback); + + function recurse(value, index) { + if (Array.isArray(value)) { + return Object(utils_array["m" /* map */])(value, function (child, i) { + // we create a copy of the index array and append the new index value + return recurse(child, index.concat(i + 1)); // one based index, hence i + 1 + }); + } else { + // invoke the (typed) callback function with the right number of arguments + if (argsCount === 1) { + return callback(value); + } else if (argsCount === 2) { + return callback(value, index); + } else { + // 3 or -1 + return callback(value, index, orig); + } + } + } + + return recurse(array, []); +} +// CONCATENATED MODULE: ./src/expression/transform/max.transform.js + + + + +var max_transform_name = 'max'; +var max_transform_dependencies = ['typed', 'larger']; +var createMaxTransform = /* #__PURE__ */Object(factory["a" /* factory */])(max_transform_name, max_transform_dependencies, function (_ref) { + var typed = _ref.typed, + larger = _ref.larger; + var max = createMax({ + typed: typed, + larger: larger + }); + /** + * Attach a transform function to math.max + * Adds a property transform containing the transform function. + * + * This transform changed the last `dim` parameter of function max + * from one-based to zero based + */ + + return typed('max', { + '...any': function any(args) { + // change last argument dim from one-based to zero-based + if (args.length === 2 && Object(is["i" /* isCollection */])(args[0])) { + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + } + + try { + return max.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/mean.transform.js + + + + +var mean_transform_name = 'mean'; +var mean_transform_dependencies = ['typed', 'add', 'divide']; +var createMeanTransform = /* #__PURE__ */Object(factory["a" /* factory */])(mean_transform_name, mean_transform_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + divide = _ref.divide; + var mean = createMean({ + typed: typed, + add: add, + divide: divide + }); + /** + * Attach a transform function to math.mean + * Adds a property transform containing the transform function. + * + * This transform changed the last `dim` parameter of function mean + * from one-based to zero based + */ + + return typed('mean', { + '...any': function any(args) { + // change last argument dim from one-based to zero-based + if (args.length === 2 && Object(is["i" /* isCollection */])(args[0])) { + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + } + + try { + return mean.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/min.transform.js + + + + +var min_transform_name = 'min'; +var min_transform_dependencies = ['typed', 'smaller']; +var createMinTransform = /* #__PURE__ */Object(factory["a" /* factory */])(min_transform_name, min_transform_dependencies, function (_ref) { + var typed = _ref.typed, + smaller = _ref.smaller; + var min = createMin({ + typed: typed, + smaller: smaller + }); + /** + * Attach a transform function to math.min + * Adds a property transform containing the transform function. + * + * This transform changed the last `dim` parameter of function min + * from one-based to zero based + */ + + return typed('min', { + '...any': function any(args) { + // change last argument dim from one-based to zero-based + if (args.length === 2 && Object(is["i" /* isCollection */])(args[0])) { + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + } + + try { + return min.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/range.transform.js + + +var range_transform_name = 'range'; +var range_transform_dependencies = ['typed', 'config', '?matrix', '?bignumber', 'smaller', 'smallerEq', 'larger', 'largerEq']; +var createRangeTransform = /* #__PURE__ */Object(factory["a" /* factory */])(range_transform_name, range_transform_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + bignumber = _ref.bignumber, + smaller = _ref.smaller, + smallerEq = _ref.smallerEq, + larger = _ref.larger, + largerEq = _ref.largerEq; + var range = range_createRange({ + typed: typed, + config: config, + matrix: matrix, + bignumber: bignumber, + smaller: smaller, + smallerEq: smallerEq, + larger: larger, + largerEq: largerEq + }); + /** + * Attach a transform function to math.range + * Adds a property transform containing the transform function. + * + * This transform creates a range which includes the end value + */ + + return typed('range', { + '...any': function any(args) { + var lastIndex = args.length - 1; + var last = args[lastIndex]; + + if (typeof last !== 'boolean') { + // append a parameter includeEnd=true + args.push(true); + } + + return range.apply(null, args); + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/row.transform.js + + + + +var row_transform_name = 'row'; +var row_transform_dependencies = ['typed', 'Index', 'matrix', 'range']; +/** + * Attach a transform function to matrix.column + * Adds a property transform containing the transform function. + * + * This transform changed the last `index` parameter of function column + * from zero-based to one-based + */ + +var createRowTransform = /* #__PURE__ */Object(factory["a" /* factory */])(row_transform_name, row_transform_dependencies, function (_ref) { + var typed = _ref.typed, + Index = _ref.Index, + matrix = _ref.matrix, + range = _ref.range; + var row = createRow({ + typed: typed, + Index: Index, + matrix: matrix, + range: range + }); // @see: comment of row itself + + return typed('row', { + '...any': function any(args) { + // change last argument from zero-based to one-based + var lastIndex = args.length - 1; + var last = args[lastIndex]; + + if (Object(is["y" /* isNumber */])(last)) { + args[lastIndex] = last - 1; + } + + try { + return row.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/subset.transform.js + + + +var subset_transform_name = 'subset'; +var subset_transform_dependencies = ['typed', 'matrix']; +var createSubsetTransform = /* #__PURE__ */Object(factory["a" /* factory */])(subset_transform_name, subset_transform_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + var subset = createSubset({ + typed: typed, + matrix: matrix + }); + /** + * Attach a transform function to math.subset + * Adds a property transform containing the transform function. + * + * This transform creates a range which includes the end value + */ + + return typed('subset', { + '...any': function any(args) { + try { + return subset.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/concat.transform.js + + + + +var concat_transform_name = 'concat'; +var concat_transform_dependencies = ['typed', 'matrix', 'isInteger']; +var createConcatTransform = /* #__PURE__ */Object(factory["a" /* factory */])(concat_transform_name, concat_transform_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + isInteger = _ref.isInteger; + var concat = createConcat({ + typed: typed, + matrix: matrix, + isInteger: isInteger + }); + /** + * Attach a transform function to math.range + * Adds a property transform containing the transform function. + * + * This transform changed the last `dim` parameter of function concat + * from one-based to zero based + */ + + return typed('concat', { + '...any': function any(args) { + // change last argument from one-based to zero-based + var lastIndex = args.length - 1; + var last = args[lastIndex]; + + if (Object(is["y" /* isNumber */])(last)) { + args[lastIndex] = last - 1; + } else if (Object(is["e" /* isBigNumber */])(last)) { + args[lastIndex] = last.minus(1); + } + + try { + return concat.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/std.transform.js + + + + +var std_transform_name = 'std'; +var std_transform_dependencies = ['typed', 'sqrt', 'variance']; +/** + * Attach a transform function to math.std + * Adds a property transform containing the transform function. + * + * This transform changed the `dim` parameter of function std + * from one-based to zero based + */ + +var createStdTransform = /* #__PURE__ */Object(factory["a" /* factory */])(std_transform_name, std_transform_dependencies, function (_ref) { + var typed = _ref.typed, + sqrt = _ref.sqrt, + variance = _ref.variance; + var std = createStd({ + typed: typed, + sqrt: sqrt, + variance: variance + }); + return typed('std', { + '...any': function any(args) { + // change last argument dim from one-based to zero-based + if (args.length >= 2 && Object(is["i" /* isCollection */])(args[0])) { + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + } + + try { + return std.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/sum.transform.js + + + + +/** + * Attach a transform function to math.sum + * Adds a property transform containing the transform function. + * + * This transform changed the last `dim` parameter of function mean + * from one-based to zero based + */ + +var sum_transform_name = 'sum'; +var sum_transform_dependencies = ['typed', 'config', 'add', '?bignumber', '?fraction']; +var createSumTransform = /* #__PURE__ */Object(factory["a" /* factory */])(sum_transform_name, sum_transform_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + add = _ref.add, + bignumber = _ref.bignumber, + fraction = _ref.fraction; + var sum = createSum({ + typed: typed, + config: config, + add: add, + bignumber: bignumber, + fraction: fraction + }); + return typed(sum_transform_name, { + '...any': function any(args) { + // change last argument dim from one-based to zero-based + if (args.length === 2 && Object(is["i" /* isCollection */])(args[0])) { + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + } + + try { + return sum.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/variance.transform.js + + + + +var variance_transform_name = 'variance'; +var variance_transform_dependencies = ['typed', 'add', 'subtract', 'multiply', 'divide', 'apply', 'isNaN']; +/** + * Attach a transform function to math.var + * Adds a property transform containing the transform function. + * + * This transform changed the `dim` parameter of function var + * from one-based to zero based + */ + +var createVarianceTransform = /* #__PURE__ */Object(factory["a" /* factory */])(variance_transform_name, variance_transform_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + subtract = _ref.subtract, + multiply = _ref.multiply, + divide = _ref.divide, + apply = _ref.apply, + isNaN = _ref.isNaN; + var variance = createVariance({ + typed: typed, + add: add, + subtract: subtract, + multiply: multiply, + divide: divide, + apply: apply, + isNaN: isNaN + }); + return typed(variance_transform_name, { + '...any': function any(args) { + // change last argument dim from one-based to zero-based + if (args.length >= 2 && Object(is["i" /* isCollection */])(args[0])) { + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + } + + try { + return variance.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/factoriesAny.js + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/***/ }), +/* 22 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, "create", function() { return /* binding */ create; }); + +// EXTERNAL MODULE: ./src/utils/object.js +var utils_object = __webpack_require__(3); + +// EXTERNAL MODULE: ./node_modules/tiny-emitter/index.js +var tiny_emitter = __webpack_require__(18); +var tiny_emitter_default = /*#__PURE__*/__webpack_require__.n(tiny_emitter); + +// CONCATENATED MODULE: ./src/utils/emitter.js + +/** + * Extend given object with emitter functions `on`, `off`, `once`, `emit` + * @param {Object} obj + * @return {Object} obj + */ + +function mixin(obj) { + // create event emitter + var emitter = new tiny_emitter_default.a(); // bind methods to obj (we don't want to expose the emitter.e Array...) + + obj.on = emitter.on.bind(emitter); + obj.off = emitter.off.bind(emitter); + obj.once = emitter.once.bind(emitter); + obj.emit = emitter.emit.bind(emitter); + return obj; +} +// EXTERNAL MODULE: ./src/utils/is.js +var is = __webpack_require__(1); + +// EXTERNAL MODULE: ./src/utils/factory.js +var utils_factory = __webpack_require__(0); + +// EXTERNAL MODULE: ./src/utils/array.js +var array = __webpack_require__(2); + +// EXTERNAL MODULE: ./src/error/ArgumentsError.js +var ArgumentsError = __webpack_require__(13); + +// EXTERNAL MODULE: ./src/utils/log.js +var log = __webpack_require__(8); + +// CONCATENATED MODULE: ./src/core/function/import.js +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + + + + + + + +function importFactory(typed, load, math, importedFactories) { + /** + * Import functions from an object or a module. + * + * This function is only available on a mathjs instance created using `create`. + * + * Syntax: + * + * math.import(functions) + * math.import(functions, options) + * + * Where: + * + * - `functions: Object` + * An object with functions or factories to be imported. + * - `options: Object` An object with import options. Available options: + * - `override: boolean` + * If true, existing functions will be overwritten. False by default. + * - `silent: boolean` + * If true, the function will not throw errors on duplicates or invalid + * types. False by default. + * - `wrap: boolean` + * If true, the functions will be wrapped in a wrapper function + * which converts data types like Matrix to primitive data types like Array. + * The wrapper is needed when extending math.js with libraries which do not + * support these data type. False by default. + * + * Examples: + * + * import { create, all } from 'mathjs' + * import * as numbers from 'numbers' + * + * // create a mathjs instance + * const math = create(all) + * + * // define new functions and variables + * math.import({ + * myvalue: 42, + * hello: function (name) { + * return 'hello, ' + name + '!' + * } + * }) + * + * // use the imported function and variable + * math.myvalue * 2 // 84 + * math.hello('user') // 'hello, user!' + * + * // import the npm module 'numbers' + * // (must be installed first with `npm install numbers`) + * math.import(numbers, {wrap: true}) + * + * math.fibonacci(7) // returns 13 + * + * @param {Object | Array} functions Object with functions to be imported. + * @param {Object} [options] Import options. + */ + function mathImport(functions, options) { + var num = arguments.length; + + if (num !== 1 && num !== 2) { + throw new ArgumentsError["a" /* ArgumentsError */]('import', num, 1, 2); + } + + if (!options) { + options = {}; + } + + function flattenImports(flatValues, value, name) { + if (Object(utils_object["g" /* isLegacyFactory */])(value)) { + // legacy factories don't always have a name, + // let's not handle them via the new flatValues + _importLegacyFactory(value, options); + } else if (Array.isArray(value)) { + value.forEach(function (item) { + return flattenImports(flatValues, item); + }); + } else if (_typeof(value) === 'object') { + for (var _name in value) { + if (Object(utils_object["f" /* hasOwnProperty */])(value, _name)) { + flattenImports(flatValues, value[_name], _name); + } + } + } else if (Object(utils_factory["b" /* isFactory */])(value) || name !== undefined) { + var flatName = Object(utils_factory["b" /* isFactory */])(value) ? isTransformFunctionFactory(value) ? value.fn + '.transform' : // TODO: this is ugly + value.fn : name; // we allow importing the same function twice if it points to the same implementation + + if (Object(utils_object["f" /* hasOwnProperty */])(flatValues, flatName) && flatValues[flatName] !== value && !options.silent) { + throw new Error('Cannot import "' + flatName + '" twice'); + } + + flatValues[flatName] = value; + } else { + if (!options.silent) { + throw new TypeError('Factory, Object, or Array expected'); + } + } + } + + var flatValues = {}; + flattenImports(flatValues, functions); + + for (var name in flatValues) { + if (Object(utils_object["f" /* hasOwnProperty */])(flatValues, name)) { + // console.log('import', name) + var value = flatValues[name]; + + if (Object(utils_factory["b" /* isFactory */])(value)) { + // we ignore name here and enforce the name of the factory + // maybe at some point we do want to allow overriding it + // in that case we can implement an option overrideFactoryNames: true + _importFactory(value, options); + } else if (isSupportedType(value)) { + _import(name, value, options); + } else { + if (!options.silent) { + throw new TypeError('Factory, Object, or Array expected'); + } + } + } + } + } + /** + * Add a property to the math namespace + * @param {string} name + * @param {*} value + * @param {Object} options See import for a description of the options + * @private + */ + + + function _import(name, value, options) { + // TODO: refactor this function, it's to complicated and contains duplicate code + if (options.wrap && typeof value === 'function') { + // create a wrapper around the function + value = _wrap(value); + } // turn a plain function with a typed-function signature into a typed-function + + + if (hasTypedFunctionSignature(value)) { + value = typed(name, _defineProperty({}, value.signature, value)); + } + + if (isTypedFunction(math[name]) && isTypedFunction(value)) { + if (options.override) { + // give the typed function the right name + value = typed(name, value.signatures); + } else { + // merge the existing and typed function + value = typed(math[name], value); + } + + math[name] = value; + delete importedFactories[name]; + + _importTransform(name, value); + + math.emit('import', name, function resolver() { + return value; + }); + return; + } + + if (math[name] === undefined || options.override) { + math[name] = value; + delete importedFactories[name]; + + _importTransform(name, value); + + math.emit('import', name, function resolver() { + return value; + }); + return; + } + + if (!options.silent) { + throw new Error('Cannot import "' + name + '": already exists'); + } + } + + function _importTransform(name, value) { + if (value && typeof value.transform === 'function') { + math.expression.transform[name] = value.transform; + + if (allowedInExpressions(name)) { + math.expression.mathWithTransform[name] = value.transform; + } + } else { + // remove existing transform + delete math.expression.transform[name]; + + if (allowedInExpressions(name)) { + math.expression.mathWithTransform[name] = value; + } + } + } + + function _deleteTransform(name) { + delete math.expression.transform[name]; + + if (allowedInExpressions(name)) { + math.expression.mathWithTransform[name] = math[name]; + } else { + delete math.expression.mathWithTransform[name]; + } + } + /** + * Create a wrapper a round an function which converts the arguments + * to their primitive values (like convert a Matrix to Array) + * @param {Function} fn + * @return {Function} Returns the wrapped function + * @private + */ + + + function _wrap(fn) { + var wrapper = function wrapper() { + var args = []; + + for (var i = 0, len = arguments.length; i < len; i++) { + var arg = arguments[i]; + args[i] = arg && arg.valueOf(); + } + + return fn.apply(math, args); + }; + + if (fn.transform) { + wrapper.transform = fn.transform; + } + + return wrapper; + } + /** + * Import an instance of a factory into math.js + * @param {{factory: Function, name: string, path: string, math: boolean}} factory + * @param {Object} options See import for a description of the options + * @private + */ + // TODO: _importLegacyFactory is deprecated since v6.0.0, clean up some day + + + function _importLegacyFactory(factory, options) { + Object(log["a" /* warnOnce */])('Factories of type { name, factory } are deprecated since v6. ' + 'Please create your factory functions using the math.factory function.'); + + if (typeof factory.name === 'string') { + var name = factory.name; + var existingTransform = (name in math.expression.transform); + var namespace = factory.path ? Object(utils_object["k" /* traverse */])(math, factory.path) : math; + var existing = Object(utils_object["f" /* hasOwnProperty */])(namespace, name) ? namespace[name] : undefined; + + var resolver = function resolver() { + var instance = load(factory); + + if (instance && typeof instance.transform === 'function') { + throw new Error('Transforms cannot be attached to factory functions. ' + 'Please create a separate function for it with exports.path="expression.transform"'); + } + + if (isTypedFunction(existing) && isTypedFunction(instance)) { + if (options.override) {// replace the existing typed function (nothing to do) + } else { + // merge the existing and new typed function + instance = typed(existing, instance); + } + + return instance; + } + + if (existing === undefined || options.override) { + return instance; + } + + if (options.silent) { + return existing; + } else { + throw new Error('Cannot import "' + name + '": already exists'); + } + }; + + if (factory.lazy !== false) { + Object(utils_object["h" /* lazy */])(namespace, name, resolver); + + if (existingTransform) { + _deleteTransform(name); + } else { + if (factory.path === 'expression.transform' || legacyFactoryAllowedInExpressions(factory)) { + Object(utils_object["h" /* lazy */])(math.expression.mathWithTransform, name, resolver); + } + } + } else { + namespace[name] = resolver(); + + if (existingTransform) { + _deleteTransform(name); + } else { + if (factory.path === 'expression.transform' || legacyFactoryAllowedInExpressions(factory)) { + math.expression.mathWithTransform[name] = resolver(); + } + } + } + + var key = factory.path ? factory.path + '.' + factory.name : factory.name; + importedFactories[key] = factory; + math.emit('import', name, resolver, factory.path); + } else { + // unnamed factory. + // no lazy loading + load(factory); + } + } + /** + * Import an instance of a factory into math.js + * @param {function(scope: object)} factory + * @param {Object} options See import for a description of the options + * @param {string} [name=factory.name] Optional custom name + * @private + */ + + + function _importFactory(factory, options) { + var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : factory.fn; + + if (Object(array["b" /* contains */])(name, '.')) { + throw new Error('Factory name should not contain a nested path. ' + 'Name: ' + JSON.stringify(name)); + } + + var namespace = isTransformFunctionFactory(factory) ? math.expression.transform : math; + var existingTransform = (name in math.expression.transform); + var existing = Object(utils_object["f" /* hasOwnProperty */])(namespace, name) ? namespace[name] : undefined; + + var resolver = function resolver() { + // collect all dependencies, handle finding both functions and classes and other special cases + var dependencies = {}; + factory.dependencies.map(utils_factory["c" /* stripOptionalNotation */]).forEach(function (dependency) { + if (Object(array["b" /* contains */])(dependency, '.')) { + throw new Error('Factory dependency should not contain a nested path. ' + 'Name: ' + JSON.stringify(dependency)); + } + + if (dependency === 'math') { + dependencies.math = math; + } else if (dependency === 'mathWithTransform') { + dependencies.mathWithTransform = math.expression.mathWithTransform; + } else if (dependency === 'classes') { + // special case for json reviver + dependencies.classes = math; + } else { + dependencies[dependency] = math[dependency]; + } + }); + var instance = /* #__PURE__ */factory(dependencies); + + if (instance && typeof instance.transform === 'function') { + throw new Error('Transforms cannot be attached to factory functions. ' + 'Please create a separate function for it with exports.path="expression.transform"'); + } + + if (existing === undefined || options.override) { + return instance; + } + + if (isTypedFunction(existing) && isTypedFunction(instance)) { + // merge the existing and new typed function + return typed(existing, instance); + } + + if (options.silent) { + // keep existing, ignore imported function + return existing; + } else { + throw new Error('Cannot import "' + name + '": already exists'); + } + }; // TODO: add unit test with non-lazy factory + + + if (!factory.meta || factory.meta.lazy !== false) { + Object(utils_object["h" /* lazy */])(namespace, name, resolver); // FIXME: remove the `if (existing &&` condition again. Can we make sure subset is loaded before subset.transform? (Name collision, and no dependencies between the two) + + if (existing && existingTransform) { + _deleteTransform(name); + } else { + if (isTransformFunctionFactory(factory) || factoryAllowedInExpressions(factory)) { + Object(utils_object["h" /* lazy */])(math.expression.mathWithTransform, name, function () { + return namespace[name]; + }); + } + } + } else { + namespace[name] = resolver(); // FIXME: remove the `if (existing &&` condition again. Can we make sure subset is loaded before subset.transform? (Name collision, and no dependencies between the two) + + if (existing && existingTransform) { + _deleteTransform(name); + } else { + if (isTransformFunctionFactory(factory) || factoryAllowedInExpressions(factory)) { + Object(utils_object["h" /* lazy */])(math.expression.mathWithTransform, name, function () { + return namespace[name]; + }); + } + } + } // TODO: improve factories, store a list with imports instead which can be re-played + + + importedFactories[name] = factory; + math.emit('import', name, resolver); + } + /** + * Check whether given object is a type which can be imported + * @param {Function | number | string | boolean | null | Unit | Complex} object + * @return {boolean} + * @private + */ + + + function isSupportedType(object) { + return typeof object === 'function' || typeof object === 'number' || typeof object === 'string' || typeof object === 'boolean' || object === null || Object(is["L" /* isUnit */])(object) || Object(is["j" /* isComplex */])(object) || Object(is["e" /* isBigNumber */])(object) || Object(is["o" /* isFraction */])(object) || Object(is["v" /* isMatrix */])(object) || Array.isArray(object); + } + /** + * Test whether a given thing is a typed-function + * @param {*} fn + * @return {boolean} Returns true when `fn` is a typed-function + */ + + + function isTypedFunction(fn) { + return typeof fn === 'function' && _typeof(fn.signatures) === 'object'; + } + + function hasTypedFunctionSignature(fn) { + return typeof fn === 'function' && typeof fn.signature === 'string'; + } + + function allowedInExpressions(name) { + return !Object(utils_object["f" /* hasOwnProperty */])(unsafe, name); + } + + function legacyFactoryAllowedInExpressions(factory) { + return factory.path === undefined && !Object(utils_object["f" /* hasOwnProperty */])(unsafe, factory.name); + } + + function factoryAllowedInExpressions(factory) { + return factory.fn.indexOf('.') === -1 && // FIXME: make checking on path redundant, check on meta data instead + !Object(utils_object["f" /* hasOwnProperty */])(unsafe, factory.fn) && (!factory.meta || !factory.meta.isClass); + } + + function isTransformFunctionFactory(factory) { + return factory !== undefined && factory.meta !== undefined && factory.meta.isTransformFunction === true || false; + } // namespaces and functions not available in the parser for safety reasons + + + var unsafe = { + expression: true, + type: true, + docs: true, + error: true, + json: true, + chain: true // chain method not supported. Note that there is a unit chain too. + + }; + return mathImport; +} +// CONCATENATED MODULE: ./src/core/config.js +var DEFAULT_CONFIG = { + // minimum relative difference between two compared values, + // used by all comparison functions + epsilon: 1e-12, + // type of default matrix output. Choose 'matrix' (default) or 'array' + matrix: 'Matrix', + // type of default number output. Choose 'number' (default) 'BigNumber', or 'Fraction + number: 'number', + // number of significant digits in BigNumbers + precision: 64, + // predictable output type of functions. When true, output type depends only + // on the input types. When false (default), output type can vary depending + // on input values. For example `math.sqrt(-4)` returns `complex('2i')` when + // predictable is false, and returns `NaN` when true. + predictable: false, + // random seed for seeded pseudo random number generation + // null = randomly seed + randomSeed: null +}; +// CONCATENATED MODULE: ./src/core/function/config.js + + +var MATRIX_OPTIONS = ['Matrix', 'Array']; // valid values for option matrix + +var NUMBER_OPTIONS = ['number', 'BigNumber', 'Fraction']; // valid values for option number + +function configFactory(config, emit) { + /** + * Set configuration options for math.js, and get current options. + * Will emit a 'config' event, with arguments (curr, prev, changes). + * + * This function is only available on a mathjs instance created using `create`. + * + * Syntax: + * + * math.config(config: Object): Object + * + * Examples: + * + * + * import { create, all } from 'mathjs' + * + * // create a mathjs instance + * const math = create(all) + * + * math.config().number // outputs 'number' + * math.evaluate('0.4') // outputs number 0.4 + * math.config({number: 'Fraction'}) + * math.evaluate('0.4') // outputs Fraction 2/5 + * + * @param {Object} [options] Available options: + * {number} epsilon + * Minimum relative difference between two + * compared values, used by all comparison functions. + * {string} matrix + * A string 'Matrix' (default) or 'Array'. + * {string} number + * A string 'number' (default), 'BigNumber', or 'Fraction' + * {number} precision + * The number of significant digits for BigNumbers. + * Not applicable for Numbers. + * {string} parenthesis + * How to display parentheses in LaTeX and string + * output. + * {string} randomSeed + * Random seed for seeded pseudo random number generator. + * Set to null to randomly seed. + * @return {Object} Returns the current configuration + */ + function _config(options) { + if (options) { + var prev = Object(utils_object["i" /* mapObject */])(config, utils_object["a" /* clone */]); // validate some of the options + + validateOption(options, 'matrix', MATRIX_OPTIONS); + validateOption(options, 'number', NUMBER_OPTIONS); // merge options + + Object(utils_object["b" /* deepExtend */])(config, options); + var curr = Object(utils_object["i" /* mapObject */])(config, utils_object["a" /* clone */]); + var changes = Object(utils_object["i" /* mapObject */])(options, utils_object["a" /* clone */]); // emit 'config' event + + emit('config', curr, prev, changes); + return curr; + } else { + return Object(utils_object["i" /* mapObject */])(config, utils_object["a" /* clone */]); + } + } // attach the valid options to the function so they can be extended + + + _config.MATRIX_OPTIONS = MATRIX_OPTIONS; + _config.NUMBER_OPTIONS = NUMBER_OPTIONS; // attach the config properties as readonly properties to the config function + + Object.keys(DEFAULT_CONFIG).forEach(function (key) { + Object.defineProperty(_config, key, { + get: function get() { + return config[key]; + }, + enumerable: true, + configurable: true + }); + }); + return _config; +} +/** + * Test whether an Array contains a specific item. + * @param {Array.} array + * @param {string} item + * @return {boolean} + */ + +function contains(array, item) { + return array.indexOf(item) !== -1; +} +/** + * Find a string in an array. Case insensitive search + * @param {Array.} array + * @param {string} item + * @return {number} Returns the index when found. Returns -1 when not found + */ + + +function findIndex(array, item) { + return array.map(function (i) { + return i.toLowerCase(); + }).indexOf(item.toLowerCase()); +} +/** + * Validate an option + * @param {Object} options Object with options + * @param {string} name Name of the option to validate + * @param {Array.} values Array with valid values for this option + */ + + +function validateOption(options, name, values) { + if (options[name] !== undefined && !contains(values, options[name])) { + var index = findIndex(values, options[name]); + + if (index !== -1) { + // right value, wrong casing + // TODO: lower case values are deprecated since v3, remove this warning some day. + console.warn('Warning: Wrong casing for configuration option "' + name + '", should be "' + values[index] + '" instead of "' + options[name] + '".'); + options[name] = values[index]; // change the option to the right casing + } else { + // unknown value + console.warn('Warning: Unknown value "' + options[name] + '" for configuration option "' + name + '". Available options: ' + values.map(JSON.stringify).join(', ') + '.'); + } + } +} +// EXTERNAL MODULE: ./src/error/DimensionError.js +var DimensionError = __webpack_require__(6); + +// EXTERNAL MODULE: ./src/error/IndexError.js +var IndexError = __webpack_require__(10); + +// CONCATENATED MODULE: ./src/core/create.js +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + + + + + + + + + + + + + + +/** + * Create a mathjs instance from given factory functions and optionally config + * + * Usage: + * + * const mathjs1 = create({ createAdd, createMultiply, ...}) + * const config = { number: 'BigNumber' } + * const mathjs2 = create(all, config) + * + * @param {Object} [factories] An object with factory functions + * The object can contain nested objects, + * all nested objects will be flattened. + * @param {Object} [config] Available options: + * {number} epsilon + * Minimum relative difference between two + * compared values, used by all comparison functions. + * {string} matrix + * A string 'Matrix' (default) or 'Array'. + * {string} number + * A string 'number' (default), 'BigNumber', or 'Fraction' + * {number} precision + * The number of significant digits for BigNumbers. + * Not applicable for Numbers. + * {boolean} predictable + * Predictable output type of functions. When true, + * output type depends only on the input types. When + * false (default), output type can vary depending + * on input values. For example `math.sqrt(-4)` + * returns `complex('2i')` when predictable is false, and + * returns `NaN` when true. + * {string} randomSeed + * Random seed for seeded pseudo random number generator. + * Set to null to randomly seed. + * @returns {Object} Returns a bare-bone math.js instance containing + * functions: + * - `import` to add new functions + * - `config` to change configuration + * - `on`, `off`, `once`, `emit` for events + */ + +function create(factories, config) { + var configInternal = _extends({}, DEFAULT_CONFIG, config); // simple test for ES5 support + + + if (typeof Object.create !== 'function') { + throw new Error('ES5 not supported by this JavaScript engine. ' + 'Please load the es5-shim and es5-sham library for compatibility.'); + } // create the mathjs instance + + + var math = mixin({ + // only here for backward compatibility for legacy factory functions + isNumber: is["y" /* isNumber */], + isComplex: is["j" /* isComplex */], + isBigNumber: is["e" /* isBigNumber */], + isFraction: is["o" /* isFraction */], + isUnit: is["L" /* isUnit */], + isString: is["I" /* isString */], + isArray: is["b" /* isArray */], + isMatrix: is["v" /* isMatrix */], + isCollection: is["i" /* isCollection */], + isDenseMatrix: is["n" /* isDenseMatrix */], + isSparseMatrix: is["H" /* isSparseMatrix */], + isRange: is["D" /* isRange */], + isIndex: is["t" /* isIndex */], + isBoolean: is["g" /* isBoolean */], + isResultSet: is["G" /* isResultSet */], + isHelp: is["s" /* isHelp */], + isFunction: is["p" /* isFunction */], + isDate: is["m" /* isDate */], + isRegExp: is["F" /* isRegExp */], + isObject: is["z" /* isObject */], + isNull: is["x" /* isNull */], + isUndefined: is["K" /* isUndefined */], + isAccessorNode: is["a" /* isAccessorNode */], + isArrayNode: is["c" /* isArrayNode */], + isAssignmentNode: is["d" /* isAssignmentNode */], + isBlockNode: is["f" /* isBlockNode */], + isConditionalNode: is["k" /* isConditionalNode */], + isConstantNode: is["l" /* isConstantNode */], + isFunctionAssignmentNode: is["q" /* isFunctionAssignmentNode */], + isFunctionNode: is["r" /* isFunctionNode */], + isIndexNode: is["u" /* isIndexNode */], + isNode: is["w" /* isNode */], + isObjectNode: is["A" /* isObjectNode */], + isOperatorNode: is["B" /* isOperatorNode */], + isParenthesisNode: is["C" /* isParenthesisNode */], + isRangeNode: is["E" /* isRangeNode */], + isSymbolNode: is["J" /* isSymbolNode */], + isChain: is["h" /* isChain */] + }); // load config function and apply provided config + + math.config = configFactory(configInternal, math.emit); + math.expression = { + transform: {}, + mathWithTransform: { + config: math.config + } + }; // cached factories and instances used by function load + + var legacyFactories = []; + var legacyInstances = []; + /** + * Load a function or data type from a factory. + * If the function or data type already exists, the existing instance is + * returned. + * @param {Function} factory + * @returns {*} + */ + + function load(factory) { + if (Object(utils_factory["b" /* isFactory */])(factory)) { + return factory(math); + } + + var firstProperty = factory[Object.keys(factory)[0]]; + + if (Object(utils_factory["b" /* isFactory */])(firstProperty)) { + return firstProperty(math); + } + + if (!Object(utils_object["g" /* isLegacyFactory */])(factory)) { + console.warn('Factory object with properties `type`, `name`, and `factory` expected', factory); + throw new Error('Factory object with properties `type`, `name`, and `factory` expected'); + } + + var index = legacyFactories.indexOf(factory); + var instance; + + if (index === -1) { + // doesn't yet exist + if (factory.math === true) { + // pass with math namespace + instance = factory.factory(math.type, configInternal, load, math.typed, math); + } else { + instance = factory.factory(math.type, configInternal, load, math.typed); + } // append to the cache + + + legacyFactories.push(factory); + legacyInstances.push(instance); + } else { + // already existing function, return the cached instance + instance = legacyInstances[index]; + } + + return instance; + } + + var importedFactories = {}; // load the import function + + function lazyTyped() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return math.typed.apply(math.typed, args); + } + + var internalImport = importFactory(lazyTyped, load, math, importedFactories); + math["import"] = internalImport; // listen for changes in config, import all functions again when changed + // TODO: move this listener into the import function? + + math.on('config', function () { + Object(utils_object["l" /* values */])(importedFactories).forEach(function (factory) { + if (factory && factory.meta && factory.meta.recreateOnConfigChange) { + // FIXME: only re-create when the current instance is the same as was initially created + // FIXME: delete the functions/constants before importing them again? + internalImport(factory, { + override: true + }); + } + }); + }); // the create function exposed on the mathjs instance is bound to + // the factory functions passed before + + math.create = create.bind(null, factories); // export factory function + + math.factory = utils_factory["a" /* factory */]; // import the factory functions like createAdd as an array instead of object, + // else they will get a different naming (`createAdd` instead of `add`). + + math["import"](Object(utils_object["l" /* values */])(Object(utils_object["c" /* deepFlatten */])(factories))); // TODO: deprecated since v6.0.0. Clean up some day + + var movedNames = ['type.isNumber', 'type.isComplex', 'type.isBigNumber', 'type.isFraction', 'type.isUnit', 'type.isString', 'type.isArray', 'type.isMatrix', 'type.isDenseMatrix', 'type.isSparseMatrix', 'type.isCollection', 'type.isRange', 'type.isIndex', 'type.isBoolean', 'type.isResultSet', 'type.isHelp', 'type.isFunction', 'type.isDate', 'type.isRegExp', 'type.isObject', 'type.isNull', 'type.isUndefined', 'type.isAccessorNode', 'type.isArrayNode', 'type.isAssignmentNode', 'type.isBlockNode', 'type.isConditionalNode', 'type.isConstantNode', 'type.isFunctionAssignmentNode', 'type.isFunctionNode', 'type.isIndexNode', 'type.isNode', 'type.isObjectNode', 'type.isOperatorNode', 'type.isParenthesisNode', 'type.isRangeNode', 'type.isSymbolNode', 'type.isChain', 'type.BigNumber', 'type.Chain', 'type.Complex', 'type.Fraction', 'type.Matrix', 'type.DenseMatrix', 'type.SparseMatrix', 'type.Spa', 'type.FibonacciHeap', 'type.ImmutableDenseMatrix', 'type.Index', 'type.Range', 'type.ResultSet', 'type.Unit', 'type.Help', 'type.Parser', 'expression.parse', 'expression.Parser', 'expression.node.AccessorNode', 'expression.node.ArrayNode', 'expression.node.AssignmentNode', 'expression.node.BlockNode', 'expression.node.ConditionalNode', 'expression.node.ConstantNode', 'expression.node.IndexNode', 'expression.node.FunctionAssignmentNode', 'expression.node.FunctionNode', 'expression.node.Node', 'expression.node.ObjectNode', 'expression.node.OperatorNode', 'expression.node.ParenthesisNode', 'expression.node.RangeNode', 'expression.node.RelationalNode', 'expression.node.SymbolNode', 'json.reviver', 'error.ArgumentsError', 'error.DimensionError', 'error.IndexError']; + movedNames.forEach(function (fullName) { + var parts = fullName.split('.'); + var path = Object(array["j" /* initial */])(parts); + var name = Object(array["l" /* last */])(parts); + var obj = Object(utils_object["k" /* traverse */])(math, path); + Object(utils_object["h" /* lazy */])(obj, name, function () { + Object(log["a" /* warnOnce */])("math.".concat(fullName, " is moved to math.").concat(name, " in v6.0.0. ") + 'Please use the new location instead.'); + return math[name]; + }); + }); + Object(utils_object["h" /* lazy */])(math.expression, 'docs', function () { + throw new Error('math.expression.docs has been moved. ' + 'Please import via "import { docs } from \'mathjs\'"'); + }); + math.ArgumentsError = ArgumentsError["a" /* ArgumentsError */]; + math.DimensionError = DimensionError["a" /* DimensionError */]; + math.IndexError = IndexError["a" /* IndexError */]; + return math; +} + +/***/ }) +/******/ ]); +}); + +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).jsyaml=e()}}(function(){return function o(a,s,c){function u(t,e){if(!s[t]){if(!a[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(l)return l(t,!0);var i=new Error("Cannot find module '"+t+"'");throw i.code="MODULE_NOT_FOUND",i}var r=s[t]={exports:{}};a[t][0].call(r.exports,function(e){return u(a[t][1][e]||e)},r,r.exports,o,a,s,c)}return s[t].exports}for(var l="function"==typeof require&&require,e=0;e=i.flowLevel;switch(H(r,n,i.indent,t,function(e){return function(e,t){var n,i;for(n=0,i=e.implicitTypes.length;n"+V(r,i.indent)+Z(L(function(t,n){var e,i,r=/(\n+)([^\n]*)/g,o=function(){var e=t.indexOf("\n");return e=-1!==e?e:t.length,r.lastIndex=e,z(t.slice(0,e),n)}(),a="\n"===t[0]||" "===t[0];for(;i=r.exec(t);){var s=i[1],c=i[2];e=" "===c[0],o+=s+(a||e||""===c?"":"\n")+z(c,n),a=e}return o}(r,t),e));case $:return'"'+function(e){for(var t,n,i,r="",o=0;ot&&o tag resolver accepts not "'+c+'" style');i=s.represent[c](t,c)}e.dump=i}return!0}return!1}function Q(e,t,n,i,r,o){e.tag=null,e.dump=n,J(e,n,!1)||J(e,n,!0);var a=p.call(e.dump);i&&(i=e.flowLevel<0||e.flowLevel>t);var s,c,u="[object Object]"===a||"[object Array]"===a;if(u&&(c=-1!==(s=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||c||2!==e.indent&&0 "+e.dump)}return!0}function X(e,t){var n,i,r=[],o=[];for(function e(t,n,i){var r,o,a;if(null!==t&&"object"==typeof t)if(-1!==(o=n.indexOf(t)))-1===i.indexOf(o)&&i.push(o);else if(n.push(t),Array.isArray(t))for(o=0,a=t.length;ot)&&0!==i)N(e,"bad indentation of a sequence entry");else if(e.lineIndentt?d=1:e.lineIndent===t?d=0:e.lineIndentt?d=1:e.lineIndent===t?d=0:e.lineIndentt)&&($(e,t,b,!0,r)&&(m?d=e.result:h=e.result),m||(U(e,l,p,f,d,h,o,a),f=d=h=null),Y(e,!0,-1),s=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==s)N(e,"bad indentation of a mapping entry");else if(e.lineIndentl&&(l=e.lineIndent),j(o))p++;else{if(e.lineIndent>10),56320+(c-65536&1023)),e.position++}else N(e,"unknown escape sequence");n=i=e.position}else j(s)?(L(e,n,i,!0),B(e,Y(e,!1,t)),n=i=e.position):e.position===e.lineStart&&R(e)?N(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}N(e,"unexpected end of the stream within a double quoted scalar")}(e,p)?m=!0:!function(e){var t,n,i;if(42!==(i=e.input.charCodeAt(e.position)))return!1;for(i=e.input.charCodeAt(++e.position),t=e.position;0!==i&&!I(i)&&!O(i);)i=e.input.charCodeAt(++e.position);return e.position===t&&N(e,"name of an alias node must contain at least one character"),n=e.input.slice(t,e.position),e.anchorMap.hasOwnProperty(n)||N(e,'unidentified alias "'+n+'"'),e.result=e.anchorMap[n],Y(e,!0,-1),!0}(e)?function(e,t,n){var i,r,o,a,s,c,u,l,p=e.kind,f=e.result;if(I(l=e.input.charCodeAt(e.position))||O(l)||35===l||38===l||42===l||33===l||124===l||62===l||39===l||34===l||37===l||64===l||96===l)return!1;if((63===l||45===l)&&(I(i=e.input.charCodeAt(e.position+1))||n&&O(i)))return!1;for(e.kind="scalar",e.result="",r=o=e.position,a=!1;0!==l;){if(58===l){if(I(i=e.input.charCodeAt(e.position+1))||n&&O(i))break}else if(35===l){if(I(e.input.charCodeAt(e.position-1)))break}else{if(e.position===e.lineStart&&R(e)||n&&O(l))break;if(j(l)){if(s=e.line,c=e.lineStart,u=e.lineIndent,Y(e,!1,-1),e.lineIndent>=t){a=!0,l=e.input.charCodeAt(e.position);continue}e.position=o,e.line=s,e.lineStart=c,e.lineIndent=u;break}}a&&(L(e,r,o,!1),B(e,e.line-s),r=o=e.position,a=!1),S(l)||(o=e.position+1),l=e.input.charCodeAt(++e.position)}return L(e,r,o,!1),!!e.result||(e.kind=p,e.result=f,!1)}(e,p,x===n)&&(m=!0,null===e.tag&&(e.tag="?")):(m=!0,null===e.tag&&null===e.anchor||N(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===d&&(m=s&&P(e,f))),null!==e.tag&&"!"!==e.tag)if("?"===e.tag){for(c=0,u=e.implicitTypes.length;c tag; it should be "'+l.kind+'", not "'+e.kind+'"'),l.resolve(e.result)?(e.result=l.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):N(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):N(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||m}function H(e){var t,n,i,r,o=e.position,a=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap={},e.anchorMap={};0!==(r=e.input.charCodeAt(e.position))&&(Y(e,!0,-1),r=e.input.charCodeAt(e.position),!(0t/2-1){n=" ... ",i+=5;break}for(r="",o=this.position;ot/2-1){r=" ... ",o-=5;break}return a=this.buffer.slice(i,o),s.repeat(" ",e)+n+a+r+"\n"+s.repeat(" ",e+this.position-i+n.length)+"^"},i.prototype.toString=function(e){var t,n="";return this.name&&(n+='in "'+this.name+'" '),n+="at line "+(this.line+1)+", column "+(this.column+1),e||(t=this.getSnippet())&&(n+=":\n"+t),n},t.exports=i},{"./common":2}],7:[function(e,t,n){"use strict";var i=e("./common"),r=e("./exception"),o=e("./type");function a(e,t,i){var r=[];return e.include.forEach(function(e){i=a(e,t,i)}),e[t].forEach(function(n){i.forEach(function(e,t){e.tag===n.tag&&e.kind===n.kind&&r.push(t)}),i.push(n)}),i.filter(function(e,t){return-1===r.indexOf(t)})}function s(e){this.include=e.include||[],this.implicit=e.implicit||[],this.explicit=e.explicit||[],this.implicit.forEach(function(e){if(e.loadKind&&"scalar"!==e.loadKind)throw new r("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=a(this,"implicit",[]),this.compiledExplicit=a(this,"explicit",[]),this.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{}};function i(e){n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e>16&255),s.push(a>>8&255),s.push(255&a)),a=a<<6|o.indexOf(i.charAt(t));return 0==(n=r%4*6)?(s.push(a>>16&255),s.push(a>>8&255),s.push(255&a)):18==n?(s.push(a>>10&255),s.push(a>>2&255)):12==n&&s.push(a>>4&255),c?c.from?c.from(s):new c(s):s},predicate:function(e){return c&&c.isBuffer(e)},represent:function(e){var t,n,i="",r=0,o=e.length,a=u;for(t=0;t>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]),r=(r<<8)+e[t];return 0==(n=o%3)?(i+=a[r>>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]):2==n?(i+=a[r>>10&63],i+=a[r>>4&63],i+=a[r<<2&63],i+=a[64]):1==n&&(i+=a[r>>2&63],i+=a[r<<4&63],i+=a[64],i+=a[64]),i}})},{"../type":13}],15:[function(e,t,n){"use strict";var i=e("../type");t.exports=new i("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t=e.length;return 4===t&&("true"===e||"True"===e||"TRUE"===e)||5===t&&("false"===e||"False"===e||"FALSE"===e)},construct:function(e){return"true"===e||"True"===e||"TRUE"===e},predicate:function(e){return"[object Boolean]"===Object.prototype.toString.call(e)},represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})},{"../type":13}],16:[function(e,t,n){"use strict";var i=e("../common"),r=e("../type"),o=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var a=/^[-+]?[0-9]+e/;t.exports=new r("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!o.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n,i,r;return n="-"===(t=e.replace(/_/g,"").toLowerCase())[0]?-1:1,r=[],0<="+-".indexOf(t[0])&&(t=t.slice(1)),".inf"===t?1==n?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:0<=t.indexOf(":")?(t.split(":").forEach(function(e){r.unshift(parseFloat(e,10))}),t=0,i=1,r.forEach(function(e){t+=e*i,i*=60}),n*t):n*parseFloat(t,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||i.isNegativeZero(e))},represent:function(e,t){var n;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(i.isNegativeZero(e))return"-0.0";return n=e.toString(10),a.test(n)?n.replace("e",".e"):n},defaultStyle:"lowercase"})},{"../common":2,"../type":13}],17:[function(e,t,n){"use strict";var i=e("../common"),r=e("../type");t.exports=new r("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,i,r,o=e.length,a=0,s=!1;if(!o)return!1;if("-"!==(t=e[a])&&"+"!==t||(t=e[++a]),"0"===t){if(a+1===o)return!0;if("b"===(t=e[++a])){for(a++;a +'use strict'; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var KG; +(function (KG) { + /* + + from underscorejs + + Copyright (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative + Reporters & Editors + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software.*/ + // I adapted these functions from the amazing underscorejs library. + function isObject(obj) { + var type = typeof obj; + return type === 'function' || type === 'object' && !!obj; + } + function allKeys(obj) { + if (!isObject(obj)) + return []; + var keys = []; + for (var key in obj) + keys.push(key); + return keys; + } + KG.allKeys = allKeys; + function defaults(obj, def) { + if (def == null || obj == null) + return obj; + var keys = allKeys(def), l = keys.length; + for (var i = 0; i < l; i++) { + var key = keys[i]; + if (obj[key] === void 0) + obj[key] = def[key]; + } + return obj; + } + // End of underscorejs functions + function setDefaults(def, defaultValues) { + def = defaults(def, defaultValues); + return def; + } + KG.setDefaults = setDefaults; + function setProperties(def, name, props) { + def[name] = (def[name] || []).concat(props); + return def; + } + KG.setProperties = setProperties; +})(KG || (KG = {})); +/// +var KGAuthor; +(function (KGAuthor) { + function extractTypeAndDef(def) { + if (def.hasOwnProperty('type')) { + return def; + } + else { + def.type = Object.keys(def)[0]; + def.def = def[def.type]; + return def; + } + } + KGAuthor.extractTypeAndDef = extractTypeAndDef; + function parse(data, parsedData) { + data.forEach(function (obj) { + if (KGAuthor.hasOwnProperty(obj.type)) { + parsedData = new KGAuthor[obj.type](obj.def).parse(parsedData); + } + else { + console.log("Sorry, there's no ", obj.type, " object type in KGAuthor. Maybe you have a typo?"); + } + }); + return parsedData; + } + KGAuthor.parse = parse; + function getDefinitionProperty(def) { + if (typeof def == 'string') { + if (def.match(/[\*/+-]/)) { + return '(' + def + ')'; + } + else { + return def; + } + } + else { + return def; + } + } + KGAuthor.getDefinitionProperty = getDefinitionProperty; + function getPropertyAsString(def) { + var d = def; + if (typeof d == 'number') { + return d.toString(); + } + else { + return "(" + d.toString() + ")"; + } + } + KGAuthor.getPropertyAsString = getPropertyAsString; + function getParameterName(str) { + if (typeof str == 'string') { + return str.replace('params.', ''); + } + else { + return str; + } + } + KGAuthor.getParameterName = getParameterName; + function namedCalc(str) { + console.log('name is ', this.name); + return "calcs." + this.name + "." + str; + } + KGAuthor.namedCalc = namedCalc; + function negativeDef(def) { + return multiplyDefs(-1, def); + } + KGAuthor.negativeDef = negativeDef; + function binaryFunction(def1, def2, fn) { + if (typeof def1 == 'number' && typeof def2 == 'number') { + switch (fn) { + case "+": + return def1 + def2; + case "-": + return def1 - def2; + case "/": + return def1 / def2; + case "*": + return def1 * def2; + case "^": + return Math.pow(def1, def2); + } + } + else { + return "(" + getDefinitionProperty(def1) + fn + getDefinitionProperty(def2) + ")"; + } + } + KGAuthor.binaryFunction = binaryFunction; + function addDefs(def1, def2) { + if (def1 == 0) { + return def2; + } + if (def2 == 0) { + return def1; + } + return binaryFunction(def1, def2, '+'); + } + KGAuthor.addDefs = addDefs; + function subtractDefs(def1, def2) { + if (def2 == 0) { + return def1; + } + return binaryFunction(def1, def2, '-'); + } + KGAuthor.subtractDefs = subtractDefs; + function divideDefs(def1, def2) { + if (def1 == 0) { + return 0; + } + if (def2 == 1) { + return def1; + } + return binaryFunction(def1, def2, '/'); + } + KGAuthor.divideDefs = divideDefs; + function absDef(def) { + return ""; + } + KGAuthor.absDef = absDef; + function invertDef(def) { + return binaryFunction(1, def, '/'); + } + KGAuthor.invertDef = invertDef; + function multiplyDefs(def1, def2) { + if (def1 == 0 || def2 == 0) { + return 0; + } + if (def1 == 1) { + return def2; + } + if (def2 == 1) { + return def1; + } + return binaryFunction(def1, def2, '*'); + } + KGAuthor.multiplyDefs = multiplyDefs; + function averageDefs(def1, def2, weight) { + weight = weight || 0.5; + return addDefs(multiplyDefs(weight, def1), multiplyDefs(subtractDefs(1, weight), def2)); + } + KGAuthor.averageDefs = averageDefs; + function squareDef(def) { + return binaryFunction(def, def, '*'); + } + KGAuthor.squareDef = squareDef; + function sqrtDef(def) { + return raiseDefToDef(def, 0.5); + } + KGAuthor.sqrtDef = sqrtDef; + function raiseDefToDef(def1, def2) { + return binaryFunction(def1, def2, '^'); + } + KGAuthor.raiseDefToDef = raiseDefToDef; + function quadraticRootDef(def1, def2, def3, positive) { + var negagtiveB = negativeDef(def2); + var bSquaredMinus4ac = subtractDefs(squareDef(def2), multiplyDefs(4, multiplyDefs(def1, def3))); + var numerator = positive ? addDefs(negagtiveB, sqrtDef(bSquaredMinus4ac)) : subtractDefs(negagtiveB, sqrtDef(bSquaredMinus4ac)); + var denominator = multiplyDefs(2, def1); + return divideDefs(numerator, denominator); + } + KGAuthor.quadraticRootDef = quadraticRootDef; + function paramName(def) { + if (typeof (def) == 'string') { + return def.replace('params.', ''); + } + else { + return def; + } + } + KGAuthor.paramName = paramName; + function makeDraggable(def) { + if (def.hasOwnProperty('draggable') && !def.hasOwnProperty('drag')) { + if ((def.draggable == true) || (def.draggable == 'true')) { + def.drag = []; + if (def.x == "params." + paramName(def.x)) { + def.drag.push({ horizontal: paramName(def.x) }); + } + if (def.y == "params." + paramName(def.y)) { + def.drag.push({ vertical: paramName(def.y) }); + } + } + } + return def; + } + KGAuthor.makeDraggable = makeDraggable; + function curvesFromFunctions(fns, def, graph) { + return fns.map(function (fn) { + var curveDef = copyJSON(def); + if (curveDef.hasOwnProperty('min')) { + fn.min = curveDef.min; + } + if (curveDef.hasOwnProperty('max')) { + fn.max = curveDef.max; + } + if (fn.hasOwnProperty('show')) { + curveDef.show = fn.show; + } + if (fn.hasOwnProperty('parametric')) { + curveDef.parametricFunction = fn; + } + else { + curveDef.univariateFunction = fn; + } + //console.log('creating curve from def', curveDef); + return new KGAuthor.Curve(curveDef, graph); + }); + } + KGAuthor.curvesFromFunctions = curvesFromFunctions; + // allow author to set fill color either by "color" attribute or "fill" attribute + function setFillColor(def) { + if (def.open) { + def.fill = 'white'; + return KG.setDefaults(def, { + color: def.stroke, + stroke: def.color + }); + } + return KG.setDefaults(def, { + color: def.fill, + fill: def.color + }); + } + KGAuthor.setFillColor = setFillColor; + // allow author to set stroke color either by "color" attribute or "stroke" attribute + function setStrokeColor(def) { + return KG.setDefaults(def, { + color: def.stroke, + stroke: def.color + }); + } + KGAuthor.setStrokeColor = setStrokeColor; + // create a fresh copy of a JSON object + function copyJSON(def) { + return JSON.parse(JSON.stringify(def)); + } + KGAuthor.copyJSON = copyJSON; + function replaceVariable(target, search, replacement) { + return "(" + target.split(search).join(replacement) + ")"; + } + KGAuthor.replaceVariable = replaceVariable; + // allow author to specify a function using a single string rather than a function object + function parseFn(def, authorName, codeName) { + if (!def.hasOwnProperty(codeName) && def.hasOwnProperty(authorName)) { + if (codeName == 'parametricFunction') { + def.parametricFunction = { + xFunction: def.xFn, + yFunction: def.yFn, + min: def.min, + max: def.max, + samplePoints: def.samplePoints + }; + } + else { + def[codeName] = { + fn: def[authorName], + ind: (def[authorName].indexOf('(y)') > -1) ? 'y' : 'x', + min: def.min, + max: def.max, + samplePoints: def.samplePoints + }; + } + } + } + KGAuthor.parseFn = parseFn; + // allow author to set a fill color rather than a fill object + function parseFill(def, attr) { + var v = def[attr]; + if (typeof v == 'string') { + def[attr] = { fill: v }; + } + if (typeof v == 'boolean' && v) { + var fillColor = def.hasOwnProperty('fill') ? def.fill : def.color; + def[attr] = { fill: fillColor }; + } + } + KGAuthor.parseFill = parseFill; + // inherit properties from a parent + function inheritFromParent(props, parent, child) { + props.forEach(function (prop) { + if (parent.hasOwnProperty(prop) && !child.hasOwnProperty(prop)) { + child[prop] = parent[prop]; + } + }); + } + KGAuthor.inheritFromParent = inheritFromParent; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var AuthoringObject = /** @class */ (function () { + function AuthoringObject(def) { + this.def = def; + this.name = def.name; + this.subObjects = []; + } + AuthoringObject.prototype.parseSelf = function (parsedData) { + return parsedData; + }; + AuthoringObject.prototype.parse = function (parsedData) { + this.subObjects.forEach(function (obj) { + parsedData = obj.parse(parsedData); + }); + delete this.subObjects; + parsedData = this.parseSelf(parsedData); + return parsedData; + }; + AuthoringObject.prototype.addSecondGraph = function (graph2) { + var def = this.def; + if (def.hasOwnProperty('yScale2Name')) { + def.xScale2Name = graph2.xScale.name; + def.yScale2Name = graph2.yScale.name; + } + this.subObjects.forEach(function (obj) { + obj.addSecondGraph(graph2); + }); + }; + return AuthoringObject; + }()); + KGAuthor.AuthoringObject = AuthoringObject; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Schema = /** @class */ (function (_super) { + __extends(Schema, _super); + function Schema(def) { + var _this = this; + var palette = { + blue: 'd3.schemeCategory10[0]', + orange: 'd3.schemeCategory10[1]', + green: 'd3.schemeCategory10[2]', + red: 'd3.schemeCategory10[3]', + purple: 'd3.schemeCategory10[4]', + brown: 'd3.schemeCategory10[5]', + magenta: 'd3.schemeCategory10[6]', + grey: 'd3.schemeCategory10[7]', + gray: 'd3.schemeCategory10[7]', + olive: 'd3.schemeCategory10[8]' //#637939 + }; + for (var color in def.colors) { + var colorName = def.colors[color]; + if (palette.hasOwnProperty(colorName)) { + def.colors[color] = palette[colorName]; + } + } + def.colors = KG.setDefaults(def.colors || {}, palette); + _this = _super.call(this, def) || this; + _this.colors = def.colors; + _this.idioms = def.idioms; + return _this; + } + Schema.prototype.parseSelf = function (parsedData) { + var colors = this.colors; + parsedData.colors = KG.setDefaults(parsedData.colors || {}, colors); + parsedData.idioms = this.idioms; + return parsedData; + }; + return Schema; + }(KGAuthor.AuthoringObject)); + KGAuthor.Schema = Schema; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Layout = /** @class */ (function (_super) { + __extends(Layout, _super); + function Layout(def) { + var _this = _super.call(this, def) || this; + _this.aspectRatio = 2; + _this.nosvg = false; + var l = _this; + if (def.hasOwnProperty('explanation')) { + l.subObjects.push(new KGAuthor.Explanation(def.explanation)); + } + return _this; + } + Layout.prototype.parseSelf = function (parsedData) { + parsedData.aspectRatio = this.aspectRatio; + parsedData.nosvg = this.nosvg; + return parsedData; + }; + return Layout; + }(KGAuthor.AuthoringObject)); + KGAuthor.Layout = Layout; + var SquareLayout = /** @class */ (function (_super) { + __extends(SquareLayout, _super); + // creates a square layout (aspect ratio of 1) within the main body of the text + // to make a square graph, the ratio of width to height should be 0.82 + function SquareLayout(def) { + var _this = _super.call(this, def) || this; + _this.aspectRatio = 1.22; + return _this; + } + return SquareLayout; + }(Layout)); + KGAuthor.SquareLayout = SquareLayout; + var WideRectangleLayout = /** @class */ (function (_super) { + __extends(WideRectangleLayout, _super); + // creates a rectangle, twice as wide as it is high, within the main body of the text + // to make a square graph, the ratio of width to height should be 0.41 + function WideRectangleLayout(def) { + var _this = _super.call(this, def) || this; + _this.aspectRatio = 2.44; + return _this; + } + return WideRectangleLayout; + }(Layout)); + KGAuthor.WideRectangleLayout = WideRectangleLayout; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var HTMLLayout = /** @class */ (function (_super) { + __extends(HTMLLayout, _super); + function HTMLLayout(def) { + var _this = _super.call(this, def) || this; + var l = _this; + l.nosvg = true; + var divDef = { "html": def['html'] }; + l.subObjects.push(new KGAuthor.Div(divDef)); + return _this; + } + return HTMLLayout; + }(KGAuthor.Layout)); + KGAuthor.HTMLLayout = HTMLLayout; + var HTMLPlusSidebarLayout = /** @class */ (function (_super) { + __extends(HTMLPlusSidebarLayout, _super); + function HTMLPlusSidebarLayout(def) { + var _this = _super.call(this, def) || this; + var l = _this; + l.nosvg = true; + var sidebarDef = def['sidebar']; + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return HTMLPlusSidebarLayout; + }(HTMLLayout)); + KGAuthor.HTMLPlusSidebarLayout = HTMLPlusSidebarLayout; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var OneGraph = /** @class */ (function (_super) { + __extends(OneGraph, _super); + function OneGraph(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var graphDef = def['graph']; + graphDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.74, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.Graph(graphDef)); + return _this; + } + return OneGraph; + }(KGAuthor.SquareLayout)); + KGAuthor.OneGraph = OneGraph; + var OneTree = /** @class */ (function (_super) { + __extends(OneTree, _super); + function OneTree(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var treeDef = def['tree']; + treeDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.74, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.Tree(treeDef)); + return _this; + } + return OneTree; + }(KGAuthor.SquareLayout)); + KGAuthor.OneTree = OneTree; + var OneWideGraph = /** @class */ (function (_super) { + __extends(OneWideGraph, _super); + function OneWideGraph(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var graphDef = def['graph']; + graphDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.74, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.Graph(graphDef)); + return _this; + } + return OneWideGraph; + }(KGAuthor.WideRectangleLayout)); + KGAuthor.OneWideGraph = OneWideGraph; + var OneGraphPlusSidebar = /** @class */ (function (_super) { + __extends(OneGraphPlusSidebar, _super); + function OneGraphPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var graphDef = def['graph'], sidebarDef = def['sidebar']; + graphDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.738, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.Graph(graphDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return OneGraphPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.OneGraphPlusSidebar = OneGraphPlusSidebar; + var OneTreePlusSidebar = /** @class */ (function (_super) { + __extends(OneTreePlusSidebar, _super); + function OneTreePlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var treeDef = def['tree'], sidebarDef = def['sidebar']; + treeDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.738, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.Tree(treeDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return OneTreePlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.OneTreePlusSidebar = OneTreePlusSidebar; + var OneWideGraphPlusSidebar = /** @class */ (function (_super) { + __extends(OneWideGraphPlusSidebar, _super); + function OneWideGraphPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var graphDef = def['graph'], sidebarDef = def['sidebar']; + graphDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.738, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.Graph(graphDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return OneWideGraphPlusSidebar; + }(KGAuthor.WideRectangleLayout)); + KGAuthor.OneWideGraphPlusSidebar = OneWideGraphPlusSidebar; + var OneGraphPlusSidebarRoom200 = /** @class */ (function (_super) { + __extends(OneGraphPlusSidebarRoom200, _super); + function OneGraphPlusSidebarRoom200(def) { + var _this = _super.call(this, def) || this; + _this.aspectRatio = 2; + return _this; + } + return OneGraphPlusSidebarRoom200; + }(OneGraphPlusSidebar)); + KGAuthor.OneGraphPlusSidebarRoom200 = OneGraphPlusSidebarRoom200; + var GeoGebraPlusSidebar = /** @class */ (function (_super) { + __extends(GeoGebraPlusSidebar, _super); + function GeoGebraPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var ggbAppletDef = def['ggbApplet'], sidebarDef = def['sidebar']; + ggbAppletDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.738, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.GeoGebraContainer(ggbAppletDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return GeoGebraPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.GeoGebraPlusSidebar = GeoGebraPlusSidebar; + var MathboxPlusSidebar = /** @class */ (function (_super) { + __extends(MathboxPlusSidebar, _super); + function MathboxPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var mathboxDef = def['mathbox'], sidebarDef = def['sidebar']; + mathboxDef.position = { + "x": 0.025, + "y": 0.025, + "width": 0.95, + "height": 0.95 + }; + l.subObjects.push(new KGAuthor.MathboxContainer(mathboxDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return MathboxPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.MathboxPlusSidebar = MathboxPlusSidebar; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var TwoHorizontalGraphs = /** @class */ (function (_super) { + __extends(TwoHorizontalGraphs, _super); + function TwoHorizontalGraphs(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var leftGraphDef = def['leftGraph'], rightGraphDef = def['rightGraph']; + var leftX = 0.15, rightX = 0.65, topY = 0.1, bottomY = 0.9, width = 0.3, controlHeight = 0.25; + var includeControls = false; + console.log('layout: ', l); + if (def.hasOwnProperty('leftControls')) { + l.subObjects.push(new KGAuthor.DivContainer({ + position: { + x: leftX, + y: bottomY, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['leftControls'] + } + ] + })); + includeControls = true; + } + if (def.hasOwnProperty('rightControls')) { + l.subObjects.push(new KGAuthor.DivContainer({ + position: { + x: rightX, + y: bottomY, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['rightControls'] + } + ] + })); + includeControls = true; + } + var graphHeight = includeControls ? 0.5 : 0.9; + _this.aspectRatio = includeControls ? 2 : 4; + leftGraphDef.position = { + x: leftX, + y: topY, + width: width, + height: graphHeight + }; + l.subObjects.push(new KGAuthor.Graph(leftGraphDef)); + rightGraphDef.position = { + "x": rightX, + "y": topY, + "width": width, + "height": graphHeight + }; + l.subObjects.push(new KGAuthor.Graph(rightGraphDef)); + return _this; + } + return TwoHorizontalGraphs; + }(KGAuthor.Layout)); + KGAuthor.TwoHorizontalGraphs = TwoHorizontalGraphs; + var TwoHorizontalGraphsPlusSidebar = /** @class */ (function (_super) { + __extends(TwoHorizontalGraphsPlusSidebar, _super); + function TwoHorizontalGraphsPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var leftGraphDef = def['leftGraph'], rightGraphDef = def['rightGraph'], sidebarDef = def['sidebar']; + var includeControls = false; + var leftX = 0.1, rightX = 0.6, topY = 0.025, bottomY = 1.2, width = 0.369, controlHeight = 0.3, controlBottom = 0.65; + if (def.hasOwnProperty('leftControls')) { + var leftControlsContainer = { + position: { + x: leftX, + y: controlBottom, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['leftControls'] + } + ] + }; + includeControls = true; + l.subObjects.push(new KGAuthor.DivContainer(leftControlsContainer)); + } + if (def.hasOwnProperty('rightControls')) { + var rightControlsContainer = { + position: { + x: rightX, + y: controlBottom, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['rightControls'] + } + ] + }; + includeControls = true; + l.subObjects.push(new KGAuthor.DivContainer(rightControlsContainer)); + } + var graphHeight = includeControls ? 0.5 : 0.9; + _this.aspectRatio = includeControls ? 1.2 : 2.4; + leftGraphDef.position = { + "x": leftX, + "y": topY, + "width": width, + "height": graphHeight + }; + rightGraphDef.position = { + "x": rightX, + "y": topY, + "width": width, + "height": graphHeight + }; + var leftGraph = new KGAuthor.Graph(leftGraphDef), rightGraph = new KGAuthor.Graph(rightGraphDef), sidebar = new KGAuthor.Sidebar(sidebarDef); + l.subObjects.push(leftGraph); + l.subObjects.push(rightGraph); + l.subObjects.push(sidebar); + return _this; + } + return TwoHorizontalGraphsPlusSidebar; + }(KGAuthor.Layout)); + KGAuthor.TwoHorizontalGraphsPlusSidebar = TwoHorizontalGraphsPlusSidebar; + var MathboxPlusGraph = /** @class */ (function (_super) { + __extends(MathboxPlusGraph, _super); + function MathboxPlusGraph(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var mathboxDef = def['mathbox'], graphDef = def['graph']; + mathboxDef.position = { + "x": 0.05, + "y": 0.025, + "width": 0.45, + "height": 0.9 + }; + graphDef.position = { + "x": 0.6, + "y": 0.2, + "width": 0.3, + "height": 0.6 + }; + l.subObjects.push(new KGAuthor.Mathbox(mathboxDef)); + l.subObjects.push(new KGAuthor.Graph(graphDef)); + return _this; + } + return MathboxPlusGraph; + }(KGAuthor.Layout)); + KGAuthor.MathboxPlusGraph = MathboxPlusGraph; + var GameMatrixPlusGraph = /** @class */ (function (_super) { + __extends(GameMatrixPlusGraph, _super); + function GameMatrixPlusGraph(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var graphDef = def['graph']; + var gameDivDef = { + position: { + x: 0.05, + y: 0.1, + width: 0.35, + height: 0.7 + }, + children: [ + { + type: "GameMatrix", + def: def.game + } + ] + }; + graphDef.position = { + x: 0.6, + y: 0.1, + width: 0.35, + height: 0.7 + }; + l.subObjects.push(new KGAuthor.DivContainer(gameDivDef)); + l.subObjects.push(new KGAuthor.Graph(graphDef)); + return _this; + } + return GameMatrixPlusGraph; + }(KGAuthor.Layout)); + KGAuthor.GameMatrixPlusGraph = GameMatrixPlusGraph; + var GameMatrixPlusGraphPlusSidebar = /** @class */ (function (_super) { + __extends(GameMatrixPlusGraphPlusSidebar, _super); + function GameMatrixPlusGraphPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var graphDef = def['graph']; + var sidebarDef = def['sidebar']; + var gameDivDef = { + position: { + x: 0.05, + y: 0.1, + width: 0.35, + height: 0.7 + }, + children: [ + { + type: "GameMatrix", + def: def.game + } + ] + }; + graphDef.position = { + x: 0.6, + y: 0.1, + width: 0.35, + height: 0.7 + }; + l.subObjects.push(new KGAuthor.DivContainer(gameDivDef)); + l.subObjects.push(new KGAuthor.Graph(graphDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return GameMatrixPlusGraphPlusSidebar; + }(KGAuthor.Layout)); + KGAuthor.GameMatrixPlusGraphPlusSidebar = GameMatrixPlusGraphPlusSidebar; + var GeoGebraPlusGraph = /** @class */ (function (_super) { + __extends(GeoGebraPlusGraph, _super); + function GeoGebraPlusGraph(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var ggbAppletDef = def['ggbApplet'], graphDef = def['graph']; + ggbAppletDef.position = { + "x": 0.05, + "y": 0.025, + "width": 0.45, + "height": 0.9 + }; + graphDef.position = { + "x": 0.6, + "y": 0.2, + "width": 0.3, + "height": 0.6 + }; + l.subObjects.push(new KGAuthor.GeoGebraContainer(ggbAppletDef)); + l.subObjects.push(new KGAuthor.Graph(graphDef)); + return _this; + } + return GeoGebraPlusGraph; + }(KGAuthor.Layout)); + KGAuthor.GeoGebraPlusGraph = GeoGebraPlusGraph; + var GeoGebraPlusGraphPlusSidebar = /** @class */ (function (_super) { + __extends(GeoGebraPlusGraphPlusSidebar, _super); + function GeoGebraPlusGraphPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var ggbAppletDef = def['ggbApplet'], graphDef = def['graph'], sidebarDef = def['sidebar']; + ggbAppletDef.position = { + "x": 0.1, + "y": 0.025, + "width": 0.369, + "height": 0.9 + }; + graphDef.position = { + "x": 0.6, + "y": 0.025, + "width": 0.369, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.GeoGebraContainer(ggbAppletDef)); + l.subObjects.push(new KGAuthor.Graph(graphDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return GeoGebraPlusGraphPlusSidebar; + }(KGAuthor.WideRectangleLayout)); + KGAuthor.GeoGebraPlusGraphPlusSidebar = GeoGebraPlusGraphPlusSidebar; + var MathboxPlusGraphPlusSidebar = /** @class */ (function (_super) { + __extends(MathboxPlusGraphPlusSidebar, _super); + function MathboxPlusGraphPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var mathboxDef = def['mathbox'], graphDef = def['graph'], sidebarDef = def['sidebar']; + mathboxDef.position = { + "x": 0.025, + "y": 0.025, + "width": 0.444, + "height": 0.95 + }; + graphDef.position = { + "x": 0.6, + "y": 0.025, + "width": 0.369, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.MathboxContainer(mathboxDef)); + l.subObjects.push(new KGAuthor.Graph(graphDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return MathboxPlusGraphPlusSidebar; + }(KGAuthor.WideRectangleLayout)); + KGAuthor.MathboxPlusGraphPlusSidebar = MathboxPlusGraphPlusSidebar; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var ThreeHorizontalGraphs = /** @class */ (function (_super) { + __extends(ThreeHorizontalGraphs, _super); + function ThreeHorizontalGraphs(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var leftGraphDef = def['leftGraph'], middleGraphDef = def['middleGraph'], rightGraphDef = def['rightGraph']; + var leftX = 0.05, middleX = 0.35, rightX = 0.65, topY = 0.025, bottomY = 0.65, width = 0.25, controlHeight = 0.3; + var includeControls = false; + console.log('layout: ', l); + if (def.hasOwnProperty('leftControls')) { + l.subObjects.push(new KGAuthor.DivContainer({ + position: { + x: leftX, + y: bottomY, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['leftControls'] + } + ] + })); + includeControls = true; + } + if (def.hasOwnProperty('middleControls')) { + l.subObjects.push(new KGAuthor.DivContainer({ + position: { + x: middleX, + y: bottomY, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['middleControls'] + } + ] + })); + includeControls = true; + } + if (def.hasOwnProperty('rightControls')) { + l.subObjects.push(new KGAuthor.DivContainer({ + position: { + x: rightX, + y: bottomY, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['rightControls'] + } + ] + })); + includeControls = true; + } + var graphHeight = includeControls ? 0.5 : 0.9; + _this.aspectRatio = includeControls ? 2 : 4; + leftGraphDef.position = { + x: leftX, + y: topY, + width: width, + height: graphHeight + }; + l.subObjects.push(new KGAuthor.Graph(leftGraphDef)); + middleGraphDef.position = { + "x": middleX, + "y": topY, + "width": width, + "height": graphHeight + }; + l.subObjects.push(new KGAuthor.Graph(middleGraphDef)); + rightGraphDef.position = { + "x": rightX, + "y": topY, + "width": width, + "height": graphHeight + }; + l.subObjects.push(new KGAuthor.Graph(rightGraphDef)); + return _this; + } + return ThreeHorizontalGraphs; + }(KGAuthor.Layout)); + KGAuthor.ThreeHorizontalGraphs = ThreeHorizontalGraphs; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var RectanglePlusTwoSquaresPlusSidebar = /** @class */ (function (_super) { + __extends(RectanglePlusTwoSquaresPlusSidebar, _super); + function RectanglePlusTwoSquaresPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var topGraph = def['topGraph'], bottomLeftGraph = def['bottomLeftGraph'], bottomRightGraph = def['bottomRightGraph'], sidebarDef = def['sidebar']; + topGraph.position = { + "x": 0.15, + "y": 0.05, + "width": 0.8, + "height": 0.4 + }; + bottomLeftGraph.position = { + "x": 0.15, + "y": 0.6, + "width": 0.35, + "height": 0.35 + }; + bottomRightGraph.position = { + "x": 0.6, + "y": 0.6, + "width": 0.35, + "height": 0.35 + }; + l.subObjects.push(new KGAuthor.Graph(topGraph)); + l.subObjects.push(new KGAuthor.Graph(bottomLeftGraph)); + l.subObjects.push(new KGAuthor.Graph(bottomRightGraph)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return RectanglePlusTwoSquaresPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.RectanglePlusTwoSquaresPlusSidebar = RectanglePlusTwoSquaresPlusSidebar; + var RectangleBelowTwoSquaresPlusSidebar = /** @class */ (function (_super) { + __extends(RectangleBelowTwoSquaresPlusSidebar, _super); + function RectangleBelowTwoSquaresPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var bottomGraph = def['bottomGraph'], topLeftGraph = def['topLeftGraph'], topRightGraph = def['topRightGraph'], sidebarDef = def['sidebar']; + bottomGraph.position = { + "x": 0.15, + "y": 0.55, + "width": 0.8, + "height": 0.4 + }; + topLeftGraph.position = { + "x": 0.15, + "y": 0.05, + "width": 0.35, + "height": 0.35 + }; + topRightGraph.position = { + "x": 0.6, + "y": 0.05, + "width": 0.35, + "height": 0.35 + }; + l.subObjects.push(new KGAuthor.Graph(bottomGraph)); + l.subObjects.push(new KGAuthor.Graph(topLeftGraph)); + l.subObjects.push(new KGAuthor.Graph(topRightGraph)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return RectangleBelowTwoSquaresPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.RectangleBelowTwoSquaresPlusSidebar = RectangleBelowTwoSquaresPlusSidebar; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var TwoVerticalGraphs = /** @class */ (function (_super) { + __extends(TwoVerticalGraphs, _super); + function TwoVerticalGraphs(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var topGraphDef = def['topGraph'], bottomGraphDef = def['bottomGraph']; + topGraphDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.8, + "height": 0.4 + }; + bottomGraphDef.position = { + "x": 0.15, + "y": 0.525, + "width": 0.8, + "height": 0.4 + }; + var topGraph = new KGAuthor.Graph(topGraphDef), bottomGraph = new KGAuthor.Graph(bottomGraphDef); + topGraph.subObjects.forEach(function (obj) { obj.addSecondGraph(bottomGraph); }); + bottomGraph.subObjects.forEach(function (obj) { obj.addSecondGraph(topGraph); }); + l.subObjects.push(topGraph); + l.subObjects.push(bottomGraph); + return _this; + } + return TwoVerticalGraphs; + }(KGAuthor.SquareLayout)); + KGAuthor.TwoVerticalGraphs = TwoVerticalGraphs; + var TwoVerticalGraphsPlusSidebar = /** @class */ (function (_super) { + __extends(TwoVerticalGraphsPlusSidebar, _super); + function TwoVerticalGraphsPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var topGraphDef = def['topGraph'], bottomGraphDef = def['bottomGraph'], sidebarDef = def['sidebar']; + topGraphDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.738, + "height": 0.4 + }; + bottomGraphDef.position = { + "x": 0.15, + "y": 0.525, + "width": 0.738, + "height": 0.4 + }; + var topGraph = new KGAuthor.Graph(topGraphDef), bottomGraph = new KGAuthor.Graph(bottomGraphDef), sidebar = new KGAuthor.Sidebar(sidebarDef); + topGraph.subObjects.forEach(function (obj) { obj.addSecondGraph(bottomGraph); }); + bottomGraph.subObjects.forEach(function (obj) { obj.addSecondGraph(topGraph); }); + l.subObjects.push(topGraph); + l.subObjects.push(bottomGraph); + l.subObjects.push(sidebar); + return _this; + } + return TwoVerticalGraphsPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.TwoVerticalGraphsPlusSidebar = TwoVerticalGraphsPlusSidebar; + var TwoVerticalGraphsRoom200 = /** @class */ (function (_super) { + __extends(TwoVerticalGraphsRoom200, _super); + function TwoVerticalGraphsRoom200(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var topGraphDef = def['topGraph'], bottomGraphDef = def['bottomGraph']; + topGraphDef.position = { + "x": 0.1, + "y": 0, + "width": 0.85, + "height": 0.4 + }; + bottomGraphDef.position = { + "x": 0.1, + "y": 0.62, + "width": 0.85, + "height": 0.38 + }; + var topGraph = new KGAuthor.Graph(topGraphDef), bottomGraph = new KGAuthor.Graph(bottomGraphDef); + topGraph.subObjects.forEach(function (obj) { obj.addSecondGraph(bottomGraph); }); + bottomGraph.subObjects.forEach(function (obj) { obj.addSecondGraph(topGraph); }); + l.subObjects.push(topGraph); + l.subObjects.push(bottomGraph); + l.aspectRatio = 1.3; + return _this; + } + return TwoVerticalGraphsRoom200; + }(KGAuthor.Layout)); + KGAuthor.TwoVerticalGraphsRoom200 = TwoVerticalGraphsRoom200; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var SquarePlusTwoVerticalGraphs = /** @class */ (function (_super) { + __extends(SquarePlusTwoVerticalGraphs, _super); + function SquarePlusTwoVerticalGraphs(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var bigGraphDef = def['bigGraph'], topGraphDef = def['topGraph'], bottomGraphDef = def['bottomGraph']; + bigGraphDef.position = { + "x": 0.05, + "y": 0.025, + "width": 0.5, + "height": 0.9 + }; + topGraphDef.position = { + "x": 0.6, + "y": 0.025, + "width": 0.35, + "height": 0.4 + }; + bottomGraphDef.position = { + "x": 0.6, + "y": 0.525, + "width": 0.35, + "height": 0.4 + }; + l.subObjects.push(new KGAuthor.Graph(bigGraphDef)); + l.subObjects.push(new KGAuthor.Graph(topGraphDef)); + l.subObjects.push(new KGAuthor.Graph(bottomGraphDef)); + return _this; + } + return SquarePlusTwoVerticalGraphs; + }(KGAuthor.Layout)); + KGAuthor.SquarePlusTwoVerticalGraphs = SquarePlusTwoVerticalGraphs; + var TwoVerticalSquaresOneBigSquare = /** @class */ (function (_super) { + __extends(TwoVerticalSquaresOneBigSquare, _super); + function TwoVerticalSquaresOneBigSquare(def) { + var _this = _super.call(this, def) || this; + var l = _this; + l.aspectRatio = 1.6; + var bigGraphDef = def['bigGraph'], topGraphDef = def['topGraph'], bottomGraphDef = def['bottomGraph']; + topGraphDef.position = { + "x": 0.1, + "y": 0.05, + "width": 0.25, + "height": 0.40 + }; + bottomGraphDef.position = { + "x": 0.1, + "y": 0.538, + "width": 0.25, + "height": 0.40 + }; + bigGraphDef.position = { + "x": 0.43, + "y": 0.05, + "width": 0.555, + "height": 0.888 + }; + l.subObjects.push(new KGAuthor.Graph(bigGraphDef)); + l.subObjects.push(new KGAuthor.Graph(topGraphDef)); + l.subObjects.push(new KGAuthor.Graph(bottomGraphDef)); + return _this; + } + return TwoVerticalSquaresOneBigSquare; + }(KGAuthor.Layout)); + KGAuthor.TwoVerticalSquaresOneBigSquare = TwoVerticalSquaresOneBigSquare; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var FourGraphs = /** @class */ (function (_super) { + __extends(FourGraphs, _super); + function FourGraphs(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var topLeftGraphDef = def['topLeftGraph'], bottomLeftGraphDef = def['bottomLeftGraph'], topRightGraphDef = def['topRightGraph'], bottomRightGraphDef = def['bottomRightGraph']; + var leftX = 0.05, rightX = 0.55, topY = 0.025, bottomY = 0.525; + topLeftGraphDef.position = { + "x": leftX, + "y": topY, + "width": 0.4, + "height": 0.4 + }; + bottomLeftGraphDef.position = { + "x": leftX, + "y": bottomY, + "width": 0.4, + "height": 0.4 + }; + topRightGraphDef.position = { + "x": rightX, + "y": topY, + "width": 0.4, + "height": 0.4 + }; + bottomRightGraphDef.position = { + "x": rightX, + "y": bottomY, + "width": 0.4, + "height": 0.4 + }; + l.subObjects.push(new KGAuthor.Graph(topLeftGraphDef)); + l.subObjects.push(new KGAuthor.Graph(bottomLeftGraphDef)); + l.subObjects.push(new KGAuthor.Graph(topRightGraphDef)); + l.subObjects.push(new KGAuthor.Graph(bottomRightGraphDef)); + return _this; + } + return FourGraphs; + }(KGAuthor.SquareLayout)); + KGAuthor.FourGraphs = FourGraphs; + var FourGraphsPlusSidebar = /** @class */ (function (_super) { + __extends(FourGraphsPlusSidebar, _super); + function FourGraphsPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var sidebarDef = def['sidebar']; + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return FourGraphsPlusSidebar; + }(FourGraphs)); + KGAuthor.FourGraphsPlusSidebar = FourGraphsPlusSidebar; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var GameMatrixLayout = /** @class */ (function (_super) { + __extends(GameMatrixLayout, _super); + function GameMatrixLayout(def) { + var _this = _super.call(this, def) || this; + var l = _this; + l.nosvg = true; + l.subObjects.push(new KGAuthor.GameMatrix(def.gameMatrix)); + return _this; + } + return GameMatrixLayout; + }(KGAuthor.Layout)); + KGAuthor.GameMatrixLayout = GameMatrixLayout; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Scale = /** @class */ (function (_super) { + __extends(Scale, _super); + function Scale(def) { + var _this = this; + KG.setDefaults(def, { + intercept: 0 + }); + _this = _super.call(this, def) || this; + _this.min = def.domainMin; + _this.max = def.domainMax; + _this.intercept = def.intercept; + return _this; + } + Scale.prototype.parseSelf = function (parsedData) { + parsedData.scales.push(this.def); + return parsedData; + }; + return Scale; + }(KGAuthor.AuthoringObject)); + KGAuthor.Scale = Scale; + var PositionedObject = /** @class */ (function (_super) { + __extends(PositionedObject, _super); + function PositionedObject(def) { + var _this = this; + KG.setDefaults(def, { xAxis: {}, yAxis: {} }); + KG.setDefaults(def.xAxis, { min: 0, max: 10, intercept: 0, title: '', orient: 'bottom' }); + KG.setDefaults(def.yAxis, { min: 0, max: 10, intercept: 0, title: '', orient: 'left' }); + _this = _super.call(this, def) || this; + var po = _this, xMin = def.xAxis.min, xMax = def.xAxis.max, xIntercept = def.xAxis.intercept, xLog = def.xAxis.log, yMin = def.yAxis.min, yMax = def.yAxis.max, yIntercept = def.yAxis.intercept, yLog = def.yAxis.log, leftEdge = def.position.x, rightEdge = KGAuthor.addDefs(def.position.x, def.position.width), bottomEdge = KGAuthor.addDefs(def.position.y, def.position.height), topEdge = def.position.y; + po.xScale = new Scale({ + "name": KG.randomString(10), + "axis": "x", + "domainMin": xMin, + "domainMax": xMax, + "rangeMin": leftEdge, + "rangeMax": rightEdge, + "log": xLog, + "intercept": xIntercept + }); + po.yScale = new Scale({ + "name": KG.randomString(10), + "axis": "y", + "domainMin": yMin, + "domainMax": yMax, + "rangeMin": bottomEdge, + "rangeMax": topEdge, + "log": yLog, + "intercept": yIntercept + }); + po.subObjects = [po.xScale, po.yScale]; + if (po.def.hasOwnProperty('objects')) { + po.def.objects.map(KGAuthor.extractTypeAndDef); + } + return _this; + } + return PositionedObject; + }(KGAuthor.AuthoringObject)); + KGAuthor.PositionedObject = PositionedObject; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Graph = /** @class */ (function (_super) { + __extends(Graph, _super); + function Graph(def) { + var _this = this; + def = KG.setDefaults(def, { objects: [] }); + _this = _super.call(this, def) || this; + var g = _this; + //axes need to update when the other one's domain changes + def.xAxis.otherMin = def.yAxis.min; + def.xAxis.otherMax = def.yAxis.max; + def.yAxis.otherMin = def.xAxis.min; + def.yAxis.otherMax = def.xAxis.max; + g.clipPath = new KGAuthor.ClipPath({ + "name": KG.randomString(10), + "paths": [new KGAuthor.Rectangle({ + x1: def.xAxis.min, + x2: def.xAxis.max, + y1: def.yAxis.min, + y2: def.yAxis.max, + inDef: true + }, g)] + }, g); + g.subObjects.push(g.clipPath); + g.def.objects.unshift({ + type: 'Axis', + def: g.def.xAxis + }); + g.def.objects.unshift({ + type: 'Axis', + def: g.def.yAxis + }); + g.def.objects.forEach(function (obj) { + g.subObjects.push(new KGAuthor[obj.type](obj.def, g)); + }); + console.log(g); + return _this; + } + Graph.prototype.getMarkerName = function (lookup) { + var g = this; + var name = '', found = false; + // look to see if there is already a marker of that name and type + g.subObjects.forEach(function (obj) { + if (obj.hasOwnProperty('color') && obj['color'] == lookup.color && obj.hasOwnProperty('markerType') && obj['markerType'] == lookup.markerType) { + name = obj.name; + found = true; + } + }); + // if there is, return its name + if (found) { + return name; + } + // otherwise create a new marker, add to the graph's subobjects, and return the new marker's name + else { + var newMarker = new KGAuthor[lookup.markerType]({ color: lookup.color }); + g.subObjects.push(newMarker); + return newMarker.name; + } + }; + Graph.prototype.getEndArrowName = function (color) { + return this.getMarkerName({ + markerType: 'EndArrow', + color: color + }); + }; + Graph.prototype.getStartArrowName = function (color) { + return this.getMarkerName({ + markerType: 'StartArrow', + color: color + }); + }; + return Graph; + }(KGAuthor.PositionedObject)); + KGAuthor.Graph = Graph; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Tree = /** @class */ (function (_super) { + __extends(Tree, _super); + function Tree(def) { + var _this = this; + var showGrid = def.showGrid || false; + var graphDef = { + position: def.position, + objects: def.objects, + xAxis: { max: 24, ticks: 24, show: showGrid }, + yAxis: { max: 24, ticks: 24, show: showGrid } + }; + _this = _super.call(this, graphDef) || this; + var t = _this; + t.nodeCoordinates = {}; + t.subObjects.push(new KGAuthor.Grid({ + xStep: 3, + yStep: 3, + show: showGrid + }, t)); + def.nodes.forEach(function (nodeDef) { + t.subObjects.push(new KGAuthor.Node(nodeDef, t)); + }); + if (def.hasOwnProperty('edges')) { + def.edges.forEach(function (edgeDef) { + t.subObjects.push(new KGAuthor.Edge(edgeDef, t)); + }); + } + return _this; + } + return Tree; + }(KGAuthor.Graph)); + KGAuthor.Tree = Tree; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var GeoGebraContainer = /** @class */ (function (_super) { + __extends(GeoGebraContainer, _super); + function GeoGebraContainer(def) { + var _this = this; + def.xAxis = { min: 0, max: 1 }; + def.yAxis = { min: 0, max: 1 }; + _this = _super.call(this, def) || this; + var ggb = _this; + def.xScaleName = ggb.xScale.name; + def.yScaleName = ggb.yScale.name; + ggb.subObjects.push(new KGAuthor.GeoGebraApplet(def)); + return _this; + } + return GeoGebraContainer; + }(KGAuthor.PositionedObject)); + KGAuthor.GeoGebraContainer = GeoGebraContainer; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxContainer = /** @class */ (function (_super) { + __extends(MathboxContainer, _super); + function MathboxContainer(def) { + var _this = this; + // the container, as a div, must have an x and y axis of its own. + // so we must first push down the author's specified x, y, and z axes down to be objects + def.objects.push({ + "type": "MathboxXAxis", + "def": def.xAxis + }); + if (def.xAxis.hasOwnProperty('title')) { + def.objects.push({ + "type": "MathboxLabel", + "def": { + "x": KGAuthor.multiplyDefs(def.xAxis.max, 0.95), + "y": KGAuthor.multiplyDefs(def.yAxis.max, -0.02), + "z": KGAuthor.multiplyDefs(def.zAxis.max, 0.02), + "text": def.xAxis.title, + "color": "black" + } + }); + } + def.objects.push({ + "type": "MathboxYAxis", + "def": def.yAxis + }); + if (def.yAxis.hasOwnProperty('title')) { + def.objects.push({ + "type": "MathboxLabel", + "def": { + "x": KGAuthor.multiplyDefs(def.xAxis.max, -0.02), + "y": KGAuthor.multiplyDefs(def.yAxis.max, 0.95), + "z": KGAuthor.multiplyDefs(def.zAxis.max, 0.02), + "text": def.yAxis.title, + "color": "black" + } + }); + } + def.objects.push({ + "type": "MathboxZAxis", + "def": def.zAxis + }); + if (def.zAxis.hasOwnProperty('title')) { + def.objects.push({ + "type": "MathboxLabel", + "def": { + "x": KGAuthor.multiplyDefs(def.xAxis.max, -0.02), + "y": KGAuthor.multiplyDefs(def.yAxis.max, -0.02), + "z": KGAuthor.multiplyDefs(def.zAxis.max, 0.98), + "text": def.zAxis.title, + "color": "black" + } + }); + } + delete def.zAxis; + def.xAxis = { min: 0, max: 1 }; + def.yAxis = { min: 0, max: 1 }; + _this = _super.call(this, def) || this; + var mb = _this; + def.xScaleName = mb.xScale.name; + def.yScaleName = mb.yScale.name; + def.objects.forEach(function (obj) { + if (obj.type.indexOf('Mathbox') < 0) { + obj.type = 'Mathbox' + obj.type; + } + try { + var newObj = new KGAuthor[obj.type](obj.def); + newObj.subObjects.forEach(function (subOb) { + def.objects.push(subOb); + }); + } + catch (e) { + console.log("There's no object called ", obj.type); + } + }); + console.log('creating mathbox'); + mb.subObjects.push(new KGAuthor.Mathbox(def)); + return _this; + } + return MathboxContainer; + }(KGAuthor.PositionedObject)); + KGAuthor.MathboxContainer = MathboxContainer; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var DivContainer = /** @class */ (function (_super) { + __extends(DivContainer, _super); + function DivContainer(def) { + var _this = this; + def.xAxis = { min: 0, max: 1 }; + def.yAxis = { min: 0, max: 1 }; + _this = _super.call(this, def) || this; + var dc = _this; + dc.subObjects.push(new KGAuthor.PositionedDiv(def, dc)); + return _this; + } + return DivContainer; + }(KGAuthor.PositionedObject)); + KGAuthor.DivContainer = DivContainer; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var GraphObjectGenerator = /** @class */ (function (_super) { + __extends(GraphObjectGenerator, _super); + function GraphObjectGenerator(def, graph) { + var _this = _super.call(this, def) || this; + if (graph) { + _this.def.xScaleName = graph.xScale.name; + _this.def.yScaleName = graph.yScale.name; + if (!def.inDef) { + _this.def.clipPathName = def.clipPathName || graph.clipPath.name; + } + } + _this.subObjects = []; + return _this; + } + GraphObjectGenerator.prototype.extractCoordinates = function (coordinatesKey, xKey, yKey) { + coordinatesKey = coordinatesKey || 'coordinates'; + xKey = xKey || 'x'; + yKey = yKey || 'y'; + var obj = this, def = this.def; + if (def.hasOwnProperty(coordinatesKey) && def[coordinatesKey] != undefined) { + def[xKey] = def[coordinatesKey][0].toString(); + def[yKey] = def[coordinatesKey][1].toString(); + delete def[coordinatesKey]; + } + obj[xKey] = def[xKey].toString(); + obj[yKey] = def[yKey].toString(); + }; + return GraphObjectGenerator; + }(KGAuthor.AuthoringObject)); + KGAuthor.GraphObjectGenerator = GraphObjectGenerator; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var DefObject = /** @class */ (function (_super) { + __extends(DefObject, _super); + function DefObject(def, graph) { + var _this = this; + def.inDef = true; + _this = _super.call(this, def, graph) || this; + return _this; + } + DefObject.prototype.parseSelf = function (parsedData) { + delete this.def.clipPathName; + parsedData.clipPaths.push(this.def); + return parsedData; + }; + return DefObject; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.DefObject = DefObject; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var ClipPath = /** @class */ (function (_super) { + __extends(ClipPath, _super); + function ClipPath() { + return _super !== null && _super.apply(this, arguments) || this; + } + ClipPath.prototype.parseSelf = function (parsedData) { + delete this.def.clipPathName; + parsedData.clipPaths.push(this.def); + return parsedData; + }; + return ClipPath; + }(KGAuthor.DefObject)); + KGAuthor.ClipPath = ClipPath; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Marker = /** @class */ (function (_super) { + __extends(Marker, _super); + function Marker(def, graph) { + var _this = _super.call(this, def, graph) || this; + _this.maskPath = def.maskPath; + return _this; + } + Marker.prototype.parseSelf = function (parsedData) { + parsedData.markers.push(this.def); + return parsedData; + }; + return Marker; + }(KGAuthor.DefObject)); + KGAuthor.Marker = Marker; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var ArrowDef = /** @class */ (function (_super) { + __extends(ArrowDef, _super); + function ArrowDef(def, graph) { + var _this = this; + def.name = KG.randomString(10); + _this = _super.call(this, def, graph) || this; + _this.color = def.color; + _this.arrowPath = def.arrowPath; + return _this; + } + return ArrowDef; + }(KGAuthor.Marker)); + KGAuthor.ArrowDef = ArrowDef; + var StartArrow = /** @class */ (function (_super) { + __extends(StartArrow, _super); + function StartArrow(def, graph) { + var _this = this; + def.refX = 2; + def.maskPath = "M10,1 L10,12 L0,7 L0,5 L10,1"; + def.arrowPath = "M11,2 L11,11 L2,6 L11,2"; + _this = _super.call(this, def, graph) || this; + _this.markerType = 'StartArrow'; + return _this; + } + return StartArrow; + }(ArrowDef)); + KGAuthor.StartArrow = StartArrow; + var EndArrow = /** @class */ (function (_super) { + __extends(EndArrow, _super); + function EndArrow(def, graph) { + var _this = this; + def.refX = 11; + def.maskPath = "M3,1 L3,12 L12,7 L12,5 L3,1"; + def.arrowPath = "M2,2 L2,11 L10,6 L2,2"; + _this = _super.call(this, def, graph) || this; + _this.markerType = 'EndArrow'; + return _this; + } + return EndArrow; + }(ArrowDef)); + KGAuthor.EndArrow = EndArrow; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var GraphObject = /** @class */ (function (_super) { + __extends(GraphObject, _super); + function GraphObject(def, graph) { + var _this = this; + if (def.hasOwnProperty('clipPaths')) { + def.clipPathName = KG.randomString(10); + } + KG.setDefaults(def, { + name: KG.randomString(10) + }); + _this = _super.call(this, def, graph) || this; + var g = _this; + if (def.hasOwnProperty('color')) { + g.color = def.color; + } + if (def.hasOwnProperty("clipPaths")) { + var clipPathObjects = def.clipPaths.map(function (shape) { + var shapeType = Object.keys(shape)[0]; + var shapeDef = shape[shapeType]; + shapeDef.inDef = true; + return new KGAuthor[shapeType](shapeDef, graph); + }); + g.subObjects.push(new KGAuthor.ClipPath({ name: def.clipPathName, paths: clipPathObjects }, graph)); + } + return _this; + } + GraphObject.prototype.parseSelf = function (parsedData) { + parsedData.layers[this.layer].push(this); + return parsedData; + }; + return GraphObject; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.GraphObject = GraphObject; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Axis = /** @class */ (function (_super) { + __extends(Axis, _super); + function Axis(def, graph) { + var _this = this; + KG.setDefaults(def, { + yPixelOffset: 40, + xPixelOffset: 40 + }); + _this = _super.call(this, def, graph) || this; + var a = _this; + a.type = 'Axis'; + a.layer = 2; + if (def.hasOwnProperty('title') && ("" != def.title)) { + if (def.orient == 'bottom') { + a.subObjects.push(new KGAuthor.Label({ + text: def.title, + plainText: true, + x: KGAuthor.averageDefs(graph.xScale.min, graph.xScale.max), + y: graph.yScale.min, + yPixelOffset: -1 * def.yPixelOffset + }, graph)); + } + else if (def.orient == 'left') { + a.subObjects.push(new KGAuthor.Label({ + text: def.title, + plainText: true, + x: graph.xScale.min, + y: KGAuthor.averageDefs(graph.yScale.min, graph.yScale.max), + xPixelOffset: -1 * def.xPixelOffset, + rotate: 90 + }, graph)); + } + else if (def.orient == 'top') { + a.subObjects.push(new KGAuthor.Label({ + text: "\\text{" + def.title + "}", + x: KGAuthor.averageDefs(graph.xScale.min, graph.xScale.max), + y: graph.yScale.min, + yPixelOffset: def.yPixelOffset + }, graph)); + } + else { + a.subObjects.push(new KGAuthor.Label({ + text: "\\text{" + def.title + "}", + x: graph.xScale.min, + y: KGAuthor.averageDefs(graph.yScale.min, graph.yScale.max), + xPixelOffset: def.xPixelOffset, + rotate: 270 + }, graph)); + } + } + return _this; + } + return Axis; + }(KGAuthor.GraphObject)); + KGAuthor.Axis = Axis; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Grid = /** @class */ (function (_super) { + __extends(Grid, _super); + function Grid(def, graph) { + var _this = this; + def = def || {}; + _this = _super.call(this, def, graph) || this; + KG.setDefaults(def, { + strokeWidth: 1, + stroke: 'lightgrey', + lineStyle: 'dotted', + layer: 0, + xStep: 1, + yStep: 1 + }); + var g = _this; + g.subObjects = []; + for (var i = 0; i < 10; i++) { + var x = KGAuthor.multiplyDefs(i, def.xStep), y = KGAuthor.multiplyDefs(i, def.yStep); + var gxDef = KGAuthor.copyJSON(def), gyDef = KGAuthor.copyJSON(def); + gxDef.a = [x, graph.yScale.min]; + gxDef.b = [x, graph.yScale.max]; + gyDef.a = [graph.xScale.min, y]; + gyDef.b = [graph.xScale.max, y]; + g.subObjects.push(new KGAuthor.Segment(gxDef, graph)); + g.subObjects.push(new KGAuthor.Segment(gyDef, graph)); + } + return _this; + } + return Grid; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.Grid = Grid; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Curve = /** @class */ (function (_super) { + __extends(Curve, _super); + function Curve(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + KGAuthor.parseFn(def, 'fn', 'univariateFunction'); + KGAuthor.parseFn(def, 'xFn', 'parametricFunction'); + _this = _super.call(this, def, graph) || this; + var c = _this; + c.type = 'Curve'; + c.layer = def.layer || 1; + c.pts = def.pts || []; + if (def.hasOwnProperty('areaBelow')) { + KG.setDefaults(def.areaBelow, { + color: def.color + }); + KGAuthor.parseFill(def, 'areaBelow'); + KG.setDefaults(def.areaBelow, def.univariateFunction); + KGAuthor.parseFn(def.areaBelow, 'fn', 'univariateFunction1'); + c.subObjects.push(new KGAuthor.Area(def.areaBelow, graph)); + } + if (def.hasOwnProperty('areaAbove')) { + KG.setDefaults(def.areaBelow, { + color: def.color + }); + KGAuthor.parseFill(def, 'areaAbove'); + KG.setDefaults(def.areaAbove, def.univariateFunction); + KGAuthor.parseFn(def.areaAbove, 'fn', 'univariateFunction1'); + def.areaAbove.above = true; + c.subObjects.push(new KGAuthor.Area(def.areaAbove, graph)); + } + if (def.hasOwnProperty('label')) { + var labelDef = KGAuthor.copyJSON(def); + delete labelDef.label; + labelDef = KG.setDefaults(labelDef, def.label); + labelDef = KG.setDefaults(labelDef, { + fontSize: 12, + color: def.color + }); + if (def.hasOwnProperty('univariateFunction')) { + if (labelDef.hasOwnProperty('x') && def.univariateFunction.ind != 'y') { + labelDef.coordinates = [labelDef.x, c.yOfX(labelDef.x)]; + c.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + else if (labelDef.hasOwnProperty('y') && def.univariateFunction.ind != 'x') { + labelDef.coordinates = [c.xOfY(labelDef.y), labelDef.y]; + c.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + } + if (def.hasOwnProperty('parametricFunction')) { + if (labelDef.hasOwnProperty('t')) { + labelDef.coordinates = c.xyOfT(labelDef.t); + c.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + } + } + return _this; + } + Curve.prototype.yOfX = function (x) { + return "(" + KGAuthor.replaceVariable(this.def.univariateFunction.fn, '(x)', "(" + x + ")") + ")"; + }; + Curve.prototype.xOfY = function (y) { + var c = this; + if (c.def.univariateFunction.hasOwnProperty('yFn')) { + return "(" + KGAuthor.replaceVariable(c.def.univariateFunction.yFn, '(y)', "(" + y + ")") + ")"; + } + else { + return "(" + KGAuthor.replaceVariable(c.def.univariateFunction.fn, '(y)', "(" + y + ")") + ")"; + } + }; + Curve.prototype.xyOfT = function (t) { + return [ + KGAuthor.replaceVariable(this.def.parametricFunction.xFunction, '(t)', "(" + t + ")"), + KGAuthor.replaceVariable(this.def.parametricFunction.yFunction, '(t)', "(" + t + ")") + ]; + }; + Curve.prototype.parseSelf = function (parsedData) { + var c = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[c.name] = parsedData.calcs[c.name] || {}; + c.pts.forEach(function (p) { + if (p.hasOwnProperty('x')) { + parsedData.calcs[c.name][p['name']] = { + x: p['x'], + y: c.yOfX(p['x']) + }; + } + if (p.hasOwnProperty('y')) { + parsedData.calcs[c.name][p['name']] = { + x: c.xOfY(p['y']), + y: p['y'] + }; + } + }); + return parsedData; + }; + return Curve; + }(KGAuthor.GraphObject)); + KGAuthor.Curve = Curve; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Line = /** @class */ (function (_super) { + __extends(Line, _super); + function Line(def, graph) { + var _this = this; + KG.setDefaults(def, { + color: 'colors.orange' + }); + // may define line with two points + var xIntercept = def.xIntercept, yIntercept = def.yIntercept, slope = def.slope, invSlope = def.invSlope; + if (def.hasOwnProperty('point') && def.hasOwnProperty('point2')) { + // still need to handle infinite case + slope = KGAuthor.divideDefs(KGAuthor.subtractDefs(def.point[1], def.point2[1]), KGAuthor.subtractDefs(def.point[0], def.point2[0])); + yIntercept = KGAuthor.subtractDefs(def.point[1], KGAuthor.multiplyDefs(slope, def.point[0])); + invSlope = KGAuthor.divideDefs(KGAuthor.subtractDefs(def.point[0], def.point2[0]), KGAuthor.subtractDefs(def.point[1], def.point2[1])); + xIntercept = KGAuthor.subtractDefs(def.point[0], KGAuthor.multiplyDefs(invSlope, def.point[1])); + } + else if (def.hasOwnProperty('xIntercept') && def.hasOwnProperty('yIntercept')) { + slope = KGAuthor.negativeDef(KGAuthor.divideDefs(def.yIntercept, def.xIntercept)); + invSlope = KGAuthor.negativeDef(KGAuthor.divideDefs(def.xIntercept, def.yIntercept)); + } + else if (def.hasOwnProperty('point') && def.hasOwnProperty('yIntercept')) { + slope = KGAuthor.divideDefs(KGAuthor.subtractDefs(def.point[1], def.yIntercept), def.point[0]); + invSlope = KGAuthor.divideDefs(def.point[0], KGAuthor.subtractDefs(def.point[1], def.yIntercept)); + xIntercept = KGAuthor.negativeDef(KGAuthor.multiplyDefs(yIntercept, invSlope)); + } + else if (def.hasOwnProperty('slope') && def.hasOwnProperty('yIntercept')) { + invSlope = KGAuthor.invertDef(def.slope); + xIntercept = KGAuthor.negativeDef(KGAuthor.divideDefs(yIntercept, slope)); + } + else if (def.hasOwnProperty('invSlope') && def.hasOwnProperty('xIntercept')) { + slope = KGAuthor.invertDef(def.invSlope); + yIntercept = KGAuthor.negativeDef(KGAuthor.divideDefs(xIntercept, invSlope)); + } + else if (def.hasOwnProperty('invSlope') && def.hasOwnProperty('yIntercept')) { + slope = KGAuthor.invertDef(def.invSlope); + } + else if (def.hasOwnProperty('slope') && def.hasOwnProperty('point')) { + invSlope = KGAuthor.invertDef(def.slope); + xIntercept = KGAuthor.subtractDefs(def.point[0], KGAuthor.divideDefs(def.point[1], def.slope)); + yIntercept = KGAuthor.subtractDefs(def.point[1], KGAuthor.multiplyDefs(def.point[0], def.slope)); + } + else if (def.hasOwnProperty('invSlope') && def.hasOwnProperty('point')) { + slope = KGAuthor.invertDef(def.invSlope); + xIntercept = KGAuthor.subtractDefs(def.point[0], KGAuthor.divideDefs(def.point[1], slope)); + yIntercept = KGAuthor.subtractDefs(def.point[1], KGAuthor.multiplyDefs(def.point[0], slope)); + } + else if (def.hasOwnProperty('slope')) { + invSlope = KGAuthor.invertDef(def.slope); + xIntercept = 0; + yIntercept = 0; + } + else if (def.hasOwnProperty('yIntercept')) { + invSlope = Infinity; + xIntercept = null; + yIntercept = def.yIntercept; + slope = 0; + } + else if (def.hasOwnProperty('xIntercept')) { + invSlope = 0; + xIntercept = def.xIntercept; + yIntercept = null; + slope = Infinity; + } + else { + xIntercept = 0; + yIntercept = 0; + slope = KGAuthor.divideDefs(def.point[1], def.point[0]); + invSlope = KGAuthor.divideDefs(def.point[0], def.point[1]); + } + def.univariateFunction = { + fn: yIntercept + " + (" + slope + ")*(x)", + yFn: xIntercept + " + (" + invSlope + ")*(y)", + ind: "((" + invSlope + " == 0) ? 'y' : 'x')", + samplePoints: 2 + }; + if (def.hasOwnProperty('min')) { + def.univariateFunction.min = def.min; + delete def.min; + } + if (def.hasOwnProperty('max')) { + def.univariateFunction.max = def.max; + delete def.max; + } + _this = _super.call(this, def, graph) || this; + var l = _this; + l.xIntercept = xIntercept; + l.yIntercept = yIntercept; + l.slope = slope; + l.invSlope = invSlope; + if (def.hasOwnProperty('label') && def.label.hasOwnProperty('r')) { + var labelDef = KGAuthor.copyJSON(def); + delete labelDef.label; + labelDef = KG.setDefaults(labelDef, def.label); + labelDef = KG.setDefaults(labelDef, { + fontSize: 12, + color: def.color, + coordinates: lineRadius(l, labelDef.r, labelDef.center) + }); + console.log(labelDef); + l.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + return _this; + } + Line.prototype.parseSelf = function (parsedData) { + var l = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + var d = { + slope: l.slope.toString(), + invSlope: l.invSlope.toString() + }; + if (l.xIntercept) { + d.xIntercept = l.xIntercept.toString(); + } + if (l.yIntercept) { + d.yIntercept = l.yIntercept.toString(); + } + if (!l.xIntercept) { + d.fixedPoint = "((" + d.yIntercept + ")/(1 - " + l.slope.toString() + "))"; + } + else if (!l.yIntercept) { + d.fixedPoint = "((" + d.xIntercept + ")/(1 - " + l.invSlope.toString() + "))"; + } + else { + d.fixedPoint = "(" + d.invSlope + " == 0 ? (" + d.xIntercept + ")/(1 - " + l.invSlope.toString() + ") : (" + d.yIntercept + ")/(1 - " + l.slope.toString() + "))"; + } + l.pts.forEach(function (p) { + if (p.hasOwnProperty('r')) { + var coordinates = lineRadius(l, p['r'], p['center']); + parsedData.calcs[l.name][p['name']] = { + x: coordinates[0], + y: coordinates[1] + }; + } + }); + parsedData.calcs[l.name] = KG.setDefaults(parsedData.calcs[l.name] || {}, d); + return parsedData; + }; + return Line; + }(KGAuthor.Curve)); + KGAuthor.Line = Line; + function lineIntersection(l1, l2) { + var x = KGAuthor.divideDefs(KGAuthor.addDefs(l1.xIntercept, KGAuthor.multiplyDefs(l1.invSlope, l2.yIntercept)), KGAuthor.subtractDefs("1", KGAuthor.multiplyDefs(l1.invSlope, l2.slope))); + var y = l2.yOfX(x); + return [x, y]; + } + KGAuthor.lineIntersection = lineIntersection; + // Find the intersection of a line with a circle of radius r + function lineRadius(line, r, center) { + var a = KGAuthor.addDefs(1, KGAuthor.squareDef(line.slope)); + var b = KGAuthor.multiplyDefs(2, KGAuthor.multiplyDefs(line.slope, line.yIntercept)); + var c = KGAuthor.subtractDefs(KGAuthor.squareDef(line.yIntercept), KGAuthor.squareDef(r)); + if (center) { + var cx = center[0]; + var cy = center[1] || 0; + b = KGAuthor.subtractDefs(b, KGAuthor.multiplyDefs(2, KGAuthor.addDefs(center[0], KGAuthor.multiplyDefs(line.slope, cy)))); + c = KGAuthor.addDefs(c, KGAuthor.subtractDefs(KGAuthor.addDefs(KGAuthor.squareDef(cx), KGAuthor.squareDef(cy)), KGAuthor.multiplyDefs(2, KGAuthor.multiplyDefs(line.yIntercept, cy)))); + } + var x = KGAuthor.quadraticRootDef(a, b, c, true); + var y = line.yOfX(x); + return [x, y]; + } + KGAuthor.lineRadius = lineRadius; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Ellipse = /** @class */ (function (_super) { + __extends(Ellipse, _super); + function Ellipse(def, graph) { + var _this = this; + KG.setDefaults(def, { + color: 'colors.blue', + opacity: 0.2, + rx: 1, + ry: def.rx + }); + def = KGAuthor.setFillColor(def); + def = KGAuthor.setStrokeColor(def); + _this = _super.call(this, def, graph) || this; + var c = _this; + c.type = 'Circle'; + c.layer = def.layer || 0; + // may define the center using 'coordinates' or 'center' or 'c': + if (def.hasOwnProperty('c')) { + c.extractCoordinates('c'); + } + else if (def.hasOwnProperty('center')) { + c.extractCoordinates('center'); + } + else { + c.extractCoordinates(); + } + def = KGAuthor.makeDraggable(def); + if (def.hasOwnProperty('label')) { + var labelDef = KGAuthor.copyJSON(def); + delete labelDef.label; + labelDef = KG.setDefaults(labelDef, def.label); + labelDef = KG.setDefaults(labelDef, { + fontSize: 10, + color: def.color, + bgcolor: null + }); + c.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + return _this; + } + return Ellipse; + }(KGAuthor.GraphObject)); + KGAuthor.Ellipse = Ellipse; + var Circle = /** @class */ (function (_super) { + __extends(Circle, _super); + function Circle(def, graph) { + var _this = this; + if (def.hasOwnProperty('radius')) { + def.r = def.radius; + delete def.radius; + } + if (def.hasOwnProperty('r')) { + def.rx = def.r; + def.ry = def.r; + } + _this = _super.call(this, def, graph) || this; + return _this; + } + return Circle; + }(Ellipse)); + KGAuthor.Circle = Circle; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Point = /** @class */ (function (_super) { + __extends(Point, _super); + function Point(def, graph) { + var _this = this; + KG.setDefaults(def, { + color: 'colors.blue' + }); + def = KGAuthor.setFillColor(def); + _this = _super.call(this, def, graph) || this; + var p = _this; + p.type = 'Point'; + p.layer = 3; + p.extractCoordinates(); + def = KGAuthor.makeDraggable(def); + if (def.hasOwnProperty('label')) { + var labelDef = KGAuthor.copyJSON(def); + delete labelDef.label; + labelDef = KG.setDefaults(labelDef, def.label); + labelDef = KG.setDefaults(labelDef, { + fontSize: 10, + position: 'bl', + color: def.color, + bgcolor: null + }); + p.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + if (def.hasOwnProperty('droplines')) { + if (def.droplines.hasOwnProperty('vertical')) { + var verticalDroplineDef = KGAuthor.copyJSON(def); + // only drag vertical droplines horizontally + if (verticalDroplineDef.hasOwnProperty('drag')) { + verticalDroplineDef.drag = verticalDroplineDef.drag.filter(function (value, index, arr) { return ((value.directions == 'x') || value.hasOwnProperty('horizontal')); }); + } + if (def.droplines.hasOwnProperty('top')) { + verticalDroplineDef.y = graph.yScale.max; + var xTopAxisLabelDef = KGAuthor.copyJSON(verticalDroplineDef); + xTopAxisLabelDef.y = 'OPPAXIS'; + KG.setDefaults(xTopAxisLabelDef, { + text: def.droplines.top, + fontSize: 10 + }); + p.subObjects.push(new KGAuthor.Label(xTopAxisLabelDef, graph)); + } + p.subObjects.push(new KGAuthor.VerticalDropline(verticalDroplineDef, graph)); + var xAxisLabelDef = KGAuthor.copyJSON(verticalDroplineDef); + xAxisLabelDef.y = 'AXIS'; + KG.setDefaults(xAxisLabelDef, { + text: def.droplines.vertical, + fontSize: 10 + }); + p.subObjects.push(new KGAuthor.Label(xAxisLabelDef, graph)); + } + if (def.droplines.hasOwnProperty('horizontal')) { + var horizontalDroplineDef = KGAuthor.copyJSON(def); + // only drag horizontal droplines vertically + if (horizontalDroplineDef.hasOwnProperty('drag')) { + horizontalDroplineDef.drag = horizontalDroplineDef.drag.filter(function (value, index, arr) { return ((value.directions == 'y') || value.hasOwnProperty('vertical')); }); + } + p.subObjects.push(new KGAuthor.HorizontalDropline(horizontalDroplineDef, graph)); + var yAxisLabelDef = KGAuthor.copyJSON(horizontalDroplineDef); + yAxisLabelDef.x = 'AXIS'; + KG.setDefaults(yAxisLabelDef, { + text: def.droplines.horizontal, + fontSize: 10 + }); + p.subObjects.push(new KGAuthor.Label(yAxisLabelDef, graph)); + } + } + return _this; + } + Point.prototype.parseSelf = function (parsedData) { + var p = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[p.name] = { + x: p.x.toString(), + y: p.y.toString() + }; + return parsedData; + }; + return Point; + }(KGAuthor.GraphObject)); + KGAuthor.Point = Point; + var LineCircleIntersection = /** @class */ (function (_super) { + __extends(LineCircleIntersection, _super); + function LineCircleIntersection(def, graph) { + var _this = this; + var l = new KGAuthor.Line(def.lineDef, graph); + var coordinates = KGAuthor.lineRadius(l, def.radius); + KG.setDefaults(def, { + coordinates: coordinates, + positive: true + }); + _this = _super.call(this, def, graph) || this; + var lci = _this; + lci.subObjects.push(l); + return _this; + } + return LineCircleIntersection; + }(Point)); + KGAuthor.LineCircleIntersection = LineCircleIntersection; + var Points = /** @class */ (function (_super) { + __extends(Points, _super); + function Points(def, graph) { + var _this = _super.call(this, def, graph) || this; + var ps = _this; + var coordinateArray = def.coordinates; + coordinateArray.forEach(function (c) { + var pointDef = JSON.parse(JSON.stringify(def)); + pointDef.coordinates = c; + ps.subObjects.push(new Point(pointDef, graph)); + }); + return _this; + } + return Points; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.Points = Points; + var Node = /** @class */ (function (_super) { + __extends(Node, _super); + function Node(def, tree) { + var _this = this; + KG.setDefaults(def, { + name: KG.randomString(10) + }); + if (def.hasOwnProperty('payoffs')) { + var payoff1 = "\\\\color{${colors.player1}}{" + def.payoffs.player1 + "}"; + var comma = "\\\\color{black}{,\\\\ }"; + var payoff2 = "\\\\color{${colors.player2}}{" + def.payoffs.player2 + "}"; + def.label = { + text: "`" + payoff1 + comma + payoff2 + "`", + position: def.payoffs.position || 'l', + fontSize: 14 + }; + } + _this = _super.call(this, def, tree) || this; + var node = _this; + tree.nodeCoordinates[def.name] = [node.x, node.y]; + node.name = def.name; + if (def.hasOwnProperty('children')) { + var n = def.children.length; + for (var i = 0; i < n; i++) { + var childNum = i + 1; // number of child, with first being 1 rather than 0; + var nodeDef = def.children[i]; + KG.setDefaults(nodeDef, { + name: KG.randomString(10) + }); + var edgeDef = { + node1: def.name, + node2: nodeDef.name, + color: def.color, + label: { text: nodeDef.edgeLabel } + }; + // if selectChildren is true, create a parameter called "select[nodeName]" + // which is used to select which child is active + // when true, clicking on an edge selects that edge + // unless the edge is already selected, in which case no edge is selected + if (def.hasOwnProperty('childSelectParam')) { + var param = def.childSelectParam; + var transitions = new Array(n + 1); + transitions[0] = childNum; + for (var j = 1; j < n + 1; j++) { + transitions[j] = (j == childNum) ? 0 : childNum; + } + edgeDef['click'] = [{ + param: param, + transitions: transitions + }]; + edgeDef['strokeWidth'] = "((params." + def.childSelectParam + " == " + childNum + ") ? 6 : 2)"; + } + tree.subObjects.push(new Node(nodeDef, tree)); + tree.subObjects.push(new KGAuthor.Edge(edgeDef, tree)); + } + } + return _this; + } + return Node; + }(Point)); + KGAuthor.Node = Node; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Segment = /** @class */ (function (_super) { + __extends(Segment, _super); + function Segment(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + if (def.hasOwnProperty('startArrow')) { + def.startArrowName = graph.getStartArrowName(def.color); + } + if (def.hasOwnProperty('endArrow')) { + def.endArrowName = graph.getEndArrowName(def.color); + } + _this = _super.call(this, def, graph) || this; + var s = _this; + s.type = 'Segment'; + s.layer = 1; + s.extractCoordinates('a', 'x1', 'y1'); + s.extractCoordinates('b', 'x2', 'y2'); + // new way of trimming + if (def.hasOwnProperty('trim')) { + console.log('implementing trimming'); + var x1 = s.x1; + var y1 = s.y1; + var x2 = s.x2; + var y2 = s.y2; + s.def.x1 = KGAuthor.averageDefs(x2, x1, def.trim); + s.def.x2 = KGAuthor.averageDefs(x1, x2, def.trim); + s.def.y1 = KGAuthor.averageDefs(y2, y1, def.trim); + s.def.y2 = KGAuthor.averageDefs(y1, y2, def.trim); + } + if (def.hasOwnProperty('label')) { + var labelDef = KGAuthor.copyJSON(def); + delete labelDef.label; + if (typeof def.label === "string") { + def.label = { text: def.label }; + } + labelDef = KG.setDefaults(def.label || {}, labelDef); + labelDef = KG.setDefaults(labelDef, { + fontSize: 12, + color: def.color, + location: 0.5 + }); + labelDef.coordinates = [ + KGAuthor.averageDefs(s.x1, s.x2, labelDef.location), + KGAuthor.averageDefs(s.y1, s.y2, labelDef.location) + ]; + s.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + if (def.hasOwnProperty('handles')) { + var aPointDef = { + x: s.x1, + y: s.y1, + color: def.color, + r: 4, + draggable: def.draggable, + show: def.show + }; + var bPointDef = { + x: s.x2, + y: s.y2, + color: def.color, + r: 4, + draggable: def.draggable, + show: def.show + }; + s.subObjects.push(new KGAuthor.Point(aPointDef, graph)); + s.subObjects.push(new KGAuthor.Point(bPointDef, graph)); + } + return _this; + } + return Segment; + }(KGAuthor.GraphObject)); + KGAuthor.Segment = Segment; + var CrossGraphSegment = /** @class */ (function (_super) { + __extends(CrossGraphSegment, _super); + function CrossGraphSegment(def, graph) { + var _this = this; + def.xScale2Name = ''; + _this = _super.call(this, def, graph) || this; + return _this; + } + return CrossGraphSegment; + }(Segment)); + KGAuthor.CrossGraphSegment = CrossGraphSegment; + var Edge = /** @class */ (function (_super) { + __extends(Edge, _super); + function Edge(def, tree) { + var _this = this; + def.a = tree.nodeCoordinates[def.node1]; + def.b = tree.nodeCoordinates[def.node2]; + _this = _super.call(this, def, tree) || this; + return _this; + } + return Edge; + }(Segment)); + KGAuthor.Edge = Edge; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Arrow = /** @class */ (function (_super) { + __extends(Arrow, _super); + function Arrow(def, graph) { + var _this = this; + def.endArrow = true; + if (def.hasOwnProperty('double')) { + def.startArrow = def.double; + } + def.a = def.begin; + def.b = def.end; + _this = _super.call(this, def, graph) || this; + return _this; + } + return Arrow; + }(KGAuthor.Segment)); + KGAuthor.Arrow = Arrow; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Dropline = /** @class */ (function (_super) { + __extends(Dropline, _super); + function Dropline(def, graph) { + var _this = this; + def.lineStyle = 'dotted'; + delete def.label; + _this = _super.call(this, def, graph) || this; + return _this; + } + return Dropline; + }(KGAuthor.Segment)); + KGAuthor.Dropline = Dropline; + var VerticalDropline = /** @class */ (function (_super) { + __extends(VerticalDropline, _super); + function VerticalDropline(def, graph) { + var _this = this; + def.a = [def.x, graph.xScale.intercept]; + def.b = [def.x, def.y]; + _this = _super.call(this, def, graph) || this; + return _this; + } + return VerticalDropline; + }(Dropline)); + KGAuthor.VerticalDropline = VerticalDropline; + var CrossGraphVerticalDropline = /** @class */ (function (_super) { + __extends(CrossGraphVerticalDropline, _super); + function CrossGraphVerticalDropline(def, graph) { + var _this = this; + def.xScale2Name = ''; + _this = _super.call(this, def, graph) || this; + return _this; + } + return CrossGraphVerticalDropline; + }(VerticalDropline)); + KGAuthor.CrossGraphVerticalDropline = CrossGraphVerticalDropline; + var HorizontalDropline = /** @class */ (function (_super) { + __extends(HorizontalDropline, _super); + function HorizontalDropline(def, graph) { + var _this = this; + def.a = [graph.yScale.intercept, def.y]; + def.b = [def.x, def.y]; + _this = _super.call(this, def, graph) || this; + return _this; + } + return HorizontalDropline; + }(Dropline)); + KGAuthor.HorizontalDropline = HorizontalDropline; + var CrossGraphHorizontalDropline = /** @class */ (function (_super) { + __extends(CrossGraphHorizontalDropline, _super); + function CrossGraphHorizontalDropline(def, graph) { + var _this = this; + def.xScale2Name = ''; + _this = _super.call(this, def, graph) || this; + return _this; + } + return CrossGraphHorizontalDropline; + }(HorizontalDropline)); + KGAuthor.CrossGraphHorizontalDropline = CrossGraphHorizontalDropline; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Area = /** @class */ (function (_super) { + __extends(Area, _super); + function Area(def, graph) { + var _this = this; + KG.setDefaults(def, { + color: 'colors.blue', + opacity: 0.2 + }); + def = KGAuthor.setFillColor(def); + KGAuthor.parseFn(def, 'fn', 'univariateFunction1'); + KGAuthor.parseFn(def, 'fn1', 'univariateFunction1'); + KGAuthor.parseFn(def, 'fn2', 'univariateFunction2'); + _this = _super.call(this, def, graph) || this; + _this.type = 'Area'; + _this.layer = def.layer || 0; + return _this; + } + return Area; + }(KGAuthor.GraphObject)); + KGAuthor.Area = Area; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Rectangle = /** @class */ (function (_super) { + __extends(Rectangle, _super); + function Rectangle(def, graph) { + var _this = this; + KGAuthor.setFillColor(def); + _this = _super.call(this, def, graph) || this; + var rect = _this; + rect.type = 'Rectangle'; + rect.layer = def.layer || 0; + rect.extractCoordinates('a', 'x1', 'y1'); + rect.extractCoordinates('b', 'x2', 'y2'); + if (def.hasOwnProperty('label')) { + var labelDef = KGAuthor.copyJSON(def); + delete labelDef.label; + labelDef = KG.setDefaults(labelDef, def.label); + labelDef = KG.setDefaults(labelDef, { + fontSize: 10, + color: def.color, + bgcolor: null, + x: KGAuthor.averageDefs(rect['x1'], rect['x2']), + y: KGAuthor.averageDefs(rect['y1'], rect['y2']) + }); + rect.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + return _this; + } + return Rectangle; + }(KGAuthor.GraphObject)); + KGAuthor.Rectangle = Rectangle; + var Overlap = /** @class */ (function (_super) { + __extends(Overlap, _super); + function Overlap(def, graph) { + var _this = this; + var shape1name = KG.randomString(10), shape2name = KG.randomString(10); + def = KGAuthor.setFillColor(def); + KG.setDefaults(def, { + x1: graph.def.xAxis.min, + x2: graph.def.xAxis.max, + y1: graph.def.yAxis.min, + y2: graph.def.yAxis.max, + clipPathName: shape1name, + clipPathName2: shape2name + }); + _this = _super.call(this, def, graph) || this; + var r = _this; + var clipPathObjects = def.shapes.map(function (shape) { + var shapeType = Object.keys(shape)[0]; + var shapeDef = shape[shapeType]; + shapeDef.inDef = true; + return new KGAuthor[shapeType](shapeDef, graph); + }); + // As of now this does at most two; can make more recursive in the future but this handles 80% of the use cases + r.subObjects.push(new KGAuthor.ClipPath({ name: shape1name, paths: [clipPathObjects[0]] }, graph)); + r.subObjects.push(new KGAuthor.ClipPath({ name: shape2name, paths: [clipPathObjects[1]] }, graph)); + return _this; + } + return Overlap; + }(Rectangle)); + KGAuthor.Overlap = Overlap; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Contour = /** @class */ (function (_super) { + __extends(Contour, _super); + function Contour(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + _this = _super.call(this, def, graph) || this; + var c = _this; + c.type = 'Contour'; + c.layer = def.layer || 1; + if (def.hasOwnProperty('coordinates')) { + c.extractCoordinates(); + } + if (!def.hasOwnProperty('level')) { + def.level = def.fn.replace(/\(x\)/g, "(" + def.x + ")").replace(/\(y\)/g, "(" + def.y + ")"); + } + c.level = def.level; + return _this; + } + Contour.prototype.parseSelf = function (parsedData) { + var le = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs.contourLevel = le.level; + return parsedData; + }; + return Contour; + }(KGAuthor.GraphObject)); + KGAuthor.Contour = Contour; + var ContourMap = /** @class */ (function (_super) { + __extends(ContourMap, _super); + function ContourMap(def, graph) { + var _this = this; + KG.setDefaults(def, { + color: "grey", + strokeWidth: 0.5 + }); + _this = _super.call(this, def, graph) || this; + var m = _this; + m.type = 'ContourMap'; + m.layer = def.layer || 1; + m.subObjects = def.levels.map(function (level) { + var contourDef = KGAuthor.copyJSON(def); + delete contourDef.levels; + contourDef.level = level; + return new Contour(contourDef, graph); + }); + console.log('contours: ', m.subObjects); + return _this; + } + return ContourMap; + }(KGAuthor.GraphObject)); + KGAuthor.ContourMap = ContourMap; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var AngleMarker = /** @class */ (function (_super) { + __extends(AngleMarker, _super); + function AngleMarker(def, graph) { + var _this = this; + KG.setDefaults(def, { + name: 'angle', + color: 'colors.grey', + coordinates: [0, 0], + radians: false, + start: 0, + r: KGAuthor.multiplyDefs(0.05, KGAuthor.subtractDefs(graph.def.xAxis.max, graph.def.xAxis.min)), + strokeWidth: 0.75 + }); + def = KGAuthor.setStrokeColor(def); + if (def.hasOwnProperty("measure")) { + def.end = KGAuthor.addDefs(def.start, def.measure); + } + else { + def.measure = KGAuthor.subtractDefs(def.end, def.start); + } + // convert to radians unless already radians + var start = def.radians ? def.start : KGAuthor.multiplyDefs(def.start, 0.01745329252), measure = def.radians ? def.measure : KGAuthor.multiplyDefs(def.measure, 0.01745329252), end = def.radians ? def.end : KGAuthor.multiplyDefs(def.end, 0.01745329252), mid = KGAuthor.addDefs(start, KGAuthor.multiplyDefs(0.5, measure)); + def.parametricFunction = { + xFunction: KGAuthor.addDefs(def.coordinates[0], KGAuthor.multiplyDefs(def.r, "cos(t)")), + yFunction: KGAuthor.addDefs(def.coordinates[1], KGAuthor.multiplyDefs(def.r, "sin(t)")), + min: start, + max: end + }; + _this = _super.call(this, def, graph) || this; + var dm = _this; + dm.measureDegrees = def.radians ? KGAuthor.multiplyDefs(def.measure, 57.2957795131) : def.measure; + dm.measureRadians = KGAuthor.divideDefs(measure, Math.PI); + var labelDef = KG.setDefaults(def.label || {}, { + x: KGAuthor.addDefs(def.coordinates[0], KGAuthor.multiplyDefs(KGAuthor.multiplyDefs(1.7, def.r), "cos(" + mid + ")")), + y: KGAuthor.addDefs(def.coordinates[1], KGAuthor.multiplyDefs(KGAuthor.multiplyDefs(1.7, def.r), "sin(" + mid + ")")), + fontSize: 8, + color: def.stroke, + bgcolor: "none", + radians: false, + show: def.show + }); + var labelTextRadians = "`${calcs." + dm.name + ".measureRadians.toFixed(2)}\\\\pi`", labelTextDegrees = "`${calcs." + dm.name + ".measureDegrees.toFixed(0)}^{\\\\circ}`"; + labelDef.text = labelDef.hasOwnProperty('text') ? def.label.text : labelDef.radians ? labelTextRadians : labelTextDegrees; + dm.subObjects.push(new KGAuthor.Label(labelDef, graph)); + return _this; + } + AngleMarker.prototype.parseSelf = function (parsedData) { + var dm = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[dm.name] = { + measureDegrees: dm.measureDegrees.toString(), + measureRadians: dm.measureRadians.toString() + }; + return parsedData; + }; + return AngleMarker; + }(KGAuthor.Curve)); + KGAuthor.AngleMarker = AngleMarker; + var Angle = /** @class */ (function (_super) { + __extends(Angle, _super); + function Angle(def, graph) { + var _this = this; + var A = new KGAuthor.Point(def.pointA, graph), B = new KGAuthor.Point(def.pointB, graph), C = new KGAuthor.Point(def.pointC, graph); + def.start = "atan2(" + A.y + " - " + B.y + "," + A.x + " - " + B.x + ")"; + def.end = "atan2(" + C.y + " - " + B.y + "," + C.x + " - " + B.x + ")"; + def.coordinates = [B.x, B.y]; + def.radians = true; + KG.setDefaults(def, { + label: { + radians: false + } + }); + _this = _super.call(this, def, graph) || this; + var a = _this; + a.subObjects.push(A); + a.subObjects.push(B); + a.subObjects.push(C); + if (def.showSegments) { + var ABdef = KGAuthor.copyJSON(def), CBdef = KGAuthor.copyJSON(def); + ABdef.a = [B.x, B.y]; + ABdef.b = [A.x, A.y]; + delete ABdef.label; + a.subObjects.push(new KGAuthor.Segment(ABdef, graph)); + CBdef.a = [B.x, B.y]; + CBdef.b = [C.x, C.y]; + delete CBdef.label; + a.subObjects.push(new KGAuthor.Segment(CBdef, graph)); + } + return _this; + } + return Angle; + }(AngleMarker)); + KGAuthor.Angle = Angle; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxObject = /** @class */ (function (_super) { + __extends(MathboxObject, _super); + function MathboxObject(def) { + var _this = _super.call(this, def) || this; + _this.mb = def.mb; + return _this; + } + return MathboxObject; + }(KGAuthor.AuthoringObject)); + KGAuthor.MathboxObject = MathboxObject; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxAxis = /** @class */ (function (_super) { + __extends(MathboxAxis, _super); + function MathboxAxis(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxAxis'; + return _this; + } + return MathboxAxis; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxAxis = MathboxAxis; + var MathboxXAxis = /** @class */ (function (_super) { + __extends(MathboxXAxis, _super); + function MathboxXAxis(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxXAxis'; + return _this; + } + return MathboxXAxis; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxXAxis = MathboxXAxis; + var MathboxYAxis = /** @class */ (function (_super) { + __extends(MathboxYAxis, _super); + function MathboxYAxis(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxYAxis'; + return _this; + } + return MathboxYAxis; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxYAxis = MathboxYAxis; + var MathboxZAxis = /** @class */ (function (_super) { + __extends(MathboxZAxis, _super); + function MathboxZAxis(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxZAxis'; + return _this; + } + return MathboxZAxis; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxZAxis = MathboxZAxis; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxPoint = /** @class */ (function (_super) { + __extends(MathboxPoint, _super); + function MathboxPoint(def) { + var _this = _super.call(this, def) || this; + var p = _this; + p.type = 'MathboxPoint'; + if (def.hasOwnProperty('droplines')) { + // vertical dropline to bottom plane + p.subObjects.push(new KGAuthor.MathboxLine({ + mb: def.mb, + x1: def.x, + x2: def.x, + y1: def.y, + y2: def.y, + z1: 0, + z2: def.z, + stroke: def.stroke, + linestyle: 'dotted' + })); + // dropline to x axis; assume min is 0 for now + p.subObjects.push(new KGAuthor.MathboxLine({ + mb: def.mb, + x1: def.x, + x2: 0, + y1: def.y, + y2: def.y, + z1: 0, + z2: 0, + stroke: def.stroke, + linestyle: 'dotted' + })); + // dropline to y axis; assume min is 0 for now + p.subObjects.push(new KGAuthor.MathboxLine({ + mb: def.mb, + x1: def.x, + x2: def.x, + y1: def.y, + y2: 0, + z1: 0, + z2: 0, + stroke: def.stroke, + linestyle: 'dotted' + })); + } + return _this; + } + return MathboxPoint; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxPoint = MathboxPoint; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxLine = /** @class */ (function (_super) { + __extends(MathboxLine, _super); + function MathboxLine(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxLine'; + return _this; + } + return MathboxLine; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxLine = MathboxLine; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxLabel = /** @class */ (function (_super) { + __extends(MathboxLabel, _super); + function MathboxLabel(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxLabel'; + return _this; + } + return MathboxLabel; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxLabel = MathboxLabel; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxArea = /** @class */ (function (_super) { + __extends(MathboxArea, _super); + function MathboxArea(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxAxis'; + return _this; + } + return MathboxArea; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxArea = MathboxArea; + var Area3D = /** @class */ (function (_super) { + __extends(Area3D, _super); + function Area3D() { + return _super !== null && _super.apply(this, arguments) || this; + } + return Area3D; + }(MathboxArea)); + KGAuthor.Area3D = Area3D; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxPlane = /** @class */ (function (_super) { + __extends(MathboxPlane, _super); + function MathboxPlane(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxPlane'; + return _this; + } + return MathboxPlane; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxPlane = MathboxPlane; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxFunctionSurface = /** @class */ (function (_super) { + __extends(MathboxFunctionSurface, _super); + function MathboxFunctionSurface(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxFunctionSurface'; + return _this; + } + return MathboxFunctionSurface; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxFunctionSurface = MathboxFunctionSurface; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxCurve = /** @class */ (function (_super) { + __extends(MathboxCurve, _super); + function MathboxCurve(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxCurve'; + return _this; + } + return MathboxCurve; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxCurve = MathboxCurve; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var DivObject = /** @class */ (function (_super) { + __extends(DivObject, _super); + function DivObject() { + return _super !== null && _super.apply(this, arguments) || this; + } + DivObject.prototype.parseSelf = function (parsedData) { + parsedData.divs.push(this); + return parsedData; + }; + return DivObject; + }(KGAuthor.GraphObject)); + KGAuthor.DivObject = DivObject; + var Div = /** @class */ (function (_super) { + __extends(Div, _super); + function Div(def) { + var _this = _super.call(this, def) || this; + _this.type = "Div"; + return _this; + } + return Div; + }(DivObject)); + KGAuthor.Div = Div; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var PositionedDiv = /** @class */ (function (_super) { + __extends(PositionedDiv, _super); + function PositionedDiv(def, divContainer) { + var _this = this; + delete def.xAxis; + delete def.yAxis; + def.xScaleName = divContainer.xScale.name; + def.yScaleName = divContainer.yScale.name; + _this = _super.call(this, def) || this; + _this.type = 'PositionedDiv'; + return _this; + } + return PositionedDiv; + }(KGAuthor.DivObject)); + KGAuthor.PositionedDiv = PositionedDiv; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Table = /** @class */ (function (_super) { + __extends(Table, _super); + function Table(def) { + var _this = _super.call(this, def) || this; + _this.type = 'Table'; + return _this; + } + return Table; + }(KGAuthor.Div)); + KGAuthor.Table = Table; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Label = /** @class */ (function (_super) { + __extends(Label, _super); + function Label(def, graph) { + var _this = this; + var xAxisIntercept = 0, yAxisIntercept = 0; + if (graph.def.hasOwnProperty('xAxis')) { + if (graph.def.xAxis.hasOwnProperty('intercept')) { + xAxisIntercept = graph.def.xAxis.intercept; + } + } + if (graph.def.hasOwnProperty('yAxis')) { + if (graph.def.yAxis.hasOwnProperty('intercept')) { + yAxisIntercept = graph.def.yAxis.intercept; + } + } + if (def.x == 'AXIS') { + def.x = yAxisIntercept; + def.position = "r"; + } + if (def.y == 'AXIS') { + def.y = xAxisIntercept; + def.position = "t"; + } + if (def.hasOwnProperty('position')) { + if (def.position.toLowerCase() == 'bl') { + def.xPixelOffset = 5; + def.yPixelOffset = def.fontSize; + def.align = 'left'; + } + if (def.position.toLowerCase() == 'tl') { + def.xPixelOffset = 5; + def.yPixelOffset = -(def.fontSize + 2); + def.align = 'left'; + } + if (def.position.toLowerCase() == 'tr') { + def.xPixelOffset = -5; + def.yPixelOffset = -(def.fontSize + 2); + def.align = 'right'; + } + if (def.position.toLowerCase() == 'br') { + def.xPixelOffset = -5; + def.yPixelOffset = def.fontSize; + def.align = 'right'; + } + if (def.position.toLowerCase() == 'tr') { + def.xPixelOffset = -5; + def.yPixelOffset = -(def.fontSize + 2); + def.align = 'right'; + } + if (def.position.toLowerCase() == 't') { + def.yPixelOffset = -(def.fontSize + 5); + } + if (def.position.toLowerCase() == 'b') { + def.yPixelOffset = def.fontSize + 2; + } + if (def.position.toLowerCase() == 'r') { + def.xPixelOffset = -8; + def.align = 'right'; + } + if (def.position.toLowerCase() == 'l') { + def.xPixelOffset = 8; + def.align = 'left'; + } + } + _this = _super.call(this, def, graph) || this; + _this.type = 'Label'; + _this.extractCoordinates(); + return _this; + } + return Label; + }(KGAuthor.DivObject)); + KGAuthor.Label = Label; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Sidebar = /** @class */ (function (_super) { + __extends(Sidebar, _super); + function Sidebar(def) { + var _this = this; + def.controls.forEach(function (controlDef) { + KGAuthor.parseControlsDef(controlDef); + }); + _this = _super.call(this, def) || this; + _this.type = 'Sidebar'; + return _this; + } + return Sidebar; + }(KGAuthor.DivObject)); + KGAuthor.Sidebar = Sidebar; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Explanation = /** @class */ (function (_super) { + __extends(Explanation, _super); + function Explanation(def) { + var _this = _super.call(this, def) || this; + _this.type = 'Explanation'; + return _this; + } + return Explanation; + }(KGAuthor.DivObject)); + KGAuthor.Explanation = Explanation; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + function parseControlsDef(controlDef) { + if (controlDef.hasOwnProperty('radioGroup')) { + controlDef.radios = controlDef.radioGroup.options.map(function (option, index) { + return { + param: controlDef.radioGroup.param, + optionValue: index, + label: "\\text{" + option + "}" + }; + }); + } + } + KGAuthor.parseControlsDef = parseControlsDef; + var Controls = /** @class */ (function (_super) { + __extends(Controls, _super); + function Controls(def) { + var _this = this; + parseControlsDef(def); + _this = _super.call(this, def) || this; + _this.type = 'Controls'; + return _this; + } + return Controls; + }(KGAuthor.DivObject)); + KGAuthor.Controls = Controls; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var GameMatrix = /** @class */ (function (_super) { + __extends(GameMatrix, _super); + function GameMatrix(def) { + var _this = _super.call(this, def) || this; + _this.type = 'GameMatrix'; + return _this; + } + return GameMatrix; + }(KGAuthor.DivObject)); + KGAuthor.GameMatrix = GameMatrix; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var GeoGebraApplet = /** @class */ (function (_super) { + __extends(GeoGebraApplet, _super); + function GeoGebraApplet(def) { + var _this = _super.call(this, def) || this; + _this.type = 'GeoGebraApplet'; + return _this; + } + return GeoGebraApplet; + }(KGAuthor.DivObject)); + KGAuthor.GeoGebraApplet = GeoGebraApplet; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Mathbox = /** @class */ (function (_super) { + __extends(Mathbox, _super); + function Mathbox(def) { + var _this = _super.call(this, def) || this; + var mb = _this; + mb.type = 'Mathbox'; + def.objects.forEach(function (mbo) { mbo.def.mb = mb; }); + return _this; + } + Mathbox.prototype.addObject = function (mbo) { + this.def.objects.push(mbo); + return this; + }; + return Mathbox; + }(KGAuthor.DivObject)); + KGAuthor.Mathbox = Mathbox; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconSchema = /** @class */ (function (_super) { + __extends(EconSchema, _super); + function EconSchema(def) { + var _this = this; + def.idioms = {}; + def.custom = def.custom || "0"; + var idiomMenu = [ + { + PPFlabel: ["PPF", "PPC"], + PPFword: ["frontier", "curve"], + PPFWord: ["Frontier", "Curve"] + }, + { + good1label: ["x_1", "x", "X"], + labor1label: ["L_1", "L_x", "L_X"], + good1word: ["good 1", "good X", "good X"], + good1Word: ["Good 1", "Good X", "Good X"], + good2label: ["x_2", "y", "Y"], + labor2label: ["L_2", "L_y", "L_Y"], + good2word: ["good 2", "good Y", "good Y"], + good2Word: ["Good 2", "Good Y", "Good Y"] + }, + { + oldValueLabel: ["\\ ", "_1", "0"], + newValueLabel: ["^\\prime", "_2", "1"] + } + ]; + //console.log("custom: ", def.custom) + idiomMenu.forEach(function (idiomGroup, index) { + // if the user has specified a choice, use it. + if (index < def.custom.length) { + for (var idiomName in idiomGroup) { + def.idioms[idiomName] = idiomGroup[idiomName][def.custom[index]]; + } + } + // otherwise default to first + else { + for (var idiomName in idiomGroup) { + def.idioms[idiomName] = idiomGroup[idiomName][0]; + } + } + }); + console.log("idioms: ", def.idioms); + def.colors = KG.setDefaults(def.colors || {}, { + // consumer theory + utility: 'purple', + mrs: 'blue', + dispreferred: 'red', + preferred: 'green', + offer: 'blue', + incomeOffer: 'orange', + demand: 'blue', + budget: 'green', + costlier: 'red', + endowment: 'grey', + incEffect: 'orange', + subEffect: 'red', + // producer theory + production: 'blue', + mpl: 'olive', + marginalCost: 'orange', + marginalRevenue: 'olive', + supply: 'orange', + shortRun: 'red', + longRun: 'orange', + profit: 'green', + loss: 'red', + ppf: 'red', + mrt: 'orange', + // equilibrium + price: 'grey', + paretoLens: "'#ffff99'", + equilibriumPrice: 'green', + // macro + consumption: 'blue', + depreciation: "red", + savings: "green", + tax: 'red', + // game theory + player1: 'blue', + player2: 'red', + player3: 'orange', + nature: 'green', + terminal: 'gray' + }); + _this = _super.call(this, def) || this; + _this.idiomMenu = idiomMenu; + return _this; + } + return EconSchema; + }(KGAuthor.Schema)); + KGAuthor.EconSchema = EconSchema; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var BowlesHallidaySchema = /** @class */ (function (_super) { + __extends(BowlesHallidaySchema, _super); + function BowlesHallidaySchema(def) { + var _this = this; + // create color scheme here; I took these from the spreadsheet + var purple = "'#3f007d'", blue = "'#084081'", green = "'#005824'"; + // define any overrides to the defined Econ schema here + def.colors = { + // consumer theory + demand: purple, + supply: blue, + equilibriumPrice: green, + indifferenceCurve: green, + bestResponse: purple + }; + _this = _super.call(this, def) || this; + return _this; + } + return BowlesHallidaySchema; + }(KGAuthor.EconSchema)); + KGAuthor.BowlesHallidaySchema = BowlesHallidaySchema; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EdgeworthBox = /** @class */ (function (_super) { + __extends(EdgeworthBox, _super); + function EdgeworthBox(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var agentA = def['agentA'], agentB = def['agentB']; + var width = 0.738, height = 0.8; + /* if(def.totalGood1 > def.totalGood2) { + height = def.totalGood2*height/def.totalGood1; + } + + if(def.totalGood2 > def.totalGood1) { + height = def.totalGood1*width/def.totalGood2; + } */ + _this.aspectRatio = 2; + agentA.position = { + "x": 0.15, + "y": 0.1, + "width": width, + "height": height + }; + agentB.position = { + "x": 0.15 + width, + "y": 0.1 + height, + "width": -1 * width, + "height": -1 * height + }; + agentA.xAxis.max = agentB.xAxis.max = def.totalGood1; + agentA.yAxis.max = agentB.yAxis.max = def.totalGood2; + agentB.xAxis.orient = 'top'; + agentB.yAxis.orient = 'right'; + l.subObjects.push(new KGAuthor.Graph(agentA)); + l.subObjects.push(new KGAuthor.Graph(agentB)); + return _this; + } + return EdgeworthBox; + }(KGAuthor.Layout)); + KGAuthor.EdgeworthBox = EdgeworthBox; + var EdgeworthBoxSquare = /** @class */ (function (_super) { + __extends(EdgeworthBoxSquare, _super); + function EdgeworthBoxSquare(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var agentA = def['agentA'], agentB = def['agentB']; + var width = 0.74, height = 0.9; + _this.aspectRatio = 1.22; + agentA.position = { + "x": 0.15, + "y": 0.025, + "width": width, + "height": height + }; + agentB.position = { + "x": 0.15 + width, + "y": 0.025 + height, + "width": -1 * width, + "height": -1 * height + }; + agentA.xAxis.max = agentB.xAxis.max = def.totalGood1; + agentA.yAxis.max = agentB.yAxis.max = def.totalGood2; + agentB.xAxis.orient = 'top'; + agentB.yAxis.orient = 'right'; + l.subObjects.push(new KGAuthor.Graph(agentA)); + l.subObjects.push(new KGAuthor.Graph(agentB)); + return _this; + } + return EdgeworthBoxSquare; + }(KGAuthor.SquareLayout)); + KGAuthor.EdgeworthBoxSquare = EdgeworthBoxSquare; + var EdgeworthBoxPlusSidebar = /** @class */ (function (_super) { + __extends(EdgeworthBoxPlusSidebar, _super); + function EdgeworthBoxPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var agentA = def['agentA'], agentB = def['agentB'], sidebarDef = def['sidebar']; + var width = 0.738, height = 0.8; + /* if(def.totalGood1 > def.totalGood2) { + height = def.totalGood2*height/def.totalGood1; + } + + if(def.totalGood2 > def.totalGood1) { + height = def.totalGood1*width/def.totalGood2; + } */ + _this.aspectRatio = 2; + agentA.position = { + "x": 0.15, + "y": 0.1, + "width": width, + "height": height + }; + agentB.position = { + "x": 0.15 + width, + "y": 0.1 + height, + "width": -1 * width, + "height": -1 * height + }; + agentA.xAxis.max = agentB.xAxis.max = def.totalGood1; + agentA.yAxis.max = agentB.yAxis.max = def.totalGood2; + agentB.xAxis.orient = 'top'; + agentB.yAxis.orient = 'right'; + l.subObjects.push(new KGAuthor.Graph(agentA)); + l.subObjects.push(new KGAuthor.Graph(agentB)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return EdgeworthBoxPlusSidebar; + }(KGAuthor.Layout)); + KGAuthor.EdgeworthBoxPlusSidebar = EdgeworthBoxPlusSidebar; + var EdgeworthBoxPlusTwoGraphsPlusSidebar = /** @class */ (function (_super) { + __extends(EdgeworthBoxPlusTwoGraphsPlusSidebar, _super); + function EdgeworthBoxPlusTwoGraphsPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var agentA = def['agentA'], agentB = def['agentB'], graph1 = def['graph1'], graph2 = def['graph2'], sidebarDef = def['sidebar']; + var width = 0.738, height = 0.9; + if (def.totalGood1 > def.totalGood2) { + height = def.totalGood2 * height / def.totalGood1; + } + if (def.totalGood2 > def.totalGood1) { + height = def.totalGood1 * width / def.totalGood2; + } + agentA.position = { + "x": 0.15, + "y": 0.05, + "width": width, + "height": height + }; + agentB.position = { + "x": 0.15 + width, + "y": 0.05 + height, + "width": -1 * width, + "height": -1 * height + }; + graph1.position = { + "x": 0.1, + "y": height + 0.15, + "width": 0.35, + "height": 0.85 - height + }; + graph2.position = { + "x": 0.6, + "y": height + 0.15, + "width": 0.35, + "height": 0.85 - height + }; + agentA.xAxis.max = agentB.xAxis.max = def.totalGood1; + agentA.yAxis.max = agentB.yAxis.max = def.totalGood2; + agentB.xAxis.orient = 'top'; + agentB.yAxis.orient = 'right'; + l.subObjects.push(new KGAuthor.Graph(agentB)); + l.subObjects.push(new KGAuthor.Graph(agentA)); + l.subObjects.push(new KGAuthor.Graph(graph1)); + l.subObjects.push(new KGAuthor.Graph(graph2)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return EdgeworthBoxPlusTwoGraphsPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.EdgeworthBoxPlusTwoGraphsPlusSidebar = EdgeworthBoxPlusTwoGraphsPlusSidebar; + var EdgeworthBoxAboveOneGraphPlusSidebar = /** @class */ (function (_super) { + __extends(EdgeworthBoxAboveOneGraphPlusSidebar, _super); + function EdgeworthBoxAboveOneGraphPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var agentA = def['agentA'], agentB = def['agentB'], graph = def['graph'], sidebarDef = def['sidebar']; + var width = 0.738, height = 0.9; + if (def.totalGood1 > def.totalGood2) { + height = def.totalGood2 * height / def.totalGood1; + } + if (def.totalGood2 > def.totalGood1) { + height = def.totalGood1 * width / def.totalGood2; + } + agentA.position = { + "x": 0.15, + "y": 0.05, + "width": width, + "height": height + }; + agentB.position = { + "x": 0.15 + width, + "y": 0.05 + height, + "width": -1 * width, + "height": -1 * height + }; + graph.position = { + "x": 0.15, + "y": height + 0.15, + "width": width, + "height": 0.85 - height + }; + agentA.xAxis.max = agentB.xAxis.max = def.totalGood1; + agentA.yAxis.max = agentB.yAxis.max = def.totalGood2; + agentB.xAxis.orient = 'top'; + agentB.yAxis.orient = 'right'; + l.subObjects.push(new KGAuthor.Graph(agentB)); + l.subObjects.push(new KGAuthor.Graph(agentA)); + l.subObjects.push(new KGAuthor.Graph(graph)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return EdgeworthBoxAboveOneGraphPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.EdgeworthBoxAboveOneGraphPlusSidebar = EdgeworthBoxAboveOneGraphPlusSidebar; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EntryDeterrence = /** @class */ (function (_super) { + __extends(EntryDeterrence, _super); + function EntryDeterrence(def) { + return _super.call(this, def) || this; + } + return EntryDeterrence; + }(KGAuthor.Tree)); + KGAuthor.EntryDeterrence = EntryDeterrence; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconMultivariateFunction = /** @class */ (function (_super) { + __extends(EconMultivariateFunction, _super); + function EconMultivariateFunction(def) { + var _this = this; + KG.setDefaults(def, { + name: KG.randomString(10) + }); + _this = _super.call(this, def) || this; + var fn = _this; + fn.interpolation = 'curveMonotoneX'; + if (def.hasOwnProperty('alpha')) { + fn.alpha = def.alpha; + fn.exponents = def.exponents || [def.alpha, KGAuthor.subtractDefs(1, def.alpha)]; + fn.coefficients = def.coefficients || [def.alpha, KGAuthor.subtractDefs(1, def.alpha)]; + } + else if (def.hasOwnProperty('exponents')) { + fn.exponents = def.exponents; + fn.alpha = KGAuthor.divideDefs(fn.exponents[0], KGAuthor.addDefs(fn.exponents[0], fn.exponents[1])); + fn.coefficients = def.coefficients; + } + else if (def.hasOwnProperty('coefficients')) { + fn.exponents = def.coefficients; + fn.coefficients = def.coefficients; + fn.alpha = KGAuthor.divideDefs(fn.coefficients[0], KGAuthor.addDefs(fn.coefficients[0], fn.coefficients[1])); + } + return _this; + } + EconMultivariateFunction.prototype.value = function (x) { + return null; + }; + EconMultivariateFunction.prototype.extractLevel = function (def) { + var u = this; + if (def.hasOwnProperty('level') && def.level != undefined) { + return KGAuthor.getDefinitionProperty(def.level); + } + else if (def.hasOwnProperty('point') && def.point != undefined) { + return u.value(def.point); + } + else if (def.hasOwnProperty('budgetLine')) { + var bl = new KGAuthor.EconBudgetLine(def.budgetLine, null); + return u.value(u.optimalBundle(bl)); + } + }; + EconMultivariateFunction.prototype.levelSet = function (def) { + return []; + }; + EconMultivariateFunction.prototype.levelCurve = function (def, graph) { + def.interpolation = this.interpolation; + return KGAuthor.curvesFromFunctions(this.levelSet(def), def, graph); + }; + EconMultivariateFunction.prototype.levelCurveSlope = function (x) { + return null; + }; + EconMultivariateFunction.prototype.areaBelowLevelCurve = function (def, graph) { + var fn = this; + fn.fillBelowRect = null; + def.interpolation = fn.interpolation; + var fns = fn.levelSet(def); + var objs = []; + fns.forEach(function (fn) { + var areaDef = KGAuthor.copyJSON(def); + areaDef.univariateFunction1 = fn; + objs.push(new KGAuthor.Area(areaDef, graph)); + }); + if (fn.fillBelowRect) { + fn.fillBelowRect.show = def.show; + fn.fillBelowRect.fill = def.fill; + objs.push(new KGAuthor.Rectangle(fn.fillBelowRect, graph)); + } + return objs; + }; + EconMultivariateFunction.prototype.areaAboveLevelCurve = function (def, graph) { + var fn = this; + fn.fillAboveRect = null; + def.interpolation = fn.interpolation; + var fns = fn.levelSet(def); + var objs = []; + fns.forEach(function (fn) { + var areaDef = KGAuthor.copyJSON(def); + areaDef.univariateFunction1 = fn; + areaDef.above = true; + objs.push(new KGAuthor.Area(areaDef, graph)); + }); + if (fn.fillAboveRect) { + fn.fillAboveRect.show = def.show; + fn.fillAboveRect.fill = def.fill; + fn.fillAboveRect.inDef = true; + objs.push(new KGAuthor.Rectangle(fn.fillAboveRect, graph)); + } + var clipPathName = def.hasOwnProperty('name') ? def.name + "_above" : KG.randomString(10); + return [ + new KGAuthor.Rectangle({ + clipPathName: clipPathName, + x1: graph.def.xAxis.min, + x2: graph.def.xAxis.max, + y1: graph.def.yAxis.min, + y2: graph.def.yAxis.max, + fill: def.fill, + show: def.show + }, graph), + new KGAuthor.ClipPath({ + "name": clipPathName, + "paths": objs + }, graph) + ]; + }; + EconMultivariateFunction.prototype.lowestCostBundle = function (level, prices) { + return []; // defined at the subclass level + }; + /* Optimization with an exogenous income */ + EconMultivariateFunction.prototype.cornerCondition = function (budgetLine) { + return 'false'; + }; + EconMultivariateFunction.prototype.lagrangeBundle = function (budgetLine) { + return []; + }; + EconMultivariateFunction.prototype.optimalBundle = function (budgetLine) { + return []; + }; + EconMultivariateFunction.prototype.quantityDemanded = function (budgetLine, good) { + return this.optimalBundle(budgetLine)[good - 1]; + }; + EconMultivariateFunction.prototype.priceOfferFunction = function (budgetLine, good, min, max, graph) { + var u = this; + var blDef; + if (budgetLine.hasOwnProperty('point') && budgetLine.point != undefined) { + min = 0.01; + max = 0.99; + blDef = { + p1: '(t)', + p2: '1 - (t)', + m: budgetLine.point[0] + "*(t) + " + budgetLine.point[1] + "*(1-(t))" + }; + } + else { + blDef = (good == 1) ? { p1: '(t)', p2: budgetLine.p2, m: budgetLine.m } : { + p1: budgetLine.p1, + p2: '(t)', + m: budgetLine.m + }; + } + var optimalBundle = u.optimalBundle(new KGAuthor.EconBudgetLine(blDef, graph)); + return [ + { + xFunction: optimalBundle[0], + yFunction: optimalBundle[1], + min: min, + max: max, + samplePoints: 100, + parametric: true + } + ]; + }; + EconMultivariateFunction.prototype.priceOfferCurve = function (budgetLine, good, min, max, def, graph) { + var u = this; + def.interpolation = 'curveMonotoneX'; + return KGAuthor.curvesFromFunctions(u.priceOfferFunction(budgetLine, good, min, max, graph), def, graph); + }; + EconMultivariateFunction.prototype.demandFunction = function (budgetLine, good, graph) { + var u = this, blDef = (good == 1) ? { p1: '(y)', p2: budgetLine.p2, m: budgetLine.m } : { + p1: budgetLine.p1, + p2: '(y)', + m: budgetLine.m + }; + return [ + { + "fn": u.quantityDemanded(new KGAuthor.EconBudgetLine(blDef, graph), good), + "ind": "y", + "samplePoints": 30 + } + ]; + }; + EconMultivariateFunction.prototype.demandCurve = function (budgetLine, good, def, graph) { + var u = this; + def.interpolation = 'curveMonotoneX'; + return KGAuthor.curvesFromFunctions(u.demandFunction(budgetLine, good, graph), def, graph); + }; + /* Net demand and supply from an endowment */ + EconMultivariateFunction.prototype.endowmentDemandFunction = function (budgetLine, good, graph) { + var u = this; + var netDemand = '', netSupply = '', grossDemand = ''; + var x1 = budgetLine.point[0], x2 = budgetLine.point[1]; + if (good == 2) { + var optimalBundle = u.optimalBundle(new KGAuthor.EconBudgetLine({ + p1: budgetLine.p1, + p2: '(y)', + m: "(" + x1 + "*" + budgetLine.p1 + " + " + x2 + "*(y))" + }, graph)); + grossDemand = optimalBundle[1]; + netDemand = KGAuthor.subtractDefs(grossDemand, x2); + netSupply = KGAuthor.subtractDefs(x2, grossDemand); + } + else { + var optimalBundle = u.optimalBundle(new KGAuthor.EconBudgetLine({ + p1: '(y)', + p2: budgetLine.p2, + m: "(" + x1 + "*(y) + " + x2 + "*" + budgetLine.p2 + ")" + }, graph)); + grossDemand = optimalBundle[0]; + netDemand = KGAuthor.subtractDefs(grossDemand, x1); + netSupply = KGAuthor.subtractDefs(x1, grossDemand); + } + return { + grossDemand: [ + { + fn: grossDemand, + ind: 'y' + } + ], + netDemand: [ + { + fn: netDemand, + ind: 'y' + } + ], + netSupply: [ + { + fn: netSupply, + ind: 'y' + } + ] + }; + }; + EconMultivariateFunction.prototype.grossDemandCurve = function (budgetLine, good, def, graph) { + var u = this; + def.interpolation = 'curveMonotoneX'; + return KGAuthor.curvesFromFunctions(u.endowmentDemandFunction(budgetLine, good, graph).grossDemand, def, graph); + }; + EconMultivariateFunction.prototype.netDemandCurve = function (budgetLine, good, def, graph) { + var u = this; + def.interpolation = 'curveMonotoneX'; + return KGAuthor.curvesFromFunctions(u.endowmentDemandFunction(budgetLine, good, graph).netDemand, def, graph); + }; + EconMultivariateFunction.prototype.netSupplyCurve = function (budgetLine, good, def, graph) { + var u = this; + def.interpolation = 'curveMonotoneX'; + return KGAuthor.curvesFromFunctions(u.endowmentDemandFunction(budgetLine, good, graph).netSupply, def, graph); + }; + EconMultivariateFunction.prototype.indirectUtility = function (income, prices) { + return this.extractLevel({ budgetLine: { p1: prices[0], p2: prices[1], m: income } }); + }; + EconMultivariateFunction.prototype.expenditure = function (level, prices) { + var b = this.lowestCostBundle(level, prices); + return KGAuthor.addDefs(KGAuthor.multiplyDefs(b[0], prices[0]), KGAuthor.multiplyDefs(b[1], prices[1])); + }; + EconMultivariateFunction.prototype.laborRequirement = function (level, capital) { + // defined at subclass level + }; + return EconMultivariateFunction; + }(KGAuthor.AuthoringObject)); + KGAuthor.EconMultivariateFunction = EconMultivariateFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var CobbDouglasFunction = /** @class */ (function (_super) { + __extends(CobbDouglasFunction, _super); + function CobbDouglasFunction() { + return _super !== null && _super.apply(this, arguments) || this; + } + CobbDouglasFunction.prototype.value = function (x) { + var e = this.exponents, scalar = this.coefficients.length == 1 ? this.coefficients[0] : 1; + return "(" + scalar + "*(" + x[0] + ")^(" + e[0] + "))*((" + x[1] + ")^(" + e[1] + "))"; + }; + CobbDouglasFunction.prototype.levelSet = function (def) { + var e = this.exponents, scalar = this.coefficients.length == 1 ? this.coefficients[0] : 1, level = KGAuthor.divideDefs(this.extractLevel(def), scalar), xMin = "(" + level + ")^(1/(" + e[0] + " + " + e[1] + "))", yMin = "(" + level + ")^(1/(" + e[0] + " + " + e[1] + "))"; + this.fillBelowRect = { + x1: 0, + x2: xMin, + y1: 0, + y2: yMin, + show: def.show + }; + return [ + { + "fn": "((" + level + ")/(y)^(" + e[1] + "))^(1/(" + e[0] + "))", + "ind": "y", + "min": yMin, + "samplePoints": 30 + }, + { + "fn": "((" + level + ")/(x)^(" + e[0] + "))^(1/(" + e[1] + "))", + "ind": "x", + "min": xMin, + "samplePoints": 30 + } + ]; + }; + CobbDouglasFunction.prototype.levelCurveSlope = function (x) { + var c = this.coefficients; + return KGAuthor.negativeDef(KGAuthor.divideDefs(KGAuthor.multiplyDefs(c[0], x[1]), KGAuthor.multiplyDefs(c[1], x[0]))); + }; + CobbDouglasFunction.prototype.optimalBundle = function (budgetLine) { + var a = this.alpha; + return [KGAuthor.multiplyDefs(a, budgetLine.xIntercept), KGAuthor.multiplyDefs(KGAuthor.subtractDefs(1, a), budgetLine.yIntercept)]; + }; + CobbDouglasFunction.prototype.lowestCostBundle = function (level, prices) { + var e = this.exponents, ratio = KGAuthor.multiplyDefs(KGAuthor.divideDefs(prices[0], prices[1]), KGAuthor.divideDefs(e[1], e[0])), scale = KGAuthor.addDefs(e[0], e[1]), scaledLevel = KGAuthor.raiseDefToDef(level, KGAuthor.divideDefs(1, scale)); + return [ + KGAuthor.divideDefs(scaledLevel, KGAuthor.raiseDefToDef(ratio, KGAuthor.divideDefs(e[1], scale))), + KGAuthor.multiplyDefs(scaledLevel, KGAuthor.raiseDefToDef(ratio, KGAuthor.divideDefs(e[0], scale))) + ]; + }; + CobbDouglasFunction.prototype.laborRequirement = function (level, capital) { + var e = this.exponents; + return "((" + level + ")/(" + capital + ")^(" + e[1] + "))^(1/(" + e[0] + "))"; + }; + return CobbDouglasFunction; + }(KGAuthor.EconMultivariateFunction)); + KGAuthor.CobbDouglasFunction = CobbDouglasFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MinFunction = /** @class */ (function (_super) { + __extends(MinFunction, _super); + function MinFunction(def) { + var _this = _super.call(this, def) || this; + var fn = _this; + fn.interpolation = 'curveLinear'; + if (def.hasOwnProperty('alpha')) { + fn.coefficients = [KGAuthor.divideDefs(0.5, def.alpha), KGAuthor.divideDefs(0.5, KGAuthor.subtractDefs(1, def.alpha))]; + } + return _this; + } + MinFunction.prototype.value = function (x) { + var c = this.coefficients; + return "(min((" + x[0] + ")*(" + c[0] + "),(" + x[1] + ")*(" + c[1] + ")))"; + }; + MinFunction.prototype.levelSet = function (def) { + var c = this.coefficients, level = def.level || this.value(def.point), xMin = KGAuthor.divideDefs(level, c[0]), yMin = KGAuthor.divideDefs(level, c[1]); + this.fillBelowRect = { + x1: 0, + x2: xMin, + y1: 0, + y2: yMin, + show: def.show + }; + return [ + { + "fn": KGAuthor.divideDefs(level, c[1]), + "ind": "x", + "min": xMin, + "samplePoints": 2 + }, { + "fn": KGAuthor.divideDefs(level, c[0]), + "ind": "y", + "min": yMin, + "samplePoints": 2 + } + ]; + }; + MinFunction.prototype.optimalBundle = function (budgetLine) { + var good1perBundle = KGAuthor.invertDef(this.coefficients[0]), good2perBundle = KGAuthor.invertDef(this.coefficients[1]), bundles = KGAuthor.divideDefs(budgetLine.m, KGAuthor.addDefs(KGAuthor.multiplyDefs(budgetLine.p1, good1perBundle), KGAuthor.multiplyDefs(budgetLine.p2, good2perBundle))); + return [KGAuthor.multiplyDefs(good1perBundle, bundles), KGAuthor.multiplyDefs(good2perBundle, bundles)]; + }; + MinFunction.prototype.lowestCostBundle = function (level, prices) { + var a = this.coefficients[0], b = this.coefficients[1]; + return [ + KGAuthor.divideDefs(level, a), + KGAuthor.divideDefs(level, b) + ]; + }; + return MinFunction; + }(KGAuthor.EconMultivariateFunction)); + KGAuthor.MinFunction = MinFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var LinearFunction = /** @class */ (function (_super) { + __extends(LinearFunction, _super); + function LinearFunction(def) { + var _this = _super.call(this, def) || this; + var fn = _this; + _this.interpolation = 'curveLinear'; + if (def.hasOwnProperty('alpha')) { + fn.coefficients = [def.alpha, KGAuthor.subtractDefs(1, def.alpha)]; + } + return _this; + } + LinearFunction.prototype.value = function (x) { + var c = this.coefficients; + return "((" + x[0] + ")*(" + c[0] + ")+(" + x[1] + ")*(" + c[1] + "))"; + }; + LinearFunction.prototype.levelSet = function (def) { + var c = this.coefficients, level = def.level || this.value(def.point); + return [ + { + "fn": "(" + level + " - (" + c[0] + ")*(x))/(" + c[1] + ")", + "ind": "x", + "samplePoints": 2 + } + ]; + }; + LinearFunction.prototype.optimalBundle = function (budgetLine) { + var c = this.coefficients; + var buyOnlyGood2 = "((" + c[0] + ")*(" + budgetLine.p2 + ") < (" + c[1] + ")*(" + budgetLine.p1 + "))"; + return [buyOnlyGood2 + " ? 0 : " + budgetLine.xIntercept, buyOnlyGood2 + " ? " + budgetLine.yIntercept + " : 0"]; + }; + return LinearFunction; + }(KGAuthor.EconMultivariateFunction)); + KGAuthor.LinearFunction = LinearFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var CESFunction = /** @class */ (function (_super) { + __extends(CESFunction, _super); + function CESFunction(def) { + var _this = _super.call(this, def) || this; + var fn = _this; + fn.interpolation = 'curveMonotoneX'; + if (def.hasOwnProperty('r')) { + fn.r = def.r; + fn.s = KGAuthor.divideDefs(1, KGAuthor.subtractDefs(1, def.r)); + } + else if (def.hasOwnProperty('s')) { + fn.s = def.s; + fn.r = KGAuthor.subtractDefs(1, KGAuthor.divideDefs(1, def.s)); + } + return _this; + } + CESFunction.prototype.value = function (x) { + var c = this.coefficients, r = this.r; + return KGAuthor.raiseDefToDef(KGAuthor.addDefs(KGAuthor.multiplyDefs(c[0], KGAuthor.raiseDefToDef(x[0], r)), KGAuthor.multiplyDefs(c[1], KGAuthor.raiseDefToDef(x[1], r))), KGAuthor.divideDefs(1, r)); + }; + CESFunction.prototype.levelSet = function (def) { + var u = this, a = KGAuthor.getDefinitionProperty(u.alpha), r = KGAuthor.getDefinitionProperty(u.r), b = KGAuthor.subtractDefs(1, u.alpha), level = this.extractLevel(def); + this.fillBelowRect = { + x1: 0, + x2: level, + y1: 0, + y2: level, + show: def.show + }; + return [ + { + fn: "((" + level + "^" + r + " - " + a + "*(x)^" + r + ")/" + b + ")^(1/" + r + ")", + ind: "x", + min: level + }, + { + fn: "((" + level + "^" + r + " - " + b + "*(y)^" + r + ")/" + a + ")^(1/" + r + ")", + ind: "y", + min: level + } + ]; + }; + // see http://www.gamsworld.org/mpsge/debreu/ces.pdf + CESFunction.prototype.optimalBundle = function (budgetLine) { + var s = this.s, oneMinusS = KGAuthor.subtractDefs(1, s), a = this.alpha, oneMinusA = KGAuthor.subtractDefs(1, a), theta = KGAuthor.divideDefs(budgetLine.m, KGAuthor.addDefs(KGAuthor.multiplyDefs(KGAuthor.raiseDefToDef(a, s), KGAuthor.raiseDefToDef(budgetLine.p1, oneMinusS)), KGAuthor.multiplyDefs(KGAuthor.raiseDefToDef(oneMinusA, s), KGAuthor.raiseDefToDef(budgetLine.p2, oneMinusS)))), optimalX1 = KGAuthor.multiplyDefs(KGAuthor.raiseDefToDef(KGAuthor.divideDefs(a, budgetLine.p1), s), theta), optimalX2 = KGAuthor.multiplyDefs(KGAuthor.raiseDefToDef(KGAuthor.divideDefs(oneMinusA, budgetLine.p2), s), theta); + return [optimalX1, optimalX2]; + }; + CESFunction.prototype.denominator = function (p1, p2) { + var a1 = this.alpha, a2 = KGAuthor.subtractDefs(1, a1), r = this.r, pOverA1 = KGAuthor.divideDefs(p1, a1), pOverA2 = KGAuthor.divideDefs(p2, a2), oneOverR = KGAuthor.divideDefs(1, r), rOverRminusOne = KGAuthor.divideDefs(r, KGAuthor.subtractDefs(r, 1)); + return KGAuthor.raiseDefToDef(KGAuthor.addDefs(KGAuthor.multiplyDefs(a1, KGAuthor.raiseDefToDef(pOverA1, rOverRminusOne)), KGAuthor.multiplyDefs(a2, KGAuthor.raiseDefToDef(pOverA2, rOverRminusOne))), oneOverR); + }; + // see http://personal.stthomas.edu/csmarcott/ec418/ces_cost_minimization.pdf + CESFunction.prototype.lowestCostBundle = function (level, prices) { + var a1 = this.alpha, a2 = KGAuthor.subtractDefs(1, a1), p1 = prices[0], p2 = prices[1], r = this.r, pOverA1 = KGAuthor.divideDefs(p1, a1), pOverA2 = KGAuthor.divideDefs(p2, a2), oneOverRminusOne = KGAuthor.divideDefs(1, KGAuthor.subtractDefs(r, 1)), denominator = this.denominator(p1, p2), numerator1 = KGAuthor.raiseDefToDef(pOverA1, oneOverRminusOne), numerator2 = KGAuthor.raiseDefToDef(pOverA2, oneOverRminusOne); + return [ + KGAuthor.divideDefs(KGAuthor.multiplyDefs(level, numerator1), denominator), + KGAuthor.divideDefs(KGAuthor.multiplyDefs(level, numerator2), denominator) + ]; + }; + return CESFunction; + }(KGAuthor.EconMultivariateFunction)); + KGAuthor.CESFunction = CESFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var ConcaveFunction = /** @class */ (function (_super) { + __extends(ConcaveFunction, _super); + function ConcaveFunction() { + return _super !== null && _super.apply(this, arguments) || this; + } + ConcaveFunction.prototype.value = function (x) { + var c = this.coefficients; + return "(" + c[0] + ")*(" + x[0] + ")^2+(" + c[1] + ")*(" + x[1] + ")^2"; + }; + ConcaveFunction.prototype.levelSet = function (def) { + var c = this.coefficients, level = def.level || this.value(def.point), max = "((" + level + ")/(" + c[0] + "+" + c[1] + "))^(0.5)"; + this.fillAboveRect = { + x1: max, + x2: 50, + y1: max, + y2: 50, + show: def.show + }; + return [ + { + "fn": "((" + level + "-(" + c[1] + ")*(y)*(y))/(" + c[0] + "))^(0.5)", + "ind": "y", + "min": 0, + "max": max, + "samplePoints": 30 + }, + { + "fn": "((" + level + "-(" + c[0] + ")*(x)*(x))/(" + c[1] + "))^(0.5)", + "ind": "x", + "min": 0, + "max": max, + "samplePoints": 30 + } + ]; + }; + return ConcaveFunction; + }(KGAuthor.EconMultivariateFunction)); + KGAuthor.ConcaveFunction = ConcaveFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var QuasilinearFunction = /** @class */ (function (_super) { + __extends(QuasilinearFunction, _super); + function QuasilinearFunction() { + return _super !== null && _super.apply(this, arguments) || this; + } + QuasilinearFunction.prototype.value = function (x) { + var c = this.coefficients; + return "(" + c[0] + "*log(" + x[0] + ")+" + x[1] + ")"; + }; + QuasilinearFunction.prototype.levelSet = function (def) { + var c = this.coefficients, level = this.extractLevel(def); + return [ + { + "fn": "((" + level + ")-(" + c[0] + ")*log((x)))", + "ind": "x", + "samplePoints": 100 + } + ]; + }; + QuasilinearFunction.prototype.cornerCondition = function (budgetLine) { + return "(" + this.lagrangeBundle(budgetLine)[1] + " < 0)"; + }; + QuasilinearFunction.prototype.lagrangeBundle = function (budgetLine) { + var c = this.coefficients; + return [KGAuthor.divideDefs(KGAuthor.multiplyDefs(c[0], budgetLine.p2), budgetLine.p1), KGAuthor.subtractDefs(budgetLine.yIntercept, c[0])]; + }; + QuasilinearFunction.prototype.optimalBundle = function (budgetLine) { + var lagr = this.lagrangeBundle(budgetLine), cornerCondition = this.cornerCondition(budgetLine); + return ["(" + cornerCondition + " ? " + budgetLine.xIntercept + " : " + lagr[0] + ")", "(" + cornerCondition + " ? 0 : " + lagr[1] + ")"]; + }; + return QuasilinearFunction; + }(KGAuthor.EconMultivariateFunction)); + KGAuthor.QuasilinearFunction = QuasilinearFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + function extractBudgetLine(def, graph) { + if (def.hasOwnProperty('budgetLineObject')) { + return def.budgetLineObject; + } + if (def.hasOwnProperty('budgetLine')) { + var budgetDef = JSON.parse(JSON.stringify(def.budgetLine)); + budgetDef.show = budgetDef.show || def.show; + if (!budgetDef.hasOwnProperty('m')) { + if (def.hasOwnProperty('point') && def.point.length == 2) { + budgetDef.point = def.point; + } + if (def.hasOwnProperty('coordinates') && def.coordinates.length == 2) { + budgetDef.point = def.coordinates; + } + if (def.hasOwnProperty('x') && def.hasOwnProperty('y')) { + budgetDef.x = def.x; + budgetDef.y = def.y; + } + } + budgetDef.color = budgetDef.color || def.color; + return new EconBudgetLine(budgetDef, graph); + } + //console.log('tried to instantiate a budget line without either a budget line def or object') + } + KGAuthor.extractBudgetLine = extractBudgetLine; + var EconBudgetLine = /** @class */ (function (_super) { + __extends(EconBudgetLine, _super); + function EconBudgetLine(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + def.name = def.name || 'BL' + KG.randomString(5); + // may define income either by income m or value of endowment point + if (!def.hasOwnProperty('m')) { + if (def.hasOwnProperty('x') && def.hasOwnProperty('y')) { + def.point = [def.x, def.y]; + } + if (def.hasOwnProperty('point') && def.point.length == 2) { + def.m = KGAuthor.addDefs(KGAuthor.multiplyDefs(def.p1, def.point[0]), KGAuthor.multiplyDefs(def.p2, def.point[1])); + } + } + var xIntercept = KGAuthor.divideDefs(def.m, def.p1), yIntercept = KGAuthor.divideDefs(def.m, def.p2), priceRatio = KGAuthor.divideDefs(def.p1, def.p2), endowment = { x: def.x, y: def.y }; + console.log('xIntercept', xIntercept); + if (def.inMap) { + def.strokeWidth = 1; + def.lineStyle = 'dotted'; + def.layer = 0; + def.handles = false; + def.draggable = false; + } + KG.setDefaults(def, { + a: ["calcs." + def.name + ".xIntercept", 0], + b: [0, "calcs." + def.name + ".yIntercept"], + color: 'colors.budget', + strokeWidth: 2, + lineStyle: 'solid', + buyOnly: false, + sellOnly: false + }); + if (def.sellOnly) { + def.a = [def.x, def.y]; + } + if (def.buyOnly) { + def.b = [def.x, def.y]; + } + if (def.draggable && typeof (def.m) == 'string') { + def.drag = [{ + 'directions': 'xy', + 'param': KGAuthor.paramName(def.m), + 'expression': KGAuthor.addDefs(KGAuthor.multiplyDefs('drag.x', def.p1), KGAuthor.multiplyDefs('drag.y', def.p2)) + }]; + } + if (!def.inMap) { + def.label = KG.setDefaults(def.label || {}, { + text: "BL", + location: def.sellOnly ? 0.1 : 0.9 + }); + } + _this = _super.call(this, def, graph) || this; + var bl = _this; + bl.p1 = def.p1; + bl.p2 = def.p2; + bl.m = def.m; + bl.xIntercept = xIntercept; + bl.yIntercept = yIntercept; + bl.priceRatio = priceRatio; + bl.point = def.point; + bl.endowment = endowment; + if (graph) { + var subObjects = bl.subObjects; + var xInterceptPointDef = { + coordinates: ["calcs." + bl.name + ".xIntercept", 0], + color: def.stroke, + r: 4 + }; + if (def.draggable && typeof (def.p1) == 'string') { + xInterceptPointDef['drag'] = [{ + directions: 'x', + param: KGAuthor.paramName(def.p1), + expression: KGAuthor.divideDefs("calcs." + bl.name + ".m", 'drag.x') + }]; + } + if (def.hasOwnProperty('xInterceptLabel')) { + xInterceptPointDef['droplines'] = { + vertical: def.xInterceptLabel + }; + } + bl.xInterceptPoint = new KGAuthor.Point(xInterceptPointDef, graph); + var yInterceptPointDef = { + coordinates: [0, "calcs." + bl.name + ".yIntercept"], + color: def.stroke, + r: 4 + }; + if (def.draggable && typeof (def.p2) == 'string') { + yInterceptPointDef['drag'] = [{ + directions: 'y', + param: KGAuthor.paramName(def.p2), + expression: KGAuthor.divideDefs('calcs.' + bl.name + '.m', 'drag.y') + }]; + } + if (def.hasOwnProperty('yInterceptLabel')) { + yInterceptPointDef['droplines'] = { + horizontal: def.yInterceptLabel + }; + } + bl.yInterceptPoint = new KGAuthor.Point(yInterceptPointDef, graph); + bl.budgetSetArea = new KGAuthor.Area({ + fill: "colors.budget", + univariateFunction1: { + fn: "calcs." + bl.name + ".yIntercept - calcs." + bl.name + ".priceRatio*(x)", + samplePoints: 2, + max: "calcs." + bl.name + ".xIntercept" + }, + show: def.set + }, graph); + bl.costlierArea = new KGAuthor.Area({ + fill: "colors.costlier", + univariateFunction1: { + fn: "calcs." + bl.name + ".yIntercept - calcs." + bl.name + ".priceRatio*(x)", + samplePoints: 2 + }, + show: def.costlier, + above: true + }, graph); + if (def.handles) { + subObjects.push(bl.xInterceptPoint); + subObjects.push(bl.yInterceptPoint); + } + if (def.set) { + subObjects.push(bl.budgetSetArea); + } + if (def.costlier) { + subObjects.push(bl.costlierArea); + } + } + return _this; + } + EconBudgetLine.prototype.cost = function (bundle) { + var c = "((" + this.p1 + ")*(" + bundle.x + ") + (" + this.p2 + ")*(" + bundle.y + "))"; + //console.log(c); + return c; + }; + EconBudgetLine.prototype.parseSelf = function (parsedData) { + var bl = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[bl.name] = { + xIntercept: bl.xIntercept.toString(), + yIntercept: bl.yIntercept.toString(), + m: bl.m.toString(), + p1: bl.p1.toString(), + p2: bl.p2.toString(), + priceRatio: bl.priceRatio.toString(), + endowment: bl.endowment.toString() + }; + return parsedData; + }; + return EconBudgetLine; + }(KGAuthor.Segment)); + KGAuthor.EconBudgetLine = EconBudgetLine; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + function getUtilityFunction(def) { + if (def != undefined) { + def = KGAuthor.extractTypeAndDef(def); + if (def.type == 'CobbDouglas') { + return new KGAuthor.CobbDouglasFunction(def.def); + } + else if (def.type == 'Substitutes' || def.type == 'PerfectSubstitutes') { + return new KGAuthor.LinearFunction(def.def); + } + else if (def.type == 'Complements' || def.type == 'PerfectComplements') { + return new KGAuthor.MinFunction(def.def); + } + else if (def.type == 'Concave') { + return new KGAuthor.ConcaveFunction(def.def); + } + else if (def.type == 'Quasilinear') { + return new KGAuthor.QuasilinearFunction(def.def); + } + else if (def.type == 'CESFunction' || def.type == 'CES') { + return new KGAuthor.CESFunction(def.def); + } + } + } + KGAuthor.getUtilityFunction = getUtilityFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + function extractIndifferenceCurve(def, graph) { + if (def.hasOwnProperty('indifferenceCurveObject')) { + return def.indifferenceCurveObject; + } + if (def.hasOwnProperty('indifferenceCurve')) { + var indifferenceCurveDef = KGAuthor.copyJSON(def.indifferenceCurve); + indifferenceCurveDef.show = indifferenceCurveDef.show || def.show; + indifferenceCurveDef.name = def.name + "_IC"; + return new EconIndifferenceCurve(indifferenceCurveDef, graph); + } + console.log('tried to instantiate a budget line without either a budget line def or object'); + } + KGAuthor.extractIndifferenceCurve = extractIndifferenceCurve; + var EconIndifferenceCurve = /** @class */ (function (_super) { + __extends(EconIndifferenceCurve, _super); + function EconIndifferenceCurve(def, graph) { + var _this = this; + if (def.inMap) { + def.strokeWidth = 1; + def.color = 'lightgrey'; + def.layer = 0; + } + KG.setDefaults(def, { + strokeWidth: 2, + color: 'colors.utility', + layer: 1, + showPreferred: false, + showDispreferred: false, + inMap: false, + showMapLevels: false + }); + if (def.inMap) { + if (def.showMapLevels) { + def.label = KG.setDefaults(def.label || {}, { + fontSize: 8, + x: KGAuthor.multiplyDefs(0.98, graph.xScale.max), + text: def.level + ".toFixed(0)", + color: def.color, + bgcolor: null + }); + } + } + else { + def.label = KG.setDefaults(def.label || {}, { + x: KGAuthor.multiplyDefs(0.95, graph.xScale.max), + text: "U", + color: def.color, + bgcolor: null, + position: 'bl' + }); + } + _this = _super.call(this, def, graph) || this; + var curve = _this; + var utilityFunction = KGAuthor.extractUtilityFunction(def); + curve.utilityFunction = utilityFunction; + curve.subObjects = curve.subObjects.concat(utilityFunction.levelCurve(def, graph)); + if (!def.inMap) { + if (!!def.showPreferred) { + var preferredDef = KGAuthor.copyJSON(def); + //preferredDef.fill = def.preferredColor || 'colors.preferred'; + preferredDef.fill = def.color || 'colors.preferred'; + preferredDef.show = def.showPreferred; + curve.subObjects = curve.subObjects.concat(utilityFunction.areaAboveLevelCurve(preferredDef, graph)); + } + if (!!def.showDispreferred) { + var dispreferredDef = KGAuthor.copyJSON(def); + dispreferredDef.fill = 'colors.dispreferred'; + dispreferredDef.show = def.showDispreferred; + curve.subObjects = curve.subObjects.concat(utilityFunction.areaBelowLevelCurve(dispreferredDef, graph)); + } + } + return _this; + } + return EconIndifferenceCurve; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconIndifferenceCurve = EconIndifferenceCurve; + var EconIndifferenceMap = /** @class */ (function (_super) { + __extends(EconIndifferenceMap, _super); + function EconIndifferenceMap(def, graph) { + var _this = _super.call(this, def, graph) || this; + _this.subObjects = def.levels.map(function (level) { + var icDef = KGAuthor.copyJSON(def); + icDef.inMap = true; + delete icDef.levels; + if (Array.isArray(level)) { + icDef.point = level; + } + else { + icDef.level = level; + } + return new EconIndifferenceCurve(icDef, graph); + }); + return _this; + } + return EconIndifferenceMap; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconIndifferenceMap = EconIndifferenceMap; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + function extractUtilityFunction(def) { + return def.utilityFunctionObject || KGAuthor.getUtilityFunction(def.utilityFunction); + } + KGAuthor.extractUtilityFunction = extractUtilityFunction; + var EconBundle = /** @class */ (function (_super) { + __extends(EconBundle, _super); + function EconBundle(def, graph) { + var _this = this; + KG.setDefaults(def, { + label: { text: 'X' }, + droplines: { + vertical: "x_1", + horizontal: "x_2" + }, + color: "colors.utility" + }); + KGAuthor.setFillColor(def); + _this = _super.call(this, def, graph) || this; + var bundle = _this; + bundle.budgetLine = KGAuthor.extractBudgetLine(def, graph); + if (bundle.budgetLine) { + bundle.subObjects.push(bundle.budgetLine); + } + bundle.utilityFunction = extractUtilityFunction(def); + if (bundle.utilityFunction) { + bundle.subObjects.push(bundle.utilityFunction); + if (def.hasOwnProperty('indifferenceCurve')) { + def.indifferenceCurve.level = "calcs." + bundle.name + ".level"; + def.indifferenceCurve.utilityFunction = def.utilityFunction; + bundle.subObjects.push(KGAuthor.extractIndifferenceCurve(def, graph)); + } + } + return _this; + } + EconBundle.prototype.parseSelf = function (parsedData) { + var bundle = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[bundle.name] = { + x: bundle.x, + y: bundle.y, + level: bundle.utilityFunction ? bundle.utilityFunction.value([bundle.x, bundle.y]) : '', + cost: bundle.budgetLine ? bundle.budgetLine.cost(bundle) : '', + mrs: bundle.utilityFunction ? KGAuthor.negativeDef(bundle.utilityFunction.levelCurveSlope([bundle.x, bundle.y])) : '' + }; + return parsedData; + }; + return EconBundle; + }(KGAuthor.Point)); + KGAuthor.EconBundle = EconBundle; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconOptimalBundle = /** @class */ (function (_super) { + __extends(EconOptimalBundle, _super); + function EconOptimalBundle(def, graph) { + var _this = this; + var bl = KGAuthor.extractBudgetLine(def, graph), u = KGAuthor.extractUtilityFunction(def), coords = u.optimalBundle(bl); + KG.setDefaults(def, { + coordinates: coords, + label: { text: 'X^*' }, + color: 'demand', + droplines: { + vertical: "x_1^*", + horizontal: "x_2^*" + }, + indifferenceCurve: {} + }); + console.log('coords: ', coords); + if (bl.hasOwnProperty('endowment')) { + if (bl.def.sellOnly) { + def.show = "(" + (def.show || true) + " && (" + coords[0] + " < " + bl.endowment.x + "))"; + } + if (bl.def.buyOnly) { + def.show = "(" + (def.show || true) + " && (" + coords[0] + " > " + bl.endowment.x + "))"; + } + } + def.budgetLineObject = bl; + _this = _super.call(this, def, graph) || this; + _this.level = u.value(coords); + return _this; + } + return EconOptimalBundle; + }(KGAuthor.EconBundle)); + KGAuthor.EconOptimalBundle = EconOptimalBundle; + var EconLagrangeBundle = /** @class */ (function (_super) { + __extends(EconLagrangeBundle, _super); + function EconLagrangeBundle(def, graph) { + var _this = this; + if (def.hasOwnProperty('utilityFunction') && def.hasOwnProperty('budgetLine')) { + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + coordinates: u.lagrangeBundle(bl), + color: 'colors.incomeOffer', + show: u.cornerCondition(bl), + label: { text: 'X^*_L' } + }); + } + else { + console.log('oops, need to define an EconOptimalBundle with a utility function and budget line.'); + } + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconLagrangeBundle; + }(EconOptimalBundle)); + KGAuthor.EconLagrangeBundle = EconLagrangeBundle; + var LowestCostBundle = /** @class */ (function (_super) { + __extends(LowestCostBundle, _super); + function LowestCostBundle(def, graph) { + var _this = this; + var u = KGAuthor.extractUtilityFunction(def), p1 = def.prices[0], p2 = def.prices[1], m = u.expenditure(def.level, def.prices); + delete def.prices; + delete def.level; + def.budgetLine = KG.setDefaults(def.budgetLine || {}, { + p1: p1, + p2: p2, + m: m + }); + _this = _super.call(this, def, graph) || this; + return _this; + } + return LowestCostBundle; + }(EconOptimalBundle)); + KGAuthor.LowestCostBundle = LowestCostBundle; + var EconSlutskyBundle = /** @class */ (function (_super) { + __extends(EconSlutskyBundle, _super); + function EconSlutskyBundle(def, graph) { + var _this = this; + var bl = KGAuthor.extractBudgetLine(def, graph), u = KGAuthor.extractUtilityFunction(def); + def.budgetLine = def.budgetLine || {}; + if (def.hasOwnProperty('p1')) { + def.budgetLine.p1 = def.p1; + delete def.budgetLine.m; + } + if (def.hasOwnProperty('p2')) { + def.budgetLine.p2 = def.p2; + delete def.budgetLine.m; + } + def.budgetLine.label = KG.setDefaults(def.budgetLine.label || {}, { + text: "BL_D" + }); + def.budgetLine.point = u.optimalBundle(bl); + delete def.budgetLineObject; + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconSlutskyBundle; + }(EconOptimalBundle)); + KGAuthor.EconSlutskyBundle = EconSlutskyBundle; + var EconHicksBundle = /** @class */ (function (_super) { + __extends(EconHicksBundle, _super); + function EconHicksBundle(def, graph) { + var _this = this; + var bl = KGAuthor.extractBudgetLine(def, graph), u = KGAuthor.extractUtilityFunction(def), p1 = def.hasOwnProperty('p1') ? def.p1 : def.budgetLine.p1, p2 = def.hasOwnProperty('p2') ? def.p2 : def.budgetLine.p2, level = u.value(u.optimalBundle(bl)); + def.budgetLine.p1 = p1; + def.budgetLine.p2 = p2; + def.budgetLine.m = u.expenditure(level, [p1, p2]); + def.budgetLine.label = KG.setDefaults(def.budgetLine.label || {}, { + text: "BL_C" + }); + def.coordinates = u.lowestCostBundle(level, [p1, p2]); + delete def.budgetLineObject; + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconHicksBundle; + }(EconOptimalBundle)); + KGAuthor.EconHicksBundle = EconHicksBundle; + var EconShortRunProductionBundle = /** @class */ (function (_super) { + __extends(EconShortRunProductionBundle, _super); + function EconShortRunProductionBundle(def, graph) { + var _this = this; + var u = KGAuthor.extractUtilityFunction(def), p1 = def.prices[0], p2 = def.prices[1]; + def.coordinates = [u.laborRequirement(def.level, def.capital), def.capital]; + def.budgetLine = KG.setDefaults(def.budgetLine || {}, { + p1: p1, + p2: p2 + }); + def.budgetLine.label = KG.setDefaults(def.budgetLine.label || {}, { + text: "c_s(y)" + }); + delete def.budgetLineObject; + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconShortRunProductionBundle; + }(KGAuthor.EconBundle)); + KGAuthor.EconShortRunProductionBundle = EconShortRunProductionBundle; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconDemandCurve = /** @class */ (function (_super) { + __extends(EconDemandCurve, _super); + function EconDemandCurve(def, graph) { + var _this = this; + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + stroke: 'colors.demand', + strokeWidth: 2 + }); + _this = _super.call(this, def, graph) || this; + _this.subObjects = u.demandCurve(bl, def.good, def, graph); + return _this; + } + return EconDemandCurve; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconDemandCurve = EconDemandCurve; + var EconDemandPoint = /** @class */ (function (_super) { + __extends(EconDemandPoint, _super); + function EconDemandPoint(def, graph) { + var _this = this; + if (def.hasOwnProperty('utilityFunction') && def.hasOwnProperty('budgetLine')) { + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + coordinates: [u.quantityDemanded(bl, def.good), bl['p' + def.good]], + fill: 'colors.demand', + label: { text: "x_" + def.good + "(p_" + def.good + "|p_" + (3 - def.good) + ",m)" }, + droplines: { vertical: "x_" + def.good + "^*" } + }); + } + else { + console.log('oops, need to define an EconOptimalBundle with a utility function and budget line.'); + } + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconDemandPoint; + }(KGAuthor.Point)); + KGAuthor.EconDemandPoint = EconDemandPoint; + var EconNetDemandCurve = /** @class */ (function (_super) { + __extends(EconNetDemandCurve, _super); + function EconNetDemandCurve(def, graph) { + var _this = this; + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + color: 'colors.demand', + strokeWidth: 2 + }); + _this = _super.call(this, def, graph) || this; + _this.subObjects = u.netDemandCurve(bl, def.good, def, graph); + return _this; + } + return EconNetDemandCurve; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconNetDemandCurve = EconNetDemandCurve; + var EconNetDemandPoint = /** @class */ (function (_super) { + __extends(EconNetDemandPoint, _super); + function EconNetDemandPoint(def, graph) { + var _this = this; + if (def.hasOwnProperty('utilityFunction') && def.hasOwnProperty('budgetLine')) { + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + coordinates: [KGAuthor.subtractDefs(u.quantityDemanded(bl, def.good), bl.point[def.good - 1]), bl['p' + def.good]], + fill: 'colors.demand', + label: { text: "d_" + def.good + "(p_" + def.good + "|p_" + (3 - def.good) + ")" }, + droplines: { vertical: "d_" + def.good + "^*" } + }); + } + else { + console.log('oops, need to define an EconOptimalBundle with a utility function and budget line.'); + } + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconNetDemandPoint; + }(KGAuthor.Point)); + KGAuthor.EconNetDemandPoint = EconNetDemandPoint; + var EconNetSupplyCurve = /** @class */ (function (_super) { + __extends(EconNetSupplyCurve, _super); + function EconNetSupplyCurve(def, graph) { + var _this = this; + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + color: 'colors.supply', + strokeWidth: 2 + }); + _this = _super.call(this, def, graph) || this; + _this.subObjects = u.netSupplyCurve(bl, def.good, def, graph); + return _this; + } + return EconNetSupplyCurve; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconNetSupplyCurve = EconNetSupplyCurve; + var EconNetSupplyPoint = /** @class */ (function (_super) { + __extends(EconNetSupplyPoint, _super); + function EconNetSupplyPoint(def, graph) { + var _this = this; + if (def.hasOwnProperty('utilityFunction') && def.hasOwnProperty('budgetLine')) { + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + coordinates: [KGAuthor.subtractDefs(bl.point[def.good - 1], u.quantityDemanded(bl, def.good)), bl['p' + def.good]], + fill: 'colors.supply', + label: { text: "s_" + def.good + "(p_" + def.good + "|p_" + (3 - def.good) + ")" }, + droplines: { vertical: "s_" + def.good + "^*" } + }); + } + else { + console.log('oops, need to define an EconOptimalBundle with a utility function and budget line.'); + } + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconNetSupplyPoint; + }(KGAuthor.Point)); + KGAuthor.EconNetSupplyPoint = EconNetSupplyPoint; + var EconPriceOfferCurve = /** @class */ (function (_super) { + __extends(EconPriceOfferCurve, _super); + function EconPriceOfferCurve(def, graph) { + var _this = this; + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + stroke: 'colors.offer', + strokeWidth: 2 + }); + _this = _super.call(this, def, graph) || this; + _this.subObjects = u.priceOfferCurve(bl, def.good, def.min, def.max, def, graph); + return _this; + } + return EconPriceOfferCurve; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconPriceOfferCurve = EconPriceOfferCurve; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconOneInputProductionFunction = /** @class */ (function (_super) { + __extends(EconOneInputProductionFunction, _super); + function EconOneInputProductionFunction(def, graph) { + var _this = this; + KG.setDefaults(def, { + coefficient: 1, + exponent: 0.5, + wage: 1, + price: 1 + }); + _this = _super.call(this, def) || this; + var f = _this; + f.coefficient = def.coefficient; + f.exponent = def.exponent; + f.wage = def.wage; + f.price = def.price; + // if y(L) = AL^b, L(y) = [A^(-1/b)] * y^[1/b] + f.laborRequirementExponent = KGAuthor.invertDef(def.exponent); + f.laborRequirementCoefficient = KGAuthor.raiseDefToDef(def.coefficient, KGAuthor.negativeDef(f.laborRequirementExponent)); + // if f(L) = AL^b, f'(L) = [bA] * L^[b-1] + f.marginalProductExponent = KGAuthor.subtractDefs(def.exponent, 1); + f.marginalProductCoefficient = KGAuthor.multiplyDefs(def.exponent, def.coefficient); + // if c(y) = wL(y) = w*LRC * y^LRE, c'(y) = [w*LRC*LRE] * y^[LRE - 1] + f.marginalCostCoefficient = KGAuthor.multiplyDefs(def.wage, KGAuthor.multiplyDefs(f.laborRequirementExponent, f.laborRequirementCoefficient)); + f.marginalCostExponent = KGAuthor.subtractDefs(f.laborRequirementExponent, 1); + // if c'(y) = MCC * y^MCE, y*(p) = MCC^(-1/MCE) * p^(1/MCE) + f.outputSupplyCoefficient = KGAuthor.raiseDefToDef(f.marginalCostCoefficient, KGAuthor.negativeDef(KGAuthor.invertDef(f.marginalCostExponent))); + f.outputSupplyExponent = KGAuthor.invertDef(f.marginalCostExponent); + // if MRPL = [p * MPC] * L^MPE, L*(w) = (p*MPC)^(-1/MPE) * w^(1/MPE) + f.laborDemandCoefficient = KGAuthor.raiseDefToDef(KGAuthor.multiplyDefs(f.price, f.marginalProductCoefficient), KGAuthor.negativeDef(KGAuthor.invertDef(f.marginalProductExponent))); + f.laborDemandExponent = KGAuthor.invertDef(f.marginalProductExponent); + return _this; + } + // output produced by L units of olabor + EconOneInputProductionFunction.prototype.f = function (L) { + var f = this; + return KGAuthor.multiplyDefs(f.coefficient, KGAuthor.raiseDefToDef(L, f.exponent)); + }; + // labor required to produce y units of output + EconOneInputProductionFunction.prototype.laborRequirement = function (y) { + var f = this; + return KGAuthor.multiplyDefs(f.laborRequirementCoefficient, KGAuthor.raiseDefToDef(y, f.laborRequirementExponent)); + }; + // marginal product of labor + EconOneInputProductionFunction.prototype.MPL = function (L) { + var f = this; + return KGAuthor.multiplyDefs(f.marginalProductCoefficient, KGAuthor.raiseDefToDef(L, f.marginalProductExponent)); + }; + // marginal revenue product of labor is price times MPL + EconOneInputProductionFunction.prototype.MRPL = function (L) { + var f = this; + return KGAuthor.multiplyDefs(f.price, f.MPL(L)); + }; + // cost is wage times labor requirement + EconOneInputProductionFunction.prototype.cost = function (y) { + var f = this; + return KGAuthor.multiplyDefs(f.wage, f.laborRequirement(y)); + }; + EconOneInputProductionFunction.prototype.marginalCost = function (y) { + var f = this; + return KGAuthor.multiplyDefs(f.marginalCostCoefficient, KGAuthor.raiseDefToDef(y, f.marginalCostExponent)); + }; + // labor demand + EconOneInputProductionFunction.prototype.laborDemand = function (w) { + var f = this; + return KGAuthor.multiplyDefs(f.laborDemandCoefficient, KGAuthor.raiseDefToDef(w, f.laborDemandExponent)); + }; + // optimal output + EconOneInputProductionFunction.prototype.optimalOutput = function (p) { + var f = this; + return KGAuthor.multiplyDefs(f.outputSupplyCoefficient, KGAuthor.raiseDefToDef(p, f.outputSupplyCoefficient)); + }; + EconOneInputProductionFunction.prototype.parseSelf = function (parsedData) { + var ppf = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[ppf.name] = { + coefficient: ppf.coefficient, + exponent: ppf.exponent, + curve: ppf.f('(x)') + }; + return parsedData; + }; + return EconOneInputProductionFunction; + }(KGAuthor.AuthoringObject)); + KGAuthor.EconOneInputProductionFunction = EconOneInputProductionFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconConstantElasticityCurve = /** @class */ (function (_super) { + __extends(EconConstantElasticityCurve, _super); + function EconConstantElasticityCurve(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + KG.setDefaults(def, { + name: 'constElasticityCurve' + KG.randomString(5), + color: 'colors.demand', + strokeWidth: 2, + lineStyle: 'solid', + show: true + }); + // TODO shouldn't need to convert these to strings; it should work with numbers... + if (def.hasOwnProperty('elasticity')) { + def.elasticity = def.elasticity.toString(); + } + if (def.hasOwnProperty('normalizedElasticity')) { + def.normalizedElasticity = def.normalizedElasticity.toString(); + } + // A constant elasticity curve is defined by one point and either an elasticity, a normalized elasticity, or a second point. + var curveDef = KGAuthor.copyJSON(def); + curveDef.fn = KGAuthor.multiplyDefs("calcs." + def.name + ".coefficient", KGAuthor.raiseDefToDef("(y)", "calcs." + curveDef.name + ".elasticity")); + curveDef.ind = 'y'; + curveDef.samplePoints = 500; + curveDef.show = "((" + def.show + ") && !(calcs. " + def.name + ".elastic))"; + var invCurveDef = KGAuthor.copyJSON(def); + invCurveDef.name = def.name + "inverse"; + invCurveDef.fn = KGAuthor.multiplyDefs("calcs." + invCurveDef.name + ".coefficient", KGAuthor.raiseDefToDef("(x)", "calcs." + invCurveDef.name + ".elasticity")); + invCurveDef.samplePoints = 500; + invCurveDef.ind = 'x'; + invCurveDef.show = "((" + def.show + ") && (calcs. " + def.name + ".elastic))"; + // define the control point + var pointDef = KGAuthor.copyJSON(def.point || {}); + pointDef.color = pointDef.color || def.color; + pointDef.show = pointDef.show || def.show; + // define the second control point, if applicable + if (def.hasOwnProperty('point2')) { + var point2Def = KGAuthor.copyJSON(def.point2); + point2Def.color = point2Def.color || def.color; + point2Def.show = point2Def.show || def.show; + } + _this = _super.call(this, curveDef, graph) || this; + var c = _this; + c.subObjects.push(new KGAuthor.Curve(invCurveDef, graph)); + var p = new KGAuthor.Point(pointDef, graph); + c.subObjects.push(p); + // If defined by a second point, calculate the elasticity implied by those two points + if (def.hasOwnProperty('point2')) { + var pointDef2 = def.point2; + pointDef2.color = pointDef2.color || def.color; + var p2 = new KGAuthor.Point(pointDef2, graph); + // calculate elasticity between the two points + // we have x0 = a*y0^b, x1 = a*y1^b + // therefore a = x0y0^(-b) = x1y1^(-b) + // therefore (x0/x1) = (y0/y1)^b => b = log(x0/x1)/log(y0/y1) + var x0overx1 = KGAuthor.divideDefs(p.x, p2.x); + var y0overy1 = KGAuthor.divideDefs(p.y, p2.y); + c.elasticity = KGAuthor.divideDefs("log" + x0overx1 + "", "log" + y0overy1 + ""); + c.invElasticity = KGAuthor.divideDefs("log" + y0overy1 + "", "log" + x0overx1 + ""); + c.perfectlyElastic = "(" + p.y + " == " + p2.y + ")"; + c.perfectlyInelastic = "(" + p.x + " == " + p2.x + ")"; + c.subObjects.push(p2); + } + // If the elasticity is normalized, 0 is perfectly inelastic, and 1 or -1 is perfectly elastic. + else if (def.hasOwnProperty('normalizedElasticity')) { + var absNormalizedElasticity = "(abs(" + def.normalizedElasticity + "))"; + c.elasticity = KGAuthor.divideDefs(def.normalizedElasticity, "(1 - " + absNormalizedElasticity + ")"); + c.invElasticity = KGAuthor.divideDefs("(1 - " + absNormalizedElasticity + ")", def.normalizedElasticity); + c.perfectlyElastic = "(" + absNormalizedElasticity + " == 1)"; + c.perfectlyInelastic = "(" + def.normalizedElasticity + " == 0)"; + } + // If the elasticity is defined directly, it can't be infinite + else { + c.elasticity = def.elasticity; + c.invElasticity = KGAuthor.invertDef(def.elasticity); + c.perfectlyInelastic = "(" + def.elasticity + " == 0)"; + c.perfectlyElastic = "false"; + } + // we have a function of the form x = ay^b => a = x0/y0^(b) + c.coefficient = KGAuthor.divideDefs(p.x, KGAuthor.raiseDefToDef(p.y, c.elasticity)); + // the inverse of this function is of the form y = a'x^(b') => a' = y0/x0^(b') + c.invCoefficient = KGAuthor.divideDefs(p.y, KGAuthor.raiseDefToDef(p.x, c.invElasticity)); + // Define regions of elasticity + c.absElasticity = "(abs(" + c.elasticity + "))"; + c.elastic = "(" + c.absElasticity + " > 1)"; + c.unitElastic = "(" + c.absElasticity + " == 1)"; + c.inelastic = "(" + c.absElasticity + " < 1)"; + return _this; + } + EconConstantElasticityCurve.prototype.parseSelf = function (parsedData) { + var c = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[c.name] = { + elasticity: c.elasticity, + coefficient: c.coefficient, + elastic: c.elastic, + unitElastic: c.unitElastic, + inelastic: c.inelastic, + perfectlyElastic: c.perfectlyElastic, + perfectlyInelastic: c.perfectlyInelastic + }; + parsedData.calcs[c.name + 'inverse'] = { + elasticity: c.invElasticity, + coefficient: c.invCoefficient + }; + return parsedData; + }; + return EconConstantElasticityCurve; + }(KGAuthor.Curve)); + KGAuthor.EconConstantElasticityCurve = EconConstantElasticityCurve; + var EconConstantElasticityIntersection = /** @class */ (function (_super) { + __extends(EconConstantElasticityIntersection, _super); + function EconConstantElasticityIntersection(def, graph) { + var _this = _super.call(this, def, graph) || this; + var intersection = _this; + intersection.name = def.name; + var c1 = "(calcs." + def.curve1 + ".coefficient)", e1 = "(calcs." + def.curve1 + ".elasticity)", c2 = "(calcs." + def.curve2 + ".coefficient)", e2 = "(calcs." + def.curve2 + ".elasticity)", invc1 = "(calcs." + def.curve1 + "inverse.coefficient)", inve1 = "(calcs." + def.curve1 + "inverse.elasticity)", invc2 = "(calcs." + def.curve2 + "inverse.coefficient)", inve2 = "(calcs." + def.curve2 + "inverse.elasticity)"; + // intersection occurs at the point where c1*x^(e1) = c2*x^(e2) => x = (c1/c2)^(1/(e2 - e1)) + var P = KGAuthor.raiseDefToDef(KGAuthor.divideDefs(c1, c2), KGAuthor.invertDef(KGAuthor.subtractDefs(e2, e1))); + var QofP = KGAuthor.multiplyDefs(c1, KGAuthor.raiseDefToDef(P, e1)); + intersection.Pdirect = P; + intersection.Qcalc = QofP; + // can also use the inverse curves to calculate the Q, and the P from that. + var Q = KGAuthor.raiseDefToDef(KGAuthor.divideDefs(invc1, invc2), KGAuthor.invertDef(KGAuthor.subtractDefs(inve2, inve1))); + var PofQ = KGAuthor.multiplyDefs(invc1, KGAuthor.raiseDefToDef(Q, inve1)); + intersection.Qdirect = Q; + intersection.Pcalc = PofQ; + // want to use (P, QofP) when either supply or demand is perfectly inelastic; otherwise want to use (Q, PofQ) + var eitherPerfectlyInelastic = "(" + KGAuthor.multiplyDefs(e1, e2) + " == 0)"; + intersection.Q = "(" + eitherPerfectlyInelastic + " ? " + QofP + " : " + Q + ")"; + intersection.P = "(" + eitherPerfectlyInelastic + " ? " + P + " : " + PofQ + ")"; + return _this; + } + EconConstantElasticityIntersection.prototype.parseSelf = function (parsedData) { + var c = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[c.name] = { + Pdirect: c.Pdirect, + Pcalc: c.Pcalc, + Qdirect: c.Qdirect, + Qcalc: c.Qcalc, + Q: c.Q, + P: c.P + }; + return parsedData; + }; + return EconConstantElasticityIntersection; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconConstantElasticityIntersection = EconConstantElasticityIntersection; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconConstantElasticityEquilibrium = /** @class */ (function (_super) { + __extends(EconConstantElasticityEquilibrium, _super); + function EconConstantElasticityEquilibrium(def, graph) { + var _this = this; + KG.setDefaults(def, { + name: 'equilibrium', + showCS: false, + showPS: false + }); + _this = _super.call(this, def, graph) || this; + var cee = _this; + def.equilibrium.color = def.equilibrium.color || "colors.green"; + var equilibrium = new KGAuthor.Point(def.equilibrium, graph); + cee.Q = equilibrium.x; + cee.P = equilibrium.y; + def.demand.point = def.equilibrium; + def.demand.name = def.name + "dem"; + def.demand.color = "colors.demand"; + var demand = new KGAuthor.EconConstantElasticityCurve(def.demand, graph); + console.log("demand: ", demand); + cee.subObjects.push(demand); + def.supply.point = def.equilibrium; + def.supply.name = def.name + "sup"; + def.supply.color = "colors.supply"; + var supply = new KGAuthor.EconConstantElasticityCurve(def.supply, graph); + console.log('supply: ', supply); + cee.subObjects.push(supply); + return _this; + } + EconConstantElasticityEquilibrium.prototype.parseSelf = function (parsedData) { + var cee = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[cee.name] = { + Q: cee.Q.toString(), + P: cee.P.toString() + }; + return parsedData; + }; + return EconConstantElasticityEquilibrium; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconConstantElasticityEquilibrium = EconConstantElasticityEquilibrium; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconLinearDemand = /** @class */ (function (_super) { + __extends(EconLinearDemand, _super); + function EconLinearDemand(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + KG.setDefaults(def, { + name: "demand", + point: [0, def.yIntercept], + slope: 0, + color: 'colors.demand', + strokeWidth: 2, + lineStyle: 'solid', + pts: [] + }); + if (def.draggable && typeof (def.xIntercept) == 'string') { + def.drag = [{ + 'directions': 'x', + 'param': KGAuthor.paramName(def.xIntercept), + 'expression': KGAuthor.addDefs(def.xIntercept, 'drag.dx') + }]; + } + else if (def.draggable && typeof (def.yIntercept) == 'string') { + def.drag = [{ + 'directions': 'y', + 'param': KGAuthor.paramName(def.yIntercept), + 'expression': KGAuthor.addDefs(def.yIntercept, 'drag.dy') + }]; + } + //def.max = def.xIntercept; + if (def.hasOwnProperty("price")) { + def.pts.push({ + name: "PQ", + y: def.price + }); + } + if (def.hasOwnProperty("surplus")) { + if (!def.hasOwnProperty("price") && def.surplus.hasOwnProperty("quantity")) { + def.pts.push({ + name: "PQ", + x: def.surplus.quantity + }); + } + } + _this = _super.call(this, def, graph) || this; + var ld = _this; + if (graph) { + var subObjects = ld.subObjects; + var xInterceptPointDef = { + coordinates: [ld.xIntercept, 0], + color: def.color, + r: 4 + }; + if (def.draggable && typeof (ld.xIntercept) == 'string') { + xInterceptPointDef['drag'] = [{ + directions: 'x', + param: KGAuthor.paramName(ld.xIntercept), + expression: KGAuthor.addDefs(ld.xIntercept, 'drag.dx') + }]; + } + if (def.hasOwnProperty('xInterceptLabel')) { + xInterceptPointDef['droplines'] = { + vertical: def.xInterceptLabel + }; + } + ld.xInterceptPoint = new KGAuthor.Point(xInterceptPointDef, graph); + var yInterceptPointDef = { + coordinates: [0, ld.yIntercept], + color: def.color, + r: 4 + }; + if (def.draggable && typeof (ld.yIntercept) == 'string') { + yInterceptPointDef['drag'] = [{ + directions: 'y', + param: KGAuthor.paramName(ld.invSlope), + expression: KGAuthor.negativeDef(KGAuthor.divideDefs(ld.xIntercept, 'max(drag.y,0.01)')) + }]; + } + if (def.hasOwnProperty('yInterceptLabel')) { + yInterceptPointDef['droplines'] = { + horizontal: def.yInterceptLabel + }; + } + ld.yInterceptPoint = new KGAuthor.Point(yInterceptPointDef, graph); + if (def.handles) { + subObjects.push(ld.xInterceptPoint); + subObjects.push(ld.yInterceptPoint); + } + if (def.hasOwnProperty('marginalRevenue')) { + var marginalRevenueDef = KG.setDefaults(def.marginalRevenue || {}, { + "color": "colors.marginalRevenue", + "yIntercept": ld.yIntercept, + "slope": KGAuthor.multiplyDefs(2, ld.slope), + "label": { + "text": "MR", + "x": KGAuthor.multiplyDefs(0.6, ld.xIntercept) + } + }); + ld.marginalRevenue = new KGAuthor.Line(marginalRevenueDef, graph); + ld.subObjects.push(ld.marginalRevenue); + } + if (def.hasOwnProperty('surplus')) { + var surplusDef = KG.setDefaults(def.surplus || {}, { + "fill": "colors.demand" + }); + var price = surplusDef.price || "calcs." + ld.name + ".PQ.y", quantity = surplusDef.quantity || "calcs." + ld.name + ".PQ.x"; + surplusDef.univariateFunction1 = { + fn: ld.def.univariateFunction.fn, + min: 0, + max: quantity, + samplePoints: 2 + }; + surplusDef.univariateFunction2 = { + fn: price, + min: 0, + max: quantity, + samplePoints: 2 + }; + ld.subObjects.push(new KGAuthor.Area(surplusDef, graph)); + } + } + return _this; + } + return EconLinearDemand; + }(KGAuthor.Line)); + KGAuthor.EconLinearDemand = EconLinearDemand; + var EconCompetitiveDemand = /** @class */ (function (_super) { + __extends(EconCompetitiveDemand, _super); + function EconCompetitiveDemand() { + return _super !== null && _super.apply(this, arguments) || this; + } + return EconCompetitiveDemand; + }(EconLinearDemand)); + KGAuthor.EconCompetitiveDemand = EconCompetitiveDemand; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconLinearSupply = /** @class */ (function (_super) { + __extends(EconLinearSupply, _super); + function EconLinearSupply(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + KG.setDefaults(def, { + name: 'supply', + color: 'colors.supply', + strokeWidth: 2, + lineStyle: 'solid', + pts: [] + }); + if (def.draggable && typeof (def.slope) == 'string') { + def.drag = [{ + 'directions': 'xy', + 'param': KGAuthor.paramName(def.slope), + 'expression': KGAuthor.divideDefs(KGAuthor.subtractDefs('drag.y', def.yIntercept), 'drag.x') + }]; + } + else if (def.draggable && typeof (def.invSlope) == 'string') { + def.drag = [{ + 'directions': 'xy', + 'param': KGAuthor.paramName(def.invSlope), + 'expression': KGAuthor.divideDefs('drag.x', KGAuthor.subtractDefs('drag.y', def.yIntercept)) + }]; + } + else if (def.draggable && typeof (def.yIntercept) == 'string') { + def.drag = [{ + 'directions': 'y', + 'param': KGAuthor.paramName(def.yIntercept), + 'expression': KGAuthor.addDefs(def.yIntercept, 'drag.dy') + }]; + } + if (def.hasOwnProperty("price")) { + def.pts.push({ + name: "PQ", + y: def.price + }); + } + _this = _super.call(this, def, graph) || this; + var ls = _this; + if (graph) { + var subObjects = ls.subObjects; + var yInterceptPointDef = { + coordinates: [0, ls.yIntercept], + color: def.color, + r: 4, + show: def.show + }; + if (def.draggable && typeof (ls.yIntercept) == 'string') { + yInterceptPointDef['drag'] = [{ + directions: 'y', + param: KGAuthor.paramName(ls.yIntercept), + expression: KGAuthor.addDefs(ls.yIntercept, 'drag.dy') + }]; + } + if (def.hasOwnProperty('yInterceptLabel')) { + yInterceptPointDef['droplines'] = { + horizontal: def.yInterceptLabel + }; + } + ls.yInterceptPoint = new KGAuthor.Point(yInterceptPointDef, graph); + if (def.handles) { + subObjects.push(ls.yInterceptPoint); + } + if (def.hasOwnProperty('surplus')) { + var surplusDef = KG.setDefaults(def.surplus || {}, { + "fill": "colors.supply" + }); + var price = surplusDef.price || "calcs." + ls.name + ".PQ.y", quantity = surplusDef.quantity || "calcs." + ls.name + ".PQ.x"; + surplusDef.univariateFunction1 = { + fn: ls.def.univariateFunction.fn, + min: 0, + max: quantity, + samplePoints: 2 + }; + surplusDef.univariateFunction2 = { + fn: price, + min: 0, + max: quantity, + samplePoints: 2 + }; + ls.subObjects.push(new KGAuthor.Area(surplusDef, graph)); + } + } + return _this; + } + return EconLinearSupply; + }(KGAuthor.Line)); + KGAuthor.EconLinearSupply = EconLinearSupply; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconLinearEquilibrium = /** @class */ (function (_super) { + __extends(EconLinearEquilibrium, _super); + function EconLinearEquilibrium(def, graph) { + var _this = this; + KG.setDefaults(def, { + name: 'equilibrium', + showCS: false, + showPS: false + }); + _this = _super.call(this, def, graph) || this; + var le = _this; + def.demand.price = "calcs." + le.name + ".P"; + def.supply.price = "calcs." + le.name + ".P"; + le.demand = new KGAuthor.EconLinearDemand(def.demand, graph); + le.supply = new KGAuthor.EconLinearSupply(def.supply, graph); + le.subObjects.push(_this.demand); + le.subObjects.push(_this.supply); + var eq = KGAuthor.lineIntersection(le.demand, le.supply); + le.Q = eq[0]; + le.P = eq[1]; + if (graph) { + if (def.hasOwnProperty('equilibrium')) { + def.equilibrium = KG.setDefaults(def.equilibrium, { + "color": "colors.equilibriumPrice", + "x": le.Q, + "y": le.P, + "droplines": { + "vertical": "Q^*", + "horizontal": "P^*" + } + }); + le.subObjects.push(new KGAuthor.Point(def.equilibrium, graph)); + } + } + return _this; + } + EconLinearEquilibrium.prototype.parseSelf = function (parsedData) { + var le = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[le.name] = { + Q: le.Q.toString(), + P: le.P.toString() + }; + return parsedData; + }; + return EconLinearEquilibrium; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconLinearEquilibrium = EconLinearEquilibrium; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconPPF = /** @class */ (function (_super) { + __extends(EconPPF, _super); + function EconPPF(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + KG.setDefaults(def, { + name: 'ppf', + color: 'colors.supply', + strokeWidth: 2, + lineStyle: 'solid', + labor: 100, + L1: 50, + p1: 1, + p2: 1, + max1: 100, + max2: 100, + curvature: 0.5 + }); + if (def.linear) { + def.curvature = 1; + } + var fn1coeff = KGAuthor.divideDefs(def.max1, KGAuthor.raiseDefToDef(def.labor, def.curvature)), fn2coeff = KGAuthor.divideDefs(def.max2, KGAuthor.raiseDefToDef(def.labor, def.curvature)); + var fn1 = new KGAuthor.EconOneInputProductionFunction({ + name: def.name + '_prodFn1', + coefficient: fn1coeff, + exponent: def.curvature + }), fn2 = new KGAuthor.EconOneInputProductionFunction({ + name: def.name + '_prodFn2', + coefficient: fn2coeff, + exponent: def.curvature + }); + def.parametricFunction = { + xFunction: fn1.f("(t)"), + yFunction: fn2.f(KGAuthor.subtractDefs(def.labor, "(t)")), + max: def.labor + }; + if (def.draggable) { + var dragLaborRequirement = KGAuthor.addDefs(fn1.laborRequirement('drag.x'), fn2.laborRequirement('drag.y')); + def.drag = [{ + 'directions': 'xy', + 'param': KGAuthor.paramName(def.max1), + 'expression': fn1.f(dragLaborRequirement) + }, + { + 'directions': 'xy', + 'param': KGAuthor.paramName(def.max2), + 'expression': fn2.f(dragLaborRequirement) + }]; + } + _this = _super.call(this, def, graph) || this; + var ppf = _this; + ppf.labor = def.labor; + ppf.prodFn1 = fn1; + ppf.prodFn2 = fn2; + ppf.subObjects.push(fn1); + ppf.subObjects.push(fn2); + ppf.L1 = def.L1; + ppf.L2 = KGAuthor.subtractDefs(def.labor, def.L1); + ppf.y1 = ppf.prodFn1.f(ppf.L1); + ppf.y2 = ppf.prodFn2.f(ppf.L2); + var coefficientRatio = KGAuthor.divideDefs(def.max2, def.max1), laborRatio = KGAuthor.divideDefs(ppf.L2, def.L1), priceRatio = KGAuthor.divideDefs(def.p1, def.p2); + if (def.curvature == 1) { + ppf.mrt = coefficientRatio; + ppf.optimalL1 = "((" + coefficientRatio + " > " + priceRatio + ") ? 0 : " + ppf.labor + ")"; + ppf.optimalL1 = "((" + coefficientRatio + " > " + priceRatio + ") ? " + ppf.labor + " : 0)"; + } + else { + ppf.mrt = KGAuthor.multiplyDefs(coefficientRatio, KGAuthor.raiseDefToDef(laborRatio, KGAuthor.subtractDefs(def.curvature, 1))); + var theta = KGAuthor.raiseDefToDef(KGAuthor.divideDefs(coefficientRatio, priceRatio), KGAuthor.invertDef(KGAuthor.subtractDefs(def.curvature, 1))); + ppf.optimalL1 = KGAuthor.multiplyDefs(KGAuthor.divideDefs(theta, KGAuthor.addDefs(1, theta)), ppf.labor); + ppf.optimalL2 = KGAuthor.multiplyDefs(KGAuthor.divideDefs(1, KGAuthor.addDefs(1, theta)), ppf.labor); + } + ppf.optimaly1 = ppf.prodFn1.f(ppf.optimalL1); + ppf.optimaly2 = ppf.prodFn2.f(ppf.optimalL2); + if (graph) { + var subObjects = ppf.subObjects; + var xInterceptPointDef = { + coordinates: [def.max1, 0], + fill: def.stroke, + r: 4 + }; + if (def.draggable && typeof (def.max1) == 'string') { + xInterceptPointDef['drag'] = [{ + directions: 'x', + param: KGAuthor.paramName(def.max1), + expression: KGAuthor.addDefs(def.max1, 'drag.dx') + }]; + } + if (def.hasOwnProperty('xInterceptLabel')) { + xInterceptPointDef['droplines'] = { + vertical: def.xInterceptLabel + }; + } + ppf.xInterceptPoint = new KGAuthor.Point(xInterceptPointDef, graph); + var yInterceptPointDef = { + coordinates: [0, def.max2], + fill: def.stroke, + r: 4 + }; + if (def.draggable && typeof (def.max2) == 'string') { + yInterceptPointDef['drag'] = [{ + directions: 'y', + param: KGAuthor.paramName(def.max2), + expression: KGAuthor.addDefs(def.max2, 'drag.dy') + }]; + } + if (def.hasOwnProperty('yInterceptLabel')) { + yInterceptPointDef['droplines'] = { + horizontal: def.yInterceptLabel + }; + } + ppf.yInterceptPoint = new KGAuthor.Point(yInterceptPointDef, graph); + if (def.handles) { + subObjects.push(ppf.xInterceptPoint); + subObjects.push(ppf.yInterceptPoint); + } + } + return _this; + } + EconPPF.prototype.parseSelf = function (parsedData) { + var ppf = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[ppf.name] = { + L1: ppf.L1, + L2: ppf.L2, + y1: ppf.y1, + y2: ppf.y2, + optimalL1: ppf.optimalL1, + optimalL2: ppf.optimalL2, + optimaly1: ppf.optimaly1, + optimaly2: ppf.optimaly2, + mrt: ppf.mrt + }; + return parsedData; + }; + return EconPPF; + }(KGAuthor.Curve)); + KGAuthor.EconPPF = EconPPF; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconLinearMC = /** @class */ (function (_super) { + __extends(EconLinearMC, _super); + function EconLinearMC(def, graph) { + return _super.call(this, def, graph) || this; + } + return EconLinearMC; + }(KGAuthor.EconLinearSupply)); + KGAuthor.EconLinearMC = EconLinearMC; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconLinearMonopoly = /** @class */ (function (_super) { + __extends(EconLinearMonopoly, _super); + function EconLinearMonopoly(def, graph) { + var _this = this; + KG.setDefaults(def, { + name: 'monopoly', + showCS: false, + showPS: false, + showProfit: false, + showDWL: false + }); + _this = _super.call(this, def, graph) || this; + var lm = _this; + def.demand.surplus = { show: def.showCS, price: "calcs." + lm.name + ".P", quantity: "calcs." + lm.name + ".Q" }; + def.cost.surplus = { show: def.showPS, price: "calcs." + lm.name + ".P", quantity: "calcs." + lm.name + ".Q" }; + lm.demand = new KGAuthor.EconLinearDemand(def.demand, graph); + lm.cost = new KGAuthor.EconLinearMC(def.cost, graph); + var intersectMRMC = KGAuthor.lineIntersection(lm.demand.marginalRevenue, lm.cost); + lm.Q = intersectMRMC[0]; + lm.P = lm.demand.yOfX(lm.Q); + lm.MRMC = lm.cost.yOfX(lm.Q); + var intersectDMC = KGAuthor.lineIntersection(lm.demand, lm.cost); + lm.competitiveQ = intersectDMC[0]; + lm.competitiveP = lm.demand.yOfX(lm.competitiveQ); + if (def.hasOwnProperty('showDWL')) { + var DWLDef = { + show: def.showDWL, + fill: "colors.dwl" + }; + DWLDef.univariateFunction1 = { + fn: lm.demand.def.univariateFunction.fn, + min: lm.Q, + max: lm.competitiveQ, + samplePoints: 2 + }; + DWLDef.univariateFunction2 = { + fn: lm.cost.def.univariateFunction.fn, + min: lm.Q, + max: lm.competitiveQ, + samplePoints: 2 + }; + lm.subObjects.push(new KGAuthor.Area(DWLDef, graph)); + } + lm.subObjects.push(_this.demand); + lm.subObjects.push(_this.cost); + return _this; + } + EconLinearMonopoly.prototype.parseSelf = function (parsedData) { + var lm = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[lm.name] = { + Q: lm.Q.toString(), + P: lm.P.toString(), + competitiveQ: lm.competitiveQ.toString(), + competitiveP: lm.competitiveP.toString() + }; + return parsedData; + }; + return EconLinearMonopoly; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconLinearMonopoly = EconLinearMonopoly; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var ExchangeEquilibriumBundle = /** @class */ (function (_super) { + __extends(ExchangeEquilibriumBundle, _super); + function ExchangeEquilibriumBundle(def, graph) { + var _this = this; + var agentA = new KGAuthor.EconBundle(def.agentA, graph), agentB = new KGAuthor.EconBundle(def.agentB, graph); + var p; + if (def.agentA.utilityFunction.type == 'CobbDouglas' && def.agentB.utilityFunction.type == 'CobbDouglas') { + var alphaW2 = function (agent) { + return KGAuthor.multiplyDefs(agent.y, agent.utilityFunction.alpha); + }, oneMinusAlphaW1 = function (agent) { + return KGAuthor.multiplyDefs(agent.x, KGAuthor.subtractDefs(1, agent.utilityFunction.alpha)); + }; + p = KGAuthor.divideDefs(KGAuthor.addDefs(alphaW2(agentA), alphaW2(agentB)), KGAuthor.addDefs(oneMinusAlphaW1(agentA), oneMinusAlphaW1(agentB))); + } + else { + console.log("We're just handling Edgeworth equilibrium with Cobb-Douglas so far..."); + } + KG.setDefaults(def, { + label: { text: 'E' }, + color: "colors.budget" + }); + def.utilityFunctionObject = agentA.utilityFunction; + def.budgetLine = { + p1: p, + p2: 1, + point: [agentA.x, agentA.y] + }; + _this = _super.call(this, def, graph) || this; + return _this; + } + return ExchangeEquilibriumBundle; + }(KGAuthor.EconOptimalBundle)); + KGAuthor.ExchangeEquilibriumBundle = ExchangeEquilibriumBundle; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconContractCurve = /** @class */ (function (_super) { + __extends(EconContractCurve, _super); + function EconContractCurve(def, graph) { + var _this = this; + var a = def.a, b = def.b, ab = KGAuthor.multiplyDefs(a, b), aMinusABtimesX = KGAuthor.multiplyDefs(KGAuthor.subtractDefs(a, ab), def.totalGood1), bMinusABtimesY = KGAuthor.multiplyDefs(KGAuthor.subtractDefs(b, ab), def.totalGood2), bMinusA = KGAuthor.subtractDefs(b, a), fnString = bMinusABtimesY + "*(x)/(" + aMinusABtimesX + " + " + bMinusA + "*(x))"; + def.univariateFunction = { fn: fnString }; + KG.setDefaults(def, { + interpolation: 'curveMonotoneX', + color: 'colors.budget' + }); + _this = _super.call(this, def, graph) || this; + _this.fnString = fnString; + return _this; + } + EconContractCurve.prototype.parseSelf = function (parsedData) { + var cc = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs['cc'] = cc.fnString; + return parsedData; + }; + return EconContractCurve; + }(KGAuthor.Curve)); + KGAuthor.EconContractCurve = EconContractCurve; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconParetoLens = /** @class */ (function (_super) { + __extends(EconParetoLens, _super); + function EconParetoLens(def, graph) { + var _this = _super.call(this, def, graph) || this; + _this.subObjects.push(new KGAuthor.Rectangle({ + clipPathName: def.bundleA + "_IC_above", + clipPathName2: def.bundleB + "_IC_above", + x1: graph.def.xAxis.min, + x2: graph.def.xAxis.max, + y1: graph.def.yAxis.min, + y2: graph.def.yAxis.max, + fill: "colors.paretoLens", + opacity: "0.8", + show: def.show + }, graph)); + return _this; + } + return EconParetoLens; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconParetoLens = EconParetoLens; +})(KGAuthor || (KGAuthor = {})); +/// +/* SCHEMAS */ +/// +/// +/* LAYOUTS */ +/// +/// +/* FUNCTIONAL FORMS */ +/// +/// +/// +/// +/// +/// +/// +/* MICRO */ +/* Consumer Theory */ +/// +/// +/// +/// +/// +/// +/* Producer Theory */ +/// +/* Equilibrium */ +/// +/// +/// +/// +/// +/// +/* Monopoly */ +/// +/// +/* Exchange */ +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +var KG; +(function (KG) { + var Model = /** @class */ (function () { + function Model(parsedData) { + var model = this; + model.params = parsedData.params.map(function (def) { + return new KG.Param(def); + }); + model.initialParams = parsedData.params; + model.calcs = parsedData.calcs; + model.colors = parsedData.colors; + model.idioms = parsedData.idioms; + model.clearColor = parsedData.clearColor; + model.restrictions = (parsedData.restrictions || []).map(function (def) { + return new KG.Restriction(def); + }); + model.updateListeners = []; + model.currentParamValues = model.evalParams(); + model.evalCalcs(); + model.currentColors = model.evalObject(model.colors); + model.currentIdioms = model.evalObject(model.idioms); + } + Model.prototype.addUpdateListener = function (updateListener) { + this.updateListeners.push(updateListener); + return this; + }; + Model.prototype.resetParams = function () { + console.log("resetting model parameters"); + var model = this; + console.log('initial parameters are: ', model.initialParams); + model.initialParams.forEach(function (p) { + console.log('setting ', p.name, ' to ', p.value); + model.updateParam(p.name, p.value); + }); + model.update(true); + }; + Model.prototype.evalParams = function () { + var p = {}; + this.params.forEach(function (param) { + p[param.name] = param.value; + }); + return p; + }; + // evaluates the calcs object; then re-evaluates to capture calcs that depend on other calcs + Model.prototype.evalCalcs = function () { + var model = this; + // clear calculations so old values aren't used; + model.currentCalcValues = {}; + // generate as many calculations from params as possible + model.currentCalcValues = model.evalObject(model.calcs, true); + // calculate values based on other calculations (up to a depth of 5) + for (var i = 0; i < 5; i++) { + for (var calcName in model.currentCalcValues) { + if (typeof model.calcs[calcName] == 'object') { + model.currentCalcValues[calcName] = model.evalObject(model.calcs[calcName], true); + } + else if (isNaN(model.currentCalcValues[calcName]) && typeof model.calcs[calcName] == 'string') { + model.currentCalcValues[calcName] = model.evaluate(model.calcs[calcName], true); + } + } + } + return model.currentCalcValues; + }; + Model.prototype.evalObject = function (obj, onlyJSMath) { + var model = this; + var newObj = {}; + for (var stringOrObj in obj) { + var def = obj[stringOrObj]; + if (typeof def === 'number') { + newObj[stringOrObj] = def; + } + else if (typeof def === 'string') { + newObj[stringOrObj] = model.evaluate(def, onlyJSMath); + } + else { + newObj[stringOrObj] = model.evalObject(def, onlyJSMath); + } + } + return newObj; + }; + // the model serves as a model, and can evaluate expressions within the context of that model + // if onlyJSMath is selected, it will only try to evaluate using JSMath; this is especially important for calculations. + Model.prototype.evaluate = function (name, onlyJSMath) { + var model = this; + // don't just evaluate numbers + if (!isNaN(parseFloat(name))) { + //console.log('interpreted ', name, 'as a number.'); + return parseFloat(name); + } + // collect current values in a scope object + var params = model.currentParamValues, calcs = model.currentCalcValues, colors = model.currentColors, idioms = model.currentIdioms; + //console.log('trying to parse ', name); + // try to evaluate using mathjs + try { + var compiledMath = math.compile(name); + var result = compiledMath.evaluate({ + params: params, + calcs: calcs, + idioms: idioms, + colors: colors + }); + //onsole.log('parsed', name, 'as ', result); + return result; + } + catch (err) { + // if that doesn't work, try to evaluate using native js eval + //console.log('unable to parse', name, 'as a pure math function, trying general eval'); + //console.log('parsing did not work'); + if (onlyJSMath) { + return name; + } + else { + try { + var result = eval(name); + //console.log('parsed', name, 'as an expression with value', result); + return result; + } + catch (err) { + //console.log('unable to parse', name, 'as a valid expression; generates error:', err.message); + return name; + } + } + } + }; + // This is a utility for exporting currently used colors for use in LaTex documents. + Model.prototype.latexColors = function () { + var result = '%% econ colors %%\n', model = this; + for (var color in model.colors) { + result += "\\definecolor{" + color + "}{HTML}{" + model.evaluate(model.colors[color]).replace('#', '') + "}\n"; + } + console.log(result); + }; + Model.prototype.getParam = function (paramName) { + var params = this.params; + for (var i = 0; i < params.length; i++) { + if (params[i].name == paramName) { + return params[i]; + } + } + }; + // method exposed to viewObjects to allow them to try to change a parameter + Model.prototype.updateParam = function (name, newValue) { + var model = this, param = model.getParam(name); + var oldValue = param.value; + param.update(newValue); + // if param has changed, check to make sure the change is val + if (oldValue != param.value) { + //restrictions aren't working right now + var valid_1 = true; + model.restrictions.forEach(function (r) { + if (!r.valid(model)) { + valid_1 = false; + } + }); + if (valid_1) { + model.update(false); + } + else { + param.update(oldValue); + } + model.update(false); + } + }; + // method exposed to viewObjects to allow them to toggle a binary param + Model.prototype.toggleParam = function (name) { + var currentValue = this.getParam(name).value; + this.updateParam(name, !currentValue); + }; + // method exposed to viewObjects to allow them to cycle a discrete param + // increments by 1 if below max value, otherwise sets to zero + Model.prototype.cycleParam = function (name) { + var param = this.getParam(name); + this.updateParam(name, param.value < param.max ? param.value++ : 0); + }; + Model.prototype.update = function (force) { + var model = this; + model.currentParamValues = model.evalParams(); + model.evalCalcs(); + console.log('calcs', model.currentCalcValues); + model.currentColors = model.evalObject(model.colors); + model.updateListeners.forEach(function (listener) { + listener.update(force); + }); + }; + return Model; + }()); + KG.Model = Model; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Param = /** @class */ (function () { + function Param(def) { + function decimalPlaces(numAsString) { + var match = ('' + numAsString).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); + if (!match) { + return 0; + } + return Math.max(0, + // Number of digits right of decimal point. + (match[1] ? match[1].length : 0) + // Adjust for scientific notation. + - (match[2] ? +match[2] : 0)); + } + KG.setDefaults(def, { min: 0, max: 10, round: 1, label: '' }); + this.name = def.name; + this.label = def.label; + if (typeof def.value == 'boolean') { + this.value = +def.value; + this.min = 0; + this.max = 100; + this.round = 1; + } + else { + this.value = parseFloat(def.value); + this.min = parseFloat(def.min); + this.max = parseFloat(def.max); + this.round = parseFloat(def.round); + this.precision = parseInt(def.precision) || decimalPlaces(this.round.toString()); + } + } + // Receives an instruction to update the parameter to a new value + // Updates to the closest rounded value to the desired newValue within accepted range + Param.prototype.update = function (newValue) { + var param = this; + if (newValue < param.min) { + param.value = param.min; + } + else if (newValue > param.max) { + param.value = param.max; + } + else { + param.value = Math.round(newValue / param.round) * param.round; + } + return param.value; + }; + // Displays current value of the parameter to desired precision + // If no precision is given, uses the implied precision given by the rounding parameter + Param.prototype.formatted = function (precision) { + precision = precision || this.precision; + return d3.format("." + precision + "f")(this.value); + }; + return Param; + }()); + KG.Param = Param; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Restriction = /** @class */ (function () { + function Restriction(def) { + this.expression = def.expression; + this.type = def.type; + this.min = def.min; + this.max = def.max; + } + Restriction.prototype.valid = function (model) { + var r = this, value = model.evaluate(r.expression), min = model.evaluate(r.min), max = model.evaluate(r.max); + // restrictions aren't working right now + return true; + //return (value >= min && value <= max); + }; + return Restriction; + }()); + KG.Restriction = Restriction; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + function randomString(length) { + var text = "KGID_"; + var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + for (var i = 0; i < length; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; + } + KG.randomString = randomString; + var UpdateListener = /** @class */ (function () { + function UpdateListener(def) { + def.constants = (def.constants || []).concat(['model', 'updatables', 'name']); + var ul = this; + ul.def = def; + def.constants.forEach(function (c) { + ul[c] = isNaN(parseFloat(def[c])) ? def[c] : +def[c]; + }); + ul.id = randomString(10); + ul.model.addUpdateListener(this); + } + UpdateListener.prototype.updateArray = function (a) { + var u = this; + return a.map(function (d) { + if (Array.isArray(d)) { + return u.updateArray(d); + } + else { + var initialValue = d; + var newValue = u.model.evaluate(d); + if (initialValue != newValue) { + u.hasChanged = true; + } + return newValue; + } + }); + }; + UpdateListener.prototype.updateDef = function (name) { + var u = this; + if (u.def.hasOwnProperty(name)) { + var d = u.def[name], initialValue = u[name]; + if (Array.isArray(d)) { + u[name] = u.updateArray(d); + } + else { + var newValue = u.model.evaluate(d); + if (initialValue != newValue) { + u.hasChanged = true; + u[name] = newValue; + } + } + //console.log(u.constructor['name'],name,'changed from',initialValue,'to',u[name]); + } + return u; + }; + UpdateListener.prototype.update = function (force) { + var u = this; + u.hasChanged = !!force; + if (u.hasOwnProperty('updatables') && u.updatables != undefined) { + u.updatables.forEach(function (name) { + u.updateDef(name); + }); + } + return u; + }; + return UpdateListener; + }()); + KG.UpdateListener = UpdateListener; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var MathFunction = /** @class */ (function (_super) { + __extends(MathFunction, _super); + function MathFunction(def) { + var _this = this; + KG.setDefaults(def, { + samplePoints: 50 + }); + KG.setProperties(def, 'constants', ['samplePoints']); + KG.setProperties(def, 'updatables', ['min', 'max']); + _this = _super.call(this, def) || this; + return _this; + } + MathFunction.prototype.updateFunctionString = function (str, scope) { + function getCalc(o, s) { + s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties + s = s.replace(/^\./, ''); // strip a leading dot + var a = s.split('.'); + for (var i = 0, n = a.length; i < n; ++i) { + var k = a[i]; + if (k in o) { + o = o[k]; + } + else { + return; + } + } + return o; + } + str = str.toString(); + if (str.indexOf('null') > -1 || str.indexOf('Infinity') > -1) { + return null; + } + var re = /((calcs|params).[.\w]*)+/g; + var references = str.match(re); + if (references) { + references.forEach(function (name) { + str = KGAuthor.replaceVariable(str, name, getCalc(scope, name)); + }); + } + //console.log('updated function to ',str); + return str; + }; + return MathFunction; + }(KG.UpdateListener)); + KG.MathFunction = MathFunction; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var MathFunction = KG.MathFunction; + var UnivariateFunction = /** @class */ (function (_super) { + __extends(UnivariateFunction, _super); + function UnivariateFunction(def) { + var _this = this; + KG.setDefaults(def, { + ind: 'x' + }); + KG.setProperties(def, 'constants', ['fn', 'yFn']); + KG.setProperties(def, 'updatables', ['ind', 'min', 'max']); + _this = _super.call(this, def) || this; + _this.fnStringDef = def.fn; + _this.fnZStringDef = def.fnZ; + _this.yFnStringDef = def.yFn; + _this.yFnZStringDef = def.yFnZ; + return _this; + } + UnivariateFunction.prototype.evaluate = function (input, z) { + var fn = this; + if (z) { + if (fn.hasOwnProperty('yzCompiledFunction') && fn.ind == 'y') { + return fn.yzCompiledFunction.evaluate({ y: input }); + } + else if (fn.hasOwnProperty('zCompiledFunction') && fn.ind == 'y') { + return fn.zCompiledFunction.evaluate({ y: input }); + } + else if (fn.hasOwnProperty('zCompiledFunction')) { + return fn.zCompiledFunction.evaluate({ x: input }); + } + } + else { + if (fn.hasOwnProperty('yCompiledFunction') && fn.ind == 'y') { + return fn.yCompiledFunction.evaluate({ y: input }); + } + else if (fn.hasOwnProperty('compiledFunction') && fn.ind == 'y') { + return fn.compiledFunction.evaluate({ y: input }); + } + else if (fn.hasOwnProperty('compiledFunction')) { + return fn.compiledFunction.evaluate({ x: input }); + } + } + }; + UnivariateFunction.prototype.generateData = function (min, max) { + var fn = this, data = []; + if (undefined != fn.min) { + min = fn.min; + } + if (undefined != fn.max) { + max = fn.max; + } + for (var i = 0; i < fn.samplePoints + 1; i++) { + var a = i / fn.samplePoints, input = a * min + (1 - a) * max, output = fn.evaluate(input); + if (!isNaN(output) && output != Infinity && output != -Infinity) { + data.push((fn.ind == 'x') ? { x: input, y: output } : { x: output, y: input }); + } + } + this.data = data; + return data; + }; + UnivariateFunction.prototype.mathboxFn = function (mathbox) { + var fn = this; + if (fn.ind == 'y') { + return function (emit, y) { + var x = fn.evaluate(y), z = fn.evaluate(y, true); + if (x >= mathbox.xAxis.min && x <= mathbox.xAxis.max && z >= mathbox.zAxis.min && z <= mathbox.zAxis.max) { + emit(y, z, x); + } + }; + } + else { + return function (emit, x) { + var y = fn.evaluate(x), z = fn.evaluate(x, true); + if (y >= mathbox.yAxis.min && y <= mathbox.yAxis.max && z >= mathbox.zAxis.min && z <= mathbox.zAxis.max) { + emit(y, z, x); + } + }; + } + }; + UnivariateFunction.prototype.update = function (force) { + var fn = _super.prototype.update.call(this, force); + //console.log('updating; currently ', fn.fnString); + fn.scope = { + params: fn.model.currentParamValues, + calcs: fn.model.currentCalcValues, + colors: fn.model.currentColors + }; + var originalString = fn.fnString; + if (originalString != fn.updateFunctionString(fn.fnStringDef, fn.scope)) { + fn.hasChanged = true; + fn.fnString = fn.updateFunctionString(fn.fnStringDef, fn.scope); + fn.compiledFunction = math.compile(fn.fnString); + } + if (fn.def.hasOwnProperty('yFn')) { + if (fn.yFnString != fn.updateFunctionString(fn.yFnStringDef, fn.scope)) { + fn.hasChanged = true; + fn.yFnString = fn.updateFunctionString(fn.yFnStringDef, fn.scope); + fn.yCompiledFunction = math.compile(fn.yFnString); + } + } + if (fn.def.hasOwnProperty('fnZ')) { + if (fn.fnZString != fn.updateFunctionString(fn.fnZStringDef, fn.scope)) { + fn.hasChanged = true; + fn.fnZString = fn.updateFunctionString(fn.fnZStringDef, fn.scope); + fn.zCompiledFunction = math.compile(fn.fnZString); + } + } + if (fn.def.hasOwnProperty('yFnZ')) { + if (fn.yFnZString != fn.updateFunctionString(fn.yFnZStringDef, fn.scope)) { + fn.hasChanged = true; + fn.yFnZString = fn.updateFunctionString(fn.yFnZStringDef, fn.scope); + fn.yzCompiledFunction = math.compile(fn.yFnZString); + } + } + return fn; + }; + return UnivariateFunction; + }(MathFunction)); + KG.UnivariateFunction = UnivariateFunction; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var ParametricFunction = /** @class */ (function (_super) { + __extends(ParametricFunction, _super); + function ParametricFunction(def) { + var _this = this; + KG.setDefaults(def, { + min: 0, + max: 10 + }); + _this = _super.call(this, def) || this; + _this.xFunctionStringDef = def.xFunction; + _this.yFunctionStringDef = def.yFunction; + return _this; + } + ParametricFunction.prototype.evaluate = function (input) { + var fn = this; + fn.scope = fn.scope || { params: fn.model.currentParamValues }; + fn.scope.t = input; + return { x: fn.xCompiledFunction.evaluate(fn.scope), y: fn.yCompiledFunction.evaluate(fn.scope) }; + }; + ParametricFunction.prototype.generateData = function (min, max) { + var fn = this, data = []; + if (undefined != fn.min) { + min = fn.min; + } + if (undefined != fn.max) { + max = fn.max; + } + for (var i = 0; i < fn.samplePoints + 1; i++) { + var a = i / fn.samplePoints, input = a * min + (1 - a) * max, output = fn.evaluate(input); + if (!isNaN(output.x) && output.x != Infinity && output.x != -Infinity && !isNaN(output.y) && output.y != Infinity && output.y != -Infinity) { + data.push(output); + } + } + this.data = data; + return data; + }; + ParametricFunction.prototype.update = function (force) { + var fn = _super.prototype.update.call(this, force); + //console.log('updating; currently ', fn.fnString); + fn.scope = { + params: fn.model.currentParamValues, + calcs: fn.model.currentCalcValues, + colors: fn.model.currentColors + }; + var originalXFunctionString = fn.xFunctionString; + if (originalXFunctionString != fn.updateFunctionString(fn.xFunctionStringDef, fn.scope)) { + fn.hasChanged = true; + fn.xFunctionString = fn.updateFunctionString(fn.xFunctionStringDef, fn.scope); + fn.xCompiledFunction = math.compile(fn.xFunctionString); + } + var originalYFunctionString = fn.yFunctionString; + if (originalYFunctionString != fn.updateFunctionString(fn.yFunctionStringDef, fn.scope)) { + fn.hasChanged = true; + fn.yFunctionString = fn.updateFunctionString(fn.yFunctionStringDef, fn.scope); + fn.yCompiledFunction = math.compile(fn.yFunctionString); + } + return fn; + }; + return ParametricFunction; + }(KG.MathFunction)); + KG.ParametricFunction = ParametricFunction; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var MathFunction = KG.MathFunction; + var MultivariateFunction = /** @class */ (function (_super) { + __extends(MultivariateFunction, _super); + function MultivariateFunction(def) { + var _this = this; + def.samplePoints = 100; + KG.setProperties(def, 'constants', ['fn']); + _this = _super.call(this, def) || this; + _this.fnStringDef = def.fn; + _this.domainConditionStringDef = def.domainCondition; + return _this; + } + MultivariateFunction.prototype.inDomain = function (x, y, z) { + var fn = this; + if (fn.hasOwnProperty('compiledDomainCondition')) { + return fn.compiledDomainCondition.evaluate({ x: x, y: y, z: z }); + } + else { + return true; + } + }; + MultivariateFunction.prototype.evaluate = function (x, y) { + var fn = this; + if (fn.hasOwnProperty('compiledFunction')) { + var z = fn.compiledFunction.evaluate({ x: x, y: y }); + if (fn.inDomain(x, y, z)) { + return z; + } + } + }; + MultivariateFunction.prototype.mathboxFn = function () { + var fn = this; + return function (emit, x, y) { + emit(y, fn.evaluate(x, y), x); + }; + }; + MultivariateFunction.prototype.contour = function (level, xScale, yScale, bounds) { + var fn = this; + bounds = KG.setDefaults(bounds || {}, { + xMin: xScale.domainMin, + xMax: xScale.domainMax, + yMin: yScale.domainMin, + yMax: yScale.domainMax + }); + var n = 100, m = 100, values = new Array(n * m); + for (var j = 0.5, k = 0; j < m; ++j) { + for (var i = 0.5; i < n; ++i, ++k) { + var x = bounds.xMin + i * (bounds.xMax - bounds.xMin) / n, y = bounds.yMin + j * (bounds.yMax - bounds.yMin) / m; + values[k] = fn.evaluate(x, y); + } + } + var transform = function (_a) { + var type = _a.type, value = _a.value, coordinates = _a.coordinates; + return { + type: type, value: value, coordinates: coordinates.map(function (rings) { + return rings.map(function (points) { + return points.map(function (_a) { + var x = _a[0], y = _a[1]; + return ([xScale.scale(bounds.xMin + x * (bounds.xMax - bounds.xMin) / 100), yScale.scale(bounds.yMin + y * (bounds.yMax - bounds.yMin) / 100)]); + }); + }); + }) + }; + }; + var p = d3.geoPath(); + // Compute the contour polygons at log-spaced intervals; returns an array of MultiPolygon. + var contourLine = d3.contours().size([n, m]).contour(values, level); + return p(transform(contourLine)); + }; + MultivariateFunction.prototype.update = function (force) { + var fn = _super.prototype.update.call(this, force); + //console.log('updating; currently ', fn.fnString); + fn.scope = { + params: fn.model.currentParamValues, + calcs: fn.model.currentCalcValues, + colors: fn.model.currentColors + }; + var originalString = fn.fnString, originalDomainCondition = fn.domainConditionString; + if (originalString != fn.updateFunctionString(fn.fnStringDef, fn.scope)) { + fn.hasChanged = true; + fn.fnString = fn.updateFunctionString(fn.fnStringDef, fn.scope); + fn.compiledFunction = math.compile(fn.fnString); + } + if (fn.domainConditionStringDef != undefined) { + if (originalDomainCondition != fn.updateFunctionString(fn.domainConditionStringDef, fn.scope)) { + fn.hasChanged = true; + fn.domainConditionString = fn.updateFunctionString(fn.domainConditionStringDef, fn.scope); + fn.compiledDomainCondition = math.compile(fn.domainConditionString); + } + } + return fn; + }; + return MultivariateFunction; + }(MathFunction)); + KG.MultivariateFunction = MultivariateFunction; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + /* + + A listener is defined by a param and an expression. + When the interactionHandler senses a change, it generates a scope of the current state of the model. + The listener then determines the current value of its expression within the context of that scope, + and sends a signal to the model to update its param. + + */ + var Listener = /** @class */ (function (_super) { + __extends(Listener, _super); + function Listener(def) { + var _this = this; + KG.setProperties(def, 'updatables', ['expression']); + KG.setProperties(def, 'constants', ['param']); + _this = _super.call(this, def) || this; + return _this; + } + Listener.prototype.onChange = function (scope) { + var l = this, compiledMath = math.compile(l.expression); + var parsedMath = compiledMath.evaluate(scope); + l.model.updateParam(l.param, parsedMath); + }; + return Listener; + }(KG.UpdateListener)); + KG.Listener = Listener; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + /* + + A DragListener is a special kind of Listener that listens for drag events. + In addition to a param and an expression, it has properties for whether it is draggable + and, if so, in which directions it is draggable. + + */ + var DragListener = /** @class */ (function (_super) { + __extends(DragListener, _super); + function DragListener(def) { + var _this = this; + if (def.hasOwnProperty('vertical')) { + def.directions = 'y'; + def.param = def.vertical; + def.expression = "params." + def.vertical + " + drag.dy"; + } + if (def.hasOwnProperty('horizontal')) { + def.directions = 'x'; + def.param = def.horizontal; + def.expression = "params." + def.horizontal + " + drag.dx"; + } + KG.setDefaults(def, { + directions: "xy" + }); + KG.setProperties(def, 'updatables', ['draggable', 'directions']); + _this = _super.call(this, def) || this; + return _this; + } + DragListener.prototype.update = function (force) { + var dl = _super.prototype.update.call(this, force); + if (!dl.def.hasOwnProperty('draggable')) { + dl.draggable = (dl.directions.length > 0); + } + return dl; + }; + return DragListener; + }(KG.Listener)); + KG.DragListener = DragListener; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var ClickListener = /** @class */ (function (_super) { + __extends(ClickListener, _super); + function ClickListener(def) { + var _this = this; + KG.setDefaults(def, { transitions: [1, 0] }); // default to toggle on/off + _this = _super.call(this, def) || this; + _this.transitions = def.transitions; + return _this; + } + ClickListener.prototype.click = function () { + var c = this; + console.log("clicking", c); + var current = c.model.currentParamValues[c.param]; + var newvalue = c.transitions[current]; + c.model.updateParam(c.param, newvalue); + }; + return ClickListener; + }(KG.Listener)); + KG.ClickListener = ClickListener; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var InteractionHandler = /** @class */ (function (_super) { + __extends(InteractionHandler, _super); + function InteractionHandler(def) { + var _this = this; + KG.setDefaults(def, { dragListeners: [], clickListeners: [] }); + KG.setProperties(def, 'constants', ["viewObject", "dragListeners", "clickListeners"]); + _this = _super.call(this, def) || this; + _this.update(true); + _this.scope = { params: {}, calcs: {}, colors: {}, drag: {} }; + return _this; + } + InteractionHandler.prototype.update = function (force) { + var ih = _super.prototype.update.call(this, force); + // first update dragListeners + if (ih.hasChanged && ih.hasOwnProperty('dragListeners') && (ih.element != undefined)) { + var xDrag_1 = false, yDrag_1 = false; + ih.dragListeners.forEach(function (dul) { + dul.update(force); + if (dul.directions == "x") { + xDrag_1 = true; + } + else if (dul.directions == "y") { + yDrag_1 = true; + } + else if (dul.directions == "xy") { + xDrag_1 = true; + yDrag_1 = true; + } + }); + ih.element.style("pointer-events", (xDrag_1 || yDrag_1) ? "all" : "none"); + ih.element.style("cursor", (xDrag_1 && yDrag_1) ? "move" : xDrag_1 ? "ew-resize" : "ns-resize"); + } + if (ih.hasOwnProperty('clickListeners') && (ih.element != undefined)) { + if (ih.clickListeners.length > 0) { + ih.element.style("pointer-events", "all"); + ih.element.style("cursor", "pointer"); + } + } + return ih; + }; + InteractionHandler.prototype.addTrigger = function (element) { + var handler = this; + handler.element = element; + // add click listeners + if (handler.clickListeners.length > 0) { + element.on("click", function () { + handler.clickListeners.forEach(function (c) { c.click(); }); + }); + } + // add drag listeners + if (handler.dragListeners.length > 0) { + element.call(d3.drag() + .on('start', function () { + handler.scope.params = handler.model.currentParamValues; + handler.scope.calcs = handler.model.currentCalcValues; + handler.scope.colors = handler.model.currentColors; + handler.scope.drag.x0 = handler.viewObject.xScale.scale.invert(d3.event.x); + handler.scope.drag.y0 = handler.viewObject.yScale.scale.invert(d3.event.y); + }) + .on('drag', function () { + var drag = handler.scope.drag; + drag.x = handler.viewObject.xScale.scale.invert(d3.event.x); + drag.y = handler.viewObject.yScale.scale.invert(d3.event.y); + drag.dx = drag.x - drag.x0; + drag.dy = drag.y - drag.y0; + handler.dragListeners.forEach(function (d) { + d.onChange(handler.scope); + }); + }) + .on('end', function () { + //handler.element.style("cursor","default"); + })); + } + handler.update(true); + }; + return InteractionHandler; + }(KG.UpdateListener)); + KG.InteractionHandler = InteractionHandler; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + KG.viewData = {}; + function addView(name, def) { + KG.viewData[name] = def; + } + KG.addView = addView; + var View = /** @class */ (function () { + function View(div, data) { + this.render(data, div); + } + View.prototype.parse = function (data, div) { + if (data.hasOwnProperty('templateDefaults')) { + // Any terms not defined in the user's overrides should revert to the template defaults + var defaults = data.templateDefaults; + var dataString = JSON.stringify(data); + for (var key in defaults) { + var searchTerm = new RegExp("template.\\b" + key + "\\b", "g"); + var replaceTerm = defaults[key]; + dataString = dataString.replace(searchTerm, replaceTerm); + } + data = JSON.parse(dataString); + } + data.schema = data.schema || "Schema"; + // allow user to specify param overrides or select idioms in methods + var urlParams = new URLSearchParams(window.location.search); + // override params + data.params = (data.params || []).map(function (paramData) { + // allow author to override initial parameter values by specifying them as div attributes + if (div.hasAttribute(paramData.name)) { + paramData.value = div.getAttribute(paramData.name); + } + // allow user to override parameter values by specifying them in the URL + var urlParamValue = urlParams.get(paramData.name); + /* console.log("Searching for ", paramData.name) + if (urlParamValue) { + console.log(urlParamValue) + } else { + console.log('not found') + }*/ + if (urlParamValue) { + paramData.value = urlParamValue; + } + // convert boolean params from strings to numbers + if (paramData.value == 'true') { + paramData.value = 1; + } + if (paramData.value == 'false') { + paramData.value = 0; + } + // convert numerical params from strings to numbers + paramData.value = isNaN(+paramData.value) ? paramData.value : +paramData.value; + return paramData; + }); + // allow author to set clear color as div attribute + if (div.hasAttribute("clearColor")) { + data.clearColor = div.getAttribute("clearColor"); + } + var parsedData = { + templateDefaults: data.templateDefaults || {}, + aspectRatio: data.aspectRatio || 1, + clearColor: data.clearColor || "#FFFFFF", + params: data.params || [], + calcs: data.calcs || {}, + colors: data.colors || {}, + custom: data.custom || "", + idioms: {}, + restrictions: data.restrictions, + clipPaths: data.clipPaths || [], + markers: data.markers || [], + scales: data.scales || [{ + name: 'x', + axis: 'x', + rangeMin: 0, + rangeMax: 1, + domainMin: 0, + domainMax: 1 + }, + { + name: 'y', + axis: 'y', + rangeMin: 0, + rangeMax: 1, + domainMin: 0, + domainMax: 1 + }], + layers: data.layers || [[], [], [], []], + divs: data.divs || [] + }; + data.objects = data.objects || []; + if (data.hasOwnProperty('layout')) { + if (data.layout.hasOwnProperty('type')) { + data.objects.push(data.layout); + } + else { + var layoutType = Object.keys(data.layout)[0], layoutDef = data.layout[layoutType]; + data.objects.push({ type: layoutType, def: layoutDef }); + } + } + if (data.hasOwnProperty('explanation')) { + data.objects.push({ type: "Explanation", def: data.explanation }); + } + if (data.hasOwnProperty('schema')) { + if (urlParams.get('custom')) { + parsedData.custom = urlParams.get('custom'); + } + data.objects.push({ type: data.schema, def: { custom: parsedData.custom } }); + } + console.log('parsed data: ', parsedData); + return KGAuthor.parse(data.objects, parsedData); + }; + View.prototype.render = function (data, div) { + var view = this; + var parsedData = view.parse(data, div); + console.log('parsedData: ', parsedData); + div.innerHTML = ""; + view.aspectRatio = data.aspectRatio || parsedData.aspectRatio || 1; + view.model = new KG.Model(parsedData); + // create scales + view.scales = parsedData.scales.map(function (def) { + def.model = view.model; + return new KG.Scale(def); + }); + // create the div for the view + view.div = d3.select(div) + .style('position', 'relative'); + // create a spacer div to make sure text flows properly around the graph + view.svgContainerDiv = view.div.append('div') + .style('position', 'absolute') + .style('left', '0px') + .style('top', '0px'); + // create the SVG element for the view + if (!parsedData.nosvg) { + view.svg = view.svgContainerDiv.append('svg') + .style('overflow', 'visible') + .style('pointer-events', 'none'); + } + view.addViewObjects(parsedData); + view.parsedData = parsedData; + }; + // add view information (model, layer, scales) to an object + View.prototype.addViewToDef = function (def, layer) { + var view = this; + function getScale(name) { + var result = null; + view.scales.forEach(function (scale) { + if (scale.name == name) { + result = scale; + } + }); + return result; + } + def.model = view.model; + def.layer = layer; + def.xScale = getScale(def['xScaleName']); + def.yScale = getScale(def['yScaleName']); + if (def.hasOwnProperty('xScale2Name')) { + def.xScale2 = getScale(def['xScale2Name']); + def.yScale2 = getScale(def['yScale2Name']); + } + return def; + }; + // create view objects + View.prototype.addViewObjects = function (data) { + var view = this; + var defURLS = {}; + if (view.svg) { + var defLayer_1 = view.svg.append('defs'); + // create ClipPaths, generate their URLs, and add their paths to the SVG defs element. + if (data.clipPaths.length > 0) { + data.clipPaths.forEach(function (def) { + var clipPathURL = KG.randomString(10); + var clipPathLayer = defLayer_1.append('clipPath').attr('id', clipPathURL); + def.paths.forEach(function (td) { + td.def.inDef = true; + new KG[td.type](view.addViewToDef(td.def, clipPathLayer)); + }); + defURLS[def.name] = clipPathURL; + }); + } + // create Markers, generate their URLs, and add their paths to the SVG defs element. + if (data.markers.length > 0) { + data.markers.forEach(function (def) { + var markerURL = KG.randomString(10); + def.url = markerURL; + defURLS[def.name] = markerURL; + var markerLayer = defLayer_1.append('marker') + .attr('id', markerURL) + .attr("refX", def.refX) + .attr("refY", 6) + .attr("markerWidth", 13) + .attr("markerHeight", 13) + .attr("orient", "auto") + .attr("markerUnits", "userSpaceOnUse"); + view.addViewToDef(def, markerLayer); + new KG.Marker(def); + }); + } + // add layers of objects + data.layers.forEach(function (layerTds) { + if (layerTds.length > 0) { + var layer_1 = view.svg.append('g'); + layerTds.forEach(function (td) { + var def = td.def; + if (def.hasOwnProperty('clipPathName')) { + def.clipPath = defURLS[def['clipPathName']]; + } + if (def.hasOwnProperty('clipPathName2')) { + def.clipPath2 = defURLS[def['clipPathName2']]; + } + if (def.hasOwnProperty('startArrowName')) { + def.startArrow = defURLS[def['startArrowName']]; + } + if (def.hasOwnProperty('endArrowName')) { + def.endArrow = defURLS[def['endArrowName']]; + } + def = view.addViewToDef(def, layer_1); + new KG[td.type](def); + }); + } + }); + } + // add divs + if (data.divs.length > 0) { + data.divs.forEach(function (td) { + var def = view.addViewToDef(td.def, view.div), newDiv = new KG[td.type](def); + if (td.type == 'Sidebar') { + view.sidebar = newDiv; + } + if (td.type == 'Explanation') { + view.explanation = newDiv; + } + }); + } + view.updateDimensions(); + }; + // update dimensions, either when first rendering or when the window is resized + View.prototype.updateDimensions = function (printing) { + var view = this; + printing = !!printing; + //console.log('printing is ', printing); + var width = 0, height = 0, displayHeight = 0; + if (printing) { + width = 600; + height = width / view.aspectRatio; + displayHeight = height + 20; + } + else { + // read the client width of the enclosing div and calculate the height using the aspectRatio + var clientWidth = view.div.node().clientWidth; + width = clientWidth - 10; + height = width / view.aspectRatio; + var sidebarHeight = 0, explanationHeight = 0; + // position the sidebar to the right if the screen is wide enough, or below if it isn't + if (view.sidebar) { + if (width > view.sidebar.triggerWidth) { + height = height * 77 / 126; + var s_height = void 0; + if (view.explanation) { + s_height = height + view.explanation.rootElement.node().clientHeight + 10; + } + else { + s_height = height; + } + view.sidebar.positionRight(width, s_height); + width = width * 77 / 126; // make width of graph the same width as main Tufte column + } + else { + view.sidebar.positionBelow(width, height); + sidebarHeight = view.sidebar.rootElement.node().clientHeight + 30; + } + } + // position the explanation below + if (view.explanation) { + view.explanation.position(width, height + sidebarHeight + 10); + explanationHeight = view.explanation.rootElement.node().clientHeight + 20; + } + displayHeight = height + sidebarHeight + explanationHeight + 10; + } + view.div.style('height', displayHeight + 'px'); + // set the height of the div + view.svgContainerDiv.style('width', width); + view.svgContainerDiv.style('height', height); + if (view.svg) { + // set the dimensions of the svg + view.svg.style('width', width); + view.svg.style('height', height); + view.svg.attr('width', width); + view.svg.attr('height', height); + } + // adjust all of the scales to be proportional to the new dimensions + view.scales.forEach(function (scale) { + scale.updateDimensions(width, height); + }); + // once the scales are updated, update the coordinates of all view objects + view.model.update(true); + }; + return View; + }()); + KG.View = View; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Scale = /** @class */ (function (_super) { + __extends(Scale, _super); + function Scale(def) { + var _this = this; + KG.setDefaults(def, { + log: false + }); + def.constants = ['rangeMin', 'rangeMax', 'axis', 'name']; + def.updatables = ['domainMin', 'domainMax', 'intercept']; + _this = _super.call(this, def) || this; + _this.scale = def.log ? d3.scaleLog() : d3.scaleLinear(); + _this.update(true); + return _this; + } + Scale.prototype.update = function (force) { + var s = _super.prototype.update.call(this, force); + if (s.extent != undefined) { + var rangeMin = s.rangeMin * s.extent, rangeMax = s.rangeMax * s.extent; + s.scale.domain([s.domainMin, s.domainMax]); + s.scale.range([rangeMin, rangeMax]); + } + return s; + }; + Scale.prototype.updateDimensions = function (width, height) { + var s = this; + s.extent = (s.axis == 'x') ? width : height; + return s.update(true); + }; + return Scale; + }(KG.UpdateListener)); + KG.Scale = Scale; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var ViewObject = /** @class */ (function (_super) { + __extends(ViewObject, _super); + function ViewObject(def) { + var _this = this; + KG.setDefaults(def, { + alwaysUpdate: false, + interactive: true, + fill: 'colors.blue', + fillOpacity: 0.2, + stroke: 'colors.blue', + strokeWidth: 1, + stokeOpacity: 1, + show: true, + inDef: false, + lineStyle: 'solid', + checkOnGraph: true + }); + KG.setProperties(def, 'updatables', ['xScaleMin', 'xScaleMax', 'yScaleMin', 'yScaleMax', 'fill', 'stroke', 'strokeWidth', 'opacity', 'strokeOpacity', 'show', 'lineStyle']); + KG.setProperties(def, 'constants', ['xScale', 'yScale', 'clipPath', 'clipPath2', 'interactive', 'alwaysUpdate', 'inDef', 'checkOnGraph']); + KG.setProperties(def, 'colorAttributes', ['stroke', 'fill', 'color']); + if (def.inDef) { + def.show = true; + } + _this = _super.call(this, def) || this; + var vo = _this; + if (vo.hasOwnProperty('xScale') && vo.xScale) { + def.xScaleMin = vo.xScale.def.domainMin; + def.xScaleMax = vo.xScale.def.domainMax; + def.yScaleMin = vo.yScale.def.domainMin; + def.yScaleMax = vo.yScale.def.domainMax; + } + def.colorAttributes.forEach(function (attr) { + var c = def[attr]; + if (vo.model.colors.hasOwnProperty(c)) { + def[attr] = vo.model.colors[c]; + } + }); + // the interaction handler manages drag and hover events + if (def.interactive) { + def.drag = def.drag || []; + var dragListeners = def.drag.map(function (dragDef) { + dragDef.model = vo.model; + return new KG.DragListener(dragDef); + }); + def.click = def.click || []; + var clickListeners = def.click.map(function (clickDef) { + clickDef.model = vo.model; + return new KG.ClickListener(clickDef); + }); + vo.interactionHandler = new KG.InteractionHandler({ + viewObject: vo, + model: vo.model, + dragListeners: dragListeners, + clickListeners: clickListeners + }); + } + // the draw method creates the DOM elements for the view object + // the update method updates their attributes + if (def.hasOwnProperty('layer')) { + vo.draw(def.layer).update(true).init(); + } + return _this; + } + ViewObject.prototype.init = function () { + return this; //defined at subclass level + }; + ViewObject.prototype.addClipPathAndArrows = function () { + var vo = this; + if (vo.hasOwnProperty('clipPath') && vo.clipPath != undefined) { + vo.rootElement.attr('clip-path', "url(#" + vo.clipPath + ")"); + } + if (vo.hasOwnProperty('clipPath2') && vo.clipPath2 != undefined) { + vo.rootElement2.attr('clip-path', "url(#" + vo.clipPath2 + ")"); + } + if (vo.hasOwnProperty('endArrow') && vo.endArrow != undefined) { + vo.markedElement.attr("marker-end", "url(#" + vo.endArrow + ")"); + } + if (vo.hasOwnProperty('startArrow') && vo.endArrow != undefined) { + vo.markedElement.attr("marker-start", "url(#" + vo.startArrow + ")"); + } + return vo; + }; + ViewObject.prototype.addInteraction = function () { + var vo = this; + vo.interactionHandler.addTrigger(vo.rootElement); + return vo; + }; + ViewObject.prototype.draw = function (layer, inDef) { + return this; + }; + ViewObject.prototype.redraw = function () { + return this; + }; + ViewObject.prototype.drawStroke = function (el) { + var vo = this; + el.attr('stroke', vo.stroke); + el.attr('stroke-width', vo.strokeWidth); + el.style('stroke-opacity', vo.strokeOpacity); + if (vo.lineStyle == 'dashed') { + el.style('stroke-dashArray', '10,10'); + } + else if (vo.lineStyle == 'dotted') { + el.style('stroke-dashArray', '1,2'); + } + else { + el.style('stroke-dashArray', '10,0'); + } + }; + ViewObject.prototype.drawFill = function (el) { + var vo = this; + el.style('fill', vo.fill); + el.style('fill-opacity', vo.opacity); + }; + ViewObject.prototype.displayElement = function (show) { + var vo = this; + if (vo.hasOwnProperty('rootElement')) { + vo.rootElement.style('display', show ? null : 'none'); + } + }; + ViewObject.prototype.onGraph = function () { + var vo = this; + if (vo.checkOnGraph) { + var notBetween = function (x, a, b) { + var min = Math.min(a, b); + var max = Math.max(a, b); + return ((x < min) || (x > max)); + }; + if (vo.hasOwnProperty('x')) { + if (notBetween(vo.x, vo.xScale.domainMin, vo.xScale.domainMax)) { + return false; + } + } + if (vo.hasOwnProperty('y')) { + if (notBetween(vo.y, vo.yScale.domainMin, vo.yScale.domainMax)) { + return false; + } + } + } + return true; + }; + ViewObject.prototype.update = function (force) { + var vo = _super.prototype.update.call(this, force); + if ((vo.show && vo.onGraph()) || vo.inDef) { + vo.displayElement(true); + if (vo.hasChanged) { + vo.redraw(); + } + } + else { + vo.displayElement(false); + } + return vo; + }; + return ViewObject; + }(KG.UpdateListener)); + KG.ViewObject = ViewObject; +})(KG || (KG = {})); +var KG; +(function (KG) { + var Marker = /** @class */ (function (_super) { + __extends(Marker, _super); + function Marker(def) { + var _this = this; + KG.setProperties(def, 'constants', ['maskPath', 'arrowPath']); + KG.setProperties(def, 'updatables', ['color']); + _this = _super.call(this, def) || this; + return _this; + } + Marker.prototype.draw = function (layer) { + var m = this; + layer.append("svg:path") + .attr("d", m.maskPath) + .attr("fill", "white"); + m.arrowElement = layer.append("svg:path") + .attr("d", m.arrowPath); + return m; + }; + Marker.prototype.redraw = function () { + var m = this; + m.arrowElement.attr("fill", m.color); + return m; + }; + return Marker; + }(KG.ViewObject)); + KG.Marker = Marker; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Segment = /** @class */ (function (_super) { + __extends(Segment, _super); + function Segment(def) { + var _this = this; + KG.setDefaults(def, { + xScale2: def.xScale, + yScale2: def.yScale, + strokeWidth: 2 + }); + KG.setProperties(def, 'constants', ['xScale2', 'yScale2', 'startArrow', 'endArrow']); + KG.setProperties(def, 'updatables', ['x1', 'y1', 'x2', 'y2']); + _this = _super.call(this, def) || this; + return _this; + } + // create SVG elements + Segment.prototype.draw = function (layer) { + var segment = this; + segment.rootElement = layer.append('g'); + segment.dragLine = segment.rootElement.append('line').attr('stroke-width', '20px').style('stroke-opacity', 0); + segment.line = segment.rootElement.append('line'); + segment.markedElement = segment.line; + return segment.addClipPathAndArrows().addInteraction(); + }; + // update properties + Segment.prototype.redraw = function () { + var segment = this; + var x1 = segment.xScale.scale(segment.x1), x2 = segment.xScale.scale(segment.x2), y1 = segment.yScale2.scale(segment.y1), y2 = segment.yScale2.scale(segment.y2); + segment.dragLine + .attr("x1", x1) + .attr("y1", y1) + .attr("x2", x2) + .attr("y2", y2); + segment.line + .attr("x1", x1) + .attr("y1", y1) + .attr("x2", x2) + .attr("y2", y2); + segment.drawStroke(segment.line); + return segment; + }; + return Segment; + }(KG.ViewObject)); + KG.Segment = Segment; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Curve = /** @class */ (function (_super) { + __extends(Curve, _super); + function Curve(def) { + var _this = this; + var univariateFunction, parametricFunction; + KG.setDefaults(def, { + interpolation: 'curveBasis', + strokeWidth: 2 + }); + KG.setProperties(def, 'constants', ['interpolation']); + if (def.hasOwnProperty('univariateFunction')) { + def.univariateFunction.model = def.model; + univariateFunction = new KG.UnivariateFunction(def.univariateFunction); + KG.setProperties(def, 'updatables', []); + } + else if (def.hasOwnProperty('parametricFunction')) { + def.parametricFunction.model = def.model; + parametricFunction = new KG.ParametricFunction(def.parametricFunction); + KG.setProperties(def, 'updatables', []); + } + _this = _super.call(this, def) || this; + var curve = _this; + if (def.hasOwnProperty('univariateFunction')) { + curve.univariateFunction = univariateFunction; + } + else if (def.hasOwnProperty('parametricFunction')) { + def.parametricFunction.model = def.model; + curve.parametricFunction = parametricFunction; + } + return _this; + } + // create SVG elements + Curve.prototype.draw = function (layer) { + var curve = this; + curve.dataLine = d3.line() + .curve(d3[curve.interpolation]) + .x(function (d) { + return curve.xScale.scale(d.x); + }) + .y(function (d) { + return curve.yScale.scale(d.y); + }); + curve.rootElement = layer.append('g'); + curve.dragPath = curve.rootElement.append('path').attr('stroke-width', '20px').style('stroke-opacity', 0).style('fill', 'none'); + curve.path = curve.rootElement.append('path').style('fill', 'none'); + return curve.addClipPathAndArrows().addInteraction(); + }; + // update properties + Curve.prototype.redraw = function () { + var curve = this; + if (curve.hasOwnProperty('univariateFunction')) { + var fn = curve.univariateFunction, scale = fn.ind == 'y' ? curve.yScale : curve.xScale; + fn.generateData(scale.domainMin, scale.domainMax); + curve.dragPath.data([fn.data]).attr('d', curve.dataLine); + curve.path.data([fn.data]).attr('d', curve.dataLine); + } + if (curve.hasOwnProperty('parametricFunction')) { + var fn = curve.parametricFunction; + fn.generateData(); + curve.dragPath.data([fn.data]).attr('d', curve.dataLine); + curve.path.data([fn.data]).attr('d', curve.dataLine); + } + curve.drawStroke(curve.path); + return curve; + }; + // update self and functions + Curve.prototype.update = function (force) { + var curve = _super.prototype.update.call(this, force); + if (!curve.hasChanged) { + if (curve.hasOwnProperty('univariateFunction')) { + if (curve.univariateFunction.hasChanged) { + curve.redraw(); + } + } + if (curve.hasOwnProperty('parametricFunction')) { + if (curve.parametricFunction.hasChanged) { + curve.redraw(); + } + } + } + return curve; + }; + return Curve; + }(KG.ViewObject)); + KG.Curve = Curve; +})(KG || (KG = {})); +var KG; +(function (KG) { + var Axis = /** @class */ (function (_super) { + __extends(Axis, _super); + function Axis(def) { + var _this = this; + KG.setDefaults(def, { + ticks: 5, + intercept: 0 + }); + KG.setProperties(def, 'constants', ['orient']); + KG.setProperties(def, 'updatables', ['ticks', 'intercept', 'label', 'min', 'max', 'otherMin', 'otherMax', 'tickPrepend', 'tickPrecision']); + _this = _super.call(this, def) || this; + return _this; + } + Axis.prototype.draw = function (layer) { + var a = this; + a.rootElement = layer.append('g').attr('class', 'axis'); + return a; + }; + Axis.prototype.redraw = function () { + var a = this; + function formatTick(d) { + if (a.tickPrecision) { + d = d.toFixed(a.tickPrecision); + } + if (a.tickPrepend) { + return "" + a.tickPrepend + d; + } + else { + return d; + } + } + switch (a.orient) { + case 'bottom': + a.rootElement.attr('transform', "translate(0, " + a.yScale.scale(a.intercept) + ")"); + a.rootElement.call(d3.axisBottom(a.xScale.scale).ticks(a.ticks).tickFormat(formatTick)); + return a; + case 'left': + a.rootElement.attr('transform', "translate(" + a.xScale.scale(a.intercept) + ",0)"); + a.rootElement.call(d3.axisLeft(a.yScale.scale).ticks(a.ticks).tickFormat(formatTick)); + return a; + case 'top': + a.rootElement.attr('transform', "translate(0, " + a.yScale.scale(a.intercept) + ")"); + a.rootElement.call(d3.axisTop(a.xScale.scale).ticks(a.ticks).tickFormat(formatTick)); + return a; + case 'right': + a.rootElement.attr('transform', "translate(" + a.xScale.scale(a.intercept) + ",0)"); + a.rootElement.call(d3.axisRight(a.yScale.scale).ticks(a.ticks).tickFormat(formatTick)); + return a; + } + return a; + }; + return Axis; + }(KG.ViewObject)); + KG.Axis = Axis; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Point = /** @class */ (function (_super) { + __extends(Point, _super); + function Point(def) { + var _this = this; + KG.setDefaults(def, { + fill: 'colors.blue', + opacity: 1, + stroke: 'white', + strokeWidth: 1, + strokeOpacity: 1, + r: 6 + }); + KG.setProperties(def, 'updatables', ['x', 'y', 'r']); + _this = _super.call(this, def) || this; + return _this; + } + // create SVG elements + Point.prototype.draw = function (layer) { + var p = this; + p.rootElement = layer.append('g'); // SVG group + p.dragCircle = p.rootElement.append('circle').style('fill-opacity', 0).attr('r', 20); + p.circle = p.rootElement.append('circle'); + //p.addClipPathAndArrows() + return p.addInteraction(); + }; + // update properties + Point.prototype.redraw = function () { + var p = this; + p.rootElement.attr('transform', "translate(" + p.xScale.scale(p.x) + " " + p.yScale.scale(p.y) + ")"); + p.circle.attr('r', p.r); + p.circle.style('fill', p.fill); + p.circle.style('fill-opacity', p.opacity); + p.circle.style('stroke', p.stroke); + p.circle.style('stroke-width', p.strokeWidth + "px"); + p.circle.style('stroke-opacity', p.strokeOpacity); + return p; + }; + return Point; + }(KG.ViewObject)); + KG.Point = Point; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Ellipse = /** @class */ (function (_super) { + __extends(Ellipse, _super); + function Ellipse(def) { + var _this = this; + KG.setDefaults(def, { + fill: 'colors.blue', + opacity: 1, + stroke: 'colors.blue', + strokeWidth: 1, + strokeOpacity: 1, + rx: 1, + ry: 1, + checkOnGraph: false + }); + KG.setProperties(def, 'updatables', ['x', 'y', 'rx', 'ry']); + _this = _super.call(this, def) || this; + return _this; + } + // create SVG elements + Ellipse.prototype.draw = function (layer) { + var c = this; + c.rootElement = layer.append('ellipse'); + return c.addClipPathAndArrows().addInteraction(); + }; + // update properties + Ellipse.prototype.redraw = function () { + var c = this; + c.rootElement.attr('cx', c.xScale.scale(c.x)); + c.rootElement.attr('cy', c.yScale.scale(c.y)); + c.rootElement.attr('rx', Math.abs(c.xScale.scale(c.rx) - c.xScale.scale(0))); + c.rootElement.attr('ry', Math.abs(c.yScale.scale(c.ry) - c.yScale.scale(0))); + c.drawFill(c.rootElement); + c.drawStroke(c.rootElement); + return c; + }; + return Ellipse; + }(KG.ViewObject)); + KG.Ellipse = Ellipse; + var Circle = /** @class */ (function (_super) { + __extends(Circle, _super); + function Circle(def) { + return _super.call(this, def) || this; + } + return Circle; + }(Ellipse)); + KG.Circle = Circle; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Rectangle = /** @class */ (function (_super) { + __extends(Rectangle, _super); + function Rectangle(def) { + var _this = this; + KG.setDefaults(def, { + opacity: 0.2, + stroke: "none" + }); + KG.setProperties(def, 'updatables', ['x1', 'x2', 'y1', 'y2']); + _this = _super.call(this, def) || this; + return _this; + } + // create SVG elements + Rectangle.prototype.draw = function (layer) { + var rect = this; + if (rect.inDef) { + rect.rootElement = layer; + } + else { + rect.rootElement = layer.append('g'); + } + rect.rootElement2 = rect.rootElement.append('rect'); + //rect.interactionHandler.addTrigger(rect.rootElement); + return rect.addClipPathAndArrows().addInteraction(); + }; + // update properties + Rectangle.prototype.redraw = function () { + var rect = this; + var x1 = rect.xScale.scale(rect.x1); + var y1 = rect.yScale.scale(rect.y1); + var x2 = rect.xScale.scale(rect.x2); + var y2 = rect.yScale.scale(rect.y2); + rect.rootElement2 + .attr('x', Math.min(x1, x2)) + .attr('y', Math.min(y1, y2)) + .attr('width', Math.abs(x2 - x1)) + .attr('height', Math.abs(y2 - y1)) + .style('fill', rect.fill) + .style('fill-opacity', rect.opacity) + .style('stroke', rect.stroke) + .style('stroke-width', rect.strokeWidth + "px") + .style('stroke-opacity', rect.strokeOpacity); + return rect; + }; + return Rectangle; + }(KG.ViewObject)); + KG.Rectangle = Rectangle; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Area = /** @class */ (function (_super) { + __extends(Area, _super); + function Area(def) { + var _this = this; + var minValue = def.univariateFunction1.ind == 'x' ? def.yScale.domainMin : def.xScale.domainMin; + var maxValue = def.univariateFunction1.ind == 'x' ? def.yScale.domainMax : def.xScale.domainMax; + KG.setDefaults(def, { + interpolation: 'curveBasis', + ind: 'x', + fill: 'lightsteelblue', + opacity: 0.2, + univariateFunction2: { + "fn": ((def.above && !def.useTopScale) || (!def.above && def.useTopScale)) ? maxValue : minValue, + "ind": def.univariateFunction1['ind'], + "min": def.univariateFunction1['min'], + "max": def.univariateFunction1['max'], + "samplePoints": def.univariateFunction1['samplePoints'] + } + }); + KG.setProperties(def, 'constants', ['interpolation']); + def.univariateFunction1.model = def.model; + def.univariateFunction2.model = def.model; + // need to initialize the functions before the area, so they exist when it's time to draw the area + var univariateFunction1 = new KG.UnivariateFunction(def.univariateFunction1), univariateFunction2 = new KG.UnivariateFunction(def.univariateFunction2); + _this = _super.call(this, def) || this; + _this.univariateFunction1 = univariateFunction1; + _this.univariateFunction2 = univariateFunction2; + return _this; + } + // create SVG elements + Area.prototype.draw = function (layer) { + var ab = this; + ab.rootElement = layer.append('path'); + ab.areaShape = d3.area() + .x0(function (d) { + return ab.xScale.scale(d[0].x); + }) + .y0(function (d) { + return ab.yScale.scale(d[0].y); + }) + .x1(function (d) { + return ab.xScale.scale(d[1].x); + }) + .y1(function (d) { + return ab.yScale.scale(d[1].y); + }); + ab.areaPath = ab.rootElement; + return ab.addClipPathAndArrows(); + }; + // update properties + Area.prototype.redraw = function () { + var area = this; + if (area.univariateFunction1 != undefined && area.univariateFunction2 != undefined) { + var fn1 = area.univariateFunction1, fn2 = area.univariateFunction2, scale = fn1.ind == 'y' ? area.yScale : area.xScale; + fn1.generateData(scale.domainMin, scale.domainMax); + fn2.generateData(scale.domainMin, scale.domainMax); + area.areaPath + .data([d3.zip(fn1.data, fn2.data)]) + .attr('d', area.areaShape); + area.drawFill(area.areaPath); + } + else { + //console.log('area functions undefined') + } + return area; + }; + // update self and functions + Area.prototype.update = function (force) { + var area = _super.prototype.update.call(this, force); + if (!area.hasChanged) { + if (area.univariateFunction1.hasChanged || area.univariateFunction2.hasChanged) { + area.redraw(); + } + } + return area; + }; + return Area; + }(KG.ViewObject)); + KG.Area = Area; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var GeoGebraObject = /** @class */ (function (_super) { + __extends(GeoGebraObject, _super); + function GeoGebraObject(def) { + var _this = this; + KG.setDefaults(def, { + color: '#999999', + lineThickness: 1, + lineStyle: 0 + }); + KG.setProperties(def, 'constants', ['command', 'color', 'lineThickness', 'lineStyle']); + _this = _super.call(this, def) || this; + return _this; + } + GeoGebraObject.prototype.establishGGB = function (applet) { + // from https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb + function hexToRgb(hex) { + var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + return result ? { + r: parseInt(result[1], 16), + g: parseInt(result[2], 16), + b: parseInt(result[3], 16) + } : null; + } + var obj = this; + //console.log('sending commands to applet', applet); + // set command + var command = obj.name + " = " + obj.command; + //console.log('sending command ', obj.name + " = " + obj.command); + applet.evalCommand(command); + if (obj.hasOwnProperty('opacity')) { + applet.setFilling(obj.opacity); + } + var color = hexToRgb(obj.color); + //console.log('sending command setColor(', obj.name, ', ', color.r, ',', color.g, ', ', color.b, ')'); + applet.setColor(obj.name, color.r, color.g, color.b); + //console.log('sending command setLineThickness(', obj.name, ', ', obj.lineThickness, ')') + applet.evalCommand('SetLineThickness[' + obj.name + ', ' + obj.lineThickness + ']'); + //console.log('sending command setLineStyle(', obj.name, ', ', obj.lineStyle, ')') + applet.setLineStyle(obj.name, obj.lineStyle); + }; + return GeoGebraObject; + }(KG.ViewObject)); + KG.GeoGebraObject = GeoGebraObject; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Contour = /** @class */ (function (_super) { + __extends(Contour, _super); + function Contour(def) { + var _this = this; + KG.setDefaults(def, { + opacity: 0.2, + stroke: "grey", + fillAbove: "none", + fillBelow: "none", + strokeOpacity: 1 + }); + KG.setProperties(def, 'colorAttributes', ['fillAbove', 'fillBelow']); + KG.setProperties(def, 'updatables', ['level', 'fillBelow', 'fillAbove', 'xMin', 'xMax', 'yMin', 'yMax']); + _this = _super.call(this, def) || this; + // used for shading area above + _this.fn = new KG.MultivariateFunction({ + fn: def.fn, + model: def.model + }).update(true); + // used for shading area below + _this.negativeFn = new KG.MultivariateFunction({ + fn: "-1*(" + def.fn + ")", + model: def.model + }).update(true); + return _this; + } + Contour.prototype.draw = function (layer) { + var c = this; + if (c.inDef) { + c.rootElement = layer.append('path'); + c.path = c.rootElement; + } + else { + c.rootElement = layer.append('g'); + c.negativePath = c.rootElement.append('path'); + c.path = c.rootElement.append('path'); + } + return c.addClipPathAndArrows(); + }; + Contour.prototype.redraw = function () { + var c = this; + if (undefined != c.fn) { + var bounds_1 = {}; + ['xMin', 'xMax', 'yMin', 'yMax'].forEach(function (p) { + if (c.hasOwnProperty(p) && c[p] != undefined) { + bounds_1[p] = c[p]; + } + }); + c.path.attr("d", c.fn.contour(c.level, c.xScale, c.yScale, { + xMin: c.xMin, + xMax: c.xMax, + yMin: c.yMin, + yMax: c.yMax + })); + if (!c.inDef) { + c.path.style('fill', c.fillAbove); + c.path.style('fill-opacity', c.opacity); + c.path.style('stroke', c.stroke); + c.path.style('stroke-width', c.strokeWidth); + c.path.style('stroke-opacity', c.strokeOpacity); + c.negativePath.attr("d", c.negativeFn.contour(-1 * c.level, c.xScale, c.yScale)); + c.negativePath.style('fill', c.fillBelow); + c.negativePath.style('fill-opacity', c.opacity); + } + } + return c; + }; + // update self and functions + Contour.prototype.update = function (force) { + var c = _super.prototype.update.call(this, force); + if (!c.hasChanged) { + if (c.fn.hasChanged) { + c.redraw(); + } + } + return c; + }; + return Contour; + }(KG.ViewObject)); + KG.Contour = Contour; + var ContourMap = /** @class */ (function (_super) { + __extends(ContourMap, _super); + function ContourMap(def) { + return _super.call(this, def) || this; + } + return ContourMap; + }(KG.ViewObject)); + KG.ContourMap = ContourMap; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Label = /** @class */ (function (_super) { + __extends(Label, _super); + function Label(def) { + var _this = this; + var xAxisReversed = (def.xScale.rangeMin > def.xScale.rangeMax), yAxisReversed = (def.yScale.rangeMin < def.yScale.rangeMax); + var xOffset = xAxisReversed ? 1 : -1, yOffset = yAxisReversed ? 12 : -12; + if (def.x == 'AXIS') { + def.x = def.yScale.intercept; + def.align = xAxisReversed ? 'left' : 'right'; + def.xPixelOffset = xOffset; + } + if (def.x == 'OPPAXIS') { + def.x = def.xScale.domainMax; + def.align = xAxisReversed ? 'right' : 'left'; + def.xPixelOffset = -xOffset; + } + if (def.y == 'AXIS') { + def.y = def.yScale.intercept; + def.yPixelOffset = yOffset; + } + if (def.y == 'OPPAXIS') { + def.y = def.yScale.domainMax; + def.yPixelOffset = -yOffset; + } + //establish property defaults + KG.setDefaults(def, { + xPixelOffset: 0, + yPixelOffset: 0, + fontSize: 12, + align: 'center', + valign: 'middle', + rotate: 0, + color: 'black' + }); + // define constant and updatable properties + KG.setProperties(def, 'constants', ['xPixelOffset', 'yPixelOffset', 'fontSize', 'plainText']); + KG.setProperties(def, 'updatables', ['x', 'y', 'text', 'align', 'valign', 'rotate', 'color', 'bgcolor']); + _this = _super.call(this, def) || this; + _this.bgcolor = def.model.clearColor; + return _this; + } + // create div for text + Label.prototype.draw = function (layer) { + var label = this; + label.rootElement = layer.append('div') + .attr('class', 'draggable') + .style('position', 'absolute') + .style('font-size', label.fontSize + 'pt') + .style('text-align', 'center') + .style('padding-left', '3px') + .style('padding-right', '3px'); + return label.addInteraction(); + }; + // update properties + Label.prototype.redraw = function () { + var label = this; + label.rootElement.style('color', label.color).style('background-color', label.bgcolor); + var x = label.xScale.scale(label.x) + (+label.xPixelOffset), y = label.yScale.scale(label.y) - (+label.yPixelOffset); + if (undefined != label.text) { + if (label.plainText) { + //console.log('rendering label as plain text: ', label.text) + label.text = "\\text{" + label.text + "}"; + } + else { + //console.log('rendering label as LaTeX: ', label.text) + } + try { + katex.render(label.text.toString(), label.rootElement.node()); + } + catch (e) { + console.log("Error rendering KaTeX: ", label.text); + } + } + label.rootElement.style('left', x + 'px'); + label.rootElement.style('top', y + 'px'); + var width = label.rootElement.node().clientWidth, height = label.rootElement.node().clientHeight; + // Set left pixel margin; default to centered on x coordinate + var alignDelta = width * 0.5; + if (label.align == 'left') { + alignDelta = 0; + } + else if (label.align == 'right') { + // move left by half the width of the div if right aligned + alignDelta = width; + } + label.rootElement.style('left', (x - alignDelta) + 'px'); + // Set top pixel margin; default to centered on y coordinate + var vAlignDelta = height * 0.5; + // Default to centered on x coordinate + if (label.valign == 'top') { + vAlignDelta = 0; + } + else if (label.valign == 'bottom') { + vAlignDelta = height; + } + label.rootElement.style('top', (y - vAlignDelta) + 'px'); + var rotate = "rotate(-" + label.rotate + "deg)"; + label.rootElement.style('-webkit-transform', rotate) + .style('transform', rotate); + return label; + }; + return Label; + }(KG.ViewObject)); + KG.Label = Label; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var DivObject = /** @class */ (function (_super) { + __extends(DivObject, _super); + function DivObject() { + return _super !== null && _super.apply(this, arguments) || this; + } + DivObject.prototype.redraw = function () { + var div = this; + var width = Math.abs(div.xScale.scale(1) - div.xScale.scale(0)), height = Math.abs(div.yScale.scale(1) - div.yScale.scale(0)); + div.rootElement.style('left', div.xScale.scale(0) + 'px'); + div.rootElement.style('top', div.yScale.scale(1) + 'px'); + div.rootElement.style('width', width + 'px'); + div.rootElement.style('height', height + 'px'); + return div; + }; + return DivObject; + }(KG.ViewObject)); + KG.DivObject = DivObject; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var PositionedDiv = /** @class */ (function (_super) { + __extends(PositionedDiv, _super); + function PositionedDiv() { + return _super !== null && _super.apply(this, arguments) || this; + } + PositionedDiv.prototype.draw = function (layer) { + var div = this; + div.rootElement = layer.append('div'); + div.rootElement.style('position', 'absolute'); + if (div.def.hasOwnProperty('children')) { + div.def['children'].forEach(function (child) { + child.def.layer = div.rootElement; + child.def.model = div.model; + new KG[child.type](child.def); + }); + } + return div; + }; + PositionedDiv.prototype.redraw = function () { + var div = this; + var width = Math.abs(div.xScale.scale(1) - div.xScale.scale(0)), height = Math.abs(div.yScale.scale(1) - div.yScale.scale(0)); + div.rootElement.style('left', div.xScale.scale(0) + 'px'); + div.rootElement.style('top', div.yScale.scale(1) + 'px'); + div.rootElement.style('width', width + 'px'); + div.rootElement.style('height', height + 'px'); + return div; + }; + return PositionedDiv; + }(KG.DivObject)); + KG.PositionedDiv = PositionedDiv; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Div = /** @class */ (function (_super) { + __extends(Div, _super); + function Div(def) { + var _this = this; + //establish property defaults + KG.setDefaults(def, { + xPixelOffset: 0, + yPixelOffset: 0, + fontSize: 12 + }); + // define constant and updatable properties + KG.setProperties(def, 'constants', ['fontSize']); + KG.setProperties(def, 'updatables', ['html']); + _this = _super.call(this, def) || this; + return _this; + } + // create div for text + Div.prototype.draw = function (layer) { + var div = this; + div.rootElement = layer.append('div') + .style('font-size', div.fontSize + 'pt') + .style('padding-top', '2px') + .style('padding-bottom', '2px'); + return div; + }; + // update properties + Div.prototype.redraw = function () { + var div = this; + if (div.show) { + div.rootElement.html(div.html); + renderMathInElement(div.rootElement.node(), { + delimiters: [ + { left: "$$", right: "$$", display: true }, + { left: "\\[", right: "\\]", display: true }, + { left: "$", right: "$", display: false }, + { left: "\\(", right: "\\)", display: false } + ] + }); + } + else { + div.rootElement.html(null); + } + return div; + }; + return Div; + }(KG.DivObject)); + KG.Div = Div; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var ParamControl = /** @class */ (function (_super) { + __extends(ParamControl, _super); + function ParamControl(def) { + var _this = this; + // establish property defaults + KG.setDefaults(def, { + value: 'params.' + def.param, + alwaysUpdate: true, + plainText: false + }); + // define constant and updatable properties + KG.setProperties(def, 'constants', ['param', 'plainText']); + KG.setProperties(def, 'updatables', ['label', 'value']); + _this = _super.call(this, def) || this; + return _this; + } + return ParamControl; + }(KG.DivObject)); + KG.ParamControl = ParamControl; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Slider = /** @class */ (function (_super) { + __extends(Slider, _super); + function Slider(def) { + var _this = this; + // establish property defaults + KG.setDefaults(def, { + noAxis: false, + showNumber: true + }); + // define constant and updatable properties + KG.setProperties(def, 'constants', ['noAxis', 'label', 'digits']); + KG.setProperties(def, 'updatables', ['showNumber']); + _this = _super.call(this, def) || this; + // calculate maximum number of digits + var slider = _this; + var paramObject = slider.model.getParam(slider.param); + // number of digits for decimals + var decimalPlaces = paramObject.precision; + function maxMinDigits(x) { + if (x > 0) { + return Math.trunc(Math.log10(x) + 1); + } + else { + return Math.trunc(Math.log10(-1 * x) + 2); + } + } + // number of digits for minimum + slider.digits = Math.max(maxMinDigits(paramObject.min), maxMinDigits(paramObject.max)) + decimalPlaces; + return _this; + } + Slider.prototype.draw = function (layer) { + var slider = this; + slider.rootElement = layer.append('tr'); + var param = slider.model.getParam(slider.param); + slider.labelElement = slider.rootElement.append('td') + .style('font-size', '14pt') + .style('text-align', 'right') + .style('padding', '0px') + .style('margin', '0px') + .style('border', 'none'); + function inputUpdate() { + slider.model.updateParam(slider.param, +this.value); + } + slider.numberCell = slider.rootElement.append('td') + .style('padding', '0px') + .style('margin', '0px') + .style('border', 'none'); + slider.numberInput = slider.numberCell.append('input') + .attr('type', 'number') + .attr('min', param.min) + .attr('max', param.max) + .attr('step', param.round) + .style('font-size', '14pt') + .style('border', 'none') + .style('background', 'none') + .style('font-family', 'KaTeX_Main') + .style('margin', '0px') + .style('padding-top', '0px') + .style('padding-bottom', '0px'); + slider.numberInput.on("blur", inputUpdate); + slider.numberInput.on("click", inputUpdate); + slider.numberInput.on("keyup", function () { + if (event['keyCode'] == 13) { + slider.model.updateParam(slider.param, +this.value); + } + }); + var rangeCell = slider.rootElement.append('td') + .style('padding', '0px') + .style('margin', '0px') + .style('border', 'none'); + slider.rangeInput = rangeCell.append('input') + .attr('type', 'range') + .attr('min', param.min) + .attr('max', param.max) + .attr('step', param.round) + .style('padding', '0px') + .style('width', '100%') + .style('margin', '0px'); + slider.rangeInput.on("input", inputUpdate); + return slider; + }; + // update properties + Slider.prototype.redraw = function () { + var slider = this; + if (slider.showNumber) { + katex.render(slider.label + " = ", slider.labelElement.node()); + slider.numberInput.property('value', slider.value.toFixed(slider.model.getParam(slider.param).precision)); + slider.numberInput.style('width', 20 + slider.digits * 10 + "px"); + slider.numberInput.style('display', 'inline-block'); + } + else { + katex.render(slider.label, slider.labelElement.node()); + slider.numberCell.style('width', '10px'); + slider.numberInput.style('display', 'none'); + } + slider.rangeInput.property('value', slider.value); + return slider; + }; + return Slider; + }(KG.ParamControl)); + KG.Slider = Slider; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Checkbox = /** @class */ (function (_super) { + __extends(Checkbox, _super); + function Checkbox() { + return _super !== null && _super.apply(this, arguments) || this; + } + Checkbox.prototype.draw = function (layer) { + var checkbox = this; + checkbox.rootElement = layer.append('div').append('label'); + checkbox.inputElement = checkbox.rootElement.append('input'); + checkbox.inputElement + .attr('type', 'checkbox'); + checkbox.inputElement.on("change", function () { + checkbox.model.toggleParam(checkbox.param); + }); + checkbox.labelElement = checkbox.rootElement.append('span'); + checkbox.labelElement.style('padding-left', '10px'); + return checkbox; + }; + Checkbox.prototype.redraw = function () { + var checkbox = this; + if (checkbox.plainText) { + //console.log('rendering label as plain text: ', label.text) + checkbox.label = "\\text{" + checkbox.label + "}"; + } + else { + //console.log('rendering label as LaTeX: ', label.text) + } + checkbox.inputElement.property('checked', Boolean(checkbox.value)); + katex.render(checkbox.label, checkbox.labelElement.node()); + return checkbox; + }; + return Checkbox; + }(KG.ParamControl)); + KG.Checkbox = Checkbox; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Radio = /** @class */ (function (_super) { + __extends(Radio, _super); + function Radio(def) { + var _this = this; + KG.setProperties(def, 'constants', ['figure_id']); + KG.setProperties(def, 'updatables', ['optionValue']); + _this = _super.call(this, def) || this; + return _this; + } + Radio.prototype.draw = function (layer) { + var radio = this; + radio.rootElement = layer.append('div').append('label'); + radio.inputElement = radio.rootElement.append('input'); + radio.inputElement + .attr('type', 'radio') + .attr('name', radio.figure_id + '_' + radio.param) + .attr('value', radio.optionValue); + radio.inputElement.on("change", function () { + radio.model.updateParam(radio.param, radio.optionValue); + }); + radio.labelElement = radio.rootElement.append('span'); + radio.labelElement.style('padding-left', '10px'); + return radio; + }; + Radio.prototype.redraw = function () { + var radio = this; + radio.inputElement.property('checked', radio.value == radio.optionValue); + katex.render(radio.label, radio.labelElement.node()); + return radio; + }; + return Radio; + }(KG.ParamControl)); + KG.Radio = Radio; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Controls = /** @class */ (function (_super) { + __extends(Controls, _super); + function Controls(def) { + var _this = this; + KG.setDefaults(def, { + title: '', + description: '', + sliders: [], + checkboxes: [], + radios: [], + divs: [] + }); + KG.setProperties(def, 'constants', ['sliders', 'checkboxes', 'radios', 'divs']); + KG.setProperties(def, 'updatables', ['title', 'description']); + _this = _super.call(this, def) || this; + return _this; + } + // create div for text + Controls.prototype.draw = function (layer) { + var controls = this; + var controls_id = KG.randomString(5); + controls.rootElement = layer.append('div').style('padding-top', '10px').style('padding-bottom', '10px'); + controls.titleElement = controls.rootElement.append('div').style('font-size', '10pt').style('padding-bottom', 10); + controls.rootElement.append('hr'); + controls.descriptionElement = controls.rootElement.append('div'); + controls.descriptionElement.style('margin-bottom', '10px'); + if (controls.sliders.length > 0) { + var sliderTable_1 = controls.rootElement.append('table').style('padding', '10px').style('width', '100%').style('margin', '0px 0px 10px 0px'); + controls.sliders.forEach(function (slider) { + new KG.Slider({ layer: sliderTable_1, param: slider.param, label: slider.label, digits: slider.digits, showNumber: slider.showNumber, model: controls.model, show: slider.show }); + }); + } + controls.radios.forEach(function (radio) { + radio = KG.setDefaults(radio, { + layer: controls.rootElement, + model: controls.model, + figure_id: controls_id + }); + new KG.Radio(radio); + }); + if (controls.checkboxes.length > 0) { + if (controls.radios.length > 0) { + controls.rootElement.append('div').style('margin-bottom', '10px'); + } + controls.checkboxes.forEach(function (checkbox) { + checkbox = KG.setDefaults(checkbox, { + layer: controls.rootElement, + model: controls.model + }); + new KG.Checkbox(checkbox); + }); + } + controls.divs.forEach(function (div) { + div = KG.setDefaults(div, { + layer: controls.rootElement, + model: controls.model, + fontSize: 14 + }); + if (div.hasOwnProperty('html')) { + new KG.Div(div); + } + else if (div.hasOwnProperty('table')) { + div.rows = div.table.rows; + div.columns = div.table.columns; + div.lines = div.table.lines; + div.fontSize = 10; + delete div.table; + new KG.Table(div); + } + }); + return controls; + }; + // update properties + Controls.prototype.redraw = function () { + var controls = this; + if (controls.title.length > 0) { + controls.titleElement.text(controls.title.toUpperCase()); + } + controls.descriptionElement.html(controls.description); + return controls; + }; + return Controls; + }(KG.DivObject)); + KG.Controls = Controls; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var GameMatrix = /** @class */ (function (_super) { + __extends(GameMatrix, _super); + function GameMatrix(def) { + var _this = this; + KG.setDefaults(def, { + players: ["Player 1", "Player 2"] + }); + KG.setProperties(def, 'constants', ['players', 'strategies']); + KG.setProperties(def, 'updatables', ['payoffs']); + _this = _super.call(this, def) || this; + return _this; + } + // create div for text + GameMatrix.prototype.draw = function (layer) { + var gameMatrix = this; + var numStrategies1 = gameMatrix.strategies[0].length, numStrategies2 = gameMatrix.strategies[1].length; + gameMatrix.rootElement = layer.append('div'); + var table = gameMatrix.rootElement.append('table').attr('class', 'gameMatrix'); + var topRow = table.append('tr'); + topRow.append('td').attr('colspan', '2').attr('class', 'empty'); + topRow.append('td') + .attr('colspan', numStrategies2 * 2) + .attr('class', 'player2 strategy empty') + .text(gameMatrix.players[1]); + var secondRow = table.append('tr'); + secondRow.append('td').attr('colspan', '2').attr('class', 'empty'); + gameMatrix.strategies[1].forEach(function (s) { + secondRow.append('td').attr('colspan', '2').attr('class', 'player2 strategy').text(s); + }); + gameMatrix.payoffNodes = []; + for (var i = 0; i < numStrategies1; i++) { + var row = table.append('tr'); + var payoffRow = []; + if (i == 0) { + row.append('td') + .attr('rowSpan', numStrategies1) + .attr('class', 'player1 strategy empty') + .text(gameMatrix.players[0]); + } + row.append('td').text(gameMatrix.strategies[0][i]).attr('class', 'player1 strategy'); + for (var j = 0; j < numStrategies2; j++) { + var payoff1 = row.append('td').attr('class', 'player1 payoff'); + var payoff2 = row.append('td').attr('class', 'player2 payoff'); + payoffRow.push([payoff1, payoff2]); + } + gameMatrix.payoffNodes.push(payoffRow); + } + return gameMatrix; + }; + GameMatrix.prototype.redraw = function () { + var gameMatrix = this; + var strategies1 = gameMatrix.strategies[0], strategies2 = gameMatrix.strategies[1]; + var numStrategies1 = strategies1.length, numStrategies2 = strategies2.length; + for (var i = 0; i < numStrategies1; i++) { + for (var j = 0; j < numStrategies2; j++) { + var cell = gameMatrix.payoffNodes[i][j]; + katex.render(gameMatrix.payoffs[i][j][0].toString(), cell[0].node()); + katex.render(gameMatrix.payoffs[i][j][1].toString(), cell[1].node()); + } + } + return gameMatrix; + }; + return GameMatrix; + }(KG.DivObject)); + KG.GameMatrix = GameMatrix; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var GeoGebraApplet = /** @class */ (function (_super) { + __extends(GeoGebraApplet, _super); + function GeoGebraApplet(def) { + var _this = this; + KG.setDefaults(def, { + params: [], + objects: [], + axisLabels: [] + }); + def.params.forEach(function (param) { + def[param] = 'params.' + param; + }); + KG.setProperties(def, 'updatables', def.params); + KG.setProperties(def, 'constants', ['axes', 'params']); + _this = _super.call(this, def) || this; + var div = _this; + div.objects = def.objects.map(function (objDef) { + objDef.model = def.model; + return new KG.GeoGebraObject(objDef); + }); + //console.log('created GGB javascript object ', this) + div.axesEstablished = false; + return _this; + } + // create div for text + GeoGebraApplet.prototype.draw = function (layer) { + var div = _super.prototype.draw.call(this, layer); + var id = KG.randomString(10); + div.rootElement.append('div').attr('id', id); + var applet = new GGBApplet({ + allowStyleBar: true, + perspective: "T", + borderColor: "#FFFFFF", + dataParamId: id + }, true); + applet.setHTML5Codebase('../../../../GeoGebra/HTML5/5.0/web3d/'); + applet.inject(id); + return div; + }; + GeoGebraApplet.prototype.establishGGB = function (width, height) { + var div = this; + //console.log('called establishGGB'); + if (undefined != document['ggbApplet']) { + //console.log('applet exists'); + div.applet = document['ggbApplet']; + div.params.forEach(function (p) { + var establishParamCommand = p + " = " + div.model.currentParamValues[p]; + //console.log('setting param using command ', establishParamCommand); + div.applet.evalCommand(establishParamCommand); + }); + div.objects.forEach(function (obj) { + obj.establishGGB(div.applet); + }); + div.updateGGB(div.applet, width, height); + } + else { + //console.log('applet does not exist') + } + }; + GeoGebraApplet.prototype.updateGGB = function (applet, width, height) { + var div = this; + console.log('called updateGGB'); + if (undefined != applet) { + //console.log('applet exists'); + //console.log('setting width to ', width); + applet.setWidth(width); + //console.log('setting height to ', height); + applet.setHeight(height); + if (div.axes.length == 3) { + //console.log('setting coordinate system ', div.axes[0].min, div.axes[0].max, div.axes[1].min, div.axes[1].max, div.axes[2].min, div.axes[2].max) + applet.setCoordSystem(div.axes[0].min, div.axes[0].max, div.axes[1].min, div.axes[1].max, div.axes[2].min, div.axes[2].max); + //console.log('setting axis steps ', div.axes[0].step, div.axes[1].step, div.axes[2].step); + applet.setAxisSteps(3, div.axes[0].step, div.axes[1].step, div.axes[2].step); + //console.log('setting axis labels ', div.axes[0].label, div.axes[1].label, div.axes[2].label); + applet.setAxisLabels(3, div.axes[0].label, div.axes[1].label, div.axes[2].label); + applet.setColor('xAxis', 0, 0, 0); + applet.setColor('yAxis', 0, 0, 0); + applet.setColor('zAxis', 0, 0, 0); + } + else { + applet.setCoordSystem(div.axes[0].scale.domainMin, div.axes[0].scale.domainMax, div.axes[1].scale.domainMin, div.axes[1].scale.domainMax); + applet.setAxisSteps(2, div.axes[0].step, div.axes[1].step); + applet.setAxisLabels(2, div.axes[0].label, div.axes[1].label); + applet.setColor('xAxis', 0, 0, 0); + applet.setColor('yAxis', 0, 0, 0); + } + if (div.hasOwnProperty('params')) { + div.params.forEach(function (param) { + applet.setValue(param, div[param]); + }); + } + } + else { + //console.log('applet does not exist') + } + }; + // update properties + GeoGebraApplet.prototype.redraw = function () { + var div = _super.prototype.redraw.call(this); + var width = Math.abs(div.xScale.scale(1) - div.xScale.scale(0)), height = Math.abs(div.yScale.scale(1) - div.yScale.scale(0)); + var checkExist = setInterval(function () { + if (undefined != div.applet) { + div.updateGGB(div.applet, width, height); + clearInterval(checkExist); + } + else { + div.establishGGB(width, height); + } + }, 100); // check every 100ms + return div; + }; + return GeoGebraApplet; + }(KG.PositionedDiv)); + KG.GeoGebraApplet = GeoGebraApplet; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Mathbox = /** @class */ (function (_super) { + __extends(Mathbox, _super); + function Mathbox(def) { + var _this = this; + KG.setDefaults(def, { + objects: [] + }); + _this = _super.call(this, def) || this; + var mb = _this; + mb.objectDefs = def.objects; + mb.objects = []; + mb.objectDefs.forEach(function (td) { + td.def.mathbox = mb; + td.def.model = mb.model; + if (td.type.indexOf('Mathbox') < 0) { + td.type = 'Mathbox' + td.type; + } + try { + mb.objects.push(new KG[td.type](td.def)); + } + catch (e) { + console.log("There's no object called ", td.type); + } + }); + mb.clearColor = mb.model.clearColor; + return _this; + //console.log('created mathbox', mb); + } + Mathbox.prototype.initMathbox = function () { + var mb = this; + mb.mathbox = mathBox({ + plugins: ['core', 'controls', 'cursor', 'mathbox'], + controls: { klass: THREE.OrbitControls }, + element: mb.rootElement.node() + }); + if (mb.mathbox.fallback) + throw "WebGL not supported"; + mb.three = mb.mathbox.three; + mb.three.renderer.setClearColor(new THREE.Color(mb.clearColor), 1.0); + mb.mathbox.camera({ proxy: true, position: [-5, 0.5, 0.8], eulerOrder: "yzx" }); + mb.mathboxView = mb.mathbox.cartesian({ scale: [1.6, 1.6, 1.6] }); + mb.mathboxView.grid({ axes: [1, 3], width: 2, divideX: 10, divideY: 10, opacity: 0.3 }); + mb.xAxis.redraw(); + mb.yAxis.redraw(); + mb.zAxis.redraw(); + mb.objects.forEach(function (o) { o.draw().update(); }); + return mb; + }; + // create mb for mathbox + Mathbox.prototype.draw = function (layer) { + //console.log('creating mathbox container'); + var mb = this; + mb.rootElement = layer.append('div').style('position', 'absolute'); + return mb; + }; + Mathbox.prototype.redraw = function () { + var mb = _super.prototype.redraw.call(this); + //console.log('called redraw'); + if (mb.mathbox == undefined && mb.rootElement.node().clientWidth > 10 && mb.zAxis != undefined) { + mb.initMathbox(); + } + else { + return mb; + } + return mb; + }; + return Mathbox; + }(KG.PositionedDiv)); + KG.Mathbox = Mathbox; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Sidebar = /** @class */ (function (_super) { + __extends(Sidebar, _super); + function Sidebar(def) { + var _this = this; + KG.setDefaults(def, { + controls: [], + triggerWidth: 563 + }); + KG.setProperties(def, 'constants', ['controls', 'triggerWidth']); + _this = _super.call(this, def) || this; + return _this; + } + Sidebar.prototype.positionRight = function (width, height) { + var sidebar = this; + sidebar.rootElement + .style('left', width * 847 / 1260 + 'px') + .style('top', '0px') + .style('width', (width * 413 / 1260 - 10) + 'px') + .style('height', height + 'px') + .style('overflow-y', 'scroll') + .style('right', '-17px'); + }; + Sidebar.prototype.positionBelow = function (width, height) { + var sidebar = this; + sidebar.rootElement + .style('left', '10px') + .style('top', height + 20 + 'px') + .style('width', width - 20 + 'px') + .style('height', null); + }; + Sidebar.prototype.draw = function (layer) { + var sidebar = this; + sidebar.rootElement = layer.append('div').style('position', 'absolute').attr('class', 'sidebar'); + sidebar.controls.forEach(function (controlsDef) { + controlsDef.layer = sidebar.rootElement; + controlsDef.model = sidebar.model; + new KG.Controls(controlsDef); + }); + return sidebar; + }; + return Sidebar; + }(KG.ViewObject)); + KG.Sidebar = Sidebar; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Explanation = /** @class */ (function (_super) { + __extends(Explanation, _super); + function Explanation(def) { + var _this = this; + KG.setDefaults(def, { + height: 0, + divs: [], + border: 'none' + }); + KG.setProperties(def, 'constants', ['divs', 'height', 'border']); + _this = _super.call(this, def) || this; + return _this; + } + Explanation.prototype.position = function (width, height) { + var explanation = this; + explanation.rootElement + .style('left', '10px') + .style('top', height + 20 + 'px') + .style('width', width - 20 + 'px'); + }; + Explanation.prototype.draw = function (layer) { + var explanation = this; + explanation.rootElement = layer.append('div') + .style('position', 'absolute') + .style('height', explanation.height == 0 ? null : explanation.height + 'px') + .style('overflow-y', 'scroll') + .style('border', explanation.border); + explanation.divs.forEach(function (div) { + div = KG.setDefaults(div, { + layer: explanation.rootElement, + model: explanation.model, + fontSize: 12 + }); + if (div.hasOwnProperty('html')) { + new KG.Div(div); + } + else if (div.hasOwnProperty('table')) { + div.rows = div.table.rows; + div.columns = div.table.columns; + div.fontSize = 10; + delete div.table; + new KG.Table(div); + } + }); + return explanation; + }; + return Explanation; + }(KG.ViewObject)); + KG.Explanation = Explanation; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Table = /** @class */ (function (_super) { + __extends(Table, _super); + function Table(def) { + var _this = this; + KG.setDefaults(def, { + columns: [], + rows: [], + fontSize: 8, + lines: true + }); + KG.setProperties(def, 'constants', ['fontSize', 'lines']); + KG.setProperties(def, 'updatables', ['rows', 'columns']); + _this = _super.call(this, def) || this; + return _this; + } + // create div for text + Table.prototype.draw = function (layer) { + var t = this; + console.log('table is ', t); + var hasColumnHeaders = (t.def['columns'].length > 0), numColumns = t.def['rows'][0].length, numRows = t.def['rows'].length; + t.rootElement = layer.append('div'); + var table = t.rootElement.append('table').attr('class', 'table'); + table + .style('margin-left', 'auto') + .style('margin-right', 'auto') + .style('font-size', t.fontSize + 'pt') + .style('text-align', 'center') + .style('border-collapse', 'collapse') + .style('margin-top', '15pt') + .attr('cell-padding', '5px') + .style('width', '80%'); + t.columnCells = []; + if (hasColumnHeaders) { + var columnRow = table.append('thead').append('tr'); + for (var c = 0; c < numColumns; c++) { + var columnCell = columnRow.append('td'); + columnCell + .style('font-size', t.fontSize + 'pt') + .style('font-weight', 'bold') + .style('border-bottom', '1px solid black') + .style('text-align', 'center') + .style('padding', '0px 10px 0px 10px'); + t.columnCells.push(columnCell); + } + } + t.rowCells = []; + var tableBody = table.append('tbody'); + for (var r = 0; r < numRows; r++) { + var dataRow = []; + var tableRow = tableBody.append('tr'); + for (var c = 0; c < numColumns; c++) { + var rowCell = tableRow.append('td'); + rowCell + .style('font-size', t.fontSize + 'pt') + .style('text-align', 'center'); + if (t.lines) { + rowCell.style('border-bottom', '0.5px solid grey'); + } + dataRow.push(rowCell); + } + t.rowCells.push(dataRow); + } + return t; + }; + Table.prototype.redraw = function () { + var t = this; + var hasColumnHeaders = (t.def['columns'].length > 0), numColumns = t.rows[0].length, numRows = t.rows.length; + if (hasColumnHeaders) { + for (var c = 0; c < numColumns; c++) { + katex.render("\\text{" + t.columns[c].toString() + "}", t.columnCells[c].node()); + } + } + for (var r = 0; r < numRows; r++) { + for (var c = 0; c < numColumns; c++) { + katex.render("\\text{" + t.rows[r][c].toString() + "}", t.rowCells[r][c].node()); + } + } + return t; + }; + return Table; + }(KG.DivObject)); + KG.Table = Table; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var MathboxObject = /** @class */ (function (_super) { + __extends(MathboxObject, _super); + function MathboxObject(def) { + var _this = this; + KG.setProperties(def, 'constants', ['mathbox']); + _this = _super.call(this, def) || this; + return _this; + } + MathboxObject.prototype.onGraph = function () { + return true; // we won't check yet to see if it's on the graph... + }; + MathboxObject.prototype.displayElement = function (show) { + var mbo = this; + if (mbo.hasOwnProperty("mo")) { + this.mo.set("visible", show); + } + }; + return MathboxObject; + }(KG.ViewObject)); + KG.MathboxObject = MathboxObject; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxAxis = /** @class */ (function (_super) { + __extends(MathboxAxis, _super); + function MathboxAxis(def) { + var _this = this; + KG.setDefaults(def, { + ticks: 5, + min: 0, + max: 10 + }); + KG.setProperties(def, 'constants', ['axisNumber', 'ticks']); + KG.setProperties(def, 'updatables', ['ticks', 'label', 'min', 'max']); + _this = _super.call(this, def) || this; + return _this; + } + MathboxAxis.prototype.redraw = function () { + var a = this; + var view = a.mathbox.mathboxView; + if (view == undefined) { + return a; + } + view.set("range", [[a.mathbox.yAxis.min, a.mathbox.yAxis.max], [a.mathbox.zAxis.min, a.mathbox.zAxis.max], [a.mathbox.xAxis.min, a.mathbox.xAxis.max]]); + var axis = view.axis({ axis: a.axisNumber, width: 8, detail: 40, color: "black" }); + var scale = view.scale({ axis: a.axisNumber, divide: a.ticks, nice: false, zero: true }); + var ticks = view.ticks({ width: 5, size: 5, color: "gray", zBias: 2 }); + var format = view.format({ digits: 2, classes: ["tick"], style: "normal", source: scale }); + var ticklabel = view.label({ color: "gray", zIndex: 1, offset: [0, 0], points: scale, text: format, size: 10 }); + return a; + }; + return MathboxAxis; + }(KG.MathboxObject)); + KG.MathboxAxis = MathboxAxis; + var MathboxXAxis = /** @class */ (function (_super) { + __extends(MathboxXAxis, _super); + function MathboxXAxis(def) { + var _this = this; + def.axisNumber = 3; + _this = _super.call(this, def) || this; + var xAxis = _this; + xAxis.mathbox.xAxis = xAxis; + return _this; + } + return MathboxXAxis; + }(MathboxAxis)); + KG.MathboxXAxis = MathboxXAxis; + var MathboxYAxis = /** @class */ (function (_super) { + __extends(MathboxYAxis, _super); + function MathboxYAxis(def) { + var _this = this; + def.axisNumber = 1; + _this = _super.call(this, def) || this; + var yAxis = _this; + yAxis.mathbox.yAxis = yAxis; + return _this; + } + return MathboxYAxis; + }(MathboxAxis)); + KG.MathboxYAxis = MathboxYAxis; + var MathboxZAxis = /** @class */ (function (_super) { + __extends(MathboxZAxis, _super); + function MathboxZAxis(def) { + var _this = this; + def.axisNumber = 2; + _this = _super.call(this, def) || this; + var zAxis = _this; + zAxis.mathbox.zAxis = zAxis; + return _this; + } + return MathboxZAxis; + }(MathboxAxis)); + KG.MathboxZAxis = MathboxZAxis; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxPoint = /** @class */ (function (_super) { + __extends(MathboxPoint, _super); + function MathboxPoint(def) { + var _this = this; + KG.setDefaults(def, { + x: 0, + y: 0, + z: 0 + }); + KG.setProperties(def, 'updatables', ['x', 'y', 'z']); + _this = _super.call(this, def) || this; + return _this; + } + MathboxPoint.prototype.draw = function () { + var p = this; + p.pointData = p.mathbox.mathboxView.array({ + width: 1, + channels: 3 + }); + p.mo = p.mathbox.mathboxView.point({ + size: 20, + points: p.pointData, + zIndex: 4 + }); + return p; + }; + MathboxPoint.prototype.redraw = function () { + var p = this; + //console.log(p); + p.pointData.set("data", [[p.y, p.z, p.x]]); + p.mo.set("color", p.stroke); + return p; + }; + return MathboxPoint; + }(KG.MathboxObject)); + KG.MathboxPoint = MathboxPoint; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxCurve = /** @class */ (function (_super) { + __extends(MathboxCurve, _super); + function MathboxCurve(def) { + var _this = this; + KG.setDefaults(def, { + text: "#666666", + strokeWidth: 10 + }); + _this = _super.call(this, def) || this; + def.fn = KG.setDefaults(def.fn, { + model: def.model, + samplePoints: 100 + }); + _this.fn = new KG.UnivariateFunction(def.fn).update(true); + return _this; + } + MathboxCurve.prototype.draw = function () { + var c = this; + c.curveData = c.mathbox.mathboxView.interval({ + axis: 1, + channels: 3, + width: c.fn.samplePoints + }); + c.mo = c.mathbox.mathboxView.line({ + points: c.curveData, + zIndex: 3 + }); + return c; + }; + MathboxCurve.prototype.redraw = function () { + var c = this; + //console.log(c); + c.curveData.set("expr", c.fn.mathboxFn(c.mathbox)); + c.mo.set("color", c.stroke); + c.mo.set("width", c.strokeWidth); + c.mo.set("stroke", c.lineStyle); + return c; + }; + return MathboxCurve; + }(KG.MathboxObject)); + KG.MathboxCurve = MathboxCurve; + var CurveThreeD = /** @class */ (function (_super) { + __extends(CurveThreeD, _super); + function CurveThreeD(def) { + return _super.call(this, def) || this; + } + return CurveThreeD; + }(MathboxCurve)); + KG.CurveThreeD = CurveThreeD; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxSurface = /** @class */ (function (_super) { + __extends(MathboxSurface, _super); + function MathboxSurface(def) { + var _this = this; + KG.setDefaults(def, { + fill: "#666666", + strokeWidth: 10, + opacity: 0.2, + meshWidth: 1, + samplePoints: 100, + axis1: "x", + axis2: "y" + }); + KG.setProperties(def, 'constants', ['meshWidth', 'samplePoints']); + _this = _super.call(this, def) || this; + var s = _this; + var axis1 = [0, "y", "z", "x"].indexOf(def.axis1); + var axis2 = [0, "y", "z", "x"].indexOf(def.axis2); + s.axes = [axis1, axis2]; + return _this; + } + MathboxSurface.prototype.draw = function () { + var s = this; + s.surfaceData = s.mathbox.mathboxView.area({ + axes: s.axes, + channels: 3, + width: s.samplePoints, + height: s.samplePoints + }); + console.log('surface data: ', s.surfaceData); + /* + + #TODO Someday we'll improve shading + + var graphColors = s.mathbox.mathboxView.area({ + expr: function (emit, x, y, i, j, t) { + if (x < 0) + emit(1.0, 0.0, 0.0, 1.0); + else + emit(0.0, 1.0, 0.0, 1.0); + }, + axes: [1, 3], + width: 64, height: 64, + channels: 4, // RGBA + }); + + graphColors.set("expr", + function (emit, x, y, i, j, t) + { + var z = x*x + y*y; + const zMin = 0, zMax=200; + var percent = (z - zMin) / (zMax - zMin); + emit( percent, percent, percent, 1.0 ); + } + );*/ + s.mo = s.mathbox.mathboxView.surface({ + points: s.surfaceData, + shaded: true, + fill: true, + lineX: true, + lineY: true, + width: s.meshWidth, + zIndex: 2 + }); + return s; + }; + MathboxSurface.prototype.redraw = function () { + var c = this; + //console.log(c); + c.surfaceData.set("expr", c.mathboxFn()); + c.mo.set("color", c.fill); + c.mo.set("opacity", c.opacity); + return c; + }; + return MathboxSurface; + }(KG.MathboxObject)); + KG.MathboxSurface = MathboxSurface; + var MathboxFunctionSurface = /** @class */ (function (_super) { + __extends(MathboxFunctionSurface, _super); + function MathboxFunctionSurface(def) { + var _this = this; + def.fn = KG.setDefaults(def.fn, { + model: def.model, + samplePoints: 100 + }); + KG.setDefaults(def, { + samplePoints: def.fn.samplePoints + }); + _this = _super.call(this, def) || this; + _this.fn = new KG.MultivariateFunction(def.fn).update(true); + return _this; + } + MathboxFunctionSurface.prototype.mathboxFn = function () { + var s = this; + return function (emit, x, y) { + emit(y, s.fn.evaluate(x, y), x); + }; + }; + return MathboxFunctionSurface; + }(MathboxSurface)); + KG.MathboxFunctionSurface = MathboxFunctionSurface; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxDataSurface = /** @class */ (function (_super) { + __extends(MathboxDataSurface, _super); + function MathboxDataSurface(def) { + var _this = this; + KG.setDefaults(def, { + fill: "#666666", + strokeWidth: 10, + opacity: 0.2, + meshWidth: 1, + samplePoints: 100, + axis1: "x", + axis2: "y" + }); + KG.setProperties(def, 'constants', ['meshWidth', 'samplePoints']); + _this = _super.call(this, def) || this; + var s = _this; + var axis1 = [0, "y", "z", "x"].indexOf(def.axis1); + var axis2 = [0, "y", "z", "x"].indexOf(def.axis2); + s.axes = [axis1, axis2]; + return _this; + } + MathboxDataSurface.prototype.draw = function () { + var s = this; + s.surfaceData = s.mathbox.mathboxView.area({ + axes: s.axes, + channels: 3, + width: s.samplePoints, + height: s.samplePoints + }); + /* + + #TODO Someday we'll improve shading + + var graphColors = s.mathbox.mathboxView.area({ + expr: function (emit, x, y, i, j, t) { + if (x < 0) + emit(1.0, 0.0, 0.0, 1.0); + else + emit(0.0, 1.0, 0.0, 1.0); + }, + axes: [1, 3], + width: 64, height: 64, + channels: 4, // RGBA + }); + + graphColors.set("expr", + function (emit, x, y, i, j, t) + { + var z = x*x + y*y; + const zMin = 0, zMax=200; + var percent = (z - zMin) / (zMax - zMin); + emit( percent, percent, percent, 1.0 ); + } + );*/ + s.mo = s.mathbox.mathboxView.surface({ + points: s.surfaceData, + shaded: true, + fill: true, + lineX: true, + lineY: true, + width: s.meshWidth, + zIndex: 2 + }); + return s; + }; + MathboxDataSurface.prototype.redraw = function () { + var c = this; + //console.log(c); + c.surfaceData.set("expr", c.mathboxFn()); + c.mo.set("color", c.fill); + c.mo.set("opacity", c.opacity); + return c; + }; + return MathboxDataSurface; + }(KG.MathboxSurface)); + KG.MathboxDataSurface = MathboxDataSurface; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxPlane = /** @class */ (function (_super) { + __extends(MathboxPlane, _super); + function MathboxPlane(def) { + var _this = this; + var planeType = 'z'; + if (def.hasOwnProperty('x')) { + def.axis1 = "y"; + def.axis2 = "z"; + planeType = "x"; + } + else if (def.hasOwnProperty('y')) { + def.axis1 = "x"; + def.axis2 = "z"; + planeType = "y"; + } + else { + def.axis1 = "x"; + def.axis2 = "y"; + } + def.samplePoints = 2; + KG.setProperties(def, 'updatables', ['x', 'y', 'z']); + _this = _super.call(this, def) || this; + _this.planeType = planeType; + return _this; + } + MathboxPlane.prototype.mathboxFn = function () { + var p = this; + if (p.planeType == "x") { + return function (emit, y, z) { + emit(y, z, p.x); + }; + } + else if (p.planeType == "y") { + return function (emit, x, z) { + emit(p.y, z, x); + }; + } + else { + return function (emit, x, y) { + emit(y, p.z, x); + }; + } + }; + return MathboxPlane; + }(KG.MathboxSurface)); + KG.MathboxPlane = MathboxPlane; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxShape = /** @class */ (function (_super) { + __extends(MathboxShape, _super); + function MathboxShape(def) { + var _this = this; + KG.setDefaults(def, { + fill: "#666666", + strokeWidth: 10, + opacity: 0.2 + }); + _this = _super.call(this, def) || this; + return _this; + } + MathboxShape.prototype.draw = function () { + var s = this; + s.surfaceData = s.mathbox.mathboxView.area({ + axes: [1, 3], + channels: 3, + width: s.fn.samplePoints, + height: s.fn.samplePoints + }); + s.mo = s.mathbox.mathboxView.surface({ + points: s.surfaceData, + shaded: true, + fill: true, + lineX: false, + lineY: false, + width: 0, + zIndex: 2 + }); + return s; + }; + MathboxShape.prototype.redraw = function () { + var c = this; + //console.log(c); + c.surfaceData.set("expr", c.fn.mathboxFn()); + c.mo.set("color", c.fill); + c.mo.set("opacity", c.opacity); + return c; + }; + return MathboxShape; + }(KG.MathboxObject)); + KG.MathboxShape = MathboxShape; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxLabel = /** @class */ (function (_super) { + __extends(MathboxLabel, _super); + function MathboxLabel(def) { + var _this = this; + KG.setDefaults(def, { + text: "foo" + }); + KG.setProperties(def, 'updatables', ['text']); + _this = _super.call(this, def) || this; + return _this; + } + MathboxLabel.prototype.draw = function () { + var l = this; + l.pointData = l.mathbox.mathboxView.array({ + width: 1, + channels: 3 + }); + l.labelData = l.mathbox.mathboxView.format({ + font: "KaTeX_Main", + style: "normal" + }); + l.mo = l.mathbox.mathboxView.label({ + points: l.pointData, + zIndex: 4, + text: l.labelData + }); + return l; + }; + MathboxLabel.prototype.redraw = function () { + var l = _super.prototype.redraw.call(this); + l.labelData.set("data", [l.text]); + return l; + }; + return MathboxLabel; + }(KG.MathboxPoint)); + KG.MathboxLabel = MathboxLabel; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxLine = /** @class */ (function (_super) { + __extends(MathboxLine, _super); + function MathboxLine(def) { + var _this = this; + KG.setDefaults(def, { + x1: 0, + y1: 0, + z1: 0, + x2: 0, + y2: 0, + z2: 0, + lineStyle: "solid" + }); + KG.setProperties(def, 'updatables', ['x1', 'y1', 'z1', 'x2', 'y2', 'z2']); + KG.setProperties(def, 'constants', ['start', 'end']); + _this = _super.call(this, def) || this; + return _this; + } + MathboxLine.prototype.draw = function () { + var p = this; + p.pointData = p.mathbox.mathboxView.array({ + width: 2, + channels: 3 + }); + p.mo = p.mathbox.mathboxView.line({ + points: p.pointData, + zIndex: 4 + }); + return p; + }; + MathboxLine.prototype.redraw = function () { + var p = this; + //console.log(p); + p.pointData.set("data", [[p.y1, p.z1, p.x1], [p.y2, p.z2, p.x2]]); + p.mo.set("color", p.stroke); + p.mo.set("stroke", p.lineStyle); + p.mo.set("width", p.strokeWidth); + p.mo.set("start", p.start); + p.mo.set("end", p.end); + return p; + }; + return MathboxLine; + }(KG.MathboxObject)); + KG.MathboxLine = MathboxLine; +})(KG || (KG = {})); +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +// this file provides the interface with the overall web page +var views = []; +// initialize the diagram from divs with class kg-container +function loadGraphs() { + views = []; + var viewDivs = document.getElementsByClassName('kg-container'); + var _loop_1 = function (i) { + var d = viewDivs[i], src = d.getAttribute('src'), tmp = d.getAttribute('template'), fmt = d.getAttribute('format'); + //greenscreen = d.getAttribute('greenscreen') || false; + if (d.innerHTML.indexOf('svg') > -1) { + //console.log('already loaded'); + } + else { + // if there is no src attribute + if (!src || src.indexOf('.yml') > -1) { + try { + function generateViewFromYamlText(t) { + var y = jsyaml.safeLoad(t); + var j = JSON.parse(JSON.stringify(y).replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&')); + //j.greenscreen = greenscreen; + // If there is a template file, then load that and use the yml in the description to replace terms defined by "macro" + var custom = ""; + if (tmp) { + d3.text(tmp).then(function (template_file) { + var yt = jsyaml.safeLoad(template_file); + var yts = JSON.stringify(yt).replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&'); + for (var key in j) { + if (key == "custom") { + custom = j[key]; + } + var searchTerm = new RegExp("template.\\b" + key + "\\b", "g"); + var replaceTerm = j[key]; + yts = yts.replace(searchTerm, replaceTerm); + } + var jt = JSON.parse(yts); + jt.custom = custom; + views.push(new KG.View(d, jt)); + }); + } + else { + views.push(new KG.View(d, j)); + } + } + if (src) { + // load YAML from source file + d3.text(src).then(function (yaml_file) { + generateViewFromYamlText(yaml_file); + }); + } + else { + // read inner HTML of div as YAML + var inlineDef = d.innerHTML; + d.innerHTML = ""; + generateViewFromYamlText(inlineDef); + } + } + catch (e) { + console.log('Error reading YAML: ', e.message); + } + } + // first look to see if there's a definition in the KG.viewData object + else if (KG['viewData'].hasOwnProperty(src)) { + viewDivs[i].innerHTML = ""; + views.push(new KG.View(viewDivs[i], KG['viewData'][src])); + } + else { + // then look to see if the src is available by a URL + d3.json(src + "?update=true").then(function (data) { + if (!data) { + d.innerHTML = "

oops, " + src + " doesn't seem to exist.

"; + } + else { + d.innerHTML = ""; + //data.greenscreen = greenscreen; + views.push(new KG.View(d, data)); + } + }); + } + d.classList.add('kg-loaded'); + } + }; + // for each div, fetch the JSON definition and create a View object with that div and data + for (var i = 0; i < viewDivs.length; i++) { + _loop_1(i); + } +} +; +// When the page loads, load the graphs +window.addEventListener("load", loadGraphs); +// if the window changes size, update the dimensions of the containers +window.onresize = function () { + views.forEach(function (c) { + c.updateDimensions(); + }); +}; +(function () { + var beforePrint = function () { + views.forEach(function (c) { + c.updateDimensions(true); + }); + }; + var afterPrint = function () { + views.forEach(function (c) { + c.updateDimensions(false); + }); + }; + if (window.matchMedia) { + var mediaQueryList = window.matchMedia('print'); + mediaQueryList.addListener(function (mql) { + if (mql.matches) { + beforePrint(); + } + else { + afterPrint(); + } + }); + } + window.onbeforeprint = beforePrint; + window.onafterprint = afterPrint; +}()); +// if embedded within a slide, send slide transitions to the parent +document.addEventListener("keyup", function (event) { + if (event.key == 'PageDown') { + event.preventDefault(); + console.log('trigger next page'); + if (window != window.parent) { + window.parent.postMessage(JSON.stringify({ + method: 'next' + }), '*'); + } + } + if (event.key == 'PageUp') { + event.preventDefault(); + if (window != window.parent) { + window.parent.postMessage(JSON.stringify({ + method: 'prev' + }), '*'); + } + } +}); +var KG; +(function (KG) { + function resetAllParams() { + console.log("Resetting parameters on all views"); + views.forEach(function (v) { + v.model.resetParams(); + }); + } + KG.resetAllParams = resetAllParams; +})(KG || (KG = {})); + + diff --git a/static/js/kg3d.0.3.2.js b/static/js/kg3d.0.3.2.js new file mode 100644 index 0000000..0527ced --- /dev/null +++ b/static/js/kg3d.0.3.2.js @@ -0,0 +1,71435 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.katex=e():t.katex=e()}("undefined"!=typeof self?self:this,function(){return function(t){var e={};function r(a){if(e[a])return e[a].exports;var n=e[a]={i:a,l:!1,exports:{}};return t[a].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=t,r.c=e,r.d=function(t,e,a){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:a})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var a=Object.create(null);if(r.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var n in t)r.d(a,n,function(e){return t[e]}.bind(null,n));return a},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=1)}([function(t,e,r){},function(t,e,r){"use strict";r.r(e);r(0);var a=function(){function t(t,e,r){this.lexer=void 0,this.start=void 0,this.end=void 0,this.lexer=t,this.start=e,this.end=r}return t.range=function(e,r){return r?e&&e.loc&&r.loc&&e.loc.lexer===r.loc.lexer?new t(e.loc.lexer,e.loc.start,r.loc.end):null:e&&e.loc},t}(),n=function(){function t(t,e){this.text=void 0,this.loc=void 0,this.text=t,this.loc=e}return t.prototype.range=function(e,r){return new t(r,a.range(this,e))},t}(),i=function t(e,r){this.position=void 0;var a,n="KaTeX parse error: "+e,i=r&&r.loc;if(i&&i.start<=i.end){var o=i.lexer.input;a=i.start;var s=i.end;a===o.length?n+=" at end of input: ":n+=" at position "+(a+1)+": ";var h=o.slice(a,s).replace(/[^]/g,"$&\u0332");n+=(a>15?"\u2026"+o.slice(a-15,a):o.slice(0,a))+h+(s+15":">","<":"<",'"':""","'":"'"},l=/[&><"']/g;var m=function t(e){return"ordgroup"===e.type?1===e.body.length?t(e.body[0]):e:"color"===e.type?1===e.body.length?t(e.body[0]):e:"font"===e.type?t(e.body):e},c={contains:function(t,e){return-1!==t.indexOf(e)},deflt:function(t,e){return void 0===t?e:t},escape:function(t){return String(t).replace(l,function(t){return h[t]})},hyphenate:function(t){return t.replace(s,"-$1").toLowerCase()},getBaseElem:m,isCharacterBox:function(t){var e=m(t);return"mathord"===e.type||"textord"===e.type||"atom"===e.type},protocolFromUrl:function(t){var e=/^\s*([^\\\/#]*?)(?::|�*58|�*3a)/i.exec(t);return null!=e?e[1]:"_relative"}},u=function(){function t(t){this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void 0,this.errorColor=void 0,this.macros=void 0,this.minRuleThickness=void 0,this.colorIsTextColor=void 0,this.strict=void 0,this.trust=void 0,this.maxSize=void 0,this.maxExpand=void 0,t=t||{},this.displayMode=c.deflt(t.displayMode,!1),this.output=c.deflt(t.output,"htmlAndMathml"),this.leqno=c.deflt(t.leqno,!1),this.fleqn=c.deflt(t.fleqn,!1),this.throwOnError=c.deflt(t.throwOnError,!0),this.errorColor=c.deflt(t.errorColor,"#cc0000"),this.macros=t.macros||{},this.minRuleThickness=Math.max(0,c.deflt(t.minRuleThickness,0)),this.colorIsTextColor=c.deflt(t.colorIsTextColor,!1),this.strict=c.deflt(t.strict,"warn"),this.trust=c.deflt(t.trust,!1),this.maxSize=Math.max(0,c.deflt(t.maxSize,1/0)),this.maxExpand=Math.max(0,c.deflt(t.maxExpand,1e3))}var e=t.prototype;return e.reportNonstrict=function(t,e,r){var a=this.strict;if("function"==typeof a&&(a=a(t,e,r)),a&&"ignore"!==a){if(!0===a||"error"===a)throw new o("LaTeX-incompatible input and strict mode is set to 'error': "+e+" ["+t+"]",r);"warn"===a?"undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+e+" ["+t+"]"):"undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to unrecognized '"+a+"': "+e+" ["+t+"]")}},e.useStrictBehavior=function(t,e,r){var a=this.strict;if("function"==typeof a)try{a=a(t,e,r)}catch(t){a="error"}return!(!a||"ignore"===a)&&(!0===a||"error"===a||("warn"===a?("undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+e+" ["+t+"]"),!1):("undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to unrecognized '"+a+"': "+e+" ["+t+"]"),!1)))},e.isTrusted=function(t){t.url&&!t.protocol&&(t.protocol=c.protocolFromUrl(t.url));var e="function"==typeof this.trust?this.trust(t):this.trust;return Boolean(e)},t}(),p=function(){function t(t,e,r){this.id=void 0,this.size=void 0,this.cramped=void 0,this.id=t,this.size=e,this.cramped=r}var e=t.prototype;return e.sup=function(){return d[f[this.id]]},e.sub=function(){return d[g[this.id]]},e.fracNum=function(){return d[x[this.id]]},e.fracDen=function(){return d[v[this.id]]},e.cramp=function(){return d[b[this.id]]},e.text=function(){return d[y[this.id]]},e.isTight=function(){return this.size>=2},t}(),d=[new p(0,0,!1),new p(1,0,!0),new p(2,1,!1),new p(3,1,!0),new p(4,2,!1),new p(5,2,!0),new p(6,3,!1),new p(7,3,!0)],f=[4,5,4,5,6,7,6,7],g=[5,5,5,5,7,7,7,7],x=[2,3,4,5,6,7,6,7],v=[3,3,5,5,7,7,7,7],b=[1,1,3,3,5,5,7,7],y=[0,1,2,3,2,3,2,3],w={DISPLAY:d[0],TEXT:d[2],SCRIPT:d[4],SCRIPTSCRIPT:d[6]},k=[{name:"latin",blocks:[[256,591],[768,879]]},{name:"cyrillic",blocks:[[1024,1279]]},{name:"brahmic",blocks:[[2304,4255]]},{name:"georgian",blocks:[[4256,4351]]},{name:"cjk",blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:"hangul",blocks:[[44032,55215]]}];var S=[];function M(t){for(var e=0;e=S[e]&&t<=S[e+1])return!0;return!1}k.forEach(function(t){return t.blocks.forEach(function(t){return S.push.apply(S,t)})});var z={doubleleftarrow:"M262 157\nl10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3\n 0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28\n 14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5\nc2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5\n 157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87\n-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7\n-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z\nm8 0v40h399730v-40zm0 194v40h399730v-40z",doublerightarrow:"M399738 392l\n-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5\n 14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88\n-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68\n-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18\n-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782\nc-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3\n-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z",leftarrow:"M400000 241H110l3-3c68.7-52.7 113.7-120\n 135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8\n-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247\nc-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208\n 490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3\n 1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202\n l-3-3h399890zM100 241v40h399900v-40z",leftbrace:"M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117\n-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7\n 5-6 9-10 13-.7 1-7.3 1-20 1H6z",leftbraceunder:"M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13\n 35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688\n 0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7\n-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z",leftgroup:"M400000 80\nH435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0\n 435 0h399565z",leftgroupunder:"M400000 262\nH435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219\n 435 219h399565z",leftharpoon:"M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3\n-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5\n-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7\n-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z",leftharpoonplus:"M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5\n 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3\n-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7\n-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z\nm0 0v40h400000v-40z",leftharpoondown:"M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333\n 5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5\n 1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667\n-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z",leftharpoondownplus:"M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12\n 10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7\n-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0\nv40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z",lefthook:"M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5\n-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3\n-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21\n 71.5 23h399859zM103 281v-40h399897v40z",leftlinesegment:"M40 281 V428 H0 V94 H40 V241 H400000 v40z\nM40 281 V428 H0 V94 H40 V241 H400000 v40z",leftmapsto:"M40 281 V448H0V74H40V241H400000v40z\nM40 281 V448H0V74H40V241H400000v40z",leftToFrom:"M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23\n-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8\nc28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3\n 68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z",longequal:"M0 50 h400000 v40H0z m0 194h40000v40H0z\nM0 50 h400000 v40H0z m0 194h40000v40H0z",midbrace:"M200428 334\nc-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14\n-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7\n 311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11\n 12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z",midbraceunder:"M199572 214\nc100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14\n 53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3\n 11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0\n-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z",oiintSize1:"M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6\n-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z\nm368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8\n60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z",oiintSize2:"M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8\n-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z\nm502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2\nc0 110 84 276 504 276s502.4-166 502.4-276z",oiiintSize1:"M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6\n-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z\nm525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0\n85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z",oiiintSize2:"M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8\n-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z\nm770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1\nc0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z",rightarrow:"M0 241v40h399891c-47.3 35.3-84 78-110 128\n-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20\n 11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7\n 39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85\n-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n 151.7 139 205zm0 0v40h399900v-40z",rightbrace:"M400000 542l\n-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5\ns-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1\nc124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z",rightbraceunder:"M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3\n 28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237\n-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z",rightgroup:"M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0\n 3-1 3-3v-38c-76-158-257-219-435-219H0z",rightgroupunder:"M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18\n 0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z",rightharpoon:"M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3\n-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2\n-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58\n 69.2 92 94.5zm0 0v40h399900v-40z",rightharpoonplus:"M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11\n-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7\n 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z\nm0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z",rightharpoondown:"M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8\n 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5\n-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95\n-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z",rightharpoondownplus:"M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8\n 15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3\n 8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3\n-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z\nm0-194v40h400000v-40zm0 0v40h400000v-40z",righthook:"M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3\n 15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0\n-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21\n 66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z",rightlinesegment:"M399960 241 V94 h40 V428 h-40 V281 H0 v-40z\nM399960 241 V94 h40 V428 h-40 V281 H0 v-40z",rightToFrom:"M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23\n 1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32\n-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142\n-167z M100 147v40h399900v-40zM0 341v40h399900v-40z",twoheadleftarrow:"M0 167c68 40\n 115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69\n-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3\n-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19\n-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101\n 10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z",twoheadrightarrow:"M400000 167\nc-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3\n 41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42\n 18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333\n-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70\n 101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z",tilde1:"M200 55.538c-77 0-168 73.953-177 73.953-3 0-7\n-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0\n 114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0\n 4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128\n-68.267.847-113-73.952-191-73.952z",tilde2:"M344 55.266c-142 0-300.638 81.316-311.5 86.418\n-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9\n 31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114\nc1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751\n 181.476 676 181.476c-149 0-189-126.21-332-126.21z",tilde3:"M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457\n-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0\n 411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697\n 16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696\n -338 0-409-156.573-744-156.573z",tilde4:"M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345\n-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409\n 177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9\n 14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409\n -175.236-744-175.236z",vec:"M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5\n3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11\n10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63\n-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1\n-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59\nH213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359\nc-16-25.333-24-45-24-59z",widehat1:"M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22\nc-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z",widehat2:"M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widehat3:"M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widehat4:"M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widecheck1:"M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1,\n-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z",widecheck2:"M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",widecheck3:"M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",widecheck4:"M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",baraboveleftarrow:"M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202\nc4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5\nc-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130\ns-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47\n121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6\ns2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11\nc0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z\nM100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z",rightarrowabovebar:"M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32\n-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0\n13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39\n-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5\n-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z",baraboveshortleftharpoon:"M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17\nc2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21\nc-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40\nc-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z\nM0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z",rightharpoonaboveshortbar:"M0,241 l0,40c399126,0,399993,0,399993,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z",shortbaraboveleftharpoon:"M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9,\n1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7,\n-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z\nM93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z",shortrightharpoonabovebar:"M53,241l0,40c398570,0,399437,0,399437,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z"},T=function(){function t(t){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=t,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}var e=t.prototype;return e.hasClass=function(t){return c.contains(this.classes,t)},e.toNode=function(){for(var t=document.createDocumentFragment(),e=0;e"},N=function(){function t(t,e,r,a){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,B.call(this,t,r,a),this.children=e||[]}var e=t.prototype;return e.setAttribute=function(t,e){this.attributes[t]=e},e.hasClass=function(t){return c.contains(this.classes,t)},e.toNode=function(){return C.call(this,"span")},e.toMarkup=function(){return q.call(this,"span")},t}(),I=function(){function t(t,e,r,a){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,B.call(this,e,a),this.children=r||[],this.setAttribute("href",t)}var e=t.prototype;return e.setAttribute=function(t,e){this.attributes[t]=e},e.hasClass=function(t){return c.contains(this.classes,t)},e.toNode=function(){return C.call(this,"a")},e.toMarkup=function(){return q.call(this,"a")},t}(),R=function(){function t(t,e,r){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=e,this.src=t,this.classes=["mord"],this.style=r}var e=t.prototype;return e.hasClass=function(t){return c.contains(this.classes,t)},e.toNode=function(){var t=document.createElement("img");for(var e in t.src=this.src,t.alt=this.alt,t.className="mord",this.style)this.style.hasOwnProperty(e)&&(t.style[e]=this.style[e]);return t},e.toMarkup=function(){var t=""+this.alt+"=n[0]&&t<=n[1])return r.name}return null}(this.text.charCodeAt(0));h&&this.classes.push(h+"_fallback"),/[\xee\xef\xed\xec]/.test(this.text)&&(this.text=O[this.text])}var e=t.prototype;return e.hasClass=function(t){return c.contains(this.classes,t)},e.toNode=function(){var t=document.createTextNode(this.text),e=null;for(var r in this.italic>0&&((e=document.createElement("span")).style.marginRight=this.italic+"em"),this.classes.length>0&&((e=e||document.createElement("span")).className=A(this.classes)),this.style)this.style.hasOwnProperty(r)&&((e=e||document.createElement("span")).style[r]=this.style[r]);return e?(e.appendChild(t),e):t},e.toMarkup=function(){var t=!1,e="0&&(r+="margin-right:"+this.italic+"em;"),this.style)this.style.hasOwnProperty(a)&&(r+=c.hyphenate(a)+":"+this.style[a]+";");r&&(t=!0,e+=' style="'+c.escape(r)+'"');var n=c.escape(this.text);return t?(e+=">",e+=n,e+=""):n},t}(),L=function(){function t(t,e){this.children=void 0,this.attributes=void 0,this.children=t||[],this.attributes=e||{}}var e=t.prototype;return e.toNode=function(){var t=document.createElementNS("http://www.w3.org/2000/svg","svg");for(var e in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,e)&&t.setAttribute(e,this.attributes[e]);for(var r=0;r":""},t}(),P=function(){function t(t){this.attributes=void 0,this.attributes=t||{}}var e=t.prototype;return e.toNode=function(){var t=document.createElementNS("http://www.w3.org/2000/svg","line");for(var e in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,e)&&t.setAttribute(e,this.attributes[e]);return t},e.toMarkup=function(){var t="",">"),j("math",$,tt,":",":"),j("math",$,tt,"\u2248","\\approx",!0),j("math",$,tt,"\u2245","\\cong",!0),j("math",$,tt,"\u2265","\\ge"),j("math",$,tt,"\u2265","\\geq",!0),j("math",$,tt,"\u2190","\\gets"),j("math",$,tt,">","\\gt"),j("math",$,tt,"\u2208","\\in",!0),j("math",$,tt,"\ue020","\\@not"),j("math",$,tt,"\u2282","\\subset",!0),j("math",$,tt,"\u2283","\\supset",!0),j("math",$,tt,"\u2286","\\subseteq",!0),j("math",$,tt,"\u2287","\\supseteq",!0),j("math",Z,tt,"\u2288","\\nsubseteq",!0),j("math",Z,tt,"\u2289","\\nsupseteq",!0),j("math",$,tt,"\u22a8","\\models"),j("math",$,tt,"\u2190","\\leftarrow",!0),j("math",$,tt,"\u2264","\\le"),j("math",$,tt,"\u2264","\\leq",!0),j("math",$,tt,"<","\\lt"),j("math",$,tt,"\u2192","\\rightarrow",!0),j("math",$,tt,"\u2192","\\to"),j("math",Z,tt,"\u2271","\\ngeq",!0),j("math",Z,tt,"\u2270","\\nleq",!0),j("math",$,"spacing","\xa0","\\ "),j("math",$,"spacing","\xa0","~"),j("math",$,"spacing","\xa0","\\space"),j("math",$,"spacing","\xa0","\\nobreakspace"),j("text",$,"spacing","\xa0","\\ "),j("text",$,"spacing","\xa0","~"),j("text",$,"spacing","\xa0","\\space"),j("text",$,"spacing","\xa0","\\nobreakspace"),j("math",$,"spacing",null,"\\nobreak"),j("math",$,"spacing",null,"\\allowbreak"),j("math",$,"punct",",",","),j("math",$,"punct",";",";"),j("math",Z,K,"\u22bc","\\barwedge",!0),j("math",Z,K,"\u22bb","\\veebar",!0),j("math",$,K,"\u2299","\\odot",!0),j("math",$,K,"\u2295","\\oplus",!0),j("math",$,K,"\u2297","\\otimes",!0),j("math",$,"textord","\u2202","\\partial",!0),j("math",$,K,"\u2298","\\oslash",!0),j("math",Z,K,"\u229a","\\circledcirc",!0),j("math",Z,K,"\u22a1","\\boxdot",!0),j("math",$,K,"\u25b3","\\bigtriangleup"),j("math",$,K,"\u25bd","\\bigtriangledown"),j("math",$,K,"\u2020","\\dagger"),j("math",$,K,"\u22c4","\\diamond"),j("math",$,K,"\u22c6","\\star"),j("math",$,K,"\u25c3","\\triangleleft"),j("math",$,K,"\u25b9","\\triangleright"),j("math",$,"open","{","\\{"),j("text",$,"textord","{","\\{"),j("text",$,"textord","{","\\textbraceleft"),j("math",$,"close","}","\\}"),j("text",$,"textord","}","\\}"),j("text",$,"textord","}","\\textbraceright"),j("math",$,"open","{","\\lbrace"),j("math",$,"close","}","\\rbrace"),j("math",$,"open","[","\\lbrack"),j("text",$,"textord","[","\\lbrack"),j("math",$,"close","]","\\rbrack"),j("text",$,"textord","]","\\rbrack"),j("math",$,"open","(","\\lparen"),j("math",$,"close",")","\\rparen"),j("text",$,"textord","<","\\textless"),j("text",$,"textord",">","\\textgreater"),j("math",$,"open","\u230a","\\lfloor",!0),j("math",$,"close","\u230b","\\rfloor",!0),j("math",$,"open","\u2308","\\lceil",!0),j("math",$,"close","\u2309","\\rceil",!0),j("math",$,"textord","\\","\\backslash"),j("math",$,"textord","\u2223","|"),j("math",$,"textord","\u2223","\\vert"),j("text",$,"textord","|","\\textbar"),j("math",$,"textord","\u2225","\\|"),j("math",$,"textord","\u2225","\\Vert"),j("text",$,"textord","\u2225","\\textbardbl"),j("text",$,"textord","~","\\textasciitilde"),j("text",$,"textord","\\","\\textbackslash"),j("text",$,"textord","^","\\textasciicircum"),j("math",$,tt,"\u2191","\\uparrow",!0),j("math",$,tt,"\u21d1","\\Uparrow",!0),j("math",$,tt,"\u2193","\\downarrow",!0),j("math",$,tt,"\u21d3","\\Downarrow",!0),j("math",$,tt,"\u2195","\\updownarrow",!0),j("math",$,tt,"\u21d5","\\Updownarrow",!0),j("math",$,Q,"\u2210","\\coprod"),j("math",$,Q,"\u22c1","\\bigvee"),j("math",$,Q,"\u22c0","\\bigwedge"),j("math",$,Q,"\u2a04","\\biguplus"),j("math",$,Q,"\u22c2","\\bigcap"),j("math",$,Q,"\u22c3","\\bigcup"),j("math",$,Q,"\u222b","\\int"),j("math",$,Q,"\u222b","\\intop"),j("math",$,Q,"\u222c","\\iint"),j("math",$,Q,"\u222d","\\iiint"),j("math",$,Q,"\u220f","\\prod"),j("math",$,Q,"\u2211","\\sum"),j("math",$,Q,"\u2a02","\\bigotimes"),j("math",$,Q,"\u2a01","\\bigoplus"),j("math",$,Q,"\u2a00","\\bigodot"),j("math",$,Q,"\u222e","\\oint"),j("math",$,Q,"\u222f","\\oiint"),j("math",$,Q,"\u2230","\\oiiint"),j("math",$,Q,"\u2a06","\\bigsqcup"),j("math",$,Q,"\u222b","\\smallint"),j("text",$,"inner","\u2026","\\textellipsis"),j("math",$,"inner","\u2026","\\mathellipsis"),j("text",$,"inner","\u2026","\\ldots",!0),j("math",$,"inner","\u2026","\\ldots",!0),j("math",$,"inner","\u22ef","\\@cdots",!0),j("math",$,"inner","\u22f1","\\ddots",!0),j("math",$,"textord","\u22ee","\\varvdots"),j("math",$,"accent-token","\u02ca","\\acute"),j("math",$,"accent-token","\u02cb","\\grave"),j("math",$,"accent-token","\xa8","\\ddot"),j("math",$,"accent-token","~","\\tilde"),j("math",$,"accent-token","\u02c9","\\bar"),j("math",$,"accent-token","\u02d8","\\breve"),j("math",$,"accent-token","\u02c7","\\check"),j("math",$,"accent-token","^","\\hat"),j("math",$,"accent-token","\u20d7","\\vec"),j("math",$,"accent-token","\u02d9","\\dot"),j("math",$,"accent-token","\u02da","\\mathring"),j("math",$,J,"\u0131","\\imath",!0),j("math",$,J,"\u0237","\\jmath",!0),j("text",$,"textord","\u0131","\\i",!0),j("text",$,"textord","\u0237","\\j",!0),j("text",$,"textord","\xdf","\\ss",!0),j("text",$,"textord","\xe6","\\ae",!0),j("text",$,"textord","\xe6","\\ae",!0),j("text",$,"textord","\u0153","\\oe",!0),j("text",$,"textord","\xf8","\\o",!0),j("text",$,"textord","\xc6","\\AE",!0),j("text",$,"textord","\u0152","\\OE",!0),j("text",$,"textord","\xd8","\\O",!0),j("text",$,"accent-token","\u02ca","\\'"),j("text",$,"accent-token","\u02cb","\\`"),j("text",$,"accent-token","\u02c6","\\^"),j("text",$,"accent-token","\u02dc","\\~"),j("text",$,"accent-token","\u02c9","\\="),j("text",$,"accent-token","\u02d8","\\u"),j("text",$,"accent-token","\u02d9","\\."),j("text",$,"accent-token","\u02da","\\r"),j("text",$,"accent-token","\u02c7","\\v"),j("text",$,"accent-token","\xa8",'\\"'),j("text",$,"accent-token","\u02dd","\\H"),j("text",$,"accent-token","\u25ef","\\textcircled");var et={"--":!0,"---":!0,"``":!0,"''":!0};j("text",$,"textord","\u2013","--"),j("text",$,"textord","\u2013","\\textendash"),j("text",$,"textord","\u2014","---"),j("text",$,"textord","\u2014","\\textemdash"),j("text",$,"textord","\u2018","`"),j("text",$,"textord","\u2018","\\textquoteleft"),j("text",$,"textord","\u2019","'"),j("text",$,"textord","\u2019","\\textquoteright"),j("text",$,"textord","\u201c","``"),j("text",$,"textord","\u201c","\\textquotedblleft"),j("text",$,"textord","\u201d","''"),j("text",$,"textord","\u201d","\\textquotedblright"),j("math",$,"textord","\xb0","\\degree",!0),j("text",$,"textord","\xb0","\\degree"),j("text",$,"textord","\xb0","\\textdegree",!0),j("math",$,J,"\xa3","\\pounds"),j("math",$,J,"\xa3","\\mathsterling",!0),j("text",$,J,"\xa3","\\pounds"),j("text",$,J,"\xa3","\\textsterling",!0),j("math",Z,"textord","\u2720","\\maltese"),j("text",Z,"textord","\u2720","\\maltese"),j("text",$,"spacing","\xa0","\\ "),j("text",$,"spacing","\xa0"," "),j("text",$,"spacing","\xa0","~");for(var rt=0;rt<'0123456789/@."'.length;rt++){var at='0123456789/@."'.charAt(rt);j("math",$,"textord",at,at)}for(var nt=0;nt<'0123456789!@*()-=+[]<>|";:?/.,'.length;nt++){var it='0123456789!@*()-=+[]<>|";:?/.,'.charAt(nt);j("text",$,"textord",it,it)}for(var ot="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",st=0;st=5?0:t>=3?1:2]){var r=G[e]={cssEmPerMu:F.quad[e]/18};for(var a in F)F.hasOwnProperty(a)&&(r[a]=F[a][e])}return G[e]}(this.size)),this._fontMetrics},e.getColor=function(){return this.phantom?"transparent":this.color},t}();wt.BASESIZE=6;var kt=wt,St={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:1.00375,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:1.00375},Mt={ex:!0,em:!0,mu:!0},zt=function(t){return"string"!=typeof t&&(t=t.unit),t in St||t in Mt||"ex"===t},Tt=function(t,e){var r;if(t.unit in St)r=St[t.unit]/e.fontMetrics().ptPerEm/e.sizeMultiplier;else if("mu"===t.unit)r=e.fontMetrics().cssEmPerMu;else{var a;if(a=e.style.isTight()?e.havingStyle(e.style.text()):e,"ex"===t.unit)r=a.fontMetrics().xHeight;else{if("em"!==t.unit)throw new o("Invalid unit: '"+t.unit+"'");r=a.fontMetrics().quad}a!==e&&(r*=a.sizeMultiplier/e.sizeMultiplier)}return Math.min(t.number*r,e.maxSize)},At=["\\imath","\u0131","\\jmath","\u0237","\\pounds","\\mathsterling","\\textsterling","\xa3"],Bt=function(t,e,r){return _[r][t]&&_[r][t].replace&&(t=_[r][t].replace),{value:t,metrics:U(t,e,r)}},Ct=function(t,e,r,a,n){var i,o=Bt(t,e,r),s=o.metrics;if(t=o.value,s){var h=s.italic;("text"===r||a&&"mathit"===a.font)&&(h=0),i=new E(t,s.height,s.depth,h,s.skew,s.width,n)}else"undefined"!=typeof console&&console.warn("No character metrics for '"+t+"' in style '"+e+"' and mode '"+r+"'"),i=new E(t,0,0,0,0,0,n);if(a){i.maxFontSize=a.sizeMultiplier,a.style.isTight()&&i.classes.push("mtight");var l=a.getColor();l&&(i.style.color=l)}return i},qt=function(t,e){if(A(t.classes)!==A(e.classes)||t.skew!==e.skew||t.maxFontSize!==e.maxFontSize)return!1;for(var r in t.style)if(t.style.hasOwnProperty(r)&&t.style[r]!==e.style[r])return!1;for(var a in e.style)if(e.style.hasOwnProperty(a)&&t.style[a]!==e.style[a])return!1;return!0},Nt=function(t){for(var e=0,r=0,a=0,n=0;ne&&(e=i.height),i.depth>r&&(r=i.depth),i.maxFontSize>a&&(a=i.maxFontSize)}t.height=e,t.depth=r,t.maxFontSize=a},It=function(t,e,r,a){var n=new N(t,e,r,a);return Nt(n),n},Rt=function(t,e,r,a){return new N(t,e,r,a)},Ot=function(t){var e=new T(t);return Nt(e),e},Et=function(t,e,r){var a="";switch(t){case"amsrm":a="AMS";break;case"textrm":a="Main";break;case"textsf":a="SansSerif";break;case"texttt":a="Typewriter";break;default:a=t}return a+"-"+("textbf"===e&&"textit"===r?"BoldItalic":"textbf"===e?"Bold":"textit"===e?"Italic":"Regular")},Lt={mathbf:{variant:"bold",fontName:"Main-Bold"},mathrm:{variant:"normal",fontName:"Main-Regular"},textit:{variant:"italic",fontName:"Main-Italic"},mathit:{variant:"italic",fontName:"Main-Italic"},mathbb:{variant:"double-struck",fontName:"AMS-Regular"},mathcal:{variant:"script",fontName:"Caligraphic-Regular"},mathfrak:{variant:"fraktur",fontName:"Fraktur-Regular"},mathscr:{variant:"script",fontName:"Script-Regular"},mathsf:{variant:"sans-serif",fontName:"SansSerif-Regular"},mathtt:{variant:"monospace",fontName:"Typewriter-Regular"}},Ht={vec:["vec",.471,.714],oiintSize1:["oiintSize1",.957,.499],oiintSize2:["oiintSize2",1.472,.659],oiiintSize1:["oiiintSize1",1.304,.499],oiiintSize2:["oiiintSize2",1.98,.659]},Pt={fontMap:Lt,makeSymbol:Ct,mathsym:function(t,e,r,a){return void 0===a&&(a=[]),"boldsymbol"===r.font&&Bt(t,"Main-Bold",e).metrics?Ct(t,"Main-Bold",e,r,a.concat(["mathbf"])):"\\"===t||"main"===_[e][t].font?Ct(t,"Main-Regular",e,r,a):Ct(t,"AMS-Regular",e,r,a.concat(["amsrm"]))},makeSpan:It,makeSvgSpan:Rt,makeLineSpan:function(t,e,r){var a=It([t],[],e);return a.height=Math.max(r||e.fontMetrics().defaultRuleThickness,e.minRuleThickness),a.style.borderBottomWidth=a.height+"em",a.maxFontSize=1,a},makeAnchor:function(t,e,r,a){var n=new I(t,e,r,a);return Nt(n),n},makeFragment:Ot,wrapFragment:function(t,e){return t instanceof T?It([],[t],e):t},makeVList:function(t,e){for(var r=function(t){if("individualShift"===t.positionType){for(var e=t.children,r=[e[0]],a=-e[0].shift-e[0].elem.depth,n=a,i=1;i0&&(i.push(ue(o,e)),o=[]),i.push(n[s]));o.length>0&&i.push(ue(o,e)),r&&((a=ue(oe(r,e,!0))).classes=["tag"],i.push(a));var l=ee(["katex-html"],i);if(l.setAttribute("aria-hidden","true"),a){var m=a.children[0];m.style.height=l.height+l.depth+"em",m.style.verticalAlign=-l.depth+"em"}return l}function de(t){return new T(t)}var fe=function(){function t(t,e){this.type=void 0,this.attributes=void 0,this.children=void 0,this.type=t,this.attributes={},this.children=e||[]}var e=t.prototype;return e.setAttribute=function(t,e){this.attributes[t]=e},e.getAttribute=function(t){return this.attributes[t]},e.toNode=function(){var t=document.createElementNS("http://www.w3.org/1998/Math/MathML",this.type);for(var e in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,e)&&t.setAttribute(e,this.attributes[e]);for(var r=0;r"},e.toText=function(){return this.children.map(function(t){return t.toText()}).join("")},t}(),ge=function(){function t(t){this.text=void 0,this.text=t}var e=t.prototype;return e.toNode=function(){return document.createTextNode(this.text)},e.toMarkup=function(){return c.escape(this.toText())},e.toText=function(){return this.text},t}(),xe={MathNode:fe,TextNode:ge,SpaceNode:function(){function t(t){this.width=void 0,this.character=void 0,this.width=t,this.character=t>=.05555&&t<=.05556?"\u200a":t>=.1666&&t<=.1667?"\u2009":t>=.2222&&t<=.2223?"\u2005":t>=.2777&&t<=.2778?"\u2005\u200a":t>=-.05556&&t<=-.05555?"\u200a\u2063":t>=-.1667&&t<=-.1666?"\u2009\u2063":t>=-.2223&&t<=-.2222?"\u205f\u2063":t>=-.2778&&t<=-.2777?"\u2005\u2063":null}var e=t.prototype;return e.toNode=function(){if(this.character)return document.createTextNode(this.character);var t=document.createElementNS("http://www.w3.org/1998/Math/MathML","mspace");return t.setAttribute("width",this.width+"em"),t},e.toMarkup=function(){return this.character?""+this.character+"":''},e.toText=function(){return this.character?this.character:" "},t}(),newDocumentFragment:de},ve=function(t,e,r){return!_[e][t]||!_[e][t].replace||55349===t.charCodeAt(0)||et.hasOwnProperty(t)&&r&&(r.fontFamily&&"tt"===r.fontFamily.substr(4,2)||r.font&&"tt"===r.font.substr(4,2))||(t=_[e][t].replace),new xe.TextNode(t)},be=function(t){return 1===t.length?t[0]:new xe.MathNode("mrow",t)},ye=function(t,e){if("texttt"===e.fontFamily)return"monospace";if("textsf"===e.fontFamily)return"textit"===e.fontShape&&"textbf"===e.fontWeight?"sans-serif-bold-italic":"textit"===e.fontShape?"sans-serif-italic":"textbf"===e.fontWeight?"bold-sans-serif":"sans-serif";if("textit"===e.fontShape&&"textbf"===e.fontWeight)return"bold-italic";if("textit"===e.fontShape)return"italic";if("textbf"===e.fontWeight)return"bold";var r=e.font;if(!r||"mathnormal"===r)return null;var a=t.mode;if("mathit"===r)return"italic";if("boldsymbol"===r)return"bold-italic";if("mathbf"===r)return"bold";if("mathbb"===r)return"double-struck";if("mathfrak"===r)return"fraktur";if("mathscr"===r||"mathcal"===r)return"script";if("mathsf"===r)return"sans-serif";if("mathtt"===r)return"monospace";var n=t.text;return c.contains(["\\imath","\\jmath"],n)?null:(_[a][n]&&_[a][n].replace&&(n=_[a][n].replace),U(n,Pt.fontMap[r].fontName,a)?Pt.fontMap[r].variant:null)},we=function(t,e,r){if(1===t.length){var a=Se(t[0],e);return r&&a instanceof fe&&"mo"===a.type&&(a.setAttribute("lspace","0em"),a.setAttribute("rspace","0em")),[a]}for(var n,i=[],o=0;o0&&(p.text=p.text.slice(0,1)+"\u0338"+p.text.slice(1),i.pop())}}}i.push(s),n=s}return i},ke=function(t,e,r){return be(we(t,e,r))},Se=function(t,e){if(!t)return new xe.MathNode("mrow");if(Kt[t.type])return Kt[t.type](t,e);throw new o("Got group of unknown type: '"+t.type+"'")};function Me(t,e,r,a){var n,i=we(t,r);n=1===i.length&&i[0]instanceof fe&&c.contains(["mrow","mtable"],i[0].type)?i[0]:new xe.MathNode("mrow",i);var o=new xe.MathNode("annotation",[new xe.TextNode(e)]);o.setAttribute("encoding","application/x-tex");var s=new xe.MathNode("semantics",[n,o]),h=new xe.MathNode("math",[s]);h.setAttribute("xmlns","http://www.w3.org/1998/Math/MathML");var l=a?"katex":"katex-mathml";return Pt.makeSpan([l],[h])}var ze=function(t){return new kt({style:t.displayMode?w.DISPLAY:w.TEXT,maxSize:t.maxSize,minRuleThickness:t.minRuleThickness})},Te=function(t,e){if(e.displayMode){var r=["katex-display"];e.leqno&&r.push("leqno"),e.fleqn&&r.push("fleqn"),t=Pt.makeSpan(r,[t])}return t},Ae=function(t,e,r){var a,n=ze(r);if("mathml"===r.output)return Me(t,e,n,!0);if("html"===r.output){var i=pe(t,n);a=Pt.makeSpan(["katex"],[i])}else{var o=Me(t,e,n,!1),s=pe(t,n);a=Pt.makeSpan(["katex"],[o,s])}return Te(a,r)},Be={widehat:"^",widecheck:"\u02c7",widetilde:"~",utilde:"~",overleftarrow:"\u2190",underleftarrow:"\u2190",xleftarrow:"\u2190",overrightarrow:"\u2192",underrightarrow:"\u2192",xrightarrow:"\u2192",underbrace:"\u23df",overbrace:"\u23de",overgroup:"\u23e0",undergroup:"\u23e1",overleftrightarrow:"\u2194",underleftrightarrow:"\u2194",xleftrightarrow:"\u2194",Overrightarrow:"\u21d2",xRightarrow:"\u21d2",overleftharpoon:"\u21bc",xleftharpoonup:"\u21bc",overrightharpoon:"\u21c0",xrightharpoonup:"\u21c0",xLeftarrow:"\u21d0",xLeftrightarrow:"\u21d4",xhookleftarrow:"\u21a9",xhookrightarrow:"\u21aa",xmapsto:"\u21a6",xrightharpoondown:"\u21c1",xleftharpoondown:"\u21bd",xrightleftharpoons:"\u21cc",xleftrightharpoons:"\u21cb",xtwoheadleftarrow:"\u219e",xtwoheadrightarrow:"\u21a0",xlongequal:"=",xtofrom:"\u21c4",xrightleftarrows:"\u21c4",xrightequilibrium:"\u21cc",xleftequilibrium:"\u21cb"},Ce={overrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],overleftarrow:[["leftarrow"],.888,522,"xMinYMin"],underrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],underleftarrow:[["leftarrow"],.888,522,"xMinYMin"],xrightarrow:[["rightarrow"],1.469,522,"xMaxYMin"],xleftarrow:[["leftarrow"],1.469,522,"xMinYMin"],Overrightarrow:[["doublerightarrow"],.888,560,"xMaxYMin"],xRightarrow:[["doublerightarrow"],1.526,560,"xMaxYMin"],xLeftarrow:[["doubleleftarrow"],1.526,560,"xMinYMin"],overleftharpoon:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoonup:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoondown:[["leftharpoondown"],.888,522,"xMinYMin"],overrightharpoon:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoonup:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoondown:[["rightharpoondown"],.888,522,"xMaxYMin"],xlongequal:[["longequal"],.888,334,"xMinYMin"],xtwoheadleftarrow:[["twoheadleftarrow"],.888,334,"xMinYMin"],xtwoheadrightarrow:[["twoheadrightarrow"],.888,334,"xMaxYMin"],overleftrightarrow:[["leftarrow","rightarrow"],.888,522],overbrace:[["leftbrace","midbrace","rightbrace"],1.6,548],underbrace:[["leftbraceunder","midbraceunder","rightbraceunder"],1.6,548],underleftrightarrow:[["leftarrow","rightarrow"],.888,522],xleftrightarrow:[["leftarrow","rightarrow"],1.75,522],xLeftrightarrow:[["doubleleftarrow","doublerightarrow"],1.75,560],xrightleftharpoons:[["leftharpoondownplus","rightharpoonplus"],1.75,716],xleftrightharpoons:[["leftharpoonplus","rightharpoondownplus"],1.75,716],xhookleftarrow:[["leftarrow","righthook"],1.08,522],xhookrightarrow:[["lefthook","rightarrow"],1.08,522],overlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],underlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],overgroup:[["leftgroup","rightgroup"],.888,342],undergroup:[["leftgroupunder","rightgroupunder"],.888,342],xmapsto:[["leftmapsto","rightarrow"],1.5,522],xtofrom:[["leftToFrom","rightToFrom"],1.75,528],xrightleftarrows:[["baraboveleftarrow","rightarrowabovebar"],1.75,901],xrightequilibrium:[["baraboveshortleftharpoon","rightharpoonaboveshortbar"],1.75,716],xleftequilibrium:[["shortbaraboveleftharpoon","shortrightharpoonabovebar"],1.75,716]},qe=function(t){return"ordgroup"===t.type?t.body.length:1},Ne=function(t,e,r,a){var n,i=t.height+t.depth+2*r;if(/fbox|color/.test(e)){if(n=Pt.makeSpan(["stretchy",e],[],a),"fbox"===e){var o=a.color&&a.getColor();o&&(n.style.borderColor=o)}}else{var s=[];/^[bx]cancel$/.test(e)&&s.push(new P({x1:"0",y1:"0",x2:"100%",y2:"100%","stroke-width":"0.046em"})),/^x?cancel$/.test(e)&&s.push(new P({x1:"0",y1:"100%",x2:"100%",y2:"0","stroke-width":"0.046em"}));var h=new L(s,{width:"100%",height:i+"em"});n=Pt.makeSvgSpan([],[h],a)}return n.height=i,n.style.height=i+"em",n},Ie=function(t){var e=new xe.MathNode("mo",[new xe.TextNode(Be[t.substr(1)])]);return e.setAttribute("stretchy","true"),e},Re=function(t,e){var r=function(){var r=4e5,a=t.label.substr(1);if(c.contains(["widehat","widecheck","widetilde","utilde"],a)){var n,i,o,s=qe(t.base);if(s>5)"widehat"===a||"widecheck"===a?(n=420,r=2364,o=.42,i=a+"4"):(n=312,r=2340,o=.34,i="tilde4");else{var h=[1,1,2,2,3,3][s];"widehat"===a||"widecheck"===a?(r=[0,1062,2364,2364,2364][h],n=[0,239,300,360,420][h],o=[0,.24,.3,.3,.36,.42][h],i=a+h):(r=[0,600,1033,2339,2340][h],n=[0,260,286,306,312][h],o=[0,.26,.286,.3,.306,.34][h],i="tilde"+h)}var l=new H(i),m=new L([l],{width:"100%",height:o+"em",viewBox:"0 0 "+r+" "+n,preserveAspectRatio:"none"});return{span:Pt.makeSvgSpan([],[m],e),minWidth:0,height:o}}var u,p,d=[],f=Ce[a],g=f[0],x=f[1],v=f[2],b=v/1e3,y=g.length;if(1===y)u=["hide-tail"],p=[f[3]];else if(2===y)u=["halfarrow-left","halfarrow-right"],p=["xMinYMin","xMaxYMin"];else{if(3!==y)throw new Error("Correct katexImagesData or update code here to support\n "+y+" children.");u=["brace-left","brace-center","brace-right"],p=["xMinYMin","xMidYMin","xMaxYMin"]}for(var w=0;w0&&(a.style.minWidth=n+"em"),a},Oe=function(t,e){var r,a,n,i=Ft(t,"supsub");i?(r=(a=Dt(i.base,"accent")).base,i.base=r,n=function(t){if(t instanceof N)return t;throw new Error("Expected span but got "+String(t)+".")}(ce(i,e)),i.base=a):r=(a=Dt(t,"accent")).base;var o=ce(r,e.havingCrampedStyle()),s=0;if(a.isShifty&&c.isCharacterBox(r)){var h=c.getBaseElem(r);s=function(t){if(t instanceof E)return t;throw new Error("Expected symbolNode but got "+String(t)+".")}(ce(h,e.havingCrampedStyle())).skew}var l,m=Math.min(o.height,e.fontMetrics().xHeight);if(a.isStretchy)l=Re(a,e),l=Pt.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:o},{type:"elem",elem:l,wrapperClasses:["svg-align"],wrapperStyle:s>0?{width:"calc(100% - "+2*s+"em)",marginLeft:2*s+"em"}:void 0}]},e);else{var u,p;"\\vec"===a.label?(u=Pt.staticSvg("vec",e),p=Pt.svgData.vec[1]):((u=Pt.makeSymbol(a.label,"Main-Regular",a.mode,e)).italic=0,p=u.width),l=Pt.makeSpan(["accent-body"],[u]);var d="\\textcircled"===a.label;d&&(l.classes.push("accent-full"),m=o.height);var f=s;d||(f-=p/2),l.style.left=f+"em","\\textcircled"===a.label&&(l.style.top=".2em"),l=Pt.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:o},{type:"kern",size:-m},{type:"elem",elem:l}]},e)}var g=Pt.makeSpan(["mord","accent"],[l],e);return n?(n.children[0]=g,n.height=Math.max(g.height,n.height),n.classes[0]="mord",n):g},Ee=function(t,e){var r=t.isStretchy?Ie(t.label):new xe.MathNode("mo",[ve(t.label,t.mode)]),a=new xe.MathNode("mover",[Se(t.base,e),r]);return a.setAttribute("accent","true"),a},Le=new RegExp(["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring"].map(function(t){return"\\"+t}).join("|"));Jt({type:"accent",names:["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring","\\widecheck","\\widehat","\\widetilde","\\overrightarrow","\\overleftarrow","\\Overrightarrow","\\overleftrightarrow","\\overgroup","\\overlinesegment","\\overleftharpoon","\\overrightharpoon"],props:{numArgs:1},handler:function(t,e){var r=e[0],a=!Le.test(t.funcName),n=!a||"\\widehat"===t.funcName||"\\widetilde"===t.funcName||"\\widecheck"===t.funcName;return{type:"accent",mode:t.parser.mode,label:t.funcName,isStretchy:a,isShifty:n,base:r}},htmlBuilder:Oe,mathmlBuilder:Ee}),Jt({type:"accent",names:["\\'","\\`","\\^","\\~","\\=","\\u","\\.",'\\"',"\\r","\\H","\\v","\\textcircled"],props:{numArgs:1,allowedInText:!0,allowedInMath:!1},handler:function(t,e){var r=e[0];return{type:"accent",mode:t.parser.mode,label:t.funcName,isStretchy:!1,isShifty:!0,base:r}},htmlBuilder:Oe,mathmlBuilder:Ee}),Jt({type:"accentUnder",names:["\\underleftarrow","\\underrightarrow","\\underleftrightarrow","\\undergroup","\\underlinesegment","\\utilde"],props:{numArgs:1},handler:function(t,e){var r=t.parser,a=t.funcName,n=e[0];return{type:"accentUnder",mode:r.mode,label:a,base:n}},htmlBuilder:function(t,e){var r=ce(t.base,e),a=Re(t,e),n="\\utilde"===t.label?.12:0,i=Pt.makeVList({positionType:"bottom",positionData:a.height+n,children:[{type:"elem",elem:a,wrapperClasses:["svg-align"]},{type:"kern",size:n},{type:"elem",elem:r}]},e);return Pt.makeSpan(["mord","accentunder"],[i],e)},mathmlBuilder:function(t,e){var r=Ie(t.label),a=new xe.MathNode("munder",[Se(t.base,e),r]);return a.setAttribute("accentunder","true"),a}});var He=function(t){var e=new xe.MathNode("mpadded",t?[t]:[]);return e.setAttribute("width","+0.6em"),e.setAttribute("lspace","0.3em"),e};Jt({type:"xArrow",names:["\\xleftarrow","\\xrightarrow","\\xLeftarrow","\\xRightarrow","\\xleftrightarrow","\\xLeftrightarrow","\\xhookleftarrow","\\xhookrightarrow","\\xmapsto","\\xrightharpoondown","\\xrightharpoonup","\\xleftharpoondown","\\xleftharpoonup","\\xrightleftharpoons","\\xleftrightharpoons","\\xlongequal","\\xtwoheadrightarrow","\\xtwoheadleftarrow","\\xtofrom","\\xrightleftarrows","\\xrightequilibrium","\\xleftequilibrium"],props:{numArgs:1,numOptionalArgs:1},handler:function(t,e,r){var a=t.parser,n=t.funcName;return{type:"xArrow",mode:a.mode,label:n,body:e[0],below:r[0]}},htmlBuilder:function(t,e){var r,a=e.style,n=e.havingStyle(a.sup()),i=Pt.wrapFragment(ce(t.body,n,e),e);i.classes.push("x-arrow-pad"),t.below&&(n=e.havingStyle(a.sub()),(r=Pt.wrapFragment(ce(t.below,n,e),e)).classes.push("x-arrow-pad"));var o,s=Re(t,e),h=-e.fontMetrics().axisHeight+.5*s.height,l=-e.fontMetrics().axisHeight-.5*s.height-.111;if((i.depth>.25||"\\xleftequilibrium"===t.label)&&(l-=i.depth),r){var m=-e.fontMetrics().axisHeight+r.height+.5*s.height+.111;o=Pt.makeVList({positionType:"individualShift",children:[{type:"elem",elem:i,shift:l},{type:"elem",elem:s,shift:h},{type:"elem",elem:r,shift:m}]},e)}else o=Pt.makeVList({positionType:"individualShift",children:[{type:"elem",elem:i,shift:l},{type:"elem",elem:s,shift:h}]},e);return o.children[0].children[0].children[1].classes.push("svg-align"),Pt.makeSpan(["mrel","x-arrow"],[o],e)},mathmlBuilder:function(t,e){var r,a=Ie(t.label);if(t.body){var n=He(Se(t.body,e));if(t.below){var i=He(Se(t.below,e));r=new xe.MathNode("munderover",[a,i,n])}else r=new xe.MathNode("mover",[a,n])}else if(t.below){var o=He(Se(t.below,e));r=new xe.MathNode("munder",[a,o])}else r=He(),r=new xe.MathNode("mover",[a,r]);return r}}),Jt({type:"textord",names:["\\@char"],props:{numArgs:1,allowedInText:!0},handler:function(t,e){for(var r=t.parser,a=Dt(e[0],"ordgroup").body,n="",i=0;i","\\langle","\\rangle","/","\\backslash","\\lt","\\gt"],Ke=[0,1.2,1.8,2.4,3],Je=[{type:"small",style:w.SCRIPTSCRIPT},{type:"small",style:w.SCRIPT},{type:"small",style:w.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4}],Qe=[{type:"small",style:w.SCRIPTSCRIPT},{type:"small",style:w.SCRIPT},{type:"small",style:w.TEXT},{type:"stack"}],tr=[{type:"small",style:w.SCRIPTSCRIPT},{type:"small",style:w.SCRIPT},{type:"small",style:w.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4},{type:"stack"}],er=function(t){if("small"===t.type)return"Main-Regular";if("large"===t.type)return"Size"+t.size+"-Regular";if("stack"===t.type)return"Size4-Regular";throw new Error("Add support for delim type '"+t.type+"' here.")},rr=function(t,e,r,a){for(var n=Math.min(2,3-a.style.size);ne)return r[n]}return r[r.length-1]},ar=function(t,e,r,a,n,i){var o;"<"===t||"\\lt"===t||"\u27e8"===t?t="\\langle":">"!==t&&"\\gt"!==t&&"\u27e9"!==t||(t="\\rangle"),o=c.contains(Ze,t)?Je:c.contains(je,t)?tr:Qe;var s=rr(t,e,o,a);return"small"===s.type?function(t,e,r,a,n,i){var o=Pt.makeSymbol(t,"Main-Regular",n,a),s=Ve(o,e,a,i);return r&&Ue(s,a,e),s}(t,s.style,r,a,n,i):"large"===s.type?Ge(t,s.size,r,a,n,i):Xe(t,e,r,a,n,i)},nr=function(t,e){var r,a,n=e.havingBaseSizing(),i=rr("\\surd",t*n.sizeMultiplier,tr,n),o=n.sizeMultiplier,s=Math.max(0,e.minRuleThickness-e.fontMetrics().sqrtRuleThickness),h=0,l=0,m=0;return"small"===i.type?(t<1?o=1:t<1.4&&(o=.7),l=(1+s)/o,(r=_e("sqrtMain",h=(1+s+.08)/o,m=1e3+1e3*s+80,s,e)).style.minWidth="0.853em",a=.833/o):"large"===i.type?(m=1080*Ke[i.size],l=(Ke[i.size]+s)/o,h=(Ke[i.size]+s+.08)/o,(r=_e("sqrtSize"+i.size,h,m,s,e)).style.minWidth="1.02em",a=1/o):(h=t+s+.08,l=t+s,m=Math.floor(1e3*t+s)+80,(r=_e("sqrtTall",h,m,s,e)).style.minWidth="0.742em",a=1.056),r.height=l,r.style.height=h+"em",{span:r,advanceWidth:a,ruleWidth:(e.fontMetrics().sqrtRuleThickness+s)*o}},ir=function(t,e,r,a,n){if("<"===t||"\\lt"===t||"\u27e8"===t?t="\\langle":">"!==t&&"\\gt"!==t&&"\u27e9"!==t||(t="\\rangle"),c.contains(je,t)||c.contains(Ze,t))return Ge(t,e,!1,r,a,n);if(c.contains($e,t))return Xe(t,Ke[e],!1,r,a,n);throw new o("Illegal delimiter: '"+t+"'")},or=ar,sr=function(t,e,r,a,n,i){var o=a.fontMetrics().axisHeight*a.sizeMultiplier,s=5/a.fontMetrics().ptPerEm,h=Math.max(e-o,r+o),l=Math.max(h/500*901,2*h-s);return ar(t,l,!0,a,n,i)},hr={"\\bigl":{mclass:"mopen",size:1},"\\Bigl":{mclass:"mopen",size:2},"\\biggl":{mclass:"mopen",size:3},"\\Biggl":{mclass:"mopen",size:4},"\\bigr":{mclass:"mclose",size:1},"\\Bigr":{mclass:"mclose",size:2},"\\biggr":{mclass:"mclose",size:3},"\\Biggr":{mclass:"mclose",size:4},"\\bigm":{mclass:"mrel",size:1},"\\Bigm":{mclass:"mrel",size:2},"\\biggm":{mclass:"mrel",size:3},"\\Biggm":{mclass:"mrel",size:4},"\\big":{mclass:"mord",size:1},"\\Big":{mclass:"mord",size:2},"\\bigg":{mclass:"mord",size:3},"\\Bigg":{mclass:"mord",size:4}},lr=["(","\\lparen",")","\\rparen","[","\\lbrack","]","\\rbrack","\\{","\\lbrace","\\}","\\rbrace","\\lfloor","\\rfloor","\u230a","\u230b","\\lceil","\\rceil","\u2308","\u2309","<",">","\\langle","\u27e8","\\rangle","\u27e9","\\lt","\\gt","\\lvert","\\rvert","\\lVert","\\rVert","\\lgroup","\\rgroup","\u27ee","\u27ef","\\lmoustache","\\rmoustache","\u23b0","\u23b1","/","\\backslash","|","\\vert","\\|","\\Vert","\\uparrow","\\Uparrow","\\downarrow","\\Downarrow","\\updownarrow","\\Updownarrow","."];function mr(t,e){var r=Gt(t);if(r&&c.contains(lr,r.text))return r;throw new o("Invalid delimiter: '"+(r?r.text:JSON.stringify(t))+"' after '"+e.funcName+"'",t)}function cr(t){if(!t.body)throw new Error("Bug: The leftright ParseNode wasn't fully parsed.")}Jt({type:"delimsizing",names:["\\bigl","\\Bigl","\\biggl","\\Biggl","\\bigr","\\Bigr","\\biggr","\\Biggr","\\bigm","\\Bigm","\\biggm","\\Biggm","\\big","\\Big","\\bigg","\\Bigg"],props:{numArgs:1},handler:function(t,e){var r=mr(e[0],t);return{type:"delimsizing",mode:t.parser.mode,size:hr[t.funcName].size,mclass:hr[t.funcName].mclass,delim:r.text}},htmlBuilder:function(t,e){return"."===t.delim?Pt.makeSpan([t.mclass]):ir(t.delim,t.size,e,t.mode,[t.mclass])},mathmlBuilder:function(t){var e=[];"."!==t.delim&&e.push(ve(t.delim,t.mode));var r=new xe.MathNode("mo",e);return"mopen"===t.mclass||"mclose"===t.mclass?r.setAttribute("fence","true"):r.setAttribute("fence","false"),r}}),Jt({type:"leftright-right",names:["\\right"],props:{numArgs:1},handler:function(t,e){var r=t.parser.gullet.macros.get("\\current@color");if(r&&"string"!=typeof r)throw new o("\\current@color set to non-string in \\right");return{type:"leftright-right",mode:t.parser.mode,delim:mr(e[0],t).text,color:r}}}),Jt({type:"leftright",names:["\\left"],props:{numArgs:1},handler:function(t,e){var r=mr(e[0],t),a=t.parser;++a.leftrightDepth;var n=a.parseExpression(!1);--a.leftrightDepth,a.expect("\\right",!1);var i=Dt(a.parseFunction(),"leftright-right");return{type:"leftright",mode:a.mode,body:n,left:r.text,right:i.delim,rightColor:i.color}},htmlBuilder:function(t,e){cr(t);for(var r,a,n=oe(t.body,e,!0,["mopen","mclose"]),i=0,o=0,s=!1,h=0;h-1?"mpadded":"menclose",[Se(t.body,e)]);switch(t.label){case"\\cancel":a.setAttribute("notation","updiagonalstrike");break;case"\\bcancel":a.setAttribute("notation","downdiagonalstrike");break;case"\\sout":a.setAttribute("notation","horizontalstrike");break;case"\\fbox":a.setAttribute("notation","box");break;case"\\fcolorbox":case"\\colorbox":if(r=e.fontMetrics().fboxsep*e.fontMetrics().ptPerEm,a.setAttribute("width","+"+2*r+"pt"),a.setAttribute("height","+"+2*r+"pt"),a.setAttribute("lspace",r+"pt"),a.setAttribute("voffset",r+"pt"),"\\fcolorbox"===t.label){var n=Math.max(e.fontMetrics().fboxrule,e.minRuleThickness);a.setAttribute("style","border: "+n+"em solid "+String(t.borderColor))}break;case"\\xcancel":a.setAttribute("notation","updiagonalstrike downdiagonalstrike")}return t.backgroundColor&&a.setAttribute("mathbackground",t.backgroundColor),a};Jt({type:"enclose",names:["\\colorbox"],props:{numArgs:2,allowedInText:!0,greediness:3,argTypes:["color","text"]},handler:function(t,e,r){var a=t.parser,n=t.funcName,i=Dt(e[0],"color-token").color,o=e[1];return{type:"enclose",mode:a.mode,label:n,backgroundColor:i,body:o}},htmlBuilder:ur,mathmlBuilder:pr}),Jt({type:"enclose",names:["\\fcolorbox"],props:{numArgs:3,allowedInText:!0,greediness:3,argTypes:["color","color","text"]},handler:function(t,e,r){var a=t.parser,n=t.funcName,i=Dt(e[0],"color-token").color,o=Dt(e[1],"color-token").color,s=e[2];return{type:"enclose",mode:a.mode,label:n,backgroundColor:o,borderColor:i,body:s}},htmlBuilder:ur,mathmlBuilder:pr}),Jt({type:"enclose",names:["\\fbox"],props:{numArgs:1,argTypes:["hbox"],allowedInText:!0},handler:function(t,e){return{type:"enclose",mode:t.parser.mode,label:"\\fbox",body:e[0]}}}),Jt({type:"enclose",names:["\\cancel","\\bcancel","\\xcancel","\\sout"],props:{numArgs:1},handler:function(t,e,r){var a=t.parser,n=t.funcName,i=e[0];return{type:"enclose",mode:a.mode,label:n,body:i}},htmlBuilder:ur,mathmlBuilder:pr});var dr={};function fr(t){for(var e=t.type,r=t.names,a=t.props,n=t.handler,i=t.htmlBuilder,o=t.mathmlBuilder,s={type:e,numArgs:a.numArgs||0,greediness:1,allowedInText:!1,numOptionalArgs:0,handler:n},h=0;h0&&(b+=.25),l.push({pos:b,isDashed:t[e]})}for(y(i[0]),r=0;r0&&(M<(B+=v)&&(M=B),B=0),t.addJot&&(M+=f),z.height=S,z.depth=M,b+=S,z.pos=b,b+=M+B,h[r]=z,y(i[r+1])}var C,q,N=b/2+e.fontMetrics().axisHeight,I=t.cols||[],R=[];for(a=0,q=0;a=s)){var P=void 0;(a>0||t.hskipBeforeAndAfter)&&0!==(P=c.deflt(O.pregap,p))&&((C=Pt.makeSpan(["arraycolsep"],[])).style.width=P+"em",R.push(C));var D=[];for(r=0;r0){for(var G=Pt.makeLineSpan("hline",e,m),Y=Pt.makeLineSpan("hdashline",e,m),W=[{type:"elem",elem:h,shift:0}];l.length>0;){var X=l.pop(),_=X.pos-N;X.isDashed?W.push({type:"elem",elem:Y,shift:_}):W.push({type:"elem",elem:G,shift:_})}h=Pt.makeVList({positionType:"individualShift",children:W},e)}return Pt.makeSpan(["mord"],[h],e)},yr={c:"center ",l:"left ",r:"right "},wr=function(t,e){var r=new xe.MathNode("mtable",t.body.map(function(t){return new xe.MathNode("mtr",t.map(function(t){return new xe.MathNode("mtd",[Se(t,e)])}))})),a=.5===t.arraystretch?.1:.16+t.arraystretch-1+(t.addJot?.09:0);r.setAttribute("rowspacing",a+"em");var n="",i="";if(t.cols){var o=t.cols,s="",h=!1,l=0,m=o.length;"separator"===o[0].type&&(n+="top ",l=1),"separator"===o[o.length-1].type&&(n+="bottom ",m-=1);for(var c=l;c0?"left ":"",n+=g[g.length-1].length>0?"right ":"";for(var x=1;x0&&c&&(d=1),a[u]={type:"align",align:p,pregap:d,postgap:0}}return n.colSeparationType=c?"align":"alignat",n};fr({type:"array",names:["array","darray"],props:{numArgs:1},handler:function(t,e){var r={cols:(Gt(e[0])?[e[0]]:Dt(e[0],"ordgroup").body).map(function(t){var e=Ut(t).text;if(-1!=="lcr".indexOf(e))return{type:"align",align:e};if("|"===e)return{type:"separator",separator:"|"};if(":"===e)return{type:"separator",separator:":"};throw new o("Unknown column alignment: "+e,t)}),hskipBeforeAndAfter:!0};return xr(t.parser,r,vr(t.envName))},htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["matrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix"],props:{numArgs:0},handler:function(t){var e={matrix:null,pmatrix:["(",")"],bmatrix:["[","]"],Bmatrix:["\\{","\\}"],vmatrix:["|","|"],Vmatrix:["\\Vert","\\Vert"]}[t.envName],r=xr(t.parser,{hskipBeforeAndAfter:!1},vr(t.envName));return e?{type:"leftright",mode:t.mode,body:[r],left:e[0],right:e[1],rightColor:void 0}:r},htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["smallmatrix"],props:{numArgs:0},handler:function(t){var e=xr(t.parser,{arraystretch:.5},"script");return e.colSeparationType="small",e},htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["subarray"],props:{numArgs:1},handler:function(t,e){var r=(Gt(e[0])?[e[0]]:Dt(e[0],"ordgroup").body).map(function(t){var e=Ut(t).text;if(-1!=="lc".indexOf(e))return{type:"align",align:e};throw new o("Unknown column alignment: "+e,t)});if(r.length>1)throw new o("{subarray} can contain only one column");var a={cols:r,hskipBeforeAndAfter:!1,arraystretch:.5};if((a=xr(t.parser,a,"script")).body[0].length>1)throw new o("{subarray} can contain only one column");return a},htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["cases","dcases"],props:{numArgs:0},handler:function(t){var e=xr(t.parser,{arraystretch:1.2,cols:[{type:"align",align:"l",pregap:0,postgap:1},{type:"align",align:"l",pregap:0,postgap:0}]},vr(t.envName));return{type:"leftright",mode:t.mode,body:[e],left:"\\{",right:".",rightColor:void 0}},htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["aligned"],props:{numArgs:0},handler:kr,htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["gathered"],props:{numArgs:0},handler:function(t){return xr(t.parser,{cols:[{type:"align",align:"c"}],addJot:!0},"display")},htmlBuilder:br,mathmlBuilder:wr}),fr({type:"array",names:["alignedat"],props:{numArgs:1},handler:kr,htmlBuilder:br,mathmlBuilder:wr}),Jt({type:"text",names:["\\hline","\\hdashline"],props:{numArgs:0,allowedInText:!0,allowedInMath:!0},handler:function(t,e){throw new o(t.funcName+" valid only within array environment")}});var Sr=dr;Jt({type:"environment",names:["\\begin","\\end"],props:{numArgs:1,argTypes:["text"]},handler:function(t,e){var r=t.parser,a=t.funcName,n=e[0];if("ordgroup"!==n.type)throw new o("Invalid environment name",n);for(var i="",s=0;s=w.SCRIPT.id?r.text():w.DISPLAY:"text"===t&&r.size===w.DISPLAY.size?r=w.TEXT:"script"===t?r=w.SCRIPT:"scriptscript"===t&&(r=w.SCRIPTSCRIPT),r},Ir=function(t,e){var r,a=Nr(t.size,e.style),n=a.fracNum(),i=a.fracDen();r=e.havingStyle(n);var o=ce(t.numer,r,e);if(t.continued){var s=8.5/e.fontMetrics().ptPerEm,h=3.5/e.fontMetrics().ptPerEm;o.height=o.height0?3*c:7*c,d=e.fontMetrics().denom1):(m>0?(u=e.fontMetrics().num2,p=c):(u=e.fontMetrics().num3,p=3*c),d=e.fontMetrics().denom2),l){var y=e.fontMetrics().axisHeight;u-o.depth-(y+.5*m)0&&(e="."===(e=t)?null:e),e};Jt({type:"genfrac",names:["\\genfrac"],props:{numArgs:6,greediness:6,argTypes:["math","math","size","text","math","math"]},handler:function(t,e){var r=t.parser,a=e[4],n=e[5],i=Ft(e[0],"atom");i&&(i=Vt(e[0],"open"));var o=i?Er(i.text):null,s=Ft(e[1],"atom");s&&(s=Vt(e[1],"close"));var h,l=s?Er(s.text):null,m=Dt(e[2],"size"),c=null;h=!!m.isBlank||(c=m.value).number>0;var u="auto",p=Ft(e[3],"ordgroup");if(p){if(p.body.length>0){var d=Dt(p.body[0],"textord");u=Or[Number(d.text)]}}else p=Dt(e[3],"textord"),u=Or[Number(p.text)];return{type:"genfrac",mode:r.mode,numer:a,denom:n,continued:!1,hasBarLine:h,barSize:c,leftDelim:o,rightDelim:l,size:u}},htmlBuilder:Ir,mathmlBuilder:Rr}),Jt({type:"infix",names:["\\above"],props:{numArgs:1,argTypes:["size"],infix:!0},handler:function(t,e){var r=t.parser,a=(t.funcName,t.token);return{type:"infix",mode:r.mode,replaceWith:"\\\\abovefrac",size:Dt(e[0],"size").value,token:a}}}),Jt({type:"genfrac",names:["\\\\abovefrac"],props:{numArgs:3,argTypes:["math","size","math"]},handler:function(t,e){var r=t.parser,a=(t.funcName,e[0]),n=function(t){if(!t)throw new Error("Expected non-null, but got "+String(t));return t}(Dt(e[1],"infix").size),i=e[2],o=n.number>0;return{type:"genfrac",mode:r.mode,numer:a,denom:i,continued:!1,hasBarLine:o,barSize:n,leftDelim:null,rightDelim:null,size:"auto"}},htmlBuilder:Ir,mathmlBuilder:Rr});var Lr=function(t,e){var r,a,n=e.style,i=Ft(t,"supsub");i?(r=i.sup?ce(i.sup,e.havingStyle(n.sup()),e):ce(i.sub,e.havingStyle(n.sub()),e),a=Dt(i.base,"horizBrace")):a=Dt(t,"horizBrace");var o,s=ce(a.base,e.havingBaseStyle(w.DISPLAY)),h=Re(a,e);if(a.isOver?(o=Pt.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:s},{type:"kern",size:.1},{type:"elem",elem:h}]},e)).children[0].children[0].children[1].classes.push("svg-align"):(o=Pt.makeVList({positionType:"bottom",positionData:s.depth+.1+h.height,children:[{type:"elem",elem:h},{type:"kern",size:.1},{type:"elem",elem:s}]},e)).children[0].children[0].children[0].classes.push("svg-align"),r){var l=Pt.makeSpan(["mord",a.isOver?"mover":"munder"],[o],e);o=a.isOver?Pt.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:l},{type:"kern",size:.2},{type:"elem",elem:r}]},e):Pt.makeVList({positionType:"bottom",positionData:l.depth+.2+r.height+r.depth,children:[{type:"elem",elem:r},{type:"kern",size:.2},{type:"elem",elem:l}]},e)}return Pt.makeSpan(["mord",a.isOver?"mover":"munder"],[o],e)};Jt({type:"horizBrace",names:["\\overbrace","\\underbrace"],props:{numArgs:1},handler:function(t,e){var r=t.parser,a=t.funcName;return{type:"horizBrace",mode:r.mode,label:a,isOver:/^\\over/.test(a),base:e[0]}},htmlBuilder:Lr,mathmlBuilder:function(t,e){var r=Ie(t.label);return new xe.MathNode(t.isOver?"mover":"munder",[Se(t.base,e),r])}}),Jt({type:"href",names:["\\href"],props:{numArgs:2,argTypes:["url","original"],allowedInText:!0},handler:function(t,e){var r=t.parser,a=e[1],n=Dt(e[0],"url").url;return r.settings.isTrusted({command:"\\href",url:n})?{type:"href",mode:r.mode,href:n,body:te(a)}:r.formatUnsupportedCmd("\\href")},htmlBuilder:function(t,e){var r=oe(t.body,e,!1);return Pt.makeAnchor(t.href,[],r,e)},mathmlBuilder:function(t,e){var r=ke(t.body,e);return r instanceof fe||(r=new fe("mrow",[r])),r.setAttribute("href",t.href),r}}),Jt({type:"href",names:["\\url"],props:{numArgs:1,argTypes:["url"],allowedInText:!0},handler:function(t,e){var r=t.parser,a=Dt(e[0],"url").url;if(!r.settings.isTrusted({command:"\\url",url:a}))return r.formatUnsupportedCmd("\\url");for(var n=[],i=0;i0&&(a=Tt(t.totalheight,e)-r,a=Number(a.toFixed(2)));var n=0;t.width.number>0&&(n=Tt(t.width,e));var i={height:r+a+"em"};n>0&&(i.width=n+"em"),a>0&&(i.verticalAlign=-a+"em");var o=new R(t.src,t.alt,i);return o.height=r,o.depth=a,o},mathmlBuilder:function(t,e){var r=new xe.MathNode("mglyph",[]);r.setAttribute("alt",t.alt);var a=Tt(t.height,e),n=0;if(t.totalheight.number>0&&(n=(n=Tt(t.totalheight,e)-a).toFixed(2),r.setAttribute("valign","-"+n+"em")),r.setAttribute("height",a+n+"em"),t.width.number>0){var i=Tt(t.width,e);r.setAttribute("width",i+"em")}return r.setAttribute("src",t.src),r}}),Jt({type:"kern",names:["\\kern","\\mkern","\\hskip","\\mskip"],props:{numArgs:1,argTypes:["size"],allowedInText:!0},handler:function(t,e){var r=t.parser,a=t.funcName,n=Dt(e[0],"size");if(r.settings.strict){var i="m"===a[1],o="mu"===n.value.unit;i?(o||r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+a+" supports only mu units, not "+n.value.unit+" units"),"math"!==r.mode&&r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+a+" works only in math mode")):o&&r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+a+" doesn't support mu units")}return{type:"kern",mode:r.mode,dimension:n.value}},htmlBuilder:function(t,e){return Pt.makeGlue(t.dimension,e)},mathmlBuilder:function(t,e){var r=Tt(t.dimension,e);return new xe.SpaceNode(r)}}),Jt({type:"lap",names:["\\mathllap","\\mathrlap","\\mathclap"],props:{numArgs:1,allowedInText:!0},handler:function(t,e){var r=t.parser,a=t.funcName,n=e[0];return{type:"lap",mode:r.mode,alignment:a.slice(5),body:n}},htmlBuilder:function(t,e){var r;"clap"===t.alignment?(r=Pt.makeSpan([],[ce(t.body,e)]),r=Pt.makeSpan(["inner"],[r],e)):r=Pt.makeSpan(["inner"],[ce(t.body,e)]);var a=Pt.makeSpan(["fix"],[]),n=Pt.makeSpan([t.alignment],[r,a],e),i=Pt.makeSpan(["strut"]);return i.style.height=n.height+n.depth+"em",i.style.verticalAlign=-n.depth+"em",n.children.unshift(i),n=Pt.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:n}]},e),Pt.makeSpan(["mord"],[n],e)},mathmlBuilder:function(t,e){var r=new xe.MathNode("mpadded",[Se(t.body,e)]);if("rlap"!==t.alignment){var a="llap"===t.alignment?"-1":"-0.5";r.setAttribute("lspace",a+"width")}return r.setAttribute("width","0px"),r}}),Jt({type:"styling",names:["\\(","$"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1,consumeMode:"math"},handler:function(t,e){var r=t.funcName,a=t.parser,n=a.mode;a.switchMode("math");var i="\\("===r?"\\)":"$",o=a.parseExpression(!1,i);return a.expect(i,!1),a.switchMode(n),a.consume(),{type:"styling",mode:a.mode,style:"text",body:o}}}),Jt({type:"text",names:["\\)","\\]"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler:function(t,e){throw new o("Mismatched "+t.funcName)}});var Pr=function(t,e){switch(e.style.size){case w.DISPLAY.size:return t.display;case w.TEXT.size:return t.text;case w.SCRIPT.size:return t.script;case w.SCRIPTSCRIPT.size:return t.scriptscript;default:return t.text}};Jt({type:"mathchoice",names:["\\mathchoice"],props:{numArgs:4},handler:function(t,e){return{type:"mathchoice",mode:t.parser.mode,display:te(e[0]),text:te(e[1]),script:te(e[2]),scriptscript:te(e[3])}},htmlBuilder:function(t,e){var r=Pr(t,e),a=oe(r,e,!1);return Pt.makeFragment(a)},mathmlBuilder:function(t,e){var r=Pr(t,e);return ke(r,e)}});var Dr=function(t,e,r,a,n,i,o){var s,h,l;if(t=Pt.makeSpan([],[t]),e){var m=ce(e,a.havingStyle(n.sup()),a);h={elem:m,kern:Math.max(a.fontMetrics().bigOpSpacing1,a.fontMetrics().bigOpSpacing3-m.depth)}}if(r){var c=ce(r,a.havingStyle(n.sub()),a);s={elem:c,kern:Math.max(a.fontMetrics().bigOpSpacing2,a.fontMetrics().bigOpSpacing4-c.height)}}if(h&&s){var u=a.fontMetrics().bigOpSpacing5+s.elem.height+s.elem.depth+s.kern+t.depth+o;l=Pt.makeVList({positionType:"bottom",positionData:u,children:[{type:"kern",size:a.fontMetrics().bigOpSpacing5},{type:"elem",elem:s.elem,marginLeft:-i+"em"},{type:"kern",size:s.kern},{type:"elem",elem:t},{type:"kern",size:h.kern},{type:"elem",elem:h.elem,marginLeft:i+"em"},{type:"kern",size:a.fontMetrics().bigOpSpacing5}]},a)}else if(s){var p=t.height-o;l=Pt.makeVList({positionType:"top",positionData:p,children:[{type:"kern",size:a.fontMetrics().bigOpSpacing5},{type:"elem",elem:s.elem,marginLeft:-i+"em"},{type:"kern",size:s.kern},{type:"elem",elem:t}]},a)}else{if(!h)return t;var d=t.depth+o;l=Pt.makeVList({positionType:"bottom",positionData:d,children:[{type:"elem",elem:t},{type:"kern",size:h.kern},{type:"elem",elem:h.elem,marginLeft:i+"em"},{type:"kern",size:a.fontMetrics().bigOpSpacing5}]},a)}return Pt.makeSpan(["mop","op-limits"],[l],a)},Fr=["\\smallint"],Vr=function(t,e){var r,a,n,i=!1,o=Ft(t,"supsub");o?(r=o.sup,a=o.sub,n=Dt(o.base,"op"),i=!0):n=Dt(t,"op");var s,h=e.style,l=!1;if(h.size===w.DISPLAY.size&&n.symbol&&!c.contains(Fr,n.name)&&(l=!0),n.symbol){var m=l?"Size2-Regular":"Size1-Regular",u="";if("\\oiint"!==n.name&&"\\oiiint"!==n.name||(u=n.name.substr(1),n.name="oiint"===u?"\\iint":"\\iiint"),s=Pt.makeSymbol(n.name,m,"math",e,["mop","op-symbol",l?"large-op":"small-op"]),u.length>0){var p=s.italic,d=Pt.staticSvg(u+"Size"+(l?"2":"1"),e);s=Pt.makeVList({positionType:"individualShift",children:[{type:"elem",elem:s,shift:0},{type:"elem",elem:d,shift:l?.08:0}]},e),n.name="\\"+u,s.classes.unshift("mop"),s.italic=p}}else if(n.body){var f=oe(n.body,e,!0);1===f.length&&f[0]instanceof E?(s=f[0]).classes[0]="mop":s=Pt.makeSpan(["mop"],Pt.tryCombineChars(f),e)}else{for(var g=[],x=1;x0){for(var h=n.body.map(function(t){var e=t.text;return"string"==typeof e?{type:"textord",mode:t.mode,text:e}:t}),l=oe(h,e.withFont("mathrm"),!0),m=0;m=0?s.setAttribute("height","+"+n+"em"):(s.setAttribute("height",n+"em"),s.setAttribute("depth","+"+-n+"em")),s.setAttribute("voffset",n+"em"),s}});var _r=["\\tiny","\\sixptsize","\\scriptsize","\\footnotesize","\\small","\\normalsize","\\large","\\Large","\\LARGE","\\huge","\\Huge"];Jt({type:"sizing",names:_r,props:{numArgs:0,allowedInText:!0},handler:function(t,e){var r=t.breakOnTokenText,a=t.funcName,n=t.parser,i=n.parseExpression(!1,r);return{type:"sizing",mode:n.mode,size:_r.indexOf(a)+1,body:i}},htmlBuilder:function(t,e){var r=e.havingSize(t.size);return Xr(t.body,r,e)},mathmlBuilder:function(t,e){var r=e.havingSize(t.size),a=we(t.body,r),n=new xe.MathNode("mstyle",a);return n.setAttribute("mathsize",r.sizeMultiplier+"em"),n}}),Jt({type:"smash",names:["\\smash"],props:{numArgs:1,numOptionalArgs:1,allowedInText:!0},handler:function(t,e,r){var a=t.parser,n=!1,i=!1,o=r[0]&&Dt(r[0],"ordgroup");if(o)for(var s="",h=0;hr.height+r.depth+i&&(i=(i+c-r.height-r.depth)/2);var u=h.height-r.height-i-l;r.style.paddingLeft=m+"em";var p=Pt.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:r,wrapperClasses:["svg-align"]},{type:"kern",size:-(r.height+u)},{type:"elem",elem:h},{type:"kern",size:l}]},e);if(t.index){var d=e.havingStyle(w.SCRIPTSCRIPT),f=ce(t.index,d,e),g=.6*(p.height-p.depth),x=Pt.makeVList({positionType:"shift",positionData:-g,children:[{type:"elem",elem:f}]},e),v=Pt.makeSpan(["root"],[x]);return Pt.makeSpan(["mord","sqrt"],[v,p],e)}return Pt.makeSpan(["mord","sqrt"],[p],e)},mathmlBuilder:function(t,e){var r=t.body,a=t.index;return a?new xe.MathNode("mroot",[Se(r,e),Se(a,e)]):new xe.MathNode("msqrt",[Se(r,e)])}});var jr={display:w.DISPLAY,text:w.TEXT,script:w.SCRIPT,scriptscript:w.SCRIPTSCRIPT};Jt({type:"styling",names:["\\displaystyle","\\textstyle","\\scriptstyle","\\scriptscriptstyle"],props:{numArgs:0,allowedInText:!0},handler:function(t,e){var r=t.breakOnTokenText,a=t.funcName,n=t.parser,i=n.parseExpression(!0,r),o=a.slice(1,a.length-5);return{type:"styling",mode:n.mode,style:o,body:i}},htmlBuilder:function(t,e){var r=jr[t.style],a=e.havingStyle(r).withFont("");return Xr(t.body,a,e)},mathmlBuilder:function(t,e){var r=jr[t.style],a=e.havingStyle(r),n=we(t.body,a),i=new xe.MathNode("mstyle",n),o={display:["0","true"],text:["0","false"],script:["1","false"],scriptscript:["2","false"]}[t.style];return i.setAttribute("scriptlevel",o[0]),i.setAttribute("displaystyle",o[1]),i}});Qt({type:"supsub",htmlBuilder:function(t,e){var r=function(t,e){var r=t.base;return r?"op"===r.type?r.limits&&(e.style.size===w.DISPLAY.size||r.alwaysHandleSupSub)?Vr:null:"operatorname"===r.type?r.alwaysHandleSupSub&&(e.style.size===w.DISPLAY.size||r.limits)?Wr:null:"accent"===r.type?c.isCharacterBox(r.base)?Oe:null:"horizBrace"===r.type&&!t.sub===r.isOver?Lr:null:null}(t,e);if(r)return r(t,e);var a,n,i,o=t.base,s=t.sup,h=t.sub,l=ce(o,e),m=e.fontMetrics(),u=0,p=0,d=o&&c.isCharacterBox(o);if(s){var f=e.havingStyle(e.style.sup());a=ce(s,f,e),d||(u=l.height-f.fontMetrics().supDrop*f.sizeMultiplier/e.sizeMultiplier)}if(h){var g=e.havingStyle(e.style.sub());n=ce(h,g,e),d||(p=l.depth+g.fontMetrics().subDrop*g.sizeMultiplier/e.sizeMultiplier)}i=e.style===w.DISPLAY?m.sup1:e.style.cramped?m.sup3:m.sup2;var x,v=e.sizeMultiplier,b=.5/m.ptPerEm/v+"em",y=null;if(n){var k=t.base&&"op"===t.base.type&&t.base.name&&("\\oiint"===t.base.name||"\\oiiint"===t.base.name);(l instanceof E||k)&&(y=-l.italic+"em")}if(a&&n){u=Math.max(u,i,a.depth+.25*m.xHeight),p=Math.max(p,m.sub2);var S=4*m.defaultRuleThickness;if(u-a.depth-(n.height-p)0&&(u+=M,p-=M)}var z=[{type:"elem",elem:n,shift:p,marginRight:b,marginLeft:y},{type:"elem",elem:a,shift:-u,marginRight:b}];x=Pt.makeVList({positionType:"individualShift",children:z},e)}else if(n){p=Math.max(p,m.sub1,n.height-.8*m.xHeight);var T=[{type:"elem",elem:n,marginLeft:y,marginRight:b}];x=Pt.makeVList({positionType:"shift",positionData:p,children:T},e)}else{if(!a)throw new Error("supsub must have either sup or sub.");u=Math.max(u,i,a.depth+.25*m.xHeight),x=Pt.makeVList({positionType:"shift",positionData:-u,children:[{type:"elem",elem:a,marginRight:b}]},e)}var A=le(l,"right")||"mord";return Pt.makeSpan([A],[l,Pt.makeSpan(["msupsub"],[x])],e)},mathmlBuilder:function(t,e){var r,a=!1,n=Ft(t.base,"horizBrace");n&&!!t.sup===n.isOver&&(a=!0,r=n.isOver),!t.base||"op"!==t.base.type&&"operatorname"!==t.base.type||(t.base.parentIsSupSub=!0);var i,o=[Se(t.base,e)];if(t.sub&&o.push(Se(t.sub,e)),t.sup&&o.push(Se(t.sup,e)),a)i=r?"mover":"munder";else if(t.sub)if(t.sup){var s=t.base;i=s&&"op"===s.type&&s.limits&&e.style===w.DISPLAY?"munderover":s&&"operatorname"===s.type&&s.alwaysHandleSupSub&&(e.style===w.DISPLAY||s.limits)?"munderover":"msubsup"}else{var h=t.base;i=h&&"op"===h.type&&h.limits&&(e.style===w.DISPLAY||h.alwaysHandleSupSub)?"munder":h&&"operatorname"===h.type&&h.alwaysHandleSupSub&&(h.limits||e.style===w.DISPLAY)?"munder":"msub"}else{var l=t.base;i=l&&"op"===l.type&&l.limits&&(e.style===w.DISPLAY||l.alwaysHandleSupSub)?"mover":l&&"operatorname"===l.type&&l.alwaysHandleSupSub&&(l.limits||e.style===w.DISPLAY)?"mover":"msup"}return new xe.MathNode(i,o)}}),Qt({type:"atom",htmlBuilder:function(t,e){return Pt.mathsym(t.text,t.mode,e,["m"+t.family])},mathmlBuilder:function(t,e){var r=new xe.MathNode("mo",[ve(t.text,t.mode)]);if("bin"===t.family){var a=ye(t,e);"bold-italic"===a&&r.setAttribute("mathvariant",a)}else"punct"===t.family?r.setAttribute("separator","true"):"open"!==t.family&&"close"!==t.family||r.setAttribute("stretchy","false");return r}});var $r={mi:"italic",mn:"normal",mtext:"normal"};Qt({type:"mathord",htmlBuilder:function(t,e){return Pt.makeOrd(t,e,"mathord")},mathmlBuilder:function(t,e){var r=new xe.MathNode("mi",[ve(t.text,t.mode,e)]),a=ye(t,e)||"italic";return a!==$r[r.type]&&r.setAttribute("mathvariant",a),r}}),Qt({type:"textord",htmlBuilder:function(t,e){return Pt.makeOrd(t,e,"textord")},mathmlBuilder:function(t,e){var r,a=ve(t.text,t.mode,e),n=ye(t,e)||"normal";return r="text"===t.mode?new xe.MathNode("mtext",[a]):/[0-9]/.test(t.text)?new xe.MathNode("mn",[a]):"\\prime"===t.text?new xe.MathNode("mo",[a]):new xe.MathNode("mi",[a]),n!==$r[r.type]&&r.setAttribute("mathvariant",n),r}});var Zr={"\\nobreak":"nobreak","\\allowbreak":"allowbreak"},Kr={" ":{},"\\ ":{},"~":{className:"nobreak"},"\\space":{},"\\nobreakspace":{className:"nobreak"}};Qt({type:"spacing",htmlBuilder:function(t,e){if(Kr.hasOwnProperty(t.text)){var r=Kr[t.text].className||"";if("text"===t.mode){var a=Pt.makeOrd(t,e,"textord");return a.classes.push(r),a}return Pt.makeSpan(["mspace",r],[Pt.mathsym(t.text,t.mode,e)],e)}if(Zr.hasOwnProperty(t.text))return Pt.makeSpan(["mspace",Zr[t.text]],[],e);throw new o('Unknown type of space "'+t.text+'"')},mathmlBuilder:function(t,e){if(!Kr.hasOwnProperty(t.text)){if(Zr.hasOwnProperty(t.text))return new xe.MathNode("mspace");throw new o('Unknown type of space "'+t.text+'"')}return new xe.MathNode("mtext",[new xe.TextNode("\xa0")])}});var Jr=function(){var t=new xe.MathNode("mtd",[]);return t.setAttribute("width","50%"),t};Qt({type:"tag",mathmlBuilder:function(t,e){var r=new xe.MathNode("mtable",[new xe.MathNode("mtr",[Jr(),new xe.MathNode("mtd",[ke(t.body,e)]),Jr(),new xe.MathNode("mtd",[ke(t.tag,e)])])]);return r.setAttribute("width","100%"),r}});var Qr={"\\text":void 0,"\\textrm":"textrm","\\textsf":"textsf","\\texttt":"texttt","\\textnormal":"textrm"},ta={"\\textbf":"textbf","\\textmd":"textmd"},ea={"\\textit":"textit","\\textup":"textup"},ra=function(t,e){var r=t.font;return r?Qr[r]?e.withTextFontFamily(Qr[r]):ta[r]?e.withTextFontWeight(ta[r]):e.withTextFontShape(ea[r]):e};Jt({type:"text",names:["\\text","\\textrm","\\textsf","\\texttt","\\textnormal","\\textbf","\\textmd","\\textit","\\textup"],props:{numArgs:1,argTypes:["text"],greediness:2,allowedInText:!0,consumeMode:"text"},handler:function(t,e){var r=t.parser,a=t.funcName,n=e[0];return{type:"text",mode:r.mode,body:te(n),font:a}},htmlBuilder:function(t,e){var r=ra(t,e),a=oe(t.body,r,!0);return Pt.makeSpan(["mord","text"],Pt.tryCombineChars(a),r)},mathmlBuilder:function(t,e){var r=ra(t,e);return ke(t.body,r)}}),Jt({type:"underline",names:["\\underline"],props:{numArgs:1,allowedInText:!0},handler:function(t,e){return{type:"underline",mode:t.parser.mode,body:e[0]}},htmlBuilder:function(t,e){var r=ce(t.body,e),a=Pt.makeLineSpan("underline-line",e),n=e.fontMetrics().defaultRuleThickness,i=Pt.makeVList({positionType:"top",positionData:r.height,children:[{type:"kern",size:n},{type:"elem",elem:a},{type:"kern",size:3*n},{type:"elem",elem:r}]},e);return Pt.makeSpan(["mord","underline"],[i],e)},mathmlBuilder:function(t,e){var r=new xe.MathNode("mo",[new xe.TextNode("\u203e")]);r.setAttribute("stretchy","true");var a=new xe.MathNode("munder",[Se(t.body,e),r]);return a.setAttribute("accentunder","true"),a}}),Jt({type:"verb",names:["\\verb"],props:{numArgs:0,allowedInText:!0},handler:function(t,e,r){throw new o("\\verb ended by end of line instead of matching delimiter")},htmlBuilder:function(t,e){for(var r=aa(t),a=[],n=e.havingStyle(e.style.text()),i=0;i0&&(this.undefStack[this.undefStack.length-1][t]=e)}else{var n=this.undefStack[this.undefStack.length-1];n&&!n.hasOwnProperty(t)&&(n[t]=this.current[t])}this.current[t]=e},t}(),ma={},ca=ma;function ua(t,e){ma[t]=e}ua("\\@firstoftwo",function(t){return{tokens:t.consumeArgs(2)[0],numArgs:0}}),ua("\\@secondoftwo",function(t){return{tokens:t.consumeArgs(2)[1],numArgs:0}}),ua("\\@ifnextchar",function(t){var e=t.consumeArgs(3),r=t.future();return 1===e[0].length&&e[0][0].text===r.text?{tokens:e[1],numArgs:0}:{tokens:e[2],numArgs:0}}),ua("\\@ifstar","\\@ifnextchar *{\\@firstoftwo{#1}}"),ua("\\TextOrMath",function(t){var e=t.consumeArgs(2);return"text"===t.mode?{tokens:e[0],numArgs:0}:{tokens:e[1],numArgs:0}});var pa={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};ua("\\char",function(t){var e,r=t.popToken(),a="";if("'"===r.text)e=8,r=t.popToken();else if('"'===r.text)e=16,r=t.popToken();else if("`"===r.text)if("\\"===(r=t.popToken()).text[0])a=r.text.charCodeAt(1);else{if("EOF"===r.text)throw new o("\\char` missing argument");a=r.text.charCodeAt(0)}else e=10;if(e){if(null==(a=pa[r.text])||a>=e)throw new o("Invalid base-"+e+" digit "+r.text);for(var n;null!=(n=pa[t.future().text])&&n":"\\dotsb","-":"\\dotsb","*":"\\dotsb",":":"\\dotsb","\\DOTSB":"\\dotsb","\\coprod":"\\dotsb","\\bigvee":"\\dotsb","\\bigwedge":"\\dotsb","\\biguplus":"\\dotsb","\\bigcap":"\\dotsb","\\bigcup":"\\dotsb","\\prod":"\\dotsb","\\sum":"\\dotsb","\\bigotimes":"\\dotsb","\\bigoplus":"\\dotsb","\\bigodot":"\\dotsb","\\bigsqcup":"\\dotsb","\\And":"\\dotsb","\\longrightarrow":"\\dotsb","\\Longrightarrow":"\\dotsb","\\longleftarrow":"\\dotsb","\\Longleftarrow":"\\dotsb","\\longleftrightarrow":"\\dotsb","\\Longleftrightarrow":"\\dotsb","\\mapsto":"\\dotsb","\\longmapsto":"\\dotsb","\\hookrightarrow":"\\dotsb","\\doteq":"\\dotsb","\\mathbin":"\\dotsb","\\mathrel":"\\dotsb","\\relbar":"\\dotsb","\\Relbar":"\\dotsb","\\xrightarrow":"\\dotsb","\\xleftarrow":"\\dotsb","\\DOTSI":"\\dotsi","\\int":"\\dotsi","\\oint":"\\dotsi","\\iint":"\\dotsi","\\iiint":"\\dotsi","\\iiiint":"\\dotsi","\\idotsint":"\\dotsi","\\DOTSX":"\\dotsx"};ua("\\dots",function(t){var e="\\dotso",r=t.expandAfterFuture().text;return r in ga?e=ga[r]:"\\not"===r.substr(0,4)?e="\\dotsb":r in _.math&&c.contains(["bin","rel"],_.math[r].group)&&(e="\\dotsb"),e});var xa={")":!0,"]":!0,"\\rbrack":!0,"\\}":!0,"\\rbrace":!0,"\\rangle":!0,"\\rceil":!0,"\\rfloor":!0,"\\rgroup":!0,"\\rmoustache":!0,"\\right":!0,"\\bigr":!0,"\\biggr":!0,"\\Bigr":!0,"\\Biggr":!0,$:!0,";":!0,".":!0,",":!0};ua("\\dotso",function(t){return t.future().text in xa?"\\ldots\\,":"\\ldots"}),ua("\\dotsc",function(t){var e=t.future().text;return e in xa&&","!==e?"\\ldots\\,":"\\ldots"}),ua("\\cdots",function(t){return t.future().text in xa?"\\@cdots\\,":"\\@cdots"}),ua("\\dotsb","\\cdots"),ua("\\dotsm","\\cdots"),ua("\\dotsi","\\!\\cdots"),ua("\\dotsx","\\ldots\\,"),ua("\\DOTSI","\\relax"),ua("\\DOTSB","\\relax"),ua("\\DOTSX","\\relax"),ua("\\tmspace","\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax"),ua("\\,","\\tmspace+{3mu}{.1667em}"),ua("\\thinspace","\\,"),ua("\\>","\\mskip{4mu}"),ua("\\:","\\tmspace+{4mu}{.2222em}"),ua("\\medspace","\\:"),ua("\\;","\\tmspace+{5mu}{.2777em}"),ua("\\thickspace","\\;"),ua("\\!","\\tmspace-{3mu}{.1667em}"),ua("\\negthinspace","\\!"),ua("\\negmedspace","\\tmspace-{4mu}{.2222em}"),ua("\\negthickspace","\\tmspace-{5mu}{.277em}"),ua("\\enspace","\\kern.5em "),ua("\\enskip","\\hskip.5em\\relax"),ua("\\quad","\\hskip1em\\relax"),ua("\\qquad","\\hskip2em\\relax"),ua("\\tag","\\@ifstar\\tag@literal\\tag@paren"),ua("\\tag@paren","\\tag@literal{({#1})}"),ua("\\tag@literal",function(t){if(t.macros.get("\\df@tag"))throw new o("Multiple \\tag");return"\\gdef\\df@tag{\\text{#1}}"}),ua("\\bmod","\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}"),ua("\\pod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)"),ua("\\pmod","\\pod{{\\rm mod}\\mkern6mu#1}"),ua("\\mod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1"),ua("\\pmb","\\html@mathml{\\@binrel{#1}{\\mathrlap{#1}\\kern0.5px#1}}{\\mathbf{#1}}"),ua("\\\\","\\newline"),ua("\\TeX","\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}");var va=D["Main-Regular"]["T".charCodeAt(0)][1]-.7*D["Main-Regular"]["A".charCodeAt(0)][1]+"em";ua("\\LaTeX","\\textrm{\\html@mathml{L\\kern-.36em\\raisebox{"+va+"}{\\scriptstyle A}\\kern-.15em\\TeX}{LaTeX}}"),ua("\\KaTeX","\\textrm{\\html@mathml{K\\kern-.17em\\raisebox{"+va+"}{\\scriptstyle A}\\kern-.15em\\TeX}{KaTeX}}"),ua("\\hspace","\\@ifstar\\@hspacer\\@hspace"),ua("\\@hspace","\\hskip #1\\relax"),ua("\\@hspacer","\\rule{0pt}{0pt}\\hskip #1\\relax"),ua("\\ordinarycolon",":"),ua("\\vcentcolon","\\mathrel{\\mathop\\ordinarycolon}"),ua("\\dblcolon",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char"2237}}'),ua("\\coloneqq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2254}}'),ua("\\Coloneqq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2237\\char"3d}}'),ua("\\coloneq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"3a\\char"2212}}'),ua("\\Coloneq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"2237\\char"2212}}'),ua("\\eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2255}}'),ua("\\Eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"3d\\char"2237}}'),ua("\\eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2239}}'),ua("\\Eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"2212\\char"2237}}'),ua("\\colonapprox",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"3a\\char"2248}}'),ua("\\Colonapprox",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"2237\\char"2248}}'),ua("\\colonsim",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"3a\\char"223c}}'),ua("\\Colonsim",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"2237\\char"223c}}'),ua("\u2237","\\dblcolon"),ua("\u2239","\\eqcolon"),ua("\u2254","\\coloneqq"),ua("\u2255","\\eqqcolon"),ua("\u2a74","\\Coloneqq"),ua("\\ratio","\\vcentcolon"),ua("\\coloncolon","\\dblcolon"),ua("\\colonequals","\\coloneqq"),ua("\\coloncolonequals","\\Coloneqq"),ua("\\equalscolon","\\eqqcolon"),ua("\\equalscoloncolon","\\Eqqcolon"),ua("\\colonminus","\\coloneq"),ua("\\coloncolonminus","\\Coloneq"),ua("\\minuscolon","\\eqcolon"),ua("\\minuscoloncolon","\\Eqcolon"),ua("\\coloncolonapprox","\\Colonapprox"),ua("\\coloncolonsim","\\Colonsim"),ua("\\simcolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}"),ua("\\simcoloncolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}"),ua("\\approxcolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}"),ua("\\approxcoloncolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}"),ua("\\notni","\\html@mathml{\\not\\ni}{\\mathrel{\\char`\u220c}}"),ua("\\limsup","\\DOTSB\\operatorname*{lim\\,sup}"),ua("\\liminf","\\DOTSB\\operatorname*{lim\\,inf}"),ua("\\gvertneqq","\\html@mathml{\\@gvertneqq}{\u2269}"),ua("\\lvertneqq","\\html@mathml{\\@lvertneqq}{\u2268}"),ua("\\ngeqq","\\html@mathml{\\@ngeqq}{\u2271}"),ua("\\ngeqslant","\\html@mathml{\\@ngeqslant}{\u2271}"),ua("\\nleqq","\\html@mathml{\\@nleqq}{\u2270}"),ua("\\nleqslant","\\html@mathml{\\@nleqslant}{\u2270}"),ua("\\nshortmid","\\html@mathml{\\@nshortmid}{\u2224}"),ua("\\nshortparallel","\\html@mathml{\\@nshortparallel}{\u2226}"),ua("\\nsubseteqq","\\html@mathml{\\@nsubseteqq}{\u2288}"),ua("\\nsupseteqq","\\html@mathml{\\@nsupseteqq}{\u2289}"),ua("\\varsubsetneq","\\html@mathml{\\@varsubsetneq}{\u228a}"),ua("\\varsubsetneqq","\\html@mathml{\\@varsubsetneqq}{\u2acb}"),ua("\\varsupsetneq","\\html@mathml{\\@varsupsetneq}{\u228b}"),ua("\\varsupsetneqq","\\html@mathml{\\@varsupsetneqq}{\u2acc}"),ua("\\llbracket","\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`\u27e6}}"),ua("\\rrbracket","\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`\u27e7}}"),ua("\u27e6","\\llbracket"),ua("\u27e7","\\rrbracket"),ua("\\lBrace","\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`\u2983}}"),ua("\\rBrace","\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`\u2984}}"),ua("\u2983","\\lBrace"),ua("\u2984","\\rBrace"),ua("\\darr","\\downarrow"),ua("\\dArr","\\Downarrow"),ua("\\Darr","\\Downarrow"),ua("\\lang","\\langle"),ua("\\rang","\\rangle"),ua("\\uarr","\\uparrow"),ua("\\uArr","\\Uparrow"),ua("\\Uarr","\\Uparrow"),ua("\\N","\\mathbb{N}"),ua("\\R","\\mathbb{R}"),ua("\\Z","\\mathbb{Z}"),ua("\\alef","\\aleph"),ua("\\alefsym","\\aleph"),ua("\\Alpha","\\mathrm{A}"),ua("\\Beta","\\mathrm{B}"),ua("\\bull","\\bullet"),ua("\\Chi","\\mathrm{X}"),ua("\\clubs","\\clubsuit"),ua("\\cnums","\\mathbb{C}"),ua("\\Complex","\\mathbb{C}"),ua("\\Dagger","\\ddagger"),ua("\\diamonds","\\diamondsuit"),ua("\\empty","\\emptyset"),ua("\\Epsilon","\\mathrm{E}"),ua("\\Eta","\\mathrm{H}"),ua("\\exist","\\exists"),ua("\\harr","\\leftrightarrow"),ua("\\hArr","\\Leftrightarrow"),ua("\\Harr","\\Leftrightarrow"),ua("\\hearts","\\heartsuit"),ua("\\image","\\Im"),ua("\\infin","\\infty"),ua("\\Iota","\\mathrm{I}"),ua("\\isin","\\in"),ua("\\Kappa","\\mathrm{K}"),ua("\\larr","\\leftarrow"),ua("\\lArr","\\Leftarrow"),ua("\\Larr","\\Leftarrow"),ua("\\lrarr","\\leftrightarrow"),ua("\\lrArr","\\Leftrightarrow"),ua("\\Lrarr","\\Leftrightarrow"),ua("\\Mu","\\mathrm{M}"),ua("\\natnums","\\mathbb{N}"),ua("\\Nu","\\mathrm{N}"),ua("\\Omicron","\\mathrm{O}"),ua("\\plusmn","\\pm"),ua("\\rarr","\\rightarrow"),ua("\\rArr","\\Rightarrow"),ua("\\Rarr","\\Rightarrow"),ua("\\real","\\Re"),ua("\\reals","\\mathbb{R}"),ua("\\Reals","\\mathbb{R}"),ua("\\Rho","\\mathrm{P}"),ua("\\sdot","\\cdot"),ua("\\sect","\\S"),ua("\\spades","\\spadesuit"),ua("\\sub","\\subset"),ua("\\sube","\\subseteq"),ua("\\supe","\\supseteq"),ua("\\Tau","\\mathrm{T}"),ua("\\thetasym","\\vartheta"),ua("\\weierp","\\wp"),ua("\\Zeta","\\mathrm{Z}"),ua("\\argmin","\\DOTSB\\operatorname*{arg\\,min}"),ua("\\argmax","\\DOTSB\\operatorname*{arg\\,max}"),ua("\\plim","\\DOTSB\\mathop{\\operatorname{plim}}\\limits"),ua("\\blue","\\textcolor{##6495ed}{#1}"),ua("\\orange","\\textcolor{##ffa500}{#1}"),ua("\\pink","\\textcolor{##ff00af}{#1}"),ua("\\red","\\textcolor{##df0030}{#1}"),ua("\\green","\\textcolor{##28ae7b}{#1}"),ua("\\gray","\\textcolor{gray}{##1}"),ua("\\purple","\\textcolor{##9d38bd}{#1}"),ua("\\blueA","\\textcolor{##ccfaff}{#1}"),ua("\\blueB","\\textcolor{##80f6ff}{#1}"),ua("\\blueC","\\textcolor{##63d9ea}{#1}"),ua("\\blueD","\\textcolor{##11accd}{#1}"),ua("\\blueE","\\textcolor{##0c7f99}{#1}"),ua("\\tealA","\\textcolor{##94fff5}{#1}"),ua("\\tealB","\\textcolor{##26edd5}{#1}"),ua("\\tealC","\\textcolor{##01d1c1}{#1}"),ua("\\tealD","\\textcolor{##01a995}{#1}"),ua("\\tealE","\\textcolor{##208170}{#1}"),ua("\\greenA","\\textcolor{##b6ffb0}{#1}"),ua("\\greenB","\\textcolor{##8af281}{#1}"),ua("\\greenC","\\textcolor{##74cf70}{#1}"),ua("\\greenD","\\textcolor{##1fab54}{#1}"),ua("\\greenE","\\textcolor{##0d923f}{#1}"),ua("\\goldA","\\textcolor{##ffd0a9}{#1}"),ua("\\goldB","\\textcolor{##ffbb71}{#1}"),ua("\\goldC","\\textcolor{##ff9c39}{#1}"),ua("\\goldD","\\textcolor{##e07d10}{#1}"),ua("\\goldE","\\textcolor{##a75a05}{#1}"),ua("\\redA","\\textcolor{##fca9a9}{#1}"),ua("\\redB","\\textcolor{##ff8482}{#1}"),ua("\\redC","\\textcolor{##f9685d}{#1}"),ua("\\redD","\\textcolor{##e84d39}{#1}"),ua("\\redE","\\textcolor{##bc2612}{#1}"),ua("\\maroonA","\\textcolor{##ffbde0}{#1}"),ua("\\maroonB","\\textcolor{##ff92c6}{#1}"),ua("\\maroonC","\\textcolor{##ed5fa6}{#1}"),ua("\\maroonD","\\textcolor{##ca337c}{#1}"),ua("\\maroonE","\\textcolor{##9e034e}{#1}"),ua("\\purpleA","\\textcolor{##ddd7ff}{#1}"),ua("\\purpleB","\\textcolor{##c6b9fc}{#1}"),ua("\\purpleC","\\textcolor{##aa87ff}{#1}"),ua("\\purpleD","\\textcolor{##7854ab}{#1}"),ua("\\purpleE","\\textcolor{##543b78}{#1}"),ua("\\mintA","\\textcolor{##f5f9e8}{#1}"),ua("\\mintB","\\textcolor{##edf2df}{#1}"),ua("\\mintC","\\textcolor{##e0e5cc}{#1}"),ua("\\grayA","\\textcolor{##f6f7f7}{#1}"),ua("\\grayB","\\textcolor{##f0f1f2}{#1}"),ua("\\grayC","\\textcolor{##e3e5e6}{#1}"),ua("\\grayD","\\textcolor{##d6d8da}{#1}"),ua("\\grayE","\\textcolor{##babec2}{#1}"),ua("\\grayF","\\textcolor{##888d93}{#1}"),ua("\\grayG","\\textcolor{##626569}{#1}"),ua("\\grayH","\\textcolor{##3b3e40}{#1}"),ua("\\grayI","\\textcolor{##21242c}{#1}"),ua("\\kaBlue","\\textcolor{##314453}{#1}"),ua("\\kaGreen","\\textcolor{##71B307}{#1}");var ba={"\\relax":!0,"^":!0,_:!0,"\\limits":!0,"\\nolimits":!0},ya=function(){function t(t,e,r){this.settings=void 0,this.expansionCount=void 0,this.lexer=void 0,this.macros=void 0,this.stack=void 0,this.mode=void 0,this.settings=e,this.expansionCount=0,this.feed(t),this.macros=new la(ca,e.macros),this.mode=r,this.stack=[]}var e=t.prototype;return e.feed=function(t){this.lexer=new ha(t,this.settings)},e.switchMode=function(t){this.mode=t},e.beginGroup=function(){this.macros.beginGroup()},e.endGroup=function(){this.macros.endGroup()},e.future=function(){return 0===this.stack.length&&this.pushToken(this.lexer.lex()),this.stack[this.stack.length-1]},e.popToken=function(){return this.future(),this.stack.pop()},e.pushToken=function(t){this.stack.push(t)},e.pushTokens=function(t){var e;(e=this.stack).push.apply(e,t)},e.consumeSpaces=function(){for(;;){if(" "!==this.future().text)break;this.stack.pop()}},e.consumeArgs=function(t){for(var e=[],r=0;rthis.settings.maxExpand)throw new o("Too many expansions: infinite loop or need to increase maxExpand setting");var a=r.tokens;if(r.numArgs)for(var n=this.consumeArgs(r.numArgs),i=(a=a.slice()).length-1;i>=0;--i){var s=a[i];if("#"===s.text){if(0===i)throw new o("Incomplete placeholder at end of macro body",s);if("#"===(s=a[--i]).text)a.splice(i+1,1);else{if(!/^[1-9]$/.test(s.text))throw new o("Not a valid argument number",s);var h;(h=a).splice.apply(h,[i,2].concat(n[+s.text-1]))}}}return this.pushTokens(a),a},e.expandAfterFuture=function(){return this.expandOnce(),this.future()},e.expandNextToken=function(){for(;;){var t=this.expandOnce();if(t instanceof n){if("\\relax"!==t.text)return this.stack.pop();this.stack.pop()}}throw new Error},e.expandMacro=function(t){if(this.macros.get(t)){var e=[],r=this.stack.length;for(this.pushToken(new n(t));this.stack.length>r;){this.expandOnce()instanceof n&&e.push(this.stack.pop())}return e}},e.expandMacroAsText=function(t){var e=this.expandMacro(t);return e?e.map(function(t){return t.text}).join(""):e},e._getExpansion=function(t){var e=this.macros.get(t);if(null==e)return e;var r="function"==typeof e?e(this):e;if("string"==typeof r){var a=0;if(-1!==r.indexOf("#"))for(var n=r.replace(/##/g,"");-1!==n.indexOf("#"+(a+1));)++a;for(var i=new ha(r,this.settings),o=[],s=i.lex();"EOF"!==s.text;)o.push(s),s=i.lex();return o.reverse(),{tokens:o,numArgs:a}}return r},e.isDefined=function(t){return this.macros.has(t)||na.hasOwnProperty(t)||_.math.hasOwnProperty(t)||_.text.hasOwnProperty(t)||ba.hasOwnProperty(t)},t}(),wa={"\u0301":{text:"\\'",math:"\\acute"},"\u0300":{text:"\\`",math:"\\grave"},"\u0308":{text:'\\"',math:"\\ddot"},"\u0303":{text:"\\~",math:"\\tilde"},"\u0304":{text:"\\=",math:"\\bar"},"\u0306":{text:"\\u",math:"\\breve"},"\u030c":{text:"\\v",math:"\\check"},"\u0302":{text:"\\^",math:"\\hat"},"\u0307":{text:"\\.",math:"\\dot"},"\u030a":{text:"\\r",math:"\\mathring"},"\u030b":{text:"\\H"}},ka={"\xe1":"a\u0301","\xe0":"a\u0300","\xe4":"a\u0308","\u01df":"a\u0308\u0304","\xe3":"a\u0303","\u0101":"a\u0304","\u0103":"a\u0306","\u1eaf":"a\u0306\u0301","\u1eb1":"a\u0306\u0300","\u1eb5":"a\u0306\u0303","\u01ce":"a\u030c","\xe2":"a\u0302","\u1ea5":"a\u0302\u0301","\u1ea7":"a\u0302\u0300","\u1eab":"a\u0302\u0303","\u0227":"a\u0307","\u01e1":"a\u0307\u0304","\xe5":"a\u030a","\u01fb":"a\u030a\u0301","\u1e03":"b\u0307","\u0107":"c\u0301","\u010d":"c\u030c","\u0109":"c\u0302","\u010b":"c\u0307","\u010f":"d\u030c","\u1e0b":"d\u0307","\xe9":"e\u0301","\xe8":"e\u0300","\xeb":"e\u0308","\u1ebd":"e\u0303","\u0113":"e\u0304","\u1e17":"e\u0304\u0301","\u1e15":"e\u0304\u0300","\u0115":"e\u0306","\u011b":"e\u030c","\xea":"e\u0302","\u1ebf":"e\u0302\u0301","\u1ec1":"e\u0302\u0300","\u1ec5":"e\u0302\u0303","\u0117":"e\u0307","\u1e1f":"f\u0307","\u01f5":"g\u0301","\u1e21":"g\u0304","\u011f":"g\u0306","\u01e7":"g\u030c","\u011d":"g\u0302","\u0121":"g\u0307","\u1e27":"h\u0308","\u021f":"h\u030c","\u0125":"h\u0302","\u1e23":"h\u0307","\xed":"i\u0301","\xec":"i\u0300","\xef":"i\u0308","\u1e2f":"i\u0308\u0301","\u0129":"i\u0303","\u012b":"i\u0304","\u012d":"i\u0306","\u01d0":"i\u030c","\xee":"i\u0302","\u01f0":"j\u030c","\u0135":"j\u0302","\u1e31":"k\u0301","\u01e9":"k\u030c","\u013a":"l\u0301","\u013e":"l\u030c","\u1e3f":"m\u0301","\u1e41":"m\u0307","\u0144":"n\u0301","\u01f9":"n\u0300","\xf1":"n\u0303","\u0148":"n\u030c","\u1e45":"n\u0307","\xf3":"o\u0301","\xf2":"o\u0300","\xf6":"o\u0308","\u022b":"o\u0308\u0304","\xf5":"o\u0303","\u1e4d":"o\u0303\u0301","\u1e4f":"o\u0303\u0308","\u022d":"o\u0303\u0304","\u014d":"o\u0304","\u1e53":"o\u0304\u0301","\u1e51":"o\u0304\u0300","\u014f":"o\u0306","\u01d2":"o\u030c","\xf4":"o\u0302","\u1ed1":"o\u0302\u0301","\u1ed3":"o\u0302\u0300","\u1ed7":"o\u0302\u0303","\u022f":"o\u0307","\u0231":"o\u0307\u0304","\u0151":"o\u030b","\u1e55":"p\u0301","\u1e57":"p\u0307","\u0155":"r\u0301","\u0159":"r\u030c","\u1e59":"r\u0307","\u015b":"s\u0301","\u1e65":"s\u0301\u0307","\u0161":"s\u030c","\u1e67":"s\u030c\u0307","\u015d":"s\u0302","\u1e61":"s\u0307","\u1e97":"t\u0308","\u0165":"t\u030c","\u1e6b":"t\u0307","\xfa":"u\u0301","\xf9":"u\u0300","\xfc":"u\u0308","\u01d8":"u\u0308\u0301","\u01dc":"u\u0308\u0300","\u01d6":"u\u0308\u0304","\u01da":"u\u0308\u030c","\u0169":"u\u0303","\u1e79":"u\u0303\u0301","\u016b":"u\u0304","\u1e7b":"u\u0304\u0308","\u016d":"u\u0306","\u01d4":"u\u030c","\xfb":"u\u0302","\u016f":"u\u030a","\u0171":"u\u030b","\u1e7d":"v\u0303","\u1e83":"w\u0301","\u1e81":"w\u0300","\u1e85":"w\u0308","\u0175":"w\u0302","\u1e87":"w\u0307","\u1e98":"w\u030a","\u1e8d":"x\u0308","\u1e8b":"x\u0307","\xfd":"y\u0301","\u1ef3":"y\u0300","\xff":"y\u0308","\u1ef9":"y\u0303","\u0233":"y\u0304","\u0177":"y\u0302","\u1e8f":"y\u0307","\u1e99":"y\u030a","\u017a":"z\u0301","\u017e":"z\u030c","\u1e91":"z\u0302","\u017c":"z\u0307","\xc1":"A\u0301","\xc0":"A\u0300","\xc4":"A\u0308","\u01de":"A\u0308\u0304","\xc3":"A\u0303","\u0100":"A\u0304","\u0102":"A\u0306","\u1eae":"A\u0306\u0301","\u1eb0":"A\u0306\u0300","\u1eb4":"A\u0306\u0303","\u01cd":"A\u030c","\xc2":"A\u0302","\u1ea4":"A\u0302\u0301","\u1ea6":"A\u0302\u0300","\u1eaa":"A\u0302\u0303","\u0226":"A\u0307","\u01e0":"A\u0307\u0304","\xc5":"A\u030a","\u01fa":"A\u030a\u0301","\u1e02":"B\u0307","\u0106":"C\u0301","\u010c":"C\u030c","\u0108":"C\u0302","\u010a":"C\u0307","\u010e":"D\u030c","\u1e0a":"D\u0307","\xc9":"E\u0301","\xc8":"E\u0300","\xcb":"E\u0308","\u1ebc":"E\u0303","\u0112":"E\u0304","\u1e16":"E\u0304\u0301","\u1e14":"E\u0304\u0300","\u0114":"E\u0306","\u011a":"E\u030c","\xca":"E\u0302","\u1ebe":"E\u0302\u0301","\u1ec0":"E\u0302\u0300","\u1ec4":"E\u0302\u0303","\u0116":"E\u0307","\u1e1e":"F\u0307","\u01f4":"G\u0301","\u1e20":"G\u0304","\u011e":"G\u0306","\u01e6":"G\u030c","\u011c":"G\u0302","\u0120":"G\u0307","\u1e26":"H\u0308","\u021e":"H\u030c","\u0124":"H\u0302","\u1e22":"H\u0307","\xcd":"I\u0301","\xcc":"I\u0300","\xcf":"I\u0308","\u1e2e":"I\u0308\u0301","\u0128":"I\u0303","\u012a":"I\u0304","\u012c":"I\u0306","\u01cf":"I\u030c","\xce":"I\u0302","\u0130":"I\u0307","\u0134":"J\u0302","\u1e30":"K\u0301","\u01e8":"K\u030c","\u0139":"L\u0301","\u013d":"L\u030c","\u1e3e":"M\u0301","\u1e40":"M\u0307","\u0143":"N\u0301","\u01f8":"N\u0300","\xd1":"N\u0303","\u0147":"N\u030c","\u1e44":"N\u0307","\xd3":"O\u0301","\xd2":"O\u0300","\xd6":"O\u0308","\u022a":"O\u0308\u0304","\xd5":"O\u0303","\u1e4c":"O\u0303\u0301","\u1e4e":"O\u0303\u0308","\u022c":"O\u0303\u0304","\u014c":"O\u0304","\u1e52":"O\u0304\u0301","\u1e50":"O\u0304\u0300","\u014e":"O\u0306","\u01d1":"O\u030c","\xd4":"O\u0302","\u1ed0":"O\u0302\u0301","\u1ed2":"O\u0302\u0300","\u1ed6":"O\u0302\u0303","\u022e":"O\u0307","\u0230":"O\u0307\u0304","\u0150":"O\u030b","\u1e54":"P\u0301","\u1e56":"P\u0307","\u0154":"R\u0301","\u0158":"R\u030c","\u1e58":"R\u0307","\u015a":"S\u0301","\u1e64":"S\u0301\u0307","\u0160":"S\u030c","\u1e66":"S\u030c\u0307","\u015c":"S\u0302","\u1e60":"S\u0307","\u0164":"T\u030c","\u1e6a":"T\u0307","\xda":"U\u0301","\xd9":"U\u0300","\xdc":"U\u0308","\u01d7":"U\u0308\u0301","\u01db":"U\u0308\u0300","\u01d5":"U\u0308\u0304","\u01d9":"U\u0308\u030c","\u0168":"U\u0303","\u1e78":"U\u0303\u0301","\u016a":"U\u0304","\u1e7a":"U\u0304\u0308","\u016c":"U\u0306","\u01d3":"U\u030c","\xdb":"U\u0302","\u016e":"U\u030a","\u0170":"U\u030b","\u1e7c":"V\u0303","\u1e82":"W\u0301","\u1e80":"W\u0300","\u1e84":"W\u0308","\u0174":"W\u0302","\u1e86":"W\u0307","\u1e8c":"X\u0308","\u1e8a":"X\u0307","\xdd":"Y\u0301","\u1ef2":"Y\u0300","\u0178":"Y\u0308","\u1ef8":"Y\u0303","\u0232":"Y\u0304","\u0176":"Y\u0302","\u1e8e":"Y\u0307","\u0179":"Z\u0301","\u017d":"Z\u030c","\u1e90":"Z\u0302","\u017b":"Z\u0307","\u03ac":"\u03b1\u0301","\u1f70":"\u03b1\u0300","\u1fb1":"\u03b1\u0304","\u1fb0":"\u03b1\u0306","\u03ad":"\u03b5\u0301","\u1f72":"\u03b5\u0300","\u03ae":"\u03b7\u0301","\u1f74":"\u03b7\u0300","\u03af":"\u03b9\u0301","\u1f76":"\u03b9\u0300","\u03ca":"\u03b9\u0308","\u0390":"\u03b9\u0308\u0301","\u1fd2":"\u03b9\u0308\u0300","\u1fd1":"\u03b9\u0304","\u1fd0":"\u03b9\u0306","\u03cc":"\u03bf\u0301","\u1f78":"\u03bf\u0300","\u03cd":"\u03c5\u0301","\u1f7a":"\u03c5\u0300","\u03cb":"\u03c5\u0308","\u03b0":"\u03c5\u0308\u0301","\u1fe2":"\u03c5\u0308\u0300","\u1fe1":"\u03c5\u0304","\u1fe0":"\u03c5\u0306","\u03ce":"\u03c9\u0301","\u1f7c":"\u03c9\u0300","\u038e":"\u03a5\u0301","\u1fea":"\u03a5\u0300","\u03ab":"\u03a5\u0308","\u1fe9":"\u03a5\u0304","\u1fe8":"\u03a5\u0306","\u038f":"\u03a9\u0301","\u1ffa":"\u03a9\u0300"},Sa=function(){function t(t,e){this.mode=void 0,this.gullet=void 0,this.settings=void 0,this.leftrightDepth=void 0,this.nextToken=void 0,this.mode="math",this.gullet=new ya(t,e,this.mode),this.settings=e,this.leftrightDepth=0}var e=t.prototype;return e.expect=function(t,e){if(void 0===e&&(e=!0),this.nextToken.text!==t)throw new o("Expected '"+t+"', got '"+this.nextToken.text+"'",this.nextToken);e&&this.consume()},e.consume=function(){this.nextToken=this.gullet.expandNextToken()},e.switchMode=function(t){this.mode=t,this.gullet.switchMode(t)},e.parse=function(){this.gullet.beginGroup(),this.settings.colorIsTextColor&&this.gullet.macros.set("\\color","\\textcolor"),this.consume();var t=this.parseExpression(!1);return this.expect("EOF",!1),this.gullet.endGroup(),t},e.parseExpression=function(e,r){for(var a=[];;){"math"===this.mode&&this.consumeSpaces();var n=this.nextToken;if(-1!==t.endOfExpression.indexOf(n.text))break;if(r&&n.text===r)break;if(e&&na[n.text]&&na[n.text].infix)break;var i=this.parseAtom(r);if(!i)break;a.push(i)}return"text"===this.mode&&this.formLigatures(a),this.handleInfixNodes(a)},e.handleInfixNodes=function(t){for(var e,r=-1,a=0;a0&&!l&&this.consumeSpaces(),0!==s||l||"math"!==this.mode||this.consumeSpaces();var m=this.nextToken,c=this.parseGroupOfType("argument to '"+t+"'",h,l,a);if(!c){if(l){i.push(null);continue}throw new o("Expected group after '"+t+"'",m)}(l?i:n).push(c)}return{args:n,optArgs:i}},e.parseGroupOfType=function(t,e,r,a){switch(e){case"color":return this.parseColorGroup(r);case"size":return this.parseSizeGroup(r);case"url":return this.parseUrlGroup(r);case"math":case"text":return this.parseGroup(t,r,a,void 0,e);case"hbox":var n=this.parseGroup(t,r,a,void 0,"text");return n?{type:"styling",mode:n.mode,body:[n],style:"text"}:n;case"raw":if(r&&"{"===this.nextToken.text)return null;var i=this.parseStringGroup("raw",r,!0);if(i)return{type:"raw",mode:"text",string:i.text};throw new o("Expected raw group",this.nextToken);case"original":case null:case void 0:return this.parseGroup(t,r,a);default:throw new o("Unknown group type as "+t,this.nextToken)}},e.consumeSpaces=function(){for(;" "===this.nextToken.text;)this.consume()},e.parseStringGroup=function(t,e,r){var a=e?"[":"{",n=e?"]":"}",i=this.nextToken;if(i.text!==a){if(e)return null;if(r&&"EOF"!==i.text&&/[^{}[\]]/.test(i.text))return this.gullet.lexer.setCatcode("%",14),this.consume(),i}var s=this.mode;this.mode="text",this.expect(a);for(var h="",l=this.nextToken,m=0,c=l;r&&m>0||this.nextToken.text!==n;){switch(this.nextToken.text){case"EOF":throw new o("Unexpected end of input in "+t,l.range(c,h));case a:m++;break;case n:m--}h+=(c=this.nextToken).text,this.consume()}return this.mode=s,this.gullet.lexer.setCatcode("%",14),this.expect(n),l.range(c,h)},e.parseRegexGroup=function(t,e){var r=this.mode;this.mode="text";for(var a=this.nextToken,n=a,i="";"EOF"!==this.nextToken.text&&t.test(i+this.nextToken.text);)i+=(n=this.nextToken).text,this.consume();if(""===i)throw new o("Invalid "+e+": '"+a.text+"'",a);return this.mode=r,a.range(n,i)},e.parseColorGroup=function(t){var e=this.parseStringGroup("color",t);if(!e)return null;var r=/^(#[a-f0-9]{3}|#?[a-f0-9]{6}|[a-z]+)$/i.exec(e.text);if(!r)throw new o("Invalid color: '"+e.text+"'",e);var a=r[0];return/^[0-9a-f]{6}$/i.test(a)&&(a="#"+a),{type:"color-token",mode:this.mode,color:a}},e.parseSizeGroup=function(t){var e,r=!1;if(!(e=t||"{"===this.nextToken.text?this.parseStringGroup("size",t):this.parseRegexGroup(/^[-+]? *(?:$|\d+|\d+\.\d*|\.\d*) *[a-z]{0,2} *$/,"size")))return null;t||0!==e.text.length||(e.text="0pt",r=!0);var a=/([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(e.text);if(!a)throw new o("Invalid size: '"+e.text+"'",e);var n={number:+(a[1]+a[2]),unit:a[3]};if(!zt(n))throw new o("Invalid unit: '"+n.unit+"'",e);return{type:"size",mode:this.mode,value:n,isBlank:r}},e.parseUrlGroup=function(t){var e=this.parseStringGroup("url",t,!0);if(!e)return null;var r=e.text.replace(/\\([#$%&~_^{}])/g,"$1");return{type:"url",mode:this.mode,url:r}},e.parseGroup=function(e,r,n,i,s){var h,l,m=this.mode,c=this.nextToken,u=c.text;if(s&&this.switchMode(s),r?"["===u:"{"===u||"\\begingroup"===u){h=t.endOfGroup[u],this.gullet.beginGroup(),this.consume();var p=this.parseExpression(!1,h),d=this.nextToken;this.gullet.endGroup(),l={type:"ordgroup",mode:this.mode,loc:a.range(c,d),body:p,semisimple:"\\begingroup"===u||void 0}}else if(r)l=null;else if(null==(l=this.parseFunction(i,e,n)||this.parseSymbol())&&"\\"===u[0]&&!ba.hasOwnProperty(u)){if(this.settings.throwOnError)throw new o("Undefined control sequence: "+u,c);l=this.formatUnsupportedCmd(u),this.consume()}return s&&this.switchMode(m),h&&this.expect(h),l},e.formLigatures=function(t){for(var e=t.length-1,r=0;r=0&&this.settings.reportNonstrict("unicodeTextInMathMode",'Latin-1/Unicode text character "'+e[0]+'" used in math mode',t);var h,l=_[this.mode][e].group,m=a.range(t);if(Y.hasOwnProperty(l)){var c=l;h={type:"atom",mode:this.mode,family:c,loc:m,text:e}}else h={type:l,mode:this.mode,loc:m,text:e};i=h}else{if(!(e.charCodeAt(0)>=128))return null;this.settings.strict&&(M(e.charCodeAt(0))?"math"===this.mode&&this.settings.reportNonstrict("unicodeTextInMathMode",'Unicode text character "'+e[0]+'" used in math mode',t):this.settings.reportNonstrict("unknownSymbol",'Unrecognized Unicode character "'+e[0]+'" ('+e.charCodeAt(0)+")",t)),i={type:"textord",mode:"text",loc:a.range(t),text:e}}if(this.consume(),s)for(var u=0;un?1:t>=n?0:NaN}function e(t){var e;return 1===t.length&&(e=t,t=function(t,r){return n(e(t),r)}),{left:function(n,e,r,i){for(null==r&&(r=0),null==i&&(i=n.length);r>>1;t(n[o],e)<0?r=o+1:i=o}return r},right:function(n,e,r,i){for(null==r&&(r=0),null==i&&(i=n.length);r>>1;t(n[o],e)>0?i=o:r=o+1}return r}}}var r=e(n),i=r.right,o=r.left;function a(t,n){return[t,n]}function u(t){return null===t?NaN:+t}function c(t,n){var e,r,i=t.length,o=0,a=-1,c=0,f=0;if(null==n)for(;++a1)return f/(o-1)}function f(t,n){var e=c(t,n);return e?Math.sqrt(e):e}function s(t,n){var e,r,i,o=t.length,a=-1;if(null==n){for(;++a=e)for(r=i=e;++ae&&(r=e),i=e)for(r=i=e;++ae&&(r=e),i0)return[t];if((r=n0)for(t=Math.ceil(t/a),n=Math.floor(n/a),o=new Array(i=Math.ceil(n-t+1));++u=0?(o>=y?10:o>=_?5:o>=b?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(o>=y?10:o>=_?5:o>=b?2:1)}function w(t,n,e){var r=Math.abs(n-t)/Math.max(0,e),i=Math.pow(10,Math.floor(Math.log(r)/Math.LN10)),o=r/i;return o>=y?i*=10:o>=_?i*=5:o>=b&&(i*=2),n=1)return+e(t[r-1],r-1,t);var r,i=(r-1)*n,o=Math.floor(i),a=+e(t[o],o,t);return a+(+e(t[o+1],o+1,t)-a)*(i-o)}}function T(t,n){var e,r,i=t.length,o=-1;if(null==n){for(;++o=e)for(r=e;++or&&(r=e)}else for(;++o=e)for(r=e;++or&&(r=e);return r}function A(t){for(var n,e,r,i=t.length,o=-1,a=0;++o=0;)for(n=(r=t[i]).length;--n>=0;)e[--a]=r[n];return e}function S(t,n){var e,r,i=t.length,o=-1;if(null==n){for(;++o=e)for(r=e;++oe&&(r=e)}else for(;++o=e)for(r=e;++oe&&(r=e);return r}function k(t){if(!(i=t.length))return[];for(var n=-1,e=S(t,E),r=new Array(e);++n=0&&(e=t.slice(r+1),t=t.slice(0,r)),t&&!n.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:e}})}function X(t,n){for(var e,r=0,i=t.length;r0)for(var e,r,i=new Array(e),o=0;o=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),$.hasOwnProperty(n)?{space:$[n],local:t}:t}function Z(t){var n=W(t);return(n.local?function(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}:function(t){return function(){var n=this.ownerDocument,e=this.namespaceURI;return e===V&&n.documentElement.namespaceURI===V?n.createElement(t):n.createElementNS(e,t)}})(n)}function Q(){}function K(t){return null==t?Q:function(){return this.querySelector(t)}}function J(){return[]}function tt(t){return null==t?J:function(){return this.querySelectorAll(t)}}function nt(t){return function(){return this.matches(t)}}function et(t){return new Array(t.length)}function rt(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}rt.prototype={constructor:rt,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,n){return this._parent.insertBefore(t,n)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};var it="$";function ot(t,n,e,r,i,o){for(var a,u=0,c=n.length,f=o.length;un?1:t>=n?0:NaN}function ct(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function ft(t,n){return t.style.getPropertyValue(n)||ct(t).getComputedStyle(t,null).getPropertyValue(n)}function st(t){return t.trim().split(/^|\s+/)}function lt(t){return t.classList||new ht(t)}function ht(t){this._node=t,this._names=st(t.getAttribute("class")||"")}function dt(t,n){for(var e=lt(t),r=-1,i=n.length;++r=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var Mt={};(t.event=null,"undefined"!=typeof document)&&("onmouseenter"in document.documentElement||(Mt={mouseenter:"mouseover",mouseleave:"mouseout"}));function Nt(t,n,e){return t=Tt(t,n,e),function(n){var e=n.relatedTarget;e&&(e===this||8&e.compareDocumentPosition(this))||t.call(this,n)}}function Tt(n,e,r){return function(i){var o=t.event;t.event=i;try{n.call(this,this.__data__,e,r)}finally{t.event=o}}}function At(t){return function(){var n=this.__on;if(n){for(var e,r=0,i=-1,o=n.length;r=m&&(m=b+1);!(_=g[m])&&++m=0;)(r=i[o])&&(a&&4^r.compareDocumentPosition(a)&&a.parentNode.insertBefore(r,a),a=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=ut);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o1?this.each((null==n?function(t){return function(){this.style.removeProperty(t)}}:"function"==typeof n?function(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}:function(t,n,e){return function(){this.style.setProperty(t,n,e)}})(t,n,null==e?"":e)):ft(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?function(t){return function(){delete this[t]}}:"function"==typeof n?function(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}:function(t,n){return function(){this[t]=n}})(t,n)):this.node()[t]},classed:function(t,n){var e=st(t+"");if(arguments.length<2){for(var r=lt(this.node()),i=-1,o=e.length;++i=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}})}(t+""),a=o.length;if(!(arguments.length<2)){for(u=n?St:At,null==e&&(e=!1),r=0;r>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):(n=on.exec(t))?gn(parseInt(n[1],16)):(n=an.exec(t))?new mn(n[1],n[2],n[3],1):(n=un.exec(t))?new mn(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=cn.exec(t))?yn(n[1],n[2],n[3],n[4]):(n=fn.exec(t))?yn(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=sn.exec(t))?Nn(n[1],n[2]/100,n[3]/100,1):(n=ln.exec(t))?Nn(n[1],n[2]/100,n[3]/100,n[4]):hn.hasOwnProperty(t)?gn(hn[t]):"transparent"===t?new mn(NaN,NaN,NaN,0):null}function gn(t){return new mn(t>>16&255,t>>8&255,255&t,1)}function yn(t,n,e,r){return r<=0&&(t=n=e=NaN),new mn(t,n,e,r)}function _n(t){return t instanceof Jt||(t=vn(t)),t?new mn((t=t.rgb()).r,t.g,t.b,t.opacity):new mn}function bn(t,n,e,r){return 1===arguments.length?_n(t):new mn(t,n,e,null==r?1:r)}function mn(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function xn(){return"#"+Mn(this.r)+Mn(this.g)+Mn(this.b)}function wn(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}function Mn(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function Nn(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new Sn(t,n,e,r)}function Tn(t){if(t instanceof Sn)return new Sn(t.h,t.s,t.l,t.opacity);if(t instanceof Jt||(t=vn(t)),!t)return new Sn;if(t instanceof Sn)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),a=NaN,u=o-i,c=(o+i)/2;return u?(a=n===o?(e-r)/u+6*(e0&&c<1?0:a,new Sn(a,u,c,t.opacity)}function An(t,n,e,r){return 1===arguments.length?Tn(t):new Sn(t,n,e,null==r?1:r)}function Sn(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function kn(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}Qt(Jt,vn,{copy:function(t){return Object.assign(new this.constructor,this,t)},displayable:function(){return this.rgb().displayable()},hex:dn,formatHex:dn,formatHsl:function(){return Tn(this).formatHsl()},formatRgb:pn,toString:pn}),Qt(mn,bn,Kt(Jt,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new mn(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new mn(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:xn,formatHex:xn,formatRgb:wn,toString:wn})),Qt(Sn,An,Kt(Jt,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new Sn(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new Sn(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new mn(kn(t>=240?t-240:t+120,i,r),kn(t,i,r),kn(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===t?")":", "+t+")")}}));var En=Math.PI/180,Cn=180/Math.PI,Pn=.96422,zn=1,Rn=.82521,Dn=4/29,qn=6/29,Ln=3*qn*qn,Un=qn*qn*qn;function On(t){if(t instanceof Yn)return new Yn(t.l,t.a,t.b,t.opacity);if(t instanceof Vn)return $n(t);t instanceof mn||(t=_n(t));var n,e,r=jn(t.r),i=jn(t.g),o=jn(t.b),a=Fn((.2225045*r+.7168786*i+.0606169*o)/zn);return r===i&&i===o?n=e=a:(n=Fn((.4360747*r+.3850649*i+.1430804*o)/Pn),e=Fn((.0139322*r+.0971045*i+.7141733*o)/Rn)),new Yn(116*a-16,500*(n-a),200*(a-e),t.opacity)}function Bn(t,n,e,r){return 1===arguments.length?On(t):new Yn(t,n,e,null==r?1:r)}function Yn(t,n,e,r){this.l=+t,this.a=+n,this.b=+e,this.opacity=+r}function Fn(t){return t>Un?Math.pow(t,1/3):t/Ln+Dn}function In(t){return t>qn?t*t*t:Ln*(t-Dn)}function Hn(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function jn(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Xn(t){if(t instanceof Vn)return new Vn(t.h,t.c,t.l,t.opacity);if(t instanceof Yn||(t=On(t)),0===t.a&&0===t.b)return new Vn(NaN,0=1?(e=1,n-1):Math.floor(e*n),i=t[r],o=t[r+1],a=r>0?t[r-1]:2*i-o,u=r180||e<-180?e-360*Math.round(e/360):e):ce(isNaN(t)?n:t)}function le(t){return 1==(t=+t)?he:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):ce(isNaN(n)?e:n)}}function he(t,n){var e=n-t;return e?fe(t,e):ce(isNaN(t)?n:t)}Qt(ie,re,Kt(Jt,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new ie(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new ie(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=isNaN(this.h)?0:(this.h+120)*En,n=+this.l,e=isNaN(this.s)?0:this.s*n*(1-n),r=Math.cos(t),i=Math.sin(t);return new mn(255*(n+e*(Wn*r+Zn*i)),255*(n+e*(Qn*r+Kn*i)),255*(n+e*(Jn*r)),this.opacity)}}));var de=function t(n){var e=le(n);function r(t,n){var r=e((t=bn(t)).r,(n=bn(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),a=he(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=a(n),t+""}}return r.gamma=t,r}(1);function pe(t){return function(n){var e,r,i=n.length,o=new Array(i),a=new Array(i),u=new Array(i);for(e=0;eo&&(i=n.slice(o,i),u[a]?u[a]+=i:u[++a]=i),(e=e[0])===(r=r[0])?u[a]?u[a]+=r:u[++a]=r:(u[++a]=null,c.push({i:a,x:be(e,r)})),o=we.lastIndex;return o180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:be(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,a.rotate,u,c),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:be(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,a.skewX,u,c),function(t,n,e,r,o,a){if(t!==e||n!==r){var u=o.push(i(o)+"scale(",null,",",null,")");a.push({i:u-4,x:be(t,e)},{i:u-2,x:be(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,a.scaleX,a.scaleY,u,c),o=a=null,function(t){for(var n,e=-1,r=c.length;++e=0&&n._call.call(null,t),n=n._next;--Je}function dr(){ir=(rr=ar.now())+or,Je=tr=0;try{hr()}finally{Je=0,function(){var t,n,e=Qe,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:Qe=n);Ke=t,vr(r)}(),ir=0}}function pr(){var t=ar.now(),n=t-rr;n>er&&(or-=n,rr=t)}function vr(t){Je||(tr&&(tr=clearTimeout(tr)),t-ir>24?(t<1/0&&(tr=setTimeout(dr,t-ar.now()-or)),nr&&(nr=clearInterval(nr))):(nr||(rr=ar.now(),nr=setInterval(pr,er)),Je=1,ur(dr)))}function gr(t,n,e){var r=new sr;return n=null==n?0:+n,r.restart(function(e){r.stop(),t(e+n)},n,e),r}sr.prototype=lr.prototype={constructor:sr,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?cr():+e)+(null==n?0:+n),this._next||Ke===this||(Ke?Ke._next=this:Qe=this,Ke=this),this._call=t,this._time=e,vr()},stop:function(){this._call&&(this._call=null,this._time=1/0,vr())}};var yr=I("start","end","cancel","interrupt"),_r=[],br=0,mr=1,xr=2,wr=3,Mr=4,Nr=5,Tr=6;function Ar(t,n,e,r,i,o){var a=t.__transition;if(a){if(e in a)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(c){var f,s,l,h;if(e.state!==mr)return u();for(f in i)if((h=i[f]).name===e.name){if(h.state===wr)return gr(o);h.state===Mr?(h.state=Tr,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[f]):+fbr)throw new Error("too late; already scheduled");return e}function kr(t,n){var e=Er(t,n);if(e.state>wr)throw new Error("too late; already running");return e}function Er(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}function Cr(t,n){var e,r,i,o=t.__transition,a=!0;if(o){for(i in n=null==n?null:n+"",o)(e=o[i]).name===n?(r=e.state>xr&&e.state=0&&(t=t.slice(0,n)),!t||"start"===t})}(n)?Sr:kr;return function(){var a=o(this,t),u=a.on;u!==r&&(i=(r=u).copy()).on(n,e),a.on=i}}(e,t,n))},attr:function(t,n){var e=W(t),r="transform"===e?qe:zr;return this.attrTween(t,"function"==typeof n?(e.local?function(t,n,e){var r,i,o;return function(){var a,u,c=e(this);if(null!=c)return(a=this.getAttributeNS(t.space,t.local))===(u=c+"")?null:a===r&&u===i?o:(i=u,o=n(r=a,c));this.removeAttributeNS(t.space,t.local)}}:function(t,n,e){var r,i,o;return function(){var a,u,c=e(this);if(null!=c)return(a=this.getAttribute(t))===(u=c+"")?null:a===r&&u===i?o:(i=u,o=n(r=a,c));this.removeAttribute(t)}})(e,r,Pr(this,"attr."+t,n)):null==n?(e.local?function(t){return function(){this.removeAttributeNS(t.space,t.local)}}:function(t){return function(){this.removeAttribute(t)}})(e):(e.local?function(t,n,e){var r,i,o=e+"";return function(){var a=this.getAttributeNS(t.space,t.local);return a===o?null:a===r?i:i=n(r=a,e)}}:function(t,n,e){var r,i,o=e+"";return function(){var a=this.getAttribute(t);return a===o?null:a===r?i:i=n(r=a,e)}})(e,r,n))},attrTween:function(t,n){var e="attr."+t;if(arguments.length<2)return(e=this.tween(e))&&e._value;if(null==n)return this.tween(e,null);if("function"!=typeof n)throw new Error;var r=W(t);return this.tween(e,(r.local?function(t,n){var e,r;function i(){var i=n.apply(this,arguments);return i!==r&&(e=(r=i)&&function(t,n){return function(e){this.setAttributeNS(t.space,t.local,n(e))}}(t,i)),e}return i._value=n,i}:function(t,n){var e,r;function i(){var i=n.apply(this,arguments);return i!==r&&(e=(r=i)&&function(t,n){return function(e){this.setAttribute(t,n(e))}}(t,i)),e}return i._value=n,i})(r,n))},style:function(t,n,e){var r="transform"==(t+="")?De:zr;return null==n?this.styleTween(t,function(t,n){var e,r,i;return function(){var o=ft(this,t),a=(this.style.removeProperty(t),ft(this,t));return o===a?null:o===e&&a===r?i:i=n(e=o,r=a)}}(t,r)).on("end.style."+t,Dr(t)):"function"==typeof n?this.styleTween(t,function(t,n,e){var r,i,o;return function(){var a=ft(this,t),u=e(this),c=u+"";return null==u&&(this.style.removeProperty(t),c=u=ft(this,t)),a===c?null:a===r&&c===i?o:(i=c,o=n(r=a,u))}}(t,r,Pr(this,"style."+t,n))).each(function(t,n){var e,r,i,o,a="style."+n,u="end."+a;return function(){var c=kr(this,t),f=c.on,s=null==c.value[a]?o||(o=Dr(n)):void 0;f===e&&i===s||(r=(e=f).copy()).on(u,i=s),c.on=r}}(this._id,t)):this.styleTween(t,function(t,n,e){var r,i,o=e+"";return function(){var a=ft(this,t);return a===o?null:a===r?i:i=n(r=a,e)}}(t,r,n),e).on("end.style."+t,null)},styleTween:function(t,n,e){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==n)return this.tween(r,null);if("function"!=typeof n)throw new Error;return this.tween(r,function(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&function(t,n,e){return function(r){this.style.setProperty(t,n(r),e)}}(t,o,e)),r}return o._value=n,o}(t,n,null==e?"":e))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var n=t(this);this.textContent=null==n?"":n}}(Pr(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},remove:function(){return this.on("end.remove",function(t){return function(){var n=this.parentNode;for(var e in this.__transition)if(+e!==t)return;n&&n.removeChild(this)}}(this._id))},tween:function(t,n){var e=this._id;if(t+="",arguments.length<2){for(var r,i=Er(this.node(),e).tween,o=0,a=i.length;o0&&(r=o-P),M<0?d=p-z:M>0&&(u=c-z),x=wi,B.attr("cursor",Ci.selection),I());break;default:return}mi()},!0).on("keyup.brush",function(){switch(t.event.keyCode){case 16:R&&(g=y=R=!1,I());break;case 18:x===Ni&&(w<0?f=h:w>0&&(r=o),M<0?d=p:M>0&&(u=c),x=Mi,I());break;case 32:x===wi&&(t.event.altKey?(w&&(f=h-P*w,r=o+P*w),M&&(d=p-z*M,u=c+z*M),x=Ni):(w<0?f=h:w>0&&(r=o),M<0?d=p:M>0&&(u=c),x=Mi),B.attr("cursor",Ci[m]),I());break;default:return}mi()},!0),Ht(t.event.view)}bi(),Cr(b),s.call(b),U.start()}function F(){var t=D(b);!R||g||y||(Math.abs(t[0]-L[0])>Math.abs(t[1]-L[1])?y=!0:g=!0),L=t,v=!0,mi(),I()}function I(){var t;switch(P=L[0]-q[0],z=L[1]-q[1],x){case wi:case xi:w&&(P=Math.max(S-r,Math.min(E-f,P)),o=r+P,h=f+P),M&&(z=Math.max(k-u,Math.min(C-d,z)),c=u+z,p=d+z);break;case Mi:w<0?(P=Math.max(S-r,Math.min(E-r,P)),o=r+P,h=f):w>0&&(P=Math.max(S-f,Math.min(E-f,P)),o=r,h=f+P),M<0?(z=Math.max(k-u,Math.min(C-u,z)),c=u+z,p=d):M>0&&(z=Math.max(k-d,Math.min(C-d,z)),c=u,p=d+z);break;case Ni:w&&(o=Math.max(S,Math.min(E,r-P*w)),h=Math.max(S,Math.min(E,f+P*w))),M&&(c=Math.max(k,Math.min(C,u-z*M)),p=Math.max(k,Math.min(C,d+z*M)))}h1e-6)if(Math.abs(s*u-c*f)>1e-6&&i){var h=e-o,d=r-a,p=u*u+c*c,v=h*h+d*d,g=Math.sqrt(p),y=Math.sqrt(l),_=i*Math.tan((Zi-Math.acos((p+l-v)/(2*g*y)))/2),b=_/y,m=_/g;Math.abs(b-1)>1e-6&&(this._+="L"+(t+b*f)+","+(n+b*s)),this._+="A"+i+","+i+",0,0,"+ +(s*h>f*d)+","+(this._x1=t+m*u)+","+(this._y1=n+m*c)}else this._+="L"+(this._x1=t)+","+(this._y1=n);else;},arc:function(t,n,e,r,i,o){t=+t,n=+n,o=!!o;var a=(e=+e)*Math.cos(r),u=e*Math.sin(r),c=t+a,f=n+u,s=1^o,l=o?r-i:i-r;if(e<0)throw new Error("negative radius: "+e);null===this._x1?this._+="M"+c+","+f:(Math.abs(this._x1-c)>1e-6||Math.abs(this._y1-f)>1e-6)&&(this._+="L"+c+","+f),e&&(l<0&&(l=l%Qi+Qi),l>Ki?this._+="A"+e+","+e+",0,1,"+s+","+(t-a)+","+(n-u)+"A"+e+","+e+",0,1,"+s+","+(this._x1=c)+","+(this._y1=f):l>1e-6&&(this._+="A"+e+","+e+",0,"+ +(l>=Zi)+","+s+","+(this._x1=t+e*Math.cos(i))+","+(this._y1=n+e*Math.sin(i))))},rect:function(t,n,e,r){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+n)+"h"+ +e+"v"+ +r+"h"+-e+"Z"},toString:function(){return this._}};function ao(){}function uo(t,n){var e=new ao;if(t instanceof ao)t.each(function(t,n){e.set(n,t)});else if(Array.isArray(t)){var r,i=-1,o=t.length;if(null==n)for(;++ir!=d>r&&e<(h-f)*(r-s)/(d-s)+f&&(i=-i)}return i}function xo(t,n,e){var r,i,o,a;return function(t,n,e){return(n[0]-t[0])*(e[1]-t[1])==(e[0]-t[0])*(n[1]-t[1])}(t,n,e)&&(i=t[r=+(t[0]===n[0])],o=e[r],a=n[r],i<=o&&o<=a||a<=o&&o<=i)}function wo(){}var Mo=[[],[[[1,1.5],[.5,1]]],[[[1.5,1],[1,1.5]]],[[[1.5,1],[.5,1]]],[[[1,.5],[1.5,1]]],[[[1,1.5],[.5,1]],[[1,.5],[1.5,1]]],[[[1,.5],[1,1.5]]],[[[1,.5],[.5,1]]],[[[.5,1],[1,.5]]],[[[1,1.5],[1,.5]]],[[[.5,1],[1,.5]],[[1.5,1],[1,1.5]]],[[[1.5,1],[1,.5]]],[[[.5,1],[1.5,1]]],[[[1,1.5],[1.5,1]]],[[[.5,1],[1,1.5]]],[]];function No(){var t=1,n=1,e=M,r=u;function i(t){var n=e(t);if(Array.isArray(n))n=n.slice().sort(yo);else{var r=s(t),i=r[0],a=r[1];n=w(i,a,n),n=g(Math.floor(i/n)*n,Math.floor(a/n)*n,n)}return n.map(function(n){return o(t,n)})}function o(e,i){var o=[],u=[];return function(e,r,i){var o,u,c,f,s,l,h=new Array,d=new Array;o=u=-1,f=e[0]>=r,Mo[f<<1].forEach(p);for(;++o=r,Mo[c|f<<1].forEach(p);Mo[f<<0].forEach(p);for(;++u=r,s=e[u*t]>=r,Mo[f<<1|s<<2].forEach(p);++o=r,l=s,s=e[u*t+o+1]>=r,Mo[c|f<<1|s<<2|l<<3].forEach(p);Mo[f|s<<3].forEach(p)}o=-1,s=e[u*t]>=r,Mo[s<<2].forEach(p);for(;++o=r,Mo[s<<2|l<<3].forEach(p);function p(t){var n,e,r=[t[0][0]+o,t[0][1]+u],c=[t[1][0]+o,t[1][1]+u],f=a(r),s=a(c);(n=d[f])?(e=h[s])?(delete d[n.end],delete h[e.start],n===e?(n.ring.push(c),i(n.ring)):h[n.start]=d[e.end]={start:n.start,end:e.end,ring:n.ring.concat(e.ring)}):(delete d[n.end],n.ring.push(c),d[n.end=s]=n):(n=h[s])?(e=d[f])?(delete h[n.start],delete d[e.end],n===e?(n.ring.push(c),i(n.ring)):h[e.start]=d[n.end]={start:e.start,end:n.end,ring:e.ring.concat(n.ring)}):(delete h[n.start],n.ring.unshift(r),h[n.start=f]=n):h[f]=d[s]={start:f,end:s,ring:[r,c]}}Mo[s<<3].forEach(p)}(e,i,function(t){r(t,e,i),function(t){for(var n=0,e=t.length,r=t[e-1][1]*t[0][0]-t[e-1][0]*t[0][1];++n0?o.push([t]):u.push(t)}),u.forEach(function(t){for(var n,e=0,r=o.length;e0&&a0&&u0&&o>0))throw new Error("invalid size");return t=r,n=o,i},i.thresholds=function(t){return arguments.length?(e="function"==typeof t?t:Array.isArray(t)?_o(go.call(t)):_o(t),i):e},i.smooth=function(t){return arguments.length?(r=t?u:wo,i):r===u},i}function To(t,n,e){for(var r=t.width,i=t.height,o=1+(e<<1),a=0;a=e&&(u>=o&&(c-=t.data[u-o+a*r]),n.data[u-e+a*r]=c/Math.min(u+1,r-1+o-u,o))}function Ao(t,n,e){for(var r=t.width,i=t.height,o=1+(e<<1),a=0;a=e&&(u>=o&&(c-=t.data[a+(u-o)*r]),n.data[a+(u-e)*r]=c/Math.min(u+1,i-1+o-u,o))}function So(t){return t[0]}function ko(t){return t[1]}function Eo(){return 1}var Co={},Po={},zo=34,Ro=10,Do=13;function qo(t){return new Function("d","return {"+t.map(function(t,n){return JSON.stringify(t)+": d["+n+"]"}).join(",")+"}")}function Lo(t){var n=Object.create(null),e=[];return t.forEach(function(t){for(var r in t)r in n||e.push(n[r]=r)}),e}function Uo(t,n){var e=t+"",r=e.length;return r9999?"+"+Uo(t,6):Uo(t,4)}(t.getUTCFullYear())+"-"+Uo(t.getUTCMonth()+1,2)+"-"+Uo(t.getUTCDate(),2)+(i?"T"+Uo(n,2)+":"+Uo(e,2)+":"+Uo(r,2)+"."+Uo(i,3)+"Z":r?"T"+Uo(n,2)+":"+Uo(e,2)+":"+Uo(r,2)+"Z":e||n?"T"+Uo(n,2)+":"+Uo(e,2)+"Z":"")}function Bo(t){var n=new RegExp('["'+t+"\n\r]"),e=t.charCodeAt(0);function r(t,n){var r,i=[],o=t.length,a=0,u=0,c=o<=0,f=!1;function s(){if(c)return Po;if(f)return f=!1,Co;var n,r,i=a;if(t.charCodeAt(i)===zo){for(;a++=o?c=!0:(r=t.charCodeAt(a++))===Ro?f=!0:r===Do&&(f=!0,t.charCodeAt(a)===Ro&&++a),t.slice(i+1,n-1).replace(/""/g,'"')}for(;a=(o=(v+y)/2))?v=o:y=o,(s=e>=(a=(g+_)/2))?g=a:_=a,i=d,!(d=d[l=s<<1|f]))return i[l]=p,t;if(u=+t._x.call(null,d.data),c=+t._y.call(null,d.data),n===u&&e===c)return p.next=d,i?i[l]=p:t._root=p,t;do{i=i?i[l]=new Array(4):t._root=new Array(4),(f=n>=(o=(v+y)/2))?v=o:y=o,(s=e>=(a=(g+_)/2))?g=a:_=a}while((l=s<<1|f)==(h=(c>=a)<<1|u>=o));return i[h]=d,i[l]=p,t}function da(t,n,e,r,i){this.node=t,this.x0=n,this.y0=e,this.x1=r,this.y1=i}function pa(t){return t[0]}function va(t){return t[1]}function ga(t,n,e){var r=new ya(null==n?pa:n,null==e?va:e,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function ya(t,n,e,r,i,o){this._x=t,this._y=n,this._x0=e,this._y0=r,this._x1=i,this._y1=o,this._root=void 0}function _a(t){for(var n={data:t.data},e=n;t=t.next;)e=e.next={data:t.data};return n}var ba=ga.prototype=ya.prototype;function ma(t){return t.x+t.vx}function xa(t){return t.y+t.vy}function wa(t){return t.index}function Ma(t,n){var e=t.get(n);if(!e)throw new Error("missing: "+n);return e}function Na(t){return t.x}function Ta(t){return t.y}ba.copy=function(){var t,n,e=new ya(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return e;if(!r.length)return e._root=_a(r),e;for(t=[{source:r,target:e._root=new Array(4)}];r=t.pop();)for(var i=0;i<4;++i)(n=r.source[i])&&(n.length?t.push({source:n,target:r.target[i]=new Array(4)}):r.target[i]=_a(n));return e},ba.add=function(t){var n=+this._x.call(null,t),e=+this._y.call(null,t);return ha(this.cover(n,e),n,e,t)},ba.addAll=function(t){var n,e,r,i,o=t.length,a=new Array(o),u=new Array(o),c=1/0,f=1/0,s=-1/0,l=-1/0;for(e=0;es&&(s=r),il&&(l=i));if(c>s||f>l)return this;for(this.cover(c,f).cover(s,l),e=0;et||t>=i||r>n||n>=o;)switch(u=(nh||(o=c.y0)>d||(a=c.x1)=y)<<1|t>=g)&&(c=p[p.length-1],p[p.length-1]=p[p.length-1-f],p[p.length-1-f]=c)}else{var _=t-+this._x.call(null,v.data),b=n-+this._y.call(null,v.data),m=_*_+b*b;if(m=(u=(p+g)/2))?p=u:g=u,(s=a>=(c=(v+y)/2))?v=c:y=c,n=d,!(d=d[l=s<<1|f]))return this;if(!d.length)break;(n[l+1&3]||n[l+2&3]||n[l+3&3])&&(e=n,h=l)}for(;d.data!==t;)if(r=d,!(d=d.next))return this;return(i=d.next)&&delete d.next,r?(i?r.next=i:delete r.next,this):n?(i?n[l]=i:delete n[l],(d=n[0]||n[1]||n[2]||n[3])&&d===(n[3]||n[2]||n[1]||n[0])&&!d.length&&(e?e[h]=d:this._root=d),this):(this._root=i,this)},ba.removeAll=function(t){for(var n=0,e=t.length;n1?r[0]+r.slice(2):r,+t.slice(e+1)]}function Ea(t){return(t=ka(Math.abs(t)))?t[1]:NaN}var Ca,Pa=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function za(t){return new Ra(t)}function Ra(t){if(!(n=Pa.exec(t)))throw new Error("invalid format: "+t);var n;this.fill=n[1]||" ",this.align=n[2]||">",this.sign=n[3]||"-",this.symbol=n[4]||"",this.zero=!!n[5],this.width=n[6]&&+n[6],this.comma=!!n[7],this.precision=n[8]&&+n[8].slice(1),this.trim=!!n[9],this.type=n[10]||""}function Da(t,n){var e=ka(t,n);if(!e)return t+"";var r=e[0],i=e[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}za.prototype=Ra.prototype,Ra.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(null==this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(null==this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};var qa={"%":function(t,n){return(100*t).toFixed(n)},b:function(t){return Math.round(t).toString(2)},c:function(t){return t+""},d:function(t){return Math.round(t).toString(10)},e:function(t,n){return t.toExponential(n)},f:function(t,n){return t.toFixed(n)},g:function(t,n){return t.toPrecision(n)},o:function(t){return Math.round(t).toString(8)},p:function(t,n){return Da(100*t,n)},r:Da,s:function(t,n){var e=ka(t,n);if(!e)return t+"";var r=e[0],i=e[1],o=i-(Ca=3*Math.max(-8,Math.min(8,Math.floor(i/3))))+1,a=r.length;return o===a?r:o>a?r+new Array(o-a+1).join("0"):o>0?r.slice(0,o)+"."+r.slice(o):"0."+new Array(1-o).join("0")+ka(t,Math.max(0,n+o-1))[0]},X:function(t){return Math.round(t).toString(16).toUpperCase()},x:function(t){return Math.round(t).toString(16)}};function La(t){return t}var Ua,Oa=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Ba(t){var n,e,r=t.grouping&&t.thousands?(n=t.grouping,e=t.thousands,function(t,r){for(var i=t.length,o=[],a=0,u=n[0],c=0;i>0&&u>0&&(c+u+1>r&&(u=Math.max(1,r-c)),o.push(t.substring(i-=u,i+u)),!((c+=u+1)>r));)u=n[a=(a+1)%n.length];return o.reverse().join(e)}):La,i=t.currency,o=t.decimal,a=t.numerals?function(t){return function(n){return n.replace(/[0-9]/g,function(n){return t[+n]})}}(t.numerals):La,u=t.percent||"%";function c(t){var n=(t=za(t)).fill,e=t.align,c=t.sign,f=t.symbol,s=t.zero,l=t.width,h=t.comma,d=t.precision,p=t.trim,v=t.type;"n"===v?(h=!0,v="g"):qa[v]||(null==d&&(d=12),p=!0,v="g"),(s||"0"===n&&"="===e)&&(s=!0,n="0",e="=");var g="$"===f?i[0]:"#"===f&&/[boxX]/.test(v)?"0"+v.toLowerCase():"",y="$"===f?i[1]:/[%p]/.test(v)?u:"",_=qa[v],b=/[defgprs%]/.test(v);function m(t){var i,u,f,m=g,x=y;if("c"===v)x=_(t)+x,t="";else{var w=(t=+t)<0;if(t=_(Math.abs(t),d),p&&(t=function(t){t:for(var n,e=t.length,r=1,i=-1;r0){if(!+t[r])break t;i=0}}return i>0?t.slice(0,i)+t.slice(n+1):t}(t)),w&&0==+t&&(w=!1),m=(w?"("===c?c:"-":"-"===c||"("===c?"":c)+m,x=("s"===v?Oa[8+Ca/3]:"")+x+(w&&"("===c?")":""),b)for(i=-1,u=t.length;++i(f=t.charCodeAt(i))||f>57){x=(46===f?o+t.slice(i+1):t.slice(i))+x,t=t.slice(0,i);break}}h&&!s&&(t=r(t,1/0));var M=m.length+t.length+x.length,N=M>1)+m+t+x+N.slice(M);break;default:t=N+m+t+x}return a(t)}return d=null==d?6:/[gprs]/.test(v)?Math.max(1,Math.min(21,d)):Math.max(0,Math.min(20,d)),m.toString=function(){return t+""},m}return{format:c,formatPrefix:function(t,n){var e=c(((t=za(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor(Ea(n)/3))),i=Math.pow(10,-r),o=Oa[8+r/3];return function(t){return e(i*t)+o}}}}function Ya(n){return Ua=Ba(n),t.format=Ua.format,t.formatPrefix=Ua.formatPrefix,Ua}function Fa(t){return Math.max(0,-Ea(Math.abs(t)))}function Ia(t,n){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor(Ea(n)/3)))-Ea(Math.abs(t)))}function Ha(t,n){return t=Math.abs(t),n=Math.abs(n)-t,Math.max(0,Ea(n)-Ea(t))+1}function ja(){return new Xa}function Xa(){this.reset()}Ya({decimal:".",thousands:",",grouping:[3],currency:["$",""]}),Xa.prototype={constructor:Xa,reset:function(){this.s=this.t=0},add:function(t){Va(Ga,t,this.t),Va(this,Ga.s,this.s),this.s?this.t+=Ga.t:this.s=Ga.t},valueOf:function(){return this.s}};var Ga=new Xa;function Va(t,n,e){var r=t.s=n+e,i=r-n,o=r-i;t.t=n-o+(e-i)}var $a=1e-6,Wa=1e-12,Za=Math.PI,Qa=Za/2,Ka=Za/4,Ja=2*Za,tu=180/Za,nu=Za/180,eu=Math.abs,ru=Math.atan,iu=Math.atan2,ou=Math.cos,au=Math.ceil,uu=Math.exp,cu=Math.log,fu=Math.pow,su=Math.sin,lu=Math.sign||function(t){return t>0?1:t<0?-1:0},hu=Math.sqrt,du=Math.tan;function pu(t){return t>1?0:t<-1?Za:Math.acos(t)}function vu(t){return t>1?Qa:t<-1?-Qa:Math.asin(t)}function gu(t){return(t=su(t/2))*t}function yu(){}function _u(t,n){t&&mu.hasOwnProperty(t.type)&&mu[t.type](t,n)}var bu={Feature:function(t,n){_u(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r=0?1:-1,i=r*e,o=ou(n=(n*=nu)/2+Ka),a=su(n),u=ku*a,c=Su*o+u*ou(i),f=u*r*su(i);Eu.add(iu(f,c)),Au=t,Su=o,ku=a}function Lu(t){return[iu(t[1],t[0]),vu(t[2])]}function Uu(t){var n=t[0],e=t[1],r=ou(e);return[r*ou(n),r*su(n),su(e)]}function Ou(t,n){return t[0]*n[0]+t[1]*n[1]+t[2]*n[2]}function Bu(t,n){return[t[1]*n[2]-t[2]*n[1],t[2]*n[0]-t[0]*n[2],t[0]*n[1]-t[1]*n[0]]}function Yu(t,n){t[0]+=n[0],t[1]+=n[1],t[2]+=n[2]}function Fu(t,n){return[t[0]*n,t[1]*n,t[2]*n]}function Iu(t){var n=hu(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=n,t[1]/=n,t[2]/=n}var Hu,ju,Xu,Gu,Vu,$u,Wu,Zu,Qu,Ku,Ju,tc,nc,ec,rc,ic,oc,ac,uc,cc,fc,sc,lc,hc,dc,pc,vc=ja(),gc={point:yc,lineStart:bc,lineEnd:mc,polygonStart:function(){gc.point=xc,gc.lineStart=wc,gc.lineEnd=Mc,vc.reset(),Pu.polygonStart()},polygonEnd:function(){Pu.polygonEnd(),gc.point=yc,gc.lineStart=bc,gc.lineEnd=mc,Eu<0?(Hu=-(Xu=180),ju=-(Gu=90)):vc>$a?Gu=90:vc<-$a&&(ju=-90),Ku[0]=Hu,Ku[1]=Xu},sphere:function(){Hu=-(Xu=180),ju=-(Gu=90)}};function yc(t,n){Qu.push(Ku=[Hu=t,Xu=t]),nGu&&(Gu=n)}function _c(t,n){var e=Uu([t*nu,n*nu]);if(Zu){var r=Bu(Zu,e),i=Bu([r[1],-r[0],0],r);Iu(i),i=Lu(i);var o,a=t-Vu,u=a>0?1:-1,c=i[0]*tu*u,f=eu(a)>180;f^(u*VuGu&&(Gu=o):f^(u*Vu<(c=(c+360)%360-180)&&cGu&&(Gu=n)),f?tNc(Hu,Xu)&&(Xu=t):Nc(t,Xu)>Nc(Hu,Xu)&&(Hu=t):Xu>=Hu?(tXu&&(Xu=t)):t>Vu?Nc(Hu,t)>Nc(Hu,Xu)&&(Xu=t):Nc(t,Xu)>Nc(Hu,Xu)&&(Hu=t)}else Qu.push(Ku=[Hu=t,Xu=t]);nGu&&(Gu=n),Zu=e,Vu=t}function bc(){gc.point=_c}function mc(){Ku[0]=Hu,Ku[1]=Xu,gc.point=yc,Zu=null}function xc(t,n){if(Zu){var e=t-Vu;vc.add(eu(e)>180?e+(e>0?360:-360):e)}else $u=t,Wu=n;Pu.point(t,n),_c(t,n)}function wc(){Pu.lineStart()}function Mc(){xc($u,Wu),Pu.lineEnd(),eu(vc)>$a&&(Hu=-(Xu=180)),Ku[0]=Hu,Ku[1]=Xu,Zu=null}function Nc(t,n){return(n-=t)<0?n+360:n}function Tc(t,n){return t[0]-n[0]}function Ac(t,n){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:nZa?t+Math.round(-t/Ja)*Ja:t,n]}function Fc(t,n,e){return(t%=Ja)?n||e?Bc(Hc(t),jc(n,e)):Hc(t):n||e?jc(n,e):Yc}function Ic(t){return function(n,e){return[(n+=t)>Za?n-Ja:n<-Za?n+Ja:n,e]}}function Hc(t){var n=Ic(t);return n.invert=Ic(-t),n}function jc(t,n){var e=ou(t),r=su(t),i=ou(n),o=su(n);function a(t,n){var a=ou(n),u=ou(t)*a,c=su(t)*a,f=su(n),s=f*e+u*r;return[iu(c*i-s*o,u*e-f*r),vu(s*i+c*o)]}return a.invert=function(t,n){var a=ou(n),u=ou(t)*a,c=su(t)*a,f=su(n),s=f*i-c*o;return[iu(c*i+f*o,u*e+s*r),vu(s*e-u*r)]},a}function Xc(t){function n(n){return(n=t(n[0]*nu,n[1]*nu))[0]*=tu,n[1]*=tu,n}return t=Fc(t[0]*nu,t[1]*nu,t.length>2?t[2]*nu:0),n.invert=function(n){return(n=t.invert(n[0]*nu,n[1]*nu))[0]*=tu,n[1]*=tu,n},n}function Gc(t,n,e,r,i,o){if(e){var a=ou(n),u=su(n),c=r*e;null==i?(i=n+r*Ja,o=n-c/2):(i=Vc(a,i),o=Vc(a,o),(r>0?io)&&(i+=r*Ja));for(var f,s=i;r>0?s>o:s1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}}function Wc(t,n){return eu(t[0]-n[0])<$a&&eu(t[1]-n[1])<$a}function Zc(t,n,e,r){this.x=t,this.z=n,this.o=e,this.e=r,this.v=!1,this.n=this.p=null}function Qc(t,n,e,r,i){var o,a,u=[],c=[];if(t.forEach(function(t){if(!((n=t.length-1)<=0)){var n,e,r=t[0],a=t[n];if(Wc(r,a)){for(i.lineStart(),o=0;o=0;--o)i.point((s=f[o])[0],s[1]);else r(h.x,h.p.x,-1,i);h=h.p}f=(h=h.o).z,d=!d}while(!h.v);i.lineEnd()}}}function Kc(t){if(n=t.length){for(var n,e,r=0,i=t[0];++r=0?1:-1,T=N*M,A=T>Za,S=v*x;if(Jc.add(iu(S*N*su(T),g*w+S*ou(T))),a+=A?M+N*Ja:M,A^d>=e^b>=e){var k=Bu(Uu(h),Uu(_));Iu(k);var E=Bu(o,k);Iu(E);var C=(A^M>=0?-1:1)*vu(E[2]);(r>C||r===C&&(k[0]||k[1]))&&(u+=A^M>=0?1:-1)}}return(a<-$a||a<$a&&Jc<-$a)^1&u}function ef(t,n,e,r){return function(i){var o,a,u,c=n(i),f=$c(),s=n(f),l=!1,h={point:d,lineStart:v,lineEnd:g,polygonStart:function(){h.point=y,h.lineStart=_,h.lineEnd=b,a=[],o=[]},polygonEnd:function(){h.point=d,h.lineStart=v,h.lineEnd=g,a=A(a);var t=nf(o,r);a.length?(l||(i.polygonStart(),l=!0),Qc(a,of,t,e,i)):t&&(l||(i.polygonStart(),l=!0),i.lineStart(),e(null,null,1,i),i.lineEnd()),l&&(i.polygonEnd(),l=!1),a=o=null},sphere:function(){i.polygonStart(),i.lineStart(),e(null,null,1,i),i.lineEnd(),i.polygonEnd()}};function d(n,e){t(n,e)&&i.point(n,e)}function p(t,n){c.point(t,n)}function v(){h.point=p,c.lineStart()}function g(){h.point=d,c.lineEnd()}function y(t,n){u.push([t,n]),s.point(t,n)}function _(){s.lineStart(),u=[]}function b(){y(u[0][0],u[0][1]),s.lineEnd();var t,n,e,r,c=s.clean(),h=f.result(),d=h.length;if(u.pop(),o.push(u),u=null,d)if(1&c){if((n=(e=h[0]).length-1)>0){for(l||(i.polygonStart(),l=!0),i.lineStart(),t=0;t1&&2&c&&h.push(h.pop().concat(h.shift())),a.push(h.filter(rf))}return h}}function rf(t){return t.length>1}function of(t,n){return((t=t.x)[0]<0?t[1]-Qa-$a:Qa-t[1])-((n=n.x)[0]<0?n[1]-Qa-$a:Qa-n[1])}var af=ef(function(){return!0},function(t){var n,e=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),n=1},point:function(o,a){var u=o>0?Za:-Za,c=eu(o-e);eu(c-Za)<$a?(t.point(e,r=(r+a)/2>0?Qa:-Qa),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),t.point(o,r),n=0):i!==u&&c>=Za&&(eu(e-i)<$a&&(e-=i*$a),eu(o-u)<$a&&(o-=u*$a),r=function(t,n,e,r){var i,o,a=su(t-e);return eu(a)>$a?ru((su(n)*(o=ou(r))*su(e)-su(r)*(i=ou(n))*su(t))/(i*o*a)):(n+r)/2}(e,r,o,a),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),n=0),t.point(e=o,r=a),i=u},lineEnd:function(){t.lineEnd(),e=r=NaN},clean:function(){return 2-n}}},function(t,n,e,r){var i;if(null==t)i=e*Qa,r.point(-Za,i),r.point(0,i),r.point(Za,i),r.point(Za,0),r.point(Za,-i),r.point(0,-i),r.point(-Za,-i),r.point(-Za,0),r.point(-Za,i);else if(eu(t[0]-n[0])>$a){var o=t[0]0,i=eu(n)>$a;function o(t,e){return ou(t)*ou(e)>n}function a(t,e,r){var i=[1,0,0],o=Bu(Uu(t),Uu(e)),a=Ou(o,o),u=o[0],c=a-u*u;if(!c)return!r&&t;var f=n*a/c,s=-n*u/c,l=Bu(i,o),h=Fu(i,f);Yu(h,Fu(o,s));var d=l,p=Ou(h,d),v=Ou(d,d),g=p*p-v*(Ou(h,h)-1);if(!(g<0)){var y=hu(g),_=Fu(d,(-p-y)/v);if(Yu(_,h),_=Lu(_),!r)return _;var b,m=t[0],x=e[0],w=t[1],M=e[1];x0^_[1]<(eu(_[0]-m)<$a?w:M):w<=_[1]&&_[1]<=M:N>Za^(m<=_[0]&&_[0]<=x)){var A=Fu(d,(-p+y)/v);return Yu(A,h),[_,Lu(A)]}}}function u(n,e){var i=r?t:Za-t,o=0;return n<-i?o|=1:n>i&&(o|=2),e<-i?o|=4:e>i&&(o|=8),o}return ef(o,function(t){var n,e,c,f,s;return{lineStart:function(){f=c=!1,s=1},point:function(l,h){var d,p=[l,h],v=o(l,h),g=r?v?0:u(l,h):v?u(l+(l<0?Za:-Za),h):0;if(!n&&(f=c=v)&&t.lineStart(),v!==c&&(!(d=a(n,p))||Wc(n,d)||Wc(p,d))&&(p[0]+=$a,p[1]+=$a,v=o(p[0],p[1])),v!==c)s=0,v?(t.lineStart(),d=a(p,n),t.point(d[0],d[1])):(d=a(n,p),t.point(d[0],d[1]),t.lineEnd()),n=d;else if(i&&n&&r^v){var y;g&e||!(y=a(p,n,!0))||(s=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1])))}!v||n&&Wc(n,p)||t.point(p[0],p[1]),n=p,c=v,e=g},lineEnd:function(){c&&t.lineEnd(),n=null},clean:function(){return s|(f&&c)<<1}}},function(n,r,i,o){Gc(o,t,e,i,n,r)},r?[0,-t]:[-Za,t-Za])}var cf=1e9,ff=-cf;function sf(t,n,e,r){function i(i,o){return t<=i&&i<=e&&n<=o&&o<=r}function o(i,o,u,f){var s=0,l=0;if(null==i||(s=a(i,u))!==(l=a(o,u))||c(i,o)<0^u>0)do{f.point(0===s||3===s?t:e,s>1?r:n)}while((s=(s+u+4)%4)!==l);else f.point(o[0],o[1])}function a(r,i){return eu(r[0]-t)<$a?i>0?0:3:eu(r[0]-e)<$a?i>0?2:1:eu(r[1]-n)<$a?i>0?1:0:i>0?3:2}function u(t,n){return c(t.x,n.x)}function c(t,n){var e=a(t,1),r=a(n,1);return e!==r?e-r:0===e?n[1]-t[1]:1===e?t[0]-n[0]:2===e?t[1]-n[1]:n[0]-t[0]}return function(a){var c,f,s,l,h,d,p,v,g,y,_,b=a,m=$c(),x={point:w,lineStart:function(){x.point=M,f&&f.push(s=[]);y=!0,g=!1,p=v=NaN},lineEnd:function(){c&&(M(l,h),d&&g&&m.rejoin(),c.push(m.result()));x.point=w,g&&b.lineEnd()},polygonStart:function(){b=m,c=[],f=[],_=!0},polygonEnd:function(){var n=function(){for(var n=0,e=0,i=f.length;er&&(h-o)*(r-a)>(d-a)*(t-o)&&++n:d<=r&&(h-o)*(r-a)<(d-a)*(t-o)&&--n;return n}(),e=_&&n,i=(c=A(c)).length;(e||i)&&(a.polygonStart(),e&&(a.lineStart(),o(null,null,1,a),a.lineEnd()),i&&Qc(c,u,n,o,a),a.polygonEnd());b=a,c=f=s=null}};function w(t,n){i(t,n)&&b.point(t,n)}function M(o,a){var u=i(o,a);if(f&&s.push([o,a]),y)l=o,h=a,d=u,y=!1,u&&(b.lineStart(),b.point(o,a));else if(u&&g)b.point(o,a);else{var c=[p=Math.max(ff,Math.min(cf,p)),v=Math.max(ff,Math.min(cf,v))],m=[o=Math.max(ff,Math.min(cf,o)),a=Math.max(ff,Math.min(cf,a))];!function(t,n,e,r,i,o){var a,u=t[0],c=t[1],f=0,s=1,l=n[0]-u,h=n[1]-c;if(a=e-u,l||!(a>0)){if(a/=l,l<0){if(a0){if(a>s)return;a>f&&(f=a)}if(a=i-u,l||!(a<0)){if(a/=l,l<0){if(a>s)return;a>f&&(f=a)}else if(l>0){if(a0)){if(a/=h,h<0){if(a0){if(a>s)return;a>f&&(f=a)}if(a=o-c,h||!(a<0)){if(a/=h,h<0){if(a>s)return;a>f&&(f=a)}else if(h>0){if(a0&&(t[0]=u+f*l,t[1]=c+f*h),s<1&&(n[0]=u+s*l,n[1]=c+s*h),!0}}}}}(c,m,t,n,e,r)?u&&(b.lineStart(),b.point(o,a),_=!1):(g||(b.lineStart(),b.point(c[0],c[1])),b.point(m[0],m[1]),u||b.lineEnd(),_=!1)}p=o,v=a,g=u}return x}}var lf,hf,df,pf=ja(),vf={sphere:yu,point:yu,lineStart:function(){vf.point=yf,vf.lineEnd=gf},lineEnd:yu,polygonStart:yu,polygonEnd:yu};function gf(){vf.point=vf.lineEnd=yu}function yf(t,n){lf=t*=nu,hf=su(n*=nu),df=ou(n),vf.point=_f}function _f(t,n){t*=nu;var e=su(n*=nu),r=ou(n),i=eu(t-lf),o=ou(i),a=r*su(i),u=df*e-hf*r*o,c=hf*e+df*r*o;pf.add(iu(hu(a*a+u*u),c)),lf=t,hf=e,df=r}function bf(t){return pf.reset(),Mu(t,vf),+pf}var mf=[null,null],xf={type:"LineString",coordinates:mf};function wf(t,n){return mf[0]=t,mf[1]=n,bf(xf)}var Mf={Feature:function(t,n){return Tf(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r0&&(i=wf(t[o],t[o-1]))>0&&e<=i&&r<=i&&(e+r-i)*(1-Math.pow((e-r)/i,2))$a}).map(c)).concat(g(au(o/d)*d,i,d).filter(function(t){return eu(t%v)>$a}).map(f))}return _.lines=function(){return b().map(function(t){return{type:"LineString",coordinates:t}})},_.outline=function(){return{type:"Polygon",coordinates:[s(r).concat(l(a).slice(1),s(e).reverse().slice(1),l(u).reverse().slice(1))]}},_.extent=function(t){return arguments.length?_.extentMajor(t).extentMinor(t):_.extentMinor()},_.extentMajor=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],u=+t[0][1],a=+t[1][1],r>e&&(t=r,r=e,e=t),u>a&&(t=u,u=a,a=t),_.precision(y)):[[r,u],[e,a]]},_.extentMinor=function(e){return arguments.length?(n=+e[0][0],t=+e[1][0],o=+e[0][1],i=+e[1][1],n>t&&(e=n,n=t,t=e),o>i&&(e=o,o=i,i=e),_.precision(y)):[[n,o],[t,i]]},_.step=function(t){return arguments.length?_.stepMajor(t).stepMinor(t):_.stepMinor()},_.stepMajor=function(t){return arguments.length?(p=+t[0],v=+t[1],_):[p,v]},_.stepMinor=function(t){return arguments.length?(h=+t[0],d=+t[1],_):[h,d]},_.precision=function(h){return arguments.length?(y=+h,c=Pf(o,i,90),f=zf(n,t,y),s=Pf(u,a,90),l=zf(r,e,y),_):y},_.extentMajor([[-180,-90+$a],[180,90-$a]]).extentMinor([[-180,-80-$a],[180,80+$a]])}function Df(t){return t}var qf,Lf,Uf,Of,Bf=ja(),Yf=ja(),Ff={point:yu,lineStart:yu,lineEnd:yu,polygonStart:function(){Ff.lineStart=If,Ff.lineEnd=Xf},polygonEnd:function(){Ff.lineStart=Ff.lineEnd=Ff.point=yu,Bf.add(eu(Yf)),Yf.reset()},result:function(){var t=Bf/2;return Bf.reset(),t}};function If(){Ff.point=Hf}function Hf(t,n){Ff.point=jf,qf=Uf=t,Lf=Of=n}function jf(t,n){Yf.add(Of*t-Uf*n),Uf=t,Of=n}function Xf(){jf(qf,Lf)}var Gf=1/0,Vf=Gf,$f=-Gf,Wf=$f,Zf={point:function(t,n){t$f&&($f=t);nWf&&(Wf=n)},lineStart:yu,lineEnd:yu,polygonStart:yu,polygonEnd:yu,result:function(){var t=[[Gf,Vf],[$f,Wf]];return $f=Wf=-(Vf=Gf=1/0),t}};var Qf,Kf,Jf,ts,ns=0,es=0,rs=0,is=0,os=0,as=0,us=0,cs=0,fs=0,ss={point:ls,lineStart:hs,lineEnd:vs,polygonStart:function(){ss.lineStart=gs,ss.lineEnd=ys},polygonEnd:function(){ss.point=ls,ss.lineStart=hs,ss.lineEnd=vs},result:function(){var t=fs?[us/fs,cs/fs]:as?[is/as,os/as]:rs?[ns/rs,es/rs]:[NaN,NaN];return ns=es=rs=is=os=as=us=cs=fs=0,t}};function ls(t,n){ns+=t,es+=n,++rs}function hs(){ss.point=ds}function ds(t,n){ss.point=ps,ls(Jf=t,ts=n)}function ps(t,n){var e=t-Jf,r=n-ts,i=hu(e*e+r*r);is+=i*(Jf+t)/2,os+=i*(ts+n)/2,as+=i,ls(Jf=t,ts=n)}function vs(){ss.point=ls}function gs(){ss.point=_s}function ys(){bs(Qf,Kf)}function _s(t,n){ss.point=bs,ls(Qf=Jf=t,Kf=ts=n)}function bs(t,n){var e=t-Jf,r=n-ts,i=hu(e*e+r*r);is+=i*(Jf+t)/2,os+=i*(ts+n)/2,as+=i,us+=(i=ts*t-Jf*n)*(Jf+t),cs+=i*(ts+n),fs+=3*i,ls(Jf=t,ts=n)}function ms(t){this._context=t}ms.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._context.moveTo(t,n),this._point=1;break;case 1:this._context.lineTo(t,n);break;default:this._context.moveTo(t+this._radius,n),this._context.arc(t,n,this._radius,0,Ja)}},result:yu};var xs,ws,Ms,Ns,Ts,As=ja(),Ss={point:yu,lineStart:function(){Ss.point=ks},lineEnd:function(){xs&&Es(ws,Ms),Ss.point=yu},polygonStart:function(){xs=!0},polygonEnd:function(){xs=null},result:function(){var t=+As;return As.reset(),t}};function ks(t,n){Ss.point=Es,ws=Ns=t,Ms=Ts=n}function Es(t,n){Ns-=t,Ts-=n,As.add(hu(Ns*Ns+Ts*Ts)),Ns=t,Ts=n}function Cs(){this._string=[]}function Ps(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function zs(t){return function(n){var e=new Rs;for(var r in t)e[r]=t[r];return e.stream=n,e}}function Rs(){}function Ds(t,n,e){var r=t.clipExtent&&t.clipExtent();return t.scale(150).translate([0,0]),null!=r&&t.clipExtent(null),Mu(e,t.stream(Zf)),n(Zf.result()),null!=r&&t.clipExtent(r),t}function qs(t,n,e){return Ds(t,function(e){var r=n[1][0]-n[0][0],i=n[1][1]-n[0][1],o=Math.min(r/(e[1][0]-e[0][0]),i/(e[1][1]-e[0][1])),a=+n[0][0]+(r-o*(e[1][0]+e[0][0]))/2,u=+n[0][1]+(i-o*(e[1][1]+e[0][1]))/2;t.scale(150*o).translate([a,u])},e)}function Ls(t,n,e){return qs(t,[[0,0],n],e)}function Us(t,n,e){return Ds(t,function(e){var r=+n,i=r/(e[1][0]-e[0][0]),o=(r-i*(e[1][0]+e[0][0]))/2,a=-i*e[0][1];t.scale(150*i).translate([o,a])},e)}function Os(t,n,e){return Ds(t,function(e){var r=+n,i=r/(e[1][1]-e[0][1]),o=-i*e[0][0],a=(r-i*(e[1][1]+e[0][1]))/2;t.scale(150*i).translate([o,a])},e)}Cs.prototype={_radius:4.5,_circle:Ps(4.5),pointRadius:function(t){return(t=+t)!==this._radius&&(this._radius=t,this._circle=null),this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._string.push("Z"),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._string.push("M",t,",",n),this._point=1;break;case 1:this._string.push("L",t,",",n);break;default:null==this._circle&&(this._circle=Ps(this._radius)),this._string.push("M",t,",",n,this._circle)}},result:function(){if(this._string.length){var t=this._string.join("");return this._string=[],t}return null}},Rs.prototype={constructor:Rs,point:function(t,n){this.stream.point(t,n)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};var Bs=16,Ys=ou(30*nu);function Fs(t,n){return+n?function(t,n){function e(r,i,o,a,u,c,f,s,l,h,d,p,v,g){var y=f-r,_=s-i,b=y*y+_*_;if(b>4*n&&v--){var m=a+h,x=u+d,w=c+p,M=hu(m*m+x*x+w*w),N=vu(w/=M),T=eu(eu(w)-1)<$a||eu(o-l)<$a?(o+l)/2:iu(x,m),A=t(T,N),S=A[0],k=A[1],E=S-r,C=k-i,P=_*E-y*C;(P*P/b>n||eu((y*E+_*C)/b-.5)>.3||a*h+u*d+c*p2?t[2]%360*nu:0,S()):[g*tu,y*tu,_*tu]},T.angle=function(t){return arguments.length?(b=t%360*nu,S()):b*tu},T.precision=function(t){return arguments.length?(a=Fs(u,N=t*t),k()):hu(N)},T.fitExtent=function(t,n){return qs(T,t,n)},T.fitSize=function(t,n){return Ls(T,t,n)},T.fitWidth=function(t,n){return Us(T,t,n)},T.fitHeight=function(t,n){return Os(T,t,n)},function(){return n=t.apply(this,arguments),T.invert=n.invert&&A,S()}}function Gs(t){var n=0,e=Za/3,r=Xs(t),i=r(n,e);return i.parallels=function(t){return arguments.length?r(n=t[0]*nu,e=t[1]*nu):[n*tu,e*tu]},i}function Vs(t,n){var e=su(t),r=(e+su(n))/2;if(eu(r)<$a)return function(t){var n=ou(t);function e(t,e){return[t*n,su(e)/n]}return e.invert=function(t,e){return[t/n,vu(e*n)]},e}(t);var i=1+e*(2*r-e),o=hu(i)/r;function a(t,n){var e=hu(i-2*r*su(n))/r;return[e*su(t*=r),o-e*ou(t)]}return a.invert=function(t,n){var e=o-n;return[iu(t,eu(e))/r*lu(e),vu((i-(t*t+e*e)*r*r)/(2*r))]},a}function $s(){return Gs(Vs).scale(155.424).center([0,33.6442])}function Ws(){return $s().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}function Zs(t){return function(n,e){var r=ou(n),i=ou(e),o=t(r*i);return[o*i*su(n),o*su(e)]}}function Qs(t){return function(n,e){var r=hu(n*n+e*e),i=t(r),o=su(i),a=ou(i);return[iu(n*o,r*a),vu(r&&e*o/r)]}}var Ks=Zs(function(t){return hu(2/(1+t))});Ks.invert=Qs(function(t){return 2*vu(t/2)});var Js=Zs(function(t){return(t=pu(t))&&t/su(t)});function tl(t,n){return[t,cu(du((Qa+n)/2))]}function nl(t){var n,e,r,i=js(t),o=i.center,a=i.scale,u=i.translate,c=i.clipExtent,f=null;function s(){var o=Za*a(),u=i(Xc(i.rotate()).invert([0,0]));return c(null==f?[[u[0]-o,u[1]-o],[u[0]+o,u[1]+o]]:t===tl?[[Math.max(u[0]-o,f),n],[Math.min(u[0]+o,e),r]]:[[f,Math.max(u[1]-o,n)],[e,Math.min(u[1]+o,r)]])}return i.scale=function(t){return arguments.length?(a(t),s()):a()},i.translate=function(t){return arguments.length?(u(t),s()):u()},i.center=function(t){return arguments.length?(o(t),s()):o()},i.clipExtent=function(t){return arguments.length?(null==t?f=n=e=r=null:(f=+t[0][0],n=+t[0][1],e=+t[1][0],r=+t[1][1]),s()):null==f?null:[[f,n],[e,r]]},s()}function el(t){return du((Qa+t)/2)}function rl(t,n){var e=ou(t),r=t===n?su(t):cu(e/ou(n))/cu(el(n)/el(t)),i=e*fu(el(t),r)/r;if(!r)return tl;function o(t,n){i>0?n<-Qa+$a&&(n=-Qa+$a):n>Qa-$a&&(n=Qa-$a);var e=i/fu(el(n),r);return[e*su(r*t),i-e*ou(r*t)]}return o.invert=function(t,n){var e=i-n,o=lu(r)*hu(t*t+e*e);return[iu(t,eu(e))/r*lu(e),2*ru(fu(i/o,1/r))-Qa]},o}function il(t,n){return[t,n]}function ol(t,n){var e=ou(t),r=t===n?su(t):(e-ou(n))/(n-t),i=e/r+t;if(eu(r)<$a)return il;function o(t,n){var e=i-n,o=r*t;return[e*su(o),i-e*ou(o)]}return o.invert=function(t,n){var e=i-n;return[iu(t,eu(e))/r*lu(e),i-lu(r)*hu(t*t+e*e)]},o}Js.invert=Qs(function(t){return t}),tl.invert=function(t,n){return[t,2*ru(uu(n))-Qa]},il.invert=il;var al=1.340264,ul=-.081106,cl=893e-6,fl=.003796,sl=hu(3)/2;function ll(t,n){var e=vu(sl*su(n)),r=e*e,i=r*r*r;return[t*ou(e)/(sl*(al+3*ul*r+i*(7*cl+9*fl*r))),e*(al+ul*r+i*(cl+fl*r))]}function hl(t,n){var e=ou(n),r=ou(t)*e;return[e*su(t)/r,su(n)/r]}function dl(t,n,e,r){return 1===t&&1===n&&0===e&&0===r?Df:zs({point:function(i,o){this.stream.point(i*t+e,o*n+r)}})}function pl(t,n){var e=n*n,r=e*e;return[t*(.8707-.131979*e+r*(r*(.003971*e-.001529*r)-.013791)),n*(1.007226+e*(.015085+r*(.028874*e-.044475-.005916*r)))]}function vl(t,n){return[ou(n)*su(t),su(n)]}function gl(t,n){var e=ou(n),r=1+ou(t)*e;return[e*su(t)/r,su(n)/r]}function yl(t,n){return[cu(du((Qa+n)/2)),-t]}function _l(t,n){return t.parent===n.parent?1:2}function bl(t,n){return t+n.x}function ml(t,n){return Math.max(t,n.y)}function xl(t){var n=0,e=t.children,r=e&&e.length;if(r)for(;--r>=0;)n+=e[r].value;else n=1;t.value=n}function wl(t,n){var e,r,i,o,a,u=new Al(t),c=+t.value&&(u.value=t.value),f=[u];for(null==n&&(n=Ml);e=f.pop();)if(c&&(e.value=+e.data.value),(i=n(e.data))&&(a=i.length))for(e.children=new Array(a),o=a-1;o>=0;--o)f.push(r=e.children[o]=new Al(i[o])),r.parent=e,r.depth=e.depth+1;return u.eachBefore(Tl)}function Ml(t){return t.children}function Nl(t){t.data=t.data.data}function Tl(t){var n=0;do{t.height=n}while((t=t.parent)&&t.height<++n)}function Al(t){this.data=t,this.depth=this.height=0,this.parent=null}ll.invert=function(t,n){for(var e,r=n,i=r*r,o=i*i*i,a=0;a<12&&(o=(i=(r-=e=(r*(al+ul*i+o*(cl+fl*i))-n)/(al+3*ul*i+o*(7*cl+9*fl*i)))*r)*i*i,!(eu(e)$a&&--i>0);return[t/(.8707+(o=r*r)*(o*(o*o*o*(.003971-.001529*o)-.013791)-.131979)),r]},vl.invert=Qs(vu),gl.invert=Qs(function(t){return 2*ru(t)}),yl.invert=function(t,n){return[-n,2*ru(uu(t))-Qa]},Al.prototype=wl.prototype={constructor:Al,count:function(){return this.eachAfter(xl)},each:function(t){var n,e,r,i,o=this,a=[o];do{for(n=a.reverse(),a=[];o=n.pop();)if(t(o),e=o.children)for(r=0,i=e.length;r=0;--e)i.push(n[e]);return this},sum:function(t){return this.eachAfter(function(n){for(var e=+t(n.data)||0,r=n.children,i=r&&r.length;--i>=0;)e+=r[i].value;n.value=e})},sort:function(t){return this.eachBefore(function(n){n.children&&n.children.sort(t)})},path:function(t){for(var n=this,e=function(t,n){if(t===n)return t;var e=t.ancestors(),r=n.ancestors(),i=null;for(t=e.pop(),n=r.pop();t===n;)i=t,t=e.pop(),n=r.pop();return i}(n,t),r=[n];n!==e;)n=n.parent,r.push(n);for(var i=r.length;t!==e;)r.splice(i,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,n=[t];t=t.parent;)n.push(t);return n},descendants:function(){var t=[];return this.each(function(n){t.push(n)}),t},leaves:function(){var t=[];return this.eachBefore(function(n){n.children||t.push(n)}),t},links:function(){var t=this,n=[];return t.each(function(e){e!==t&&n.push({source:e.parent,target:e})}),n},copy:function(){return wl(this).eachBefore(Nl)}};var Sl=Array.prototype.slice;function kl(t){for(var n,e,r=0,i=(t=function(t){for(var n,e,r=t.length;r;)e=Math.random()*r--|0,n=t[r],t[r]=t[e],t[e]=n;return t}(Sl.call(t))).length,o=[];r0&&e*e>r*r+i*i}function zl(t,n){for(var e=0;e(a*=a)?(r=(f+a-i)/(2*f),o=Math.sqrt(Math.max(0,a/f-r*r)),e.x=t.x-r*u-o*c,e.y=t.y-r*c+o*u):(r=(f+i-a)/(2*f),o=Math.sqrt(Math.max(0,i/f-r*r)),e.x=n.x+r*u-o*c,e.y=n.y+r*c+o*u)):(e.x=n.x+e.r,e.y=n.y)}function Ul(t,n){var e=t.r+n.r-1e-6,r=n.x-t.x,i=n.y-t.y;return e>0&&e*e>r*r+i*i}function Ol(t){var n=t._,e=t.next._,r=n.r+e.r,i=(n.x*e.r+e.x*n.r)/r,o=(n.y*e.r+e.y*n.r)/r;return i*i+o*o}function Bl(t){this._=t,this.next=null,this.previous=null}function Yl(t){if(!(i=t.length))return 0;var n,e,r,i,o,a,u,c,f,s,l;if((n=t[0]).x=0,n.y=0,!(i>1))return n.r;if(e=t[1],n.x=-e.r,e.x=n.r,e.y=0,!(i>2))return n.r+e.r;Ll(e,n,r=t[2]),n=new Bl(n),e=new Bl(e),r=new Bl(r),n.next=r.previous=e,e.next=n.previous=r,r.next=e.previous=n;t:for(u=3;uh&&(h=u),g=s*s*v,(d=Math.max(h/g,g/l))>p){s-=u;break}p=d}y.push(a={value:s,dice:c1?n:1)},e}(fh);var hh=function t(n){function e(t,e,r,i,o){if((a=t._squarify)&&a.ratio===n)for(var a,u,c,f,s,l=-1,h=a.length,d=t.value;++l1?n:1)},e}(fh);function dh(t,n,e){return(n[0]-t[0])*(e[1]-t[1])-(n[1]-t[1])*(e[0]-t[0])}function ph(t,n){return t[0]-n[0]||t[1]-n[1]}function vh(t){for(var n=t.length,e=[0,1],r=2,i=2;i1&&dh(t[e[r-2]],t[e[r-1]],t[i])<=0;)--r;e[r++]=i}return e.slice(0,r)}function gh(){return Math.random()}var yh=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,1===arguments.length?(e=t,t=0):e-=t,function(){return n()*e+t}}return e.source=t,e}(gh),_h=function t(n){function e(t,e){var r,i;return t=null==t?0:+t,e=null==e?1:+e,function(){var o;if(null!=r)o=r,r=null;else do{r=2*n()-1,o=2*n()-1,i=r*r+o*o}while(!i||i>1);return t+e*o*Math.sqrt(-2*Math.log(i)/i)}}return e.source=t,e}(gh),bh=function t(n){function e(){var t=_h.source(n).apply(this,arguments);return function(){return Math.exp(t())}}return e.source=t,e}(gh),mh=function t(n){function e(t){return function(){for(var e=0,r=0;rr&&(n=e,e=r,r=n),function(t){return Math.max(e,Math.min(r,t))}}function Lh(t,n,e){var r=t[0],i=t[1],o=n[0],a=n[1];return i2?Uh:Lh,i=o=null,l}function l(n){return isNaN(n=+n)?e:(i||(i=r(a.map(t),u,c)))(t(f(n)))}return l.invert=function(e){return f(n((o||(o=r(u,a.map(t),be)))(e)))},l.domain=function(t){return arguments.length?(a=Ah.call(t,Ph),f===Rh||(f=qh(a)),s()):a.slice()},l.range=function(t){return arguments.length?(u=Sh.call(t),s()):u.slice()},l.rangeRound=function(t){return u=Sh.call(t),c=Te,s()},l.clamp=function(t){return arguments.length?(f=t?qh(a):Rh,l):f!==Rh},l.interpolate=function(t){return arguments.length?(c=t,s()):c},l.unknown=function(t){return arguments.length?(e=t,l):e},function(e,r){return t=e,n=r,s()}}function Yh(t,n){return Bh()(t,n)}function Fh(n,e,r,i){var o,a=w(n,e,r);switch((i=za(null==i?",f":i)).type){case"s":var u=Math.max(Math.abs(n),Math.abs(e));return null!=i.precision||isNaN(o=Ia(a,u))||(i.precision=o),t.formatPrefix(i,u);case"":case"e":case"g":case"p":case"r":null!=i.precision||isNaN(o=Ha(a,Math.max(Math.abs(n),Math.abs(e))))||(i.precision=o-("e"===i.type));break;case"f":case"%":null!=i.precision||isNaN(o=Fa(a))||(i.precision=o-2*("%"===i.type))}return t.format(i)}function Ih(t){var n=t.domain;return t.ticks=function(t){var e=n();return m(e[0],e[e.length-1],null==t?10:t)},t.tickFormat=function(t,e){var r=n();return Fh(r[0],r[r.length-1],null==t?10:t,e)},t.nice=function(e){null==e&&(e=10);var r,i=n(),o=0,a=i.length-1,u=i[o],c=i[a];return c0?r=x(u=Math.floor(u/r)*r,c=Math.ceil(c/r)*r,e):r<0&&(r=x(u=Math.ceil(u*r)/r,c=Math.floor(c*r)/r,e)),r>0?(i[o]=Math.floor(u/r)*r,i[a]=Math.ceil(c/r)*r,n(i)):r<0&&(i[o]=Math.ceil(u*r)/r,i[a]=Math.floor(c*r)/r,n(i)),t},t}function Hh(t,n){var e,r=0,i=(t=t.slice()).length-1,o=t[r],a=t[i];return a0){for(;hc)break;v.push(l)}}else for(;h=1;--s)if(!((l=f*s)c)break;v.push(l)}}else v=m(h,d,Math.min(d-h,p)).map(r);return n?v.reverse():v},i.tickFormat=function(n,o){if(null==o&&(o=10===a?".0e":","),"function"!=typeof o&&(o=t.format(o)),n===1/0)return o;null==n&&(n=10);var u=Math.max(1,a*n/i.ticks().length);return function(t){var n=t/r(Math.round(e(t)));return n*a0))return u;do{u.push(a=new Date(+e)),n(e,o),t(e)}while(a=n)for(;t(n),!e(n);)n.setTime(n-1)},function(t,r){if(t>=t)if(r<0)for(;++r<=0;)for(;n(t,-1),!e(t););else for(;--r>=0;)for(;n(t,1),!e(t););})},e&&(i.count=function(n,r){return od.setTime(+n),ad.setTime(+r),t(od),t(ad),Math.floor(e(od,ad))},i.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?i.filter(r?function(n){return r(n)%t==0}:function(n){return i.count(0,n)%t==0}):i:null}),i}var cd=ud(function(){},function(t,n){t.setTime(+t+n)},function(t,n){return n-t});cd.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?ud(function(n){n.setTime(Math.floor(n/t)*t)},function(n,e){n.setTime(+n+e*t)},function(n,e){return(e-n)/t}):cd:null};var fd=cd.range,sd=6e4,ld=6048e5,hd=ud(function(t){t.setTime(t-t.getMilliseconds())},function(t,n){t.setTime(+t+1e3*n)},function(t,n){return(n-t)/1e3},function(t){return t.getUTCSeconds()}),dd=hd.range,pd=ud(function(t){t.setTime(t-t.getMilliseconds()-1e3*t.getSeconds())},function(t,n){t.setTime(+t+n*sd)},function(t,n){return(n-t)/sd},function(t){return t.getMinutes()}),vd=pd.range,gd=ud(function(t){t.setTime(t-t.getMilliseconds()-1e3*t.getSeconds()-t.getMinutes()*sd)},function(t,n){t.setTime(+t+36e5*n)},function(t,n){return(n-t)/36e5},function(t){return t.getHours()}),yd=gd.range,_d=ud(function(t){t.setHours(0,0,0,0)},function(t,n){t.setDate(t.getDate()+n)},function(t,n){return(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*sd)/864e5},function(t){return t.getDate()-1}),bd=_d.range;function md(t){return ud(function(n){n.setDate(n.getDate()-(n.getDay()+7-t)%7),n.setHours(0,0,0,0)},function(t,n){t.setDate(t.getDate()+7*n)},function(t,n){return(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*sd)/ld})}var xd=md(0),wd=md(1),Md=md(2),Nd=md(3),Td=md(4),Ad=md(5),Sd=md(6),kd=xd.range,Ed=wd.range,Cd=Md.range,Pd=Nd.range,zd=Td.range,Rd=Ad.range,Dd=Sd.range,qd=ud(function(t){t.setDate(1),t.setHours(0,0,0,0)},function(t,n){t.setMonth(t.getMonth()+n)},function(t,n){return n.getMonth()-t.getMonth()+12*(n.getFullYear()-t.getFullYear())},function(t){return t.getMonth()}),Ld=qd.range,Ud=ud(function(t){t.setMonth(0,1),t.setHours(0,0,0,0)},function(t,n){t.setFullYear(t.getFullYear()+n)},function(t,n){return n.getFullYear()-t.getFullYear()},function(t){return t.getFullYear()});Ud.every=function(t){return isFinite(t=Math.floor(t))&&t>0?ud(function(n){n.setFullYear(Math.floor(n.getFullYear()/t)*t),n.setMonth(0,1),n.setHours(0,0,0,0)},function(n,e){n.setFullYear(n.getFullYear()+e*t)}):null};var Od=Ud.range,Bd=ud(function(t){t.setUTCSeconds(0,0)},function(t,n){t.setTime(+t+n*sd)},function(t,n){return(n-t)/sd},function(t){return t.getUTCMinutes()}),Yd=Bd.range,Fd=ud(function(t){t.setUTCMinutes(0,0,0)},function(t,n){t.setTime(+t+36e5*n)},function(t,n){return(n-t)/36e5},function(t){return t.getUTCHours()}),Id=Fd.range,Hd=ud(function(t){t.setUTCHours(0,0,0,0)},function(t,n){t.setUTCDate(t.getUTCDate()+n)},function(t,n){return(n-t)/864e5},function(t){return t.getUTCDate()-1}),jd=Hd.range;function Xd(t){return ud(function(n){n.setUTCDate(n.getUTCDate()-(n.getUTCDay()+7-t)%7),n.setUTCHours(0,0,0,0)},function(t,n){t.setUTCDate(t.getUTCDate()+7*n)},function(t,n){return(n-t)/ld})}var Gd=Xd(0),Vd=Xd(1),$d=Xd(2),Wd=Xd(3),Zd=Xd(4),Qd=Xd(5),Kd=Xd(6),Jd=Gd.range,tp=Vd.range,np=$d.range,ep=Wd.range,rp=Zd.range,ip=Qd.range,op=Kd.range,ap=ud(function(t){t.setUTCDate(1),t.setUTCHours(0,0,0,0)},function(t,n){t.setUTCMonth(t.getUTCMonth()+n)},function(t,n){return n.getUTCMonth()-t.getUTCMonth()+12*(n.getUTCFullYear()-t.getUTCFullYear())},function(t){return t.getUTCMonth()}),up=ap.range,cp=ud(function(t){t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},function(t,n){t.setUTCFullYear(t.getUTCFullYear()+n)},function(t,n){return n.getUTCFullYear()-t.getUTCFullYear()},function(t){return t.getUTCFullYear()});cp.every=function(t){return isFinite(t=Math.floor(t))&&t>0?ud(function(n){n.setUTCFullYear(Math.floor(n.getUTCFullYear()/t)*t),n.setUTCMonth(0,1),n.setUTCHours(0,0,0,0)},function(n,e){n.setUTCFullYear(n.getUTCFullYear()+e*t)}):null};var fp=cp.range;function sp(t){if(0<=t.y&&t.y<100){var n=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return n.setFullYear(t.y),n}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function lp(t){if(0<=t.y&&t.y<100){var n=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return n.setUTCFullYear(t.y),n}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function hp(t){return{y:t,m:0,d:1,H:0,M:0,S:0,L:0}}function dp(t){var n=t.dateTime,e=t.date,r=t.time,i=t.periods,o=t.days,a=t.shortDays,u=t.months,c=t.shortMonths,f=xp(i),s=wp(i),l=xp(o),h=wp(o),d=xp(a),p=wp(a),v=xp(u),g=wp(u),y=xp(c),_=wp(c),b={a:function(t){return a[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return c[t.getMonth()]},B:function(t){return u[t.getMonth()]},c:null,d:Ip,e:Ip,f:Vp,H:Hp,I:jp,j:Xp,L:Gp,m:$p,M:Wp,p:function(t){return i[+(t.getHours()>=12)]},Q:Mv,s:Nv,S:Zp,u:Qp,U:Kp,V:Jp,w:tv,W:nv,x:null,X:null,y:ev,Y:rv,Z:iv,"%":wv},m={a:function(t){return a[t.getUTCDay()]},A:function(t){return o[t.getUTCDay()]},b:function(t){return c[t.getUTCMonth()]},B:function(t){return u[t.getUTCMonth()]},c:null,d:ov,e:ov,f:sv,H:av,I:uv,j:cv,L:fv,m:lv,M:hv,p:function(t){return i[+(t.getUTCHours()>=12)]},Q:Mv,s:Nv,S:dv,u:pv,U:vv,V:gv,w:yv,W:_v,x:null,X:null,y:bv,Y:mv,Z:xv,"%":wv},x={a:function(t,n,e){var r=d.exec(n.slice(e));return r?(t.w=p[r[0].toLowerCase()],e+r[0].length):-1},A:function(t,n,e){var r=l.exec(n.slice(e));return r?(t.w=h[r[0].toLowerCase()],e+r[0].length):-1},b:function(t,n,e){var r=y.exec(n.slice(e));return r?(t.m=_[r[0].toLowerCase()],e+r[0].length):-1},B:function(t,n,e){var r=v.exec(n.slice(e));return r?(t.m=g[r[0].toLowerCase()],e+r[0].length):-1},c:function(t,e,r){return N(t,n,e,r)},d:zp,e:zp,f:Op,H:Dp,I:Dp,j:Rp,L:Up,m:Pp,M:qp,p:function(t,n,e){var r=f.exec(n.slice(e));return r?(t.p=s[r[0].toLowerCase()],e+r[0].length):-1},Q:Yp,s:Fp,S:Lp,u:Np,U:Tp,V:Ap,w:Mp,W:Sp,x:function(t,n,r){return N(t,e,n,r)},X:function(t,n,e){return N(t,r,n,e)},y:Ep,Y:kp,Z:Cp,"%":Bp};function w(t,n){return function(e){var r,i,o,a=[],u=-1,c=0,f=t.length;for(e instanceof Date||(e=new Date(+e));++u53)return null;"w"in o||(o.w=1),"Z"in o?(i=(r=lp(hp(o.y))).getUTCDay(),r=i>4||0===i?Vd.ceil(r):Vd(r),r=Hd.offset(r,7*(o.V-1)),o.y=r.getUTCFullYear(),o.m=r.getUTCMonth(),o.d=r.getUTCDate()+(o.w+6)%7):(i=(r=n(hp(o.y))).getDay(),r=i>4||0===i?wd.ceil(r):wd(r),r=_d.offset(r,7*(o.V-1)),o.y=r.getFullYear(),o.m=r.getMonth(),o.d=r.getDate()+(o.w+6)%7)}else("W"in o||"U"in o)&&("w"in o||(o.w="u"in o?o.u%7:"W"in o?1:0),i="Z"in o?lp(hp(o.y)).getUTCDay():n(hp(o.y)).getDay(),o.m=0,o.d="W"in o?(o.w+6)%7+7*o.W-(i+5)%7:o.w+7*o.U-(i+6)%7);return"Z"in o?(o.H+=o.Z/100|0,o.M+=o.Z%100,lp(o)):n(o)}}function N(t,n,e,r){for(var i,o,a=0,u=n.length,c=e.length;a=c)return-1;if(37===(i=n.charCodeAt(a++))){if(i=n.charAt(a++),!(o=x[i in vp?n.charAt(a++):i])||(r=o(t,e,r))<0)return-1}else if(i!=e.charCodeAt(r++))return-1}return r}return b.x=w(e,b),b.X=w(r,b),b.c=w(n,b),m.x=w(e,m),m.X=w(r,m),m.c=w(n,m),{format:function(t){var n=w(t+="",b);return n.toString=function(){return t},n},parse:function(t){var n=M(t+="",sp);return n.toString=function(){return t},n},utcFormat:function(t){var n=w(t+="",m);return n.toString=function(){return t},n},utcParse:function(t){var n=M(t,lp);return n.toString=function(){return t},n}}}var pp,vp={"-":"",_:" ",0:"0"},gp=/^\s*\d+/,yp=/^%/,_p=/[\\^$*+?|[\]().{}]/g;function bp(t,n,e){var r=t<0?"-":"",i=(r?-t:t)+"",o=i.length;return r+(o68?1900:2e3),e+r[0].length):-1}function Cp(t,n,e){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(n.slice(e,e+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),e+r[0].length):-1}function Pp(t,n,e){var r=gp.exec(n.slice(e,e+2));return r?(t.m=r[0]-1,e+r[0].length):-1}function zp(t,n,e){var r=gp.exec(n.slice(e,e+2));return r?(t.d=+r[0],e+r[0].length):-1}function Rp(t,n,e){var r=gp.exec(n.slice(e,e+3));return r?(t.m=0,t.d=+r[0],e+r[0].length):-1}function Dp(t,n,e){var r=gp.exec(n.slice(e,e+2));return r?(t.H=+r[0],e+r[0].length):-1}function qp(t,n,e){var r=gp.exec(n.slice(e,e+2));return r?(t.M=+r[0],e+r[0].length):-1}function Lp(t,n,e){var r=gp.exec(n.slice(e,e+2));return r?(t.S=+r[0],e+r[0].length):-1}function Up(t,n,e){var r=gp.exec(n.slice(e,e+3));return r?(t.L=+r[0],e+r[0].length):-1}function Op(t,n,e){var r=gp.exec(n.slice(e,e+6));return r?(t.L=Math.floor(r[0]/1e3),e+r[0].length):-1}function Bp(t,n,e){var r=yp.exec(n.slice(e,e+1));return r?e+r[0].length:-1}function Yp(t,n,e){var r=gp.exec(n.slice(e));return r?(t.Q=+r[0],e+r[0].length):-1}function Fp(t,n,e){var r=gp.exec(n.slice(e));return r?(t.Q=1e3*+r[0],e+r[0].length):-1}function Ip(t,n){return bp(t.getDate(),n,2)}function Hp(t,n){return bp(t.getHours(),n,2)}function jp(t,n){return bp(t.getHours()%12||12,n,2)}function Xp(t,n){return bp(1+_d.count(Ud(t),t),n,3)}function Gp(t,n){return bp(t.getMilliseconds(),n,3)}function Vp(t,n){return Gp(t,n)+"000"}function $p(t,n){return bp(t.getMonth()+1,n,2)}function Wp(t,n){return bp(t.getMinutes(),n,2)}function Zp(t,n){return bp(t.getSeconds(),n,2)}function Qp(t){var n=t.getDay();return 0===n?7:n}function Kp(t,n){return bp(xd.count(Ud(t),t),n,2)}function Jp(t,n){var e=t.getDay();return t=e>=4||0===e?Td(t):Td.ceil(t),bp(Td.count(Ud(t),t)+(4===Ud(t).getDay()),n,2)}function tv(t){return t.getDay()}function nv(t,n){return bp(wd.count(Ud(t),t),n,2)}function ev(t,n){return bp(t.getFullYear()%100,n,2)}function rv(t,n){return bp(t.getFullYear()%1e4,n,4)}function iv(t){var n=t.getTimezoneOffset();return(n>0?"-":(n*=-1,"+"))+bp(n/60|0,"0",2)+bp(n%60,"0",2)}function ov(t,n){return bp(t.getUTCDate(),n,2)}function av(t,n){return bp(t.getUTCHours(),n,2)}function uv(t,n){return bp(t.getUTCHours()%12||12,n,2)}function cv(t,n){return bp(1+Hd.count(cp(t),t),n,3)}function fv(t,n){return bp(t.getUTCMilliseconds(),n,3)}function sv(t,n){return fv(t,n)+"000"}function lv(t,n){return bp(t.getUTCMonth()+1,n,2)}function hv(t,n){return bp(t.getUTCMinutes(),n,2)}function dv(t,n){return bp(t.getUTCSeconds(),n,2)}function pv(t){var n=t.getUTCDay();return 0===n?7:n}function vv(t,n){return bp(Gd.count(cp(t),t),n,2)}function gv(t,n){var e=t.getUTCDay();return t=e>=4||0===e?Zd(t):Zd.ceil(t),bp(Zd.count(cp(t),t)+(4===cp(t).getUTCDay()),n,2)}function yv(t){return t.getUTCDay()}function _v(t,n){return bp(Vd.count(cp(t),t),n,2)}function bv(t,n){return bp(t.getUTCFullYear()%100,n,2)}function mv(t,n){return bp(t.getUTCFullYear()%1e4,n,4)}function xv(){return"+0000"}function wv(){return"%"}function Mv(t){return+t}function Nv(t){return Math.floor(+t/1e3)}function Tv(n){return pp=dp(n),t.timeFormat=pp.format,t.timeParse=pp.parse,t.utcFormat=pp.utcFormat,t.utcParse=pp.utcParse,pp}Tv({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});var Av=Date.prototype.toISOString?function(t){return t.toISOString()}:t.utcFormat("%Y-%m-%dT%H:%M:%S.%LZ");var Sv=+new Date("2000-01-01T00:00:00.000Z")?function(t){var n=new Date(t);return isNaN(n)?null:n}:t.utcParse("%Y-%m-%dT%H:%M:%S.%LZ"),kv=1e3,Ev=60*kv,Cv=60*Ev,Pv=24*Cv,zv=7*Pv,Rv=30*Pv,Dv=365*Pv;function qv(t){return new Date(t)}function Lv(t){return t instanceof Date?+t:+new Date(+t)}function Uv(t,n,r,i,o,a,u,c,f){var s=Yh(Rh,Rh),l=s.invert,h=s.domain,d=f(".%L"),p=f(":%S"),v=f("%I:%M"),g=f("%I %p"),y=f("%a %d"),_=f("%b %d"),b=f("%B"),m=f("%Y"),x=[[u,1,kv],[u,5,5*kv],[u,15,15*kv],[u,30,30*kv],[a,1,Ev],[a,5,5*Ev],[a,15,15*Ev],[a,30,30*Ev],[o,1,Cv],[o,3,3*Cv],[o,6,6*Cv],[o,12,12*Cv],[i,1,Pv],[i,2,2*Pv],[r,1,zv],[n,1,Rv],[n,3,3*Rv],[t,1,Dv]];function M(e){return(u(e)=1?My:t<=-1?-My:Math.asin(t)}function Ay(t){return t.innerRadius}function Sy(t){return t.outerRadius}function ky(t){return t.startAngle}function Ey(t){return t.endAngle}function Cy(t){return t&&t.padAngle}function Py(t,n,e,r,i,o,a){var u=t-e,c=n-r,f=(a?o:-o)/my(u*u+c*c),s=f*c,l=-f*u,h=t+s,d=n+l,p=e+s,v=r+l,g=(h+p)/2,y=(d+v)/2,_=p-h,b=v-d,m=_*_+b*b,x=i-o,w=h*v-p*d,M=(b<0?-1:1)*my(yy(0,x*x*m-w*w)),N=(w*b-_*M)/m,T=(-w*_-b*M)/m,A=(w*b+_*M)/m,S=(-w*_+b*M)/m,k=N-g,E=T-y,C=A-g,P=S-y;return k*k+E*E>C*C+P*P&&(N=A,T=S),{cx:N,cy:T,x01:-s,y01:-l,x11:N*(i/x-1),y11:T*(i/x-1)}}function zy(t){this._context=t}function Ry(t){return new zy(t)}function Dy(t){return t[0]}function qy(t){return t[1]}function Ly(){var t=Dy,n=qy,e=dy(!0),r=null,i=Ry,o=null;function a(a){var u,c,f,s=a.length,l=!1;for(null==r&&(o=i(f=to())),u=0;u<=s;++u)!(u=s;--l)u.point(g[l],y[l]);u.lineEnd(),u.areaEnd()}v&&(g[f]=+t(h,f,c),y[f]=+e(h,f,c),u.point(n?+n(h,f,c):g[f],r?+r(h,f,c):y[f]))}if(d)return u=null,d+""||null}function f(){return Ly().defined(i).curve(a).context(o)}return c.x=function(e){return arguments.length?(t="function"==typeof e?e:dy(+e),n=null,c):t},c.x0=function(n){return arguments.length?(t="function"==typeof n?n:dy(+n),c):t},c.x1=function(t){return arguments.length?(n=null==t?null:"function"==typeof t?t:dy(+t),c):n},c.y=function(t){return arguments.length?(e="function"==typeof t?t:dy(+t),r=null,c):e},c.y0=function(t){return arguments.length?(e="function"==typeof t?t:dy(+t),c):e},c.y1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:dy(+t),c):r},c.lineX0=c.lineY0=function(){return f().x(t).y(e)},c.lineY1=function(){return f().x(t).y(r)},c.lineX1=function(){return f().x(n).y(e)},c.defined=function(t){return arguments.length?(i="function"==typeof t?t:dy(!!t),c):i},c.curve=function(t){return arguments.length?(a=t,null!=o&&(u=a(o)),c):a},c.context=function(t){return arguments.length?(null==t?o=u=null:u=a(o=t),c):o},c}function Oy(t,n){return nt?1:n>=t?0:NaN}function By(t){return t}zy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:this._context.lineTo(t,n)}}};var Yy=Iy(Ry);function Fy(t){this._curve=t}function Iy(t){function n(n){return new Fy(t(n))}return n._curve=t,n}function Hy(t){var n=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?n(Iy(t)):n()._curve},t}function jy(){return Hy(Ly().curve(Yy))}function Xy(){var t=Uy().curve(Yy),n=t.curve,e=t.lineX0,r=t.lineX1,i=t.lineY0,o=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return Hy(e())},delete t.lineX0,t.lineEndAngle=function(){return Hy(r())},delete t.lineX1,t.lineInnerRadius=function(){return Hy(i())},delete t.lineY0,t.lineOuterRadius=function(){return Hy(o())},delete t.lineY1,t.curve=function(t){return arguments.length?n(Iy(t)):n()._curve},t}function Gy(t,n){return[(n=+n)*Math.cos(t-=Math.PI/2),n*Math.sin(t)]}Fy.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,n){this._curve.point(n*Math.sin(t),n*-Math.cos(t))}};var Vy=Array.prototype.slice;function $y(t){return t.source}function Wy(t){return t.target}function Zy(t){var n=$y,e=Wy,r=Dy,i=qy,o=null;function a(){var a,u=Vy.call(arguments),c=n.apply(this,u),f=e.apply(this,u);if(o||(o=a=to()),t(o,+r.apply(this,(u[0]=c,u)),+i.apply(this,u),+r.apply(this,(u[0]=f,u)),+i.apply(this,u)),a)return o=null,a+""||null}return a.source=function(t){return arguments.length?(n=t,a):n},a.target=function(t){return arguments.length?(e=t,a):e},a.x=function(t){return arguments.length?(r="function"==typeof t?t:dy(+t),a):r},a.y=function(t){return arguments.length?(i="function"==typeof t?t:dy(+t),a):i},a.context=function(t){return arguments.length?(o=null==t?null:t,a):o},a}function Qy(t,n,e,r,i){t.moveTo(n,e),t.bezierCurveTo(n=(n+r)/2,e,n,i,r,i)}function Ky(t,n,e,r,i){t.moveTo(n,e),t.bezierCurveTo(n,e=(e+i)/2,r,e,r,i)}function Jy(t,n,e,r,i){var o=Gy(n,e),a=Gy(n,e=(e+i)/2),u=Gy(r,e),c=Gy(r,i);t.moveTo(o[0],o[1]),t.bezierCurveTo(a[0],a[1],u[0],u[1],c[0],c[1])}var t_={draw:function(t,n){var e=Math.sqrt(n/wy);t.moveTo(e,0),t.arc(0,0,e,0,Ny)}},n_={draw:function(t,n){var e=Math.sqrt(n/5)/2;t.moveTo(-3*e,-e),t.lineTo(-e,-e),t.lineTo(-e,-3*e),t.lineTo(e,-3*e),t.lineTo(e,-e),t.lineTo(3*e,-e),t.lineTo(3*e,e),t.lineTo(e,e),t.lineTo(e,3*e),t.lineTo(-e,3*e),t.lineTo(-e,e),t.lineTo(-3*e,e),t.closePath()}},e_=Math.sqrt(1/3),r_=2*e_,i_={draw:function(t,n){var e=Math.sqrt(n/r_),r=e*e_;t.moveTo(0,-e),t.lineTo(r,0),t.lineTo(0,e),t.lineTo(-r,0),t.closePath()}},o_=Math.sin(wy/10)/Math.sin(7*wy/10),a_=Math.sin(Ny/10)*o_,u_=-Math.cos(Ny/10)*o_,c_={draw:function(t,n){var e=Math.sqrt(.8908130915292852*n),r=a_*e,i=u_*e;t.moveTo(0,-e),t.lineTo(r,i);for(var o=1;o<5;++o){var a=Ny*o/5,u=Math.cos(a),c=Math.sin(a);t.lineTo(c*e,-u*e),t.lineTo(u*r-c*i,c*r+u*i)}t.closePath()}},f_={draw:function(t,n){var e=Math.sqrt(n),r=-e/2;t.rect(r,r,e,e)}},s_=Math.sqrt(3),l_={draw:function(t,n){var e=-Math.sqrt(n/(3*s_));t.moveTo(0,2*e),t.lineTo(-s_*e,-e),t.lineTo(s_*e,-e),t.closePath()}},h_=Math.sqrt(3)/2,d_=1/Math.sqrt(12),p_=3*(d_/2+1),v_={draw:function(t,n){var e=Math.sqrt(n/p_),r=e/2,i=e*d_,o=r,a=e*d_+e,u=-o,c=a;t.moveTo(r,i),t.lineTo(o,a),t.lineTo(u,c),t.lineTo(-.5*r-h_*i,h_*r+-.5*i),t.lineTo(-.5*o-h_*a,h_*o+-.5*a),t.lineTo(-.5*u-h_*c,h_*u+-.5*c),t.lineTo(-.5*r+h_*i,-.5*i-h_*r),t.lineTo(-.5*o+h_*a,-.5*a-h_*o),t.lineTo(-.5*u+h_*c,-.5*c-h_*u),t.closePath()}},g_=[t_,n_,i_,f_,c_,l_,v_];function y_(){}function __(t,n,e){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+n)/6,(t._y0+4*t._y1+e)/6)}function b_(t){this._context=t}function m_(t){this._context=t}function x_(t){this._context=t}function w_(t,n){this._basis=new b_(t),this._beta=n}b_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:__(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:__(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},m_.prototype={areaStart:y_,areaEnd:y_,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x2=t,this._y2=n;break;case 1:this._point=2,this._x3=t,this._y3=n;break;case 2:this._point=3,this._x4=t,this._y4=n,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+n)/6);break;default:__(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},x_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var e=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+n)/6;this._line?this._context.lineTo(e,r):this._context.moveTo(e,r);break;case 3:this._point=4;default:__(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},w_.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,n=this._y,e=t.length-1;if(e>0)for(var r,i=t[0],o=n[0],a=t[e]-i,u=n[e]-o,c=-1;++c<=e;)r=c/e,this._basis.point(this._beta*t[c]+(1-this._beta)*(i+r*a),this._beta*n[c]+(1-this._beta)*(o+r*u));this._x=this._y=null,this._basis.lineEnd()},point:function(t,n){this._x.push(+t),this._y.push(+n)}};var M_=function t(n){function e(t){return 1===n?new b_(t):new w_(t,n)}return e.beta=function(n){return t(+n)},e}(.85);function N_(t,n,e){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-n),t._y2+t._k*(t._y1-e),t._x2,t._y2)}function T_(t,n){this._context=t,this._k=(1-n)/6}T_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:N_(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2,this._x1=t,this._y1=n;break;case 2:this._point=3;default:N_(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var A_=function t(n){function e(t){return new T_(t,n)}return e.tension=function(n){return t(+n)},e}(0);function S_(t,n){this._context=t,this._k=(1-n)/6}S_.prototype={areaStart:y_,areaEnd:y_,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:N_(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var k_=function t(n){function e(t){return new S_(t,n)}return e.tension=function(n){return t(+n)},e}(0);function E_(t,n){this._context=t,this._k=(1-n)/6}E_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:N_(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var C_=function t(n){function e(t){return new E_(t,n)}return e.tension=function(n){return t(+n)},e}(0);function P_(t,n,e){var r=t._x1,i=t._y1,o=t._x2,a=t._y2;if(t._l01_a>xy){var u=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,c=3*t._l01_a*(t._l01_a+t._l12_a);r=(r*u-t._x0*t._l12_2a+t._x2*t._l01_2a)/c,i=(i*u-t._y0*t._l12_2a+t._y2*t._l01_2a)/c}if(t._l23_a>xy){var f=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,s=3*t._l23_a*(t._l23_a+t._l12_a);o=(o*f+t._x1*t._l23_2a-n*t._l12_2a)/s,a=(a*f+t._y1*t._l23_2a-e*t._l12_2a)/s}t._context.bezierCurveTo(r,i,o,a,t._x2,t._y2)}function z_(t,n){this._context=t,this._alpha=n}z_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3;default:P_(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var R_=function t(n){function e(t){return n?new z_(t,n):new T_(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function D_(t,n){this._context=t,this._alpha=n}D_.prototype={areaStart:y_,areaEnd:y_,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:P_(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var q_=function t(n){function e(t){return n?new D_(t,n):new S_(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function L_(t,n){this._context=t,this._alpha=n}L_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:P_(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var U_=function t(n){function e(t){return n?new L_(t,n):new E_(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function O_(t){this._context=t}function B_(t){return t<0?-1:1}function Y_(t,n,e){var r=t._x1-t._x0,i=n-t._x1,o=(t._y1-t._y0)/(r||i<0&&-0),a=(e-t._y1)/(i||r<0&&-0),u=(o*i+a*r)/(r+i);return(B_(o)+B_(a))*Math.min(Math.abs(o),Math.abs(a),.5*Math.abs(u))||0}function F_(t,n){var e=t._x1-t._x0;return e?(3*(t._y1-t._y0)/e-n)/2:n}function I_(t,n,e){var r=t._x0,i=t._y0,o=t._x1,a=t._y1,u=(o-r)/3;t._context.bezierCurveTo(r+u,i+u*n,o-u,a-u*e,o,a)}function H_(t){this._context=t}function j_(t){this._context=new X_(t)}function X_(t){this._context=t}function G_(t){this._context=t}function V_(t){var n,e,r=t.length-1,i=new Array(r),o=new Array(r),a=new Array(r);for(i[0]=0,o[0]=2,a[0]=t[0]+2*t[1],n=1;n=0;--n)i[n]=(a[n]-i[n+1])/o[n];for(o[r-1]=(t[r]+i[r-1])/2,n=0;n1)for(var e,r,i,o=1,a=t[n[0]],u=a.length;o=0;)e[n]=n;return e}function Q_(t,n){return t[n]}function K_(t){var n=t.map(J_);return Z_(t).sort(function(t,e){return n[t]-n[e]})}function J_(t){for(var n,e=-1,r=0,i=t.length,o=-1/0;++eo&&(o=n,r=e);return r}function tb(t){var n=t.map(nb);return Z_(t).sort(function(t,e){return n[t]-n[e]})}function nb(t){for(var n,e=0,r=-1,i=t.length;++r0)){if(o/=h,h<0){if(o0){if(o>l)return;o>s&&(s=o)}if(o=r-c,h||!(o<0)){if(o/=h,h<0){if(o>l)return;o>s&&(s=o)}else if(h>0){if(o0)){if(o/=d,d<0){if(o0){if(o>l)return;o>s&&(s=o)}if(o=i-f,d||!(o<0)){if(o/=d,d<0){if(o>l)return;o>s&&(s=o)}else if(d>0){if(o0||l<1)||(s>0&&(t[0]=[c+s*h,f+s*d]),l<1&&(t[1]=[c+l*h,f+l*d]),!0)}}}}}function pb(t,n,e,r,i){var o=t[1];if(o)return!0;var a,u,c=t[0],f=t.left,s=t.right,l=f[0],h=f[1],d=s[0],p=s[1],v=(l+d)/2,g=(h+p)/2;if(p===h){if(v=r)return;if(l>d){if(c){if(c[1]>=i)return}else c=[v,e];o=[v,i]}else{if(c){if(c[1]1)if(l>d){if(c){if(c[1]>=i)return}else c=[(e-u)/a,e];o=[(i-u)/a,i]}else{if(c){if(c[1]=r)return}else c=[n,a*n+u];o=[r,a*r+u]}else{if(c){if(c[0]=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,n),this._context.lineTo(t,n);else{var e=this._x*(1-this._t)+t*this._t;this._context.lineTo(e,this._y),this._context.lineTo(e,n)}}this._x=t,this._y=n}},ob.prototype={constructor:ob,insert:function(t,n){var e,r,i;if(t){if(n.P=t,n.N=t.N,t.N&&(t.N.P=n),t.N=n,t.R){for(t=t.R;t.L;)t=t.L;t.L=n}else t.R=n;e=t}else this._?(t=fb(this._),n.P=null,n.N=t,t.P=t.L=n,e=t):(n.P=n.N=null,this._=n,e=null);for(n.L=n.R=null,n.U=e,n.C=!0,t=n;e&&e.C;)e===(r=e.U).L?(i=r.R)&&i.C?(e.C=i.C=!1,r.C=!0,t=r):(t===e.R&&(ub(this,e),e=(t=e).U),e.C=!1,r.C=!0,cb(this,r)):(i=r.L)&&i.C?(e.C=i.C=!1,r.C=!0,t=r):(t===e.L&&(cb(this,e),e=(t=e).U),e.C=!1,r.C=!0,ub(this,r)),e=t.U;this._.C=!1},remove:function(t){t.N&&(t.N.P=t.P),t.P&&(t.P.N=t.N),t.N=t.P=null;var n,e,r,i=t.U,o=t.L,a=t.R;if(e=o?a?fb(a):o:a,i?i.L===t?i.L=e:i.R=e:this._=e,o&&a?(r=e.C,e.C=t.C,e.L=o,o.U=e,e!==a?(i=e.U,e.U=t.U,t=e.R,i.L=t,e.R=a,a.U=e):(e.U=i,i=e,t=e.R)):(r=t.C,t=e),t&&(t.U=i),!r)if(t&&t.C)t.C=!1;else{do{if(t===this._)break;if(t===i.L){if((n=i.R).C&&(n.C=!1,i.C=!0,ub(this,i),n=i.R),n.L&&n.L.C||n.R&&n.R.C){n.R&&n.R.C||(n.L.C=!1,n.C=!0,cb(this,n),n=i.R),n.C=i.C,i.C=n.R.C=!1,ub(this,i),t=this._;break}}else if((n=i.L).C&&(n.C=!1,i.C=!0,cb(this,i),n=i.L),n.L&&n.L.C||n.R&&n.R.C){n.L&&n.L.C||(n.R.C=!1,n.C=!0,ub(this,n),n=i.L),n.C=i.C,i.C=n.L.C=!1,cb(this,i),t=this._;break}n.C=!0,t=i,i=i.U}while(!t.C);t&&(t.C=!1)}}};var _b,bb=[];function mb(){ab(this),this.x=this.y=this.arc=this.site=this.cy=null}function xb(t){var n=t.P,e=t.N;if(n&&e){var r=n.site,i=t.site,o=e.site;if(r!==o){var a=i[0],u=i[1],c=r[0]-a,f=r[1]-u,s=o[0]-a,l=o[1]-u,h=2*(c*l-f*s);if(!(h>=-Lb)){var d=c*c+f*f,p=s*s+l*l,v=(l*d-f*p)/h,g=(c*p-s*d)/h,y=bb.pop()||new mb;y.arc=t,y.site=i,y.x=v+a,y.y=(y.cy=g+u)+Math.sqrt(v*v+g*g),t.circle=y;for(var _=null,b=Rb._;b;)if(y.yqb)u=u.L;else{if(!((i=o-Cb(u,a))>qb)){r>-qb?(n=u.P,e=u):i>-qb?(n=u,e=u.N):n=e=u;break}if(!u.R){n=u;break}u=u.R}!function(t){zb[t.index]={site:t,halfedges:[]}}(t);var c=Tb(t);if(Pb.insert(n,c),n||e){if(n===e)return wb(n),e=Tb(n.site),Pb.insert(c,e),c.edge=e.edge=sb(n.site,c.site),xb(n),void xb(e);if(e){wb(n),wb(e);var f=n.site,s=f[0],l=f[1],h=t[0]-s,d=t[1]-l,p=e.site,v=p[0]-s,g=p[1]-l,y=2*(h*g-d*v),_=h*h+d*d,b=v*v+g*g,m=[(g*_-d*b)/y+s,(h*b-v*_)/y+l];hb(e.edge,f,p,m),c.edge=sb(f,t,null,m),e.edge=sb(t,p,null,m),xb(n),xb(e)}else c.edge=sb(n.site,c.site)}}function Eb(t,n){var e=t.site,r=e[0],i=e[1],o=i-n;if(!o)return r;var a=t.P;if(!a)return-1/0;var u=(e=a.site)[0],c=e[1],f=c-n;if(!f)return u;var s=u-r,l=1/o-1/f,h=s/f;return l?(-h+Math.sqrt(h*h-2*l*(s*s/(-2*f)-c+f/2+i-o/2)))/l+r:(r+u)/2}function Cb(t,n){var e=t.N;if(e)return Eb(e,n);var r=t.site;return r[1]===n?r[0]:1/0}var Pb,zb,Rb,Db,qb=1e-6,Lb=1e-12;function Ub(t,n,e){return(t[0]-e[0])*(n[1]-t[1])-(t[0]-n[0])*(e[1]-t[1])}function Ob(t,n){return n[1]-t[1]||n[0]-t[0]}function Bb(t,n){var e,r,i,o=t.sort(Ob).pop();for(Db=[],zb=new Array(t.length),Pb=new ob,Rb=new ob;;)if(i=_b,o&&(!i||o[1]qb||Math.abs(i[0][1]-i[1][1])>qb)||delete Db[o]}(a,u,c,f),function(t,n,e,r){var i,o,a,u,c,f,s,l,h,d,p,v,g=zb.length,y=!0;for(i=0;iqb||Math.abs(v-h)>qb)&&(c.splice(u,0,Db.push(lb(a,d,Math.abs(p-t)qb?[t,Math.abs(l-t)qb?[Math.abs(h-r)qb?[e,Math.abs(l-e)qb?[Math.abs(h-n)=u)return null;var c=t-i.site[0],f=n-i.site[1],s=c*c+f*f;do{i=o.cells[r=a],a=null,i.halfedges.forEach(function(e){var r=o.edges[e],u=r.left;if(u!==i.site&&u||(u=r.right)){var c=t-u[0],f=n-u[1],l=c*c+f*f;lr?(r+i)/2:Math.min(0,r)||Math.max(0,i),a>o?(o+a)/2:Math.min(0,o)||Math.max(0,a))}jb.prototype=Ib.prototype,t.active=function(t,n){var e,r,i=t.__transition;if(i)for(r in n=null==n?null:n+"",i)if((e=i[r]).state>mr&&e.name===n)return new Lr([[t]],gi,n,+r);return null},t.arc=function(){var t=Ay,n=Sy,e=dy(0),r=null,i=ky,o=Ey,a=Cy,u=null;function c(){var c,f,s=+t.apply(this,arguments),l=+n.apply(this,arguments),h=i.apply(this,arguments)-My,d=o.apply(this,arguments)-My,p=py(d-h),v=d>h;if(u||(u=c=to()),lxy)if(p>Ny-xy)u.moveTo(l*gy(h),l*by(h)),u.arc(0,0,l,h,d,!v),s>xy&&(u.moveTo(s*gy(d),s*by(d)),u.arc(0,0,s,d,h,v));else{var g,y,_=h,b=d,m=h,x=d,w=p,M=p,N=a.apply(this,arguments)/2,T=N>xy&&(r?+r.apply(this,arguments):my(s*s+l*l)),A=_y(py(l-s)/2,+e.apply(this,arguments)),S=A,k=A;if(T>xy){var E=Ty(T/s*by(N)),C=Ty(T/l*by(N));(w-=2*E)>xy?(m+=E*=v?1:-1,x-=E):(w=0,m=x=(h+d)/2),(M-=2*C)>xy?(_+=C*=v?1:-1,b-=C):(M=0,_=b=(h+d)/2)}var P=l*gy(_),z=l*by(_),R=s*gy(x),D=s*by(x);if(A>xy){var q,L=l*gy(b),U=l*by(b),O=s*gy(m),B=s*by(m);if(p1?0:t<-1?wy:Math.acos(t)}((Y*I+F*H)/(my(Y*Y+F*F)*my(I*I+H*H)))/2),X=my(q[0]*q[0]+q[1]*q[1]);S=_y(A,(s-X)/(j-1)),k=_y(A,(l-X)/(j+1))}}M>xy?k>xy?(g=Py(O,B,P,z,l,k,v),y=Py(L,U,R,D,l,k,v),u.moveTo(g.cx+g.x01,g.cy+g.y01),kxy&&w>xy?S>xy?(g=Py(R,D,L,U,s,-S,v),y=Py(P,z,O,B,s,-S,v),u.lineTo(g.cx+g.x01,g.cy+g.y01),S>a,f=i+2*u>>a,s=_o(20);function l(r){var i=new Float32Array(c*f),l=new Float32Array(c*f);r.forEach(function(r,o,s){var l=+t(r,o,s)+u>>a,h=+n(r,o,s)+u>>a,d=+e(r,o,s);l>=0&&l=0&&h>a),Ao({width:c,height:f,data:l},{width:c,height:f,data:i},o>>a),To({width:c,height:f,data:i},{width:c,height:f,data:l},o>>a),Ao({width:c,height:f,data:l},{width:c,height:f,data:i},o>>a),To({width:c,height:f,data:i},{width:c,height:f,data:l},o>>a),Ao({width:c,height:f,data:l},{width:c,height:f,data:i},o>>a);var d=s(i);if(!Array.isArray(d)){var p=T(i);d=w(0,p,d),(d=g(0,Math.floor(p/d)*d,d)).shift()}return No().thresholds(d).size([c,f])(i).map(h)}function h(t){return t.value*=Math.pow(2,-2*a),t.coordinates.forEach(d),t}function d(t){t.forEach(p)}function p(t){t.forEach(v)}function v(t){t[0]=t[0]*Math.pow(2,a)-u,t[1]=t[1]*Math.pow(2,a)-u}function y(){return c=r+2*(u=3*o)>>a,f=i+2*u>>a,l}return l.x=function(n){return arguments.length?(t="function"==typeof n?n:_o(+n),l):t},l.y=function(t){return arguments.length?(n="function"==typeof t?t:_o(+t),l):n},l.weight=function(t){return arguments.length?(e="function"==typeof t?t:_o(+t),l):e},l.size=function(t){if(!arguments.length)return[r,i];var n=Math.ceil(t[0]),e=Math.ceil(t[1]);if(!(n>=0||n>=0))throw new Error("invalid size");return r=n,i=e,y()},l.cellSize=function(t){if(!arguments.length)return 1<=1))throw new Error("invalid cell size");return a=Math.floor(Math.log(t)/Math.LN2),y()},l.thresholds=function(t){return arguments.length?(s="function"==typeof t?t:Array.isArray(t)?_o(go.call(t)):_o(t),l):s},l.bandwidth=function(t){if(!arguments.length)return Math.sqrt(o*(o+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return o=Math.round((Math.sqrt(4*t*t+1)-1)/2),y()},l},t.contours=No,t.create=function(t){return Rt(Z(t).call(document.documentElement))},t.creator=Z,t.cross=function(t,n,e){var r,i,o,u,c=t.length,f=n.length,s=new Array(c*f);for(null==e&&(e=a),r=o=0;rt?1:n>=t?0:NaN},t.deviation=f,t.dispatch=I,t.drag=function(){var n,e,r,i,o=Vt,a=$t,u=Wt,c=Zt,f={},s=I("start","drag","end"),l=0,h=0;function d(t){t.on("mousedown.drag",p).filter(c).on("touchstart.drag",y).on("touchmove.drag",_).on("touchend.drag touchcancel.drag",b).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(){if(!i&&o.apply(this,arguments)){var u=m("mouse",a.apply(this,arguments),Bt,this,arguments);u&&(Rt(t.event.view).on("mousemove.drag",v,!0).on("mouseup.drag",g,!0),Ht(t.event.view),Ft(),r=!1,n=t.event.clientX,e=t.event.clientY,u("start"))}}function v(){if(It(),!r){var i=t.event.clientX-n,o=t.event.clientY-e;r=i*i+o*o>h}f.mouse("drag")}function g(){Rt(t.event.view).on("mousemove.drag mouseup.drag",null),jt(t.event.view,r),It(),f.mouse("end")}function y(){if(o.apply(this,arguments)){var n,e,r=t.event.changedTouches,i=a.apply(this,arguments),u=r.length;for(n=0;nc+d||if+d||ou.index){var p=c-a.x-a.vx,v=f-a.y-a.vy,g=p*p+v*v;gt.r&&(t.r=t[n].r)}function u(){if(n){var r,i,o=n.length;for(e=new Array(o),r=0;r=a)){(t.data!==n||t.next)&&(0===s&&(d+=(s=la())*s),0===l&&(d+=(l=la())*l),d1?(null==e?u.remove(t):u.set(t,d(e)),n):u.get(t)},find:function(n,e,r){var i,o,a,u,c,f=0,s=t.length;for(null==r?r=1/0:r*=r,f=0;f1?(f.on(t,e),n):f.on(t)}}},t.forceX=function(t){var n,e,r,i=sa(.1);function o(t){for(var i,o=0,a=n.length;o=.12&&i<.234&&r>=-.425&&r<-.214?u:i>=.166&&i<.234&&r>=-.214&&r<-.115?c:a).invert(t)},s.stream=function(e){return t&&n===e?t:(r=[a.stream(n=e),u.stream(e),c.stream(e)],i=r.length,t={point:function(t,n){for(var e=-1;++eNc(r[0],r[1])&&(r[1]=i[1]),Nc(i[0],r[1])>Nc(r[0],r[1])&&(r[0]=i[0])):o.push(r=i);for(a=-1/0,n=0,r=o[e=o.length-1];n<=e;r=i,++n)i=o[n],(u=Nc(r[1],i[0]))>a&&(a=u,Hu=i[0],Xu=r[1])}return Qu=Ku=null,Hu===1/0||ju===1/0?[[NaN,NaN],[NaN,NaN]]:[[Hu,ju],[Xu,Gu]]},t.geoCentroid=function(t){Ju=tc=nc=ec=rc=ic=oc=ac=uc=cc=fc=0,Mu(t,Sc);var n=uc,e=cc,r=fc,i=n*n+e*e+r*r;return i2?t[2]+90:90]):[(t=e())[0],t[1],t[2]-90]},e([0,0,90]).scale(159.155)},t.geoTransverseMercatorRaw=yl,t.gray=function(t,n){return new Yn(t,0,0,null==n?1:n)},t.hcl=Gn,t.hierarchy=wl,t.histogram=function(){var t=v,n=s,e=M;function r(r){var o,a,u=r.length,c=new Array(u);for(o=0;ol;)h.pop(),--d;var p,v=new Array(d+1);for(o=0;o<=d;++o)(p=v[o]=[]).x0=o>0?h[o-1]:s,p.x1=o1)&&(t-=Math.floor(t));var n=Math.abs(t-.5);return iy.h=360*t-100,iy.s=1.5-1.5*n,iy.l=.8-.9*n,iy+""},t.interpolateRdBu=sg,t.interpolateRdGy=hg,t.interpolateRdPu=Dg,t.interpolateRdYlBu=pg,t.interpolateRdYlGn=gg,t.interpolateReds=Kg,t.interpolateRgb=de,t.interpolateRgbBasis=ve,t.interpolateRgbBasisClosed=ge,t.interpolateRound=Te,t.interpolateSinebow=function(t){var n;return t=(.5-t)*Math.PI,oy.r=255*(n=Math.sin(t))*n,oy.g=255*(n=Math.sin(t+ay))*n,oy.b=255*(n=Math.sin(t+uy))*n,oy+""},t.interpolateSpectral=_g,t.interpolateString=Me,t.interpolateTransformCss=De,t.interpolateTransformSvg=qe,t.interpolateTurbo=function(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+t*(1172.33-t*(10793.56-t*(33300.12-t*(38394.49-14825.05*t)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+t*(557.33+t*(1225.33-t*(3574.96-t*(1073.77+707.56*t)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+t*(3211.1-t*(15327.97-t*(27814-t*(22569.18-6838.66*t)))))))+")"},t.interpolateViridis=fy,t.interpolateWarm=ey,t.interpolateYlGn=Og,t.interpolateYlGnBu=Lg,t.interpolateYlOrBr=Yg,t.interpolateYlOrRd=Ig,t.interpolateZoom=Fe,t.interrupt=Cr,t.interval=function(t,n,e){var r=new sr,i=n;return null==n?(r.restart(t,n,e),r):(n=+n,e=null==e?cr():+e,r.restart(function o(a){a+=i,r.restart(o,i+=n,e),t(a)},n,e),r)},t.isoFormat=Av,t.isoParse=Sv,t.json=function(t,n){return fetch(t,n).then(oa)},t.keys=function(t){var n=[];for(var e in t)n.push(e);return n},t.lab=Bn,t.lch=function(t,n,e,r){return 1===arguments.length?Xn(t):new Vn(e,n,t,null==r?1:r)},t.line=Ly,t.lineRadial=jy,t.linkHorizontal=function(){return Zy(Qy)},t.linkRadial=function(){var t=Zy(Jy);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t},t.linkVertical=function(){return Zy(Ky)},t.local=qt,t.map=uo,t.matcher=nt,t.max=T,t.mean=function(t,n){var e,r=t.length,i=r,o=-1,a=0;if(null==n)for(;++o=r.length)return null!=t&&e.sort(t),null!=n?n(e):e;for(var c,f,s,l=-1,h=e.length,d=r[i++],p=uo(),v=a();++lr.length)return e;var a,u=i[o-1];return null!=n&&o>=r.length?a=e.entries():(a=[],e.each(function(n,e){a.push({key:e,values:t(n,o)})})),null!=u?a.sort(function(t,n){return u(t.key,n.key)}):a}(o(t,0,so,lo),0)},key:function(t){return r.push(t),e},sortKeys:function(t){return i[r.length-1]=t,e},sortValues:function(n){return t=n,e},rollup:function(t){return n=t,e}}},t.now=cr,t.pack=function(){var t=null,n=1,e=1,r=Hl;function i(i){return i.x=n/2,i.y=e/2,t?i.eachBefore(Gl(t)).eachAfter(Vl(r,.5)).eachBefore($l(1)):i.eachBefore(Gl(Xl)).eachAfter(Vl(Hl,1)).eachAfter(Vl(r,i.r/Math.min(n,e))).eachBefore($l(Math.min(n,e)/(2*i.r))),i}return i.radius=function(n){return arguments.length?(t=Fl(n),i):t},i.size=function(t){return arguments.length?(n=+t[0],e=+t[1],i):[n,e]},i.padding=function(t){return arguments.length?(r="function"==typeof t?t:jl(+t),i):r},i},t.packEnclose=kl,t.packSiblings=function(t){return Yl(t),t},t.pairs=function(t,n){null==n&&(n=a);for(var e=0,r=t.length-1,i=t[0],o=new Array(r<0?0:r);e0&&(d+=l);for(null!=n?p.sort(function(t,e){return n(v[t],v[e])}):null!=e&&p.sort(function(t,n){return e(a[t],a[n])}),u=0,f=d?(y-h*b)/d:0;u0?l*f:0)+b,v[c]={data:a[c],index:u,value:l,startAngle:g,endAngle:s,padAngle:_};return v}return a.value=function(n){return arguments.length?(t="function"==typeof n?n:dy(+n),a):t},a.sortValues=function(t){return arguments.length?(n=t,e=null,a):n},a.sort=function(t){return arguments.length?(e=t,n=null,a):e},a.startAngle=function(t){return arguments.length?(r="function"==typeof t?t:dy(+t),a):r},a.endAngle=function(t){return arguments.length?(i="function"==typeof t?t:dy(+t),a):i},a.padAngle=function(t){return arguments.length?(o="function"==typeof t?t:dy(+t),a):o},a},t.piecewise=function(t,n){for(var e=0,r=n.length-1,i=n[0],o=new Array(r<0?0:r);eu!=f>u&&a<(c-e)*(u-r)/(f-r)+e&&(s=!s),c=e,f=r;return s},t.polygonHull=function(t){if((e=t.length)<3)return null;var n,e,r=new Array(e),i=new Array(e);for(n=0;n=0;--n)f.push(t[r[o[n]][2]]);for(n=+u;n0?a[n-1]:r[0],n=o?[a[o-1],r]:[a[n-1],a[n]]},c.unknown=function(t){return arguments.length?(n=t,c):c},c.thresholds=function(){return a.slice()},c.copy=function(){return t().domain([e,r]).range(u).unknown(n)},Mh.apply(Ih(c),arguments)},t.scaleSequential=function t(){var n=Ih(Ov()(Rh));return n.copy=function(){return Bv(n,t())},Nh.apply(n,arguments)},t.scaleSequentialLog=function t(){var n=Zh(Ov()).domain([1,10]);return n.copy=function(){return Bv(n,t()).base(n.base())},Nh.apply(n,arguments)},t.scaleSequentialPow=Yv,t.scaleSequentialQuantile=function t(){var e=[],r=Rh;function o(t){if(!isNaN(t=+t))return r((i(e,t)-1)/(e.length-1))}return o.domain=function(t){if(!arguments.length)return e.slice();e=[];for(var r,i=0,a=t.length;i0)for(var e,r,i,o,a,u,c=0,f=t[n[0]].length;c=0?(r[0]=o,r[1]=o+=i):i<0?(r[1]=a,r[0]=a+=i):r[0]=o},t.stackOffsetExpand=function(t,n){if((r=t.length)>0){for(var e,r,i,o=0,a=t[0].length;o0){for(var e,r=0,i=t[n[0]],o=i.length;r0&&(r=(e=t[n[0]]).length)>0){for(var e,r,i,o=0,a=1;a0)throw new Error("cycle");return o}return e.id=function(n){return arguments.length?(t=Il(n),e):t},e.parentId=function(t){return arguments.length?(n=Il(t),e):n},e},t.style=ft,t.sum=function(t,n){var e,r=t.length,i=-1,o=0;if(null==n)for(;++i=0;--i)u.push(e=n.children[i]=new uh(r[i],i)),e.parent=n;return(a.parent=new uh(null,0)).children=[a],a}(i);if(c.eachAfter(o),c.parent.m=-c.z,c.eachBefore(a),r)i.eachBefore(u);else{var f=i,s=i,l=i;i.eachBefore(function(t){t.xs.x&&(s=t),t.depth>l.depth&&(l=t)});var h=f===s?1:t(f,s)/2,d=h-f.x,p=n/(s.x+h+d),v=e/(l.depth||1);i.eachBefore(function(t){t.x=(t.x+d)*p,t.y=t.depth*v})}return i}function o(n){var e=n.children,r=n.parent.children,i=n.i?r[n.i-1]:null;if(e){!function(t){for(var n,e=0,r=0,i=t.children,o=i.length;--o>=0;)(n=i[o]).z+=e,n.m+=e,e+=n.s+(r+=n.c)}(n);var o=(e[0].z+e[e.length-1].z)/2;i?(n.z=i.z+t(n._,i._),n.m=n.z-o):n.z=o}else i&&(n.z=i.z+t(n._,i._));n.parent.A=function(n,e,r){if(e){for(var i,o=n,a=n,u=e,c=o.parent.children[0],f=o.m,s=a.m,l=u.m,h=c.m;u=ih(u),o=rh(o),u&&o;)c=rh(c),(a=ih(a)).a=n,(i=u.z+l-o.z-f+t(u._,o._))>0&&(oh(ah(u,n,r),n,i),f+=i,s+=i),l+=u.m,f+=o.m,h+=c.m,s+=a.m;u&&!ih(a)&&(a.t=u,a.m+=l-s),o&&!rh(c)&&(c.t=o,c.m+=f-h,r=n)}return r}(n,i,n.parent.A||r[0])}function a(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function u(t){t.x*=n,t.y=t.depth*e}return i.separation=function(n){return arguments.length?(t=n,i):t},i.size=function(t){return arguments.length?(r=!1,n=+t[0],e=+t[1],i):r?null:[n,e]},i.nodeSize=function(t){return arguments.length?(r=!0,n=+t[0],e=+t[1],i):r?[n,e]:null},i},t.treemap=function(){var t=lh,n=!1,e=1,r=1,i=[0],o=Hl,a=Hl,u=Hl,c=Hl,f=Hl;function s(t){return t.x0=t.y0=0,t.x1=e,t.y1=r,t.eachBefore(l),i=[0],n&&t.eachBefore(Wl),t}function l(n){var e=i[n.depth],r=n.x0+e,s=n.y0+e,l=n.x1-e,h=n.y1-e;l=e-1){var s=u[n];return s.x0=i,s.y0=o,s.x1=a,void(s.y1=c)}for(var l=f[n],h=r/2+l,d=n+1,p=e-1;d>>1;f[v]c-o){var _=(i*y+a*g)/r;t(n,d,g,i,o,_,c),t(d,e,y,_,o,a,c)}else{var b=(o*y+c*g)/r;t(n,d,g,i,o,a,b),t(d,e,y,i,b,a,c)}}(0,c,t.value,n,e,r,i)},t.treemapDice=Zl,t.treemapResquarify=hh,t.treemapSlice=ch,t.treemapSliceDice=function(t,n,e,r,i){(1&t.depth?ch:Zl)(t,n,e,r,i)},t.treemapSquarify=lh,t.tsv=ia,t.tsvFormat=Wo,t.tsvFormatBody=Zo,t.tsvFormatRows=Qo,t.tsvParse=Vo,t.tsvParseRows=$o,t.utcDay=Hd,t.utcDays=jd,t.utcFriday=Qd,t.utcFridays=ip,t.utcHour=Fd,t.utcHours=Id,t.utcMillisecond=cd,t.utcMilliseconds=fd,t.utcMinute=Bd,t.utcMinutes=Yd,t.utcMonday=Vd,t.utcMondays=tp,t.utcMonth=ap,t.utcMonths=up,t.utcSaturday=Kd,t.utcSaturdays=op,t.utcSecond=hd,t.utcSeconds=dd,t.utcSunday=Gd,t.utcSundays=Jd,t.utcThursday=Zd,t.utcThursdays=rp,t.utcTuesday=$d,t.utcTuesdays=np,t.utcWednesday=Wd,t.utcWednesdays=ep,t.utcWeek=Gd,t.utcWeeks=Jd,t.utcYear=cp,t.utcYears=fp,t.values=function(t){var n=[];for(var e in t)n.push(t[e]);return n},t.variance=c,t.version="5.11.0",t.voronoi=function(){var t=rb,n=ib,e=null;function r(r){return new Bb(r.map(function(e,i){var o=[Math.round(t(e,i,r)/qb)*qb,Math.round(n(e,i,r)/qb)*qb];return o.index=i,o.data=e,o}),e)}return r.polygons=function(t){return r(t).polygons()},r.links=function(t){return r(t).links()},r.triangles=function(t){return r(t).triangles()},r.x=function(n){return arguments.length?(t="function"==typeof n?n:eb(+n),r):t},r.y=function(t){return arguments.length?(n="function"==typeof t?t:eb(+t),r):n},r.extent=function(t){return arguments.length?(e=null==t?null:[[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]],r):e&&[[e[0][0],e[0][1]],[e[1][0],e[1][1]]]},r.size=function(t){return arguments.length?(e=null==t?null:[[0,0],[+t[0],+t[1]]],r):e&&[e[1][0]-e[0][0],e[1][1]-e[0][1]]},r},t.window=ct,t.xml=ua,t.zip=function(){return k(arguments)},t.zoom=function(){var n,e,r=Vb,i=$b,o=Kb,a=Zb,u=Qb,c=[0,1/0],f=[[-1/0,-1/0],[1/0,1/0]],s=250,l=Fe,h=I("start","zoom","end"),d=500,p=150,v=0;function g(t){t.property("__zoom",Wb).on("wheel.zoom",M).on("mousedown.zoom",N).on("dblclick.zoom",T).filter(u).on("touchstart.zoom",A).on("touchmove.zoom",S).on("touchend.zoom touchcancel.zoom",k).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function y(t,n){return(n=Math.max(c[0],Math.min(c[1],n)))===t.k?t:new Ib(n,t.x,t.y)}function _(t,n,e){var r=n[0]-e[0]*t.k,i=n[1]-e[1]*t.k;return r===t.x&&i===t.y?t:new Ib(t.k,r,i)}function b(t){return[(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function m(t,n,e){t.on("start.zoom",function(){x(this,arguments).start()}).on("interrupt.zoom end.zoom",function(){x(this,arguments).end()}).tween("zoom",function(){var t=this,r=arguments,o=x(t,r),a=i.apply(t,r),u=null==e?b(a):"function"==typeof e?e.apply(t,r):e,c=Math.max(a[1][0]-a[0][0],a[1][1]-a[0][1]),f=t.__zoom,s="function"==typeof n?n.apply(t,r):n,h=l(f.invert(u).concat(c/f.k),s.invert(u).concat(c/s.k));return function(t){if(1===t)t=s;else{var n=h(t),e=c/n[2];t=new Ib(e,u[0]-n[0]*e,u[1]-n[1]*e)}o.zoom(null,t)}})}function x(t,n,e){return!e&&t.__zooming||new w(t,n)}function w(t,n){this.that=t,this.args=n,this.active=0,this.extent=i.apply(t,n),this.taps=0}function M(){if(r.apply(this,arguments)){var t=x(this,arguments),n=this.__zoom,e=Math.max(c[0],Math.min(c[1],n.k*Math.pow(2,a.apply(this,arguments)))),i=Bt(this);if(t.wheel)t.mouse[0][0]===i[0]&&t.mouse[0][1]===i[1]||(t.mouse[1]=n.invert(t.mouse[0]=i)),clearTimeout(t.wheel);else{if(n.k===e)return;t.mouse=[i,n.invert(i)],Cr(this),t.start()}Gb(),t.wheel=setTimeout(function(){t.wheel=null,t.end()},p),t.zoom("mouse",o(_(y(n,e),t.mouse[0],t.mouse[1]),t.extent,f))}}function N(){if(!e&&r.apply(this,arguments)){var n=x(this,arguments,!0),i=Rt(t.event.view).on("mousemove.zoom",function(){if(Gb(),!n.moved){var e=t.event.clientX-u,r=t.event.clientY-c;n.moved=e*e+r*r>v}n.zoom("mouse",o(_(n.that.__zoom,n.mouse[0]=Bt(n.that),n.mouse[1]),n.extent,f))},!0).on("mouseup.zoom",function(){i.on("mousemove.zoom mouseup.zoom",null),jt(t.event.view,n.moved),Gb(),n.end()},!0),a=Bt(this),u=t.event.clientX,c=t.event.clientY;Ht(t.event.view),Xb(),n.mouse=[a,this.__zoom.invert(a)],Cr(this),n.start()}}function T(){if(r.apply(this,arguments)){var n=this.__zoom,e=Bt(this),a=n.invert(e),u=n.k*(t.event.shiftKey?.5:2),c=o(_(y(n,u),e,a),i.apply(this,arguments),f);Gb(),s>0?Rt(this).transition().duration(s).call(m,c,e):Rt(this).call(g.transform,c)}}function A(){if(r.apply(this,arguments)){var e,i,o,a,u=t.event.touches,c=u.length,f=x(this,arguments,t.event.changedTouches.length===c);for(Xb(),i=0;i + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["math"] = factory(); + else + root["math"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 19); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return factory; }); +/* unused harmony export sortFactories */ +/* unused harmony export create */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isFactory; }); +/* unused harmony export assertDependencies */ +/* unused harmony export isOptionalDependency */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return stripOptionalNotation; }); +/* harmony import */ var _array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); +/* harmony import */ var _object__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); + + +/** + * Create a factory function, which can be used to inject dependencies. + * + * The created functions are memoized, a consecutive call of the factory + * with the exact same inputs will return the same function instance. + * The memoized cache is exposed on `factory.cache` and can be cleared + * if needed. + * + * Example: + * + * const name = 'log' + * const dependencies = ['config', 'typed', 'divideScalar', 'Complex'] + * + * export const createLog = factory(name, dependencies, ({ typed, config, divideScalar, Complex }) => { + * // ... create the function log here and return it + * } + * + * @param {string} name Name of the function to be created + * @param {string[]} dependencies The names of all required dependencies + * @param {function} create Callback function called with an object with all dependencies + * @param {Object} [meta] Optional object with meta information that will be attached + * to the created factory function as property `meta`. + * @returns {function} + */ + +function factory(name, dependencies, create, meta) { + function assertAndCreate(scope) { + // we only pass the requested dependencies to the factory function + // to prevent functions to rely on dependencies that are not explicitly + // requested. + var deps = Object(_object__WEBPACK_IMPORTED_MODULE_1__[/* pickShallow */ "j"])(scope, dependencies.map(stripOptionalNotation)); + assertDependencies(name, dependencies, scope); + return create(deps); + } + + assertAndCreate.isFactory = true; + assertAndCreate.fn = name; + assertAndCreate.dependencies = dependencies.slice().sort(); + + if (meta) { + assertAndCreate.meta = meta; + } + + return assertAndCreate; +} +/** + * Sort all factories such that when loading in order, the dependencies are resolved. + * + * @param {Array} factories + * @returns {Array} Returns a new array with the sorted factories. + */ + +function sortFactories(factories) { + var factoriesByName = {}; + factories.forEach(function (factory) { + factoriesByName[factory.fn] = factory; + }); + + function containsDependency(factory, dependency) { + // TODO: detect circular references + if (isFactory(factory)) { + if (Object(_array__WEBPACK_IMPORTED_MODULE_0__[/* contains */ "b"])(factory.dependencies, dependency.fn || dependency.name)) { + return true; + } + + if (factory.dependencies.some(function (d) { + return containsDependency(factoriesByName[d], dependency); + })) { + return true; + } + } + + return false; + } + + var sorted = []; + + function addFactory(factory) { + var index = 0; + + while (index < sorted.length && !containsDependency(sorted[index], factory)) { + index++; + } + + sorted.splice(index, 0, factory); + } // sort regular factory functions + + + factories.filter(isFactory).forEach(addFactory); // sort legacy factory functions AFTER the regular factory functions + + factories.filter(function (factory) { + return !isFactory(factory); + }).forEach(addFactory); + return sorted; +} // TODO: comment or cleanup if unused in the end + +function create(factories) { + var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + sortFactories(factories).forEach(function (factory) { + return factory(scope); + }); + return scope; +} +/** + * Test whether an object is a factory. This is the case when it has + * properties name, dependencies, and a function create. + * @param {*} obj + * @returns {boolean} + */ + +function isFactory(obj) { + return typeof obj === 'function' && typeof obj.fn === 'string' && Array.isArray(obj.dependencies); +} +/** + * Assert that all dependencies of a list with dependencies are available in the provided scope. + * + * Will throw an exception when there are dependencies missing. + * + * @param {string} name Name for the function to be created. Used to generate a useful error message + * @param {string[]} dependencies + * @param {Object} scope + */ + +function assertDependencies(name, dependencies, scope) { + var allDefined = dependencies.filter(function (dependency) { + return !isOptionalDependency(dependency); + }) // filter optionals + .every(function (dependency) { + return scope[dependency] !== undefined; + }); + + if (!allDefined) { + var missingDependencies = dependencies.filter(function (dependency) { + return scope[dependency] === undefined; + }); // TODO: create a custom error class for this, a MathjsError or something like that + + throw new Error("Cannot create function \"".concat(name, "\", ") + "some dependencies are missing: ".concat(missingDependencies.map(function (d) { + return "\"".concat(d, "\""); + }).join(', '), ".")); + } +} +function isOptionalDependency(dependency) { + return dependency && dependency[0] === '?'; +} +function stripOptionalNotation(dependency) { + return dependency && dependency[0] === '?' ? dependency.slice(1) : dependency; +} + +/***/ }), +/* 1 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "y", function() { return isNumber; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return isBigNumber; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return isComplex; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return isFraction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "L", function() { return isUnit; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "I", function() { return isString; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isArray; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "v", function() { return isMatrix; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return isCollection; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return isDenseMatrix; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "H", function() { return isSparseMatrix; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "D", function() { return isRange; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "t", function() { return isIndex; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return isBoolean; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "G", function() { return isResultSet; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return isHelp; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return isFunction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return isDate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "F", function() { return isRegExp; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "z", function() { return isObject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "x", function() { return isNull; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "K", function() { return isUndefined; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isAccessorNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return isArrayNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return isAssignmentNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return isBlockNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return isConditionalNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return isConstantNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return isFunctionAssignmentNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return isFunctionNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "u", function() { return isIndexNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "w", function() { return isNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "A", function() { return isObjectNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "B", function() { return isOperatorNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "C", function() { return isParenthesisNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "E", function() { return isRangeNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "J", function() { return isSymbolNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return isChain; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "M", function() { return typeOf; }); +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +// type checks for all known types +// +// note that: +// +// - check by duck-typing on a property like `isUnit`, instead of checking instanceof. +// instanceof cannot be used because that would not allow to pass data from +// one instance of math.js to another since each has it's own instance of Unit. +// - check the `isUnit` property via the constructor, so there will be no +// matches for "fake" instances like plain objects with a property `isUnit`. +// That is important for security reasons. +// - It must not be possible to override the type checks used internally, +// for security reasons, so these functions are not exposed in the expression +// parser. +function isNumber(x) { + return typeof x === 'number'; +} +function isBigNumber(x) { + return x && x.constructor.prototype.isBigNumber === true || false; +} +function isComplex(x) { + return x && _typeof(x) === 'object' && Object.getPrototypeOf(x).isComplex === true || false; +} +function isFraction(x) { + return x && _typeof(x) === 'object' && Object.getPrototypeOf(x).isFraction === true || false; +} +function isUnit(x) { + return x && x.constructor.prototype.isUnit === true || false; +} +function isString(x) { + return typeof x === 'string'; +} +var isArray = Array.isArray; +function isMatrix(x) { + return x && x.constructor.prototype.isMatrix === true || false; +} +/** + * Test whether a value is a collection: an Array or Matrix + * @param {*} x + * @returns {boolean} isCollection + */ + +function isCollection(x) { + return Array.isArray(x) || isMatrix(x); +} +function isDenseMatrix(x) { + return x && x.isDenseMatrix && x.constructor.prototype.isMatrix === true || false; +} +function isSparseMatrix(x) { + return x && x.isSparseMatrix && x.constructor.prototype.isMatrix === true || false; +} +function isRange(x) { + return x && x.constructor.prototype.isRange === true || false; +} +function isIndex(x) { + return x && x.constructor.prototype.isIndex === true || false; +} +function isBoolean(x) { + return typeof x === 'boolean'; +} +function isResultSet(x) { + return x && x.constructor.prototype.isResultSet === true || false; +} +function isHelp(x) { + return x && x.constructor.prototype.isHelp === true || false; +} +function isFunction(x) { + return typeof x === 'function'; +} +function isDate(x) { + return x instanceof Date; +} +function isRegExp(x) { + return x instanceof RegExp; +} +function isObject(x) { + return !!(x && _typeof(x) === 'object' && x.constructor === Object && !isComplex(x) && !isFraction(x)); +} +function isNull(x) { + return x === null; +} +function isUndefined(x) { + return x === undefined; +} +function isAccessorNode(x) { + return x && x.isAccessorNode === true && x.constructor.prototype.isNode === true || false; +} +function isArrayNode(x) { + return x && x.isArrayNode === true && x.constructor.prototype.isNode === true || false; +} +function isAssignmentNode(x) { + return x && x.isAssignmentNode === true && x.constructor.prototype.isNode === true || false; +} +function isBlockNode(x) { + return x && x.isBlockNode === true && x.constructor.prototype.isNode === true || false; +} +function isConditionalNode(x) { + return x && x.isConditionalNode === true && x.constructor.prototype.isNode === true || false; +} +function isConstantNode(x) { + return x && x.isConstantNode === true && x.constructor.prototype.isNode === true || false; +} +function isFunctionAssignmentNode(x) { + return x && x.isFunctionAssignmentNode === true && x.constructor.prototype.isNode === true || false; +} +function isFunctionNode(x) { + return x && x.isFunctionNode === true && x.constructor.prototype.isNode === true || false; +} +function isIndexNode(x) { + return x && x.isIndexNode === true && x.constructor.prototype.isNode === true || false; +} +function isNode(x) { + return x && x.isNode === true && x.constructor.prototype.isNode === true || false; +} +function isObjectNode(x) { + return x && x.isObjectNode === true && x.constructor.prototype.isNode === true || false; +} +function isOperatorNode(x) { + return x && x.isOperatorNode === true && x.constructor.prototype.isNode === true || false; +} +function isParenthesisNode(x) { + return x && x.isParenthesisNode === true && x.constructor.prototype.isNode === true || false; +} +function isRangeNode(x) { + return x && x.isRangeNode === true && x.constructor.prototype.isNode === true || false; +} +function isSymbolNode(x) { + return x && x.isSymbolNode === true && x.constructor.prototype.isNode === true || false; +} +function isChain(x) { + return x && x.constructor.prototype.isChain === true || false; +} +function typeOf(x) { + var t = _typeof(x); + + if (t === 'object') { + // JavaScript types + if (x === null) return 'null'; + if (Array.isArray(x)) return 'Array'; + if (x instanceof Date) return 'Date'; + if (x instanceof RegExp) return 'RegExp'; // math.js types + + if (isBigNumber(x)) return 'BigNumber'; + if (isComplex(x)) return 'Complex'; + if (isFraction(x)) return 'Fraction'; + if (isMatrix(x)) return 'Matrix'; + if (isUnit(x)) return 'Unit'; + if (isIndex(x)) return 'Index'; + if (isRange(x)) return 'Range'; + if (isResultSet(x)) return 'ResultSet'; + if (isNode(x)) return x.type; + if (isChain(x)) return 'Chain'; + if (isHelp(x)) return 'Help'; + return 'Object'; + } + + if (t === 'function') return 'Function'; + return t; // can be 'string', 'number', 'boolean', ... +} + +/***/ }), +/* 2 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return arraySize; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return validate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return validateIndex; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return resize; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return reshape; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return squeeze; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return unsqueeze; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return flatten; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return map; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return forEach; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return filter; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return filterRegExp; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return join; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return identify; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return generalize; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return getArrayDataType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return last; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return initial; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return contains; }); +/* harmony import */ var _number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); +/* harmony import */ var _is__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1); +/* harmony import */ var _string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5); +/* harmony import */ var _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6); +/* harmony import */ var _error_IndexError__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(10); + + + + + +/** + * Calculate the size of a multi dimensional array. + * This function checks the size of the first entry, it does not validate + * whether all dimensions match. (use function `validate` for that) + * @param {Array} x + * @Return {Number[]} size + */ + +function arraySize(x) { + var s = []; + + while (Array.isArray(x)) { + s.push(x.length); + x = x[0]; + } + + return s; +} +/** + * Recursively validate whether each element in a multi dimensional array + * has a size corresponding to the provided size array. + * @param {Array} array Array to be validated + * @param {number[]} size Array with the size of each dimension + * @param {number} dim Current dimension + * @throws DimensionError + * @private + */ + +function _validate(array, size, dim) { + var i; + var len = array.length; + + if (len !== size[dim]) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](len, size[dim]); + } + + if (dim < size.length - 1) { + // recursively validate each child array + var dimNext = dim + 1; + + for (i = 0; i < len; i++) { + var child = array[i]; + + if (!Array.isArray(child)) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](size.length - 1, size.length, '<'); + } + + _validate(array[i], size, dimNext); + } + } else { + // last dimension. none of the childs may be an array + for (i = 0; i < len; i++) { + if (Array.isArray(array[i])) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](size.length + 1, size.length, '>'); + } + } + } +} +/** + * Validate whether each element in a multi dimensional array has + * a size corresponding to the provided size array. + * @param {Array} array Array to be validated + * @param {number[]} size Array with the size of each dimension + * @throws DimensionError + */ + + +function validate(array, size) { + var isScalar = size.length === 0; + + if (isScalar) { + // scalar + if (Array.isArray(array)) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](array.length, 0); + } + } else { + // array + _validate(array, size, 0); + } +} +/** + * Test whether index is an integer number with index >= 0 and index < length + * when length is provided + * @param {number} index Zero-based index + * @param {number} [length] Length of the array + */ + +function validateIndex(index, length) { + if (!Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(index) || !Object(_number__WEBPACK_IMPORTED_MODULE_0__[/* isInteger */ "i"])(index)) { + throw new TypeError('Index must be an integer (value: ' + index + ')'); + } + + if (index < 0 || typeof length === 'number' && index >= length) { + throw new _error_IndexError__WEBPACK_IMPORTED_MODULE_4__[/* IndexError */ "a"](index, length); + } +} +/** + * Resize a multi dimensional array. The resized array is returned. + * @param {Array} array Array to be resized + * @param {Array.} size Array with the size of each dimension + * @param {*} [defaultValue=0] Value to be filled in in new entries, + * zero by default. Specify for example `null`, + * to clearly see entries that are not explicitly + * set. + * @return {Array} array The resized array + */ + +function resize(array, size, defaultValue) { + // TODO: add support for scalars, having size=[] ? + // check the type of the arguments + if (!Array.isArray(array) || !Array.isArray(size)) { + throw new TypeError('Array expected'); + } + + if (size.length === 0) { + throw new Error('Resizing to scalar is not supported'); + } // check whether size contains positive integers + + + size.forEach(function (value) { + if (!Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(value) || !Object(_number__WEBPACK_IMPORTED_MODULE_0__[/* isInteger */ "i"])(value) || value < 0) { + throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + Object(_string__WEBPACK_IMPORTED_MODULE_2__[/* format */ "d"])(size) + ')'); + } + }); // recursively resize the array + + var _defaultValue = defaultValue !== undefined ? defaultValue : 0; + + _resize(array, size, 0, _defaultValue); + + return array; +} +/** + * Recursively resize a multi dimensional array + * @param {Array} array Array to be resized + * @param {number[]} size Array with the size of each dimension + * @param {number} dim Current dimension + * @param {*} [defaultValue] Value to be filled in in new entries, + * undefined by default. + * @private + */ + +function _resize(array, size, dim, defaultValue) { + var i; + var elem; + var oldLen = array.length; + var newLen = size[dim]; + var minLen = Math.min(oldLen, newLen); // apply new length + + array.length = newLen; + + if (dim < size.length - 1) { + // non-last dimension + var dimNext = dim + 1; // resize existing child arrays + + for (i = 0; i < minLen; i++) { + // resize child array + elem = array[i]; + + if (!Array.isArray(elem)) { + elem = [elem]; // add a dimension + + array[i] = elem; + } + + _resize(elem, size, dimNext, defaultValue); + } // create new child arrays + + + for (i = minLen; i < newLen; i++) { + // get child array + elem = []; + array[i] = elem; // resize new child array + + _resize(elem, size, dimNext, defaultValue); + } + } else { + // last dimension + // remove dimensions of existing values + for (i = 0; i < minLen; i++) { + while (Array.isArray(array[i])) { + array[i] = array[i][0]; + } + } // fill new elements with the default value + + + for (i = minLen; i < newLen; i++) { + array[i] = defaultValue; + } + } +} +/** + * Re-shape a multi dimensional array to fit the specified dimensions + * @param {Array} array Array to be reshaped + * @param {Array.} sizes List of sizes for each dimension + * @returns {Array} Array whose data has been formatted to fit the + * specified dimensions + * + * @throws {DimensionError} If the product of the new dimension sizes does + * not equal that of the old ones + */ + + +function reshape(array, sizes) { + var flatArray = flatten(array); + var newArray; + + function product(arr) { + return arr.reduce(function (prev, curr) { + return prev * curr; + }); + } + + if (!Array.isArray(array) || !Array.isArray(sizes)) { + throw new TypeError('Array expected'); + } + + if (sizes.length === 0) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](0, product(arraySize(array)), '!='); + } + + var totalSize = 1; + + for (var sizeIndex = 0; sizeIndex < sizes.length; sizeIndex++) { + totalSize *= sizes[sizeIndex]; + } + + if (flatArray.length !== totalSize) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](product(sizes), product(arraySize(array)), '!='); + } + + try { + newArray = _reshape(flatArray, sizes); + } catch (e) { + if (e instanceof _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"]) { + throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](product(sizes), product(arraySize(array)), '!='); + } + + throw e; + } + + return newArray; +} +/** + * Iteratively re-shape a multi dimensional array to fit the specified dimensions + * @param {Array} array Array to be reshaped + * @param {Array.} sizes List of sizes for each dimension + * @returns {Array} Array whose data has been formatted to fit the + * specified dimensions + */ + +function _reshape(array, sizes) { + // testing if there are enough elements for the requested shape + var tmpArray = array; + var tmpArray2; // for each dimensions starting by the last one and ignoring the first one + + for (var sizeIndex = sizes.length - 1; sizeIndex > 0; sizeIndex--) { + var size = sizes[sizeIndex]; + tmpArray2 = []; // aggregate the elements of the current tmpArray in elements of the requested size + + var length = tmpArray.length / size; + + for (var i = 0; i < length; i++) { + tmpArray2.push(tmpArray.slice(i * size, (i + 1) * size)); + } // set it as the new tmpArray for the next loop turn or for return + + + tmpArray = tmpArray2; + } + + return tmpArray; +} +/** + * Squeeze a multi dimensional array + * @param {Array} array + * @param {Array} [size] + * @returns {Array} returns the array itself + */ + + +function squeeze(array, size) { + var s = size || arraySize(array); // squeeze outer dimensions + + while (Array.isArray(array) && array.length === 1) { + array = array[0]; + s.shift(); + } // find the first dimension to be squeezed + + + var dims = s.length; + + while (s[dims - 1] === 1) { + dims--; + } // squeeze inner dimensions + + + if (dims < s.length) { + array = _squeeze(array, dims, 0); + s.length = dims; + } + + return array; +} +/** + * Recursively squeeze a multi dimensional array + * @param {Array} array + * @param {number} dims Required number of dimensions + * @param {number} dim Current dimension + * @returns {Array | *} Returns the squeezed array + * @private + */ + +function _squeeze(array, dims, dim) { + var i, ii; + + if (dim < dims) { + var next = dim + 1; + + for (i = 0, ii = array.length; i < ii; i++) { + array[i] = _squeeze(array[i], dims, next); + } + } else { + while (Array.isArray(array)) { + array = array[0]; + } + } + + return array; +} +/** + * Unsqueeze a multi dimensional array: add dimensions when missing + * + * Paramter `size` will be mutated to match the new, unqueezed matrix size. + * + * @param {Array} array + * @param {number} dims Desired number of dimensions of the array + * @param {number} [outer] Number of outer dimensions to be added + * @param {Array} [size] Current size of array. + * @returns {Array} returns the array itself + * @private + */ + + +function unsqueeze(array, dims, outer, size) { + var s = size || arraySize(array); // unsqueeze outer dimensions + + if (outer) { + for (var i = 0; i < outer; i++) { + array = [array]; + s.unshift(1); + } + } // unsqueeze inner dimensions + + + array = _unsqueeze(array, dims, 0); + + while (s.length < dims) { + s.push(1); + } + + return array; +} +/** + * Recursively unsqueeze a multi dimensional array + * @param {Array} array + * @param {number} dims Required number of dimensions + * @param {number} dim Current dimension + * @returns {Array | *} Returns the squeezed array + * @private + */ + +function _unsqueeze(array, dims, dim) { + var i, ii; + + if (Array.isArray(array)) { + var next = dim + 1; + + for (i = 0, ii = array.length; i < ii; i++) { + array[i] = _unsqueeze(array[i], dims, next); + } + } else { + for (var d = dim; d < dims; d++) { + array = [array]; + } + } + + return array; +} +/** + * Flatten a multi dimensional array, put all elements in a one dimensional + * array + * @param {Array} array A multi dimensional array + * @return {Array} The flattened array (1 dimensional) + */ + + +function flatten(array) { + if (!Array.isArray(array)) { + // if not an array, return as is + return array; + } + + var flat = []; + array.forEach(function callback(value) { + if (Array.isArray(value)) { + value.forEach(callback); // traverse through sub-arrays recursively + } else { + flat.push(value); + } + }); + return flat; +} +/** + * A safe map + * @param {Array} array + * @param {function} callback + */ + +function map(array, callback) { + return Array.prototype.map.call(array, callback); +} +/** + * A safe forEach + * @param {Array} array + * @param {function} callback + */ + +function forEach(array, callback) { + Array.prototype.forEach.call(array, callback); +} +/** + * A safe filter + * @param {Array} array + * @param {function} callback + */ + +function filter(array, callback) { + if (arraySize(array).length !== 1) { + throw new Error('Only one dimensional matrices supported'); + } + + return Array.prototype.filter.call(array, callback); +} +/** + * Filter values in a callback given a regular expression + * @param {Array} array + * @param {RegExp} regexp + * @return {Array} Returns the filtered array + * @private + */ + +function filterRegExp(array, regexp) { + if (arraySize(array).length !== 1) { + throw new Error('Only one dimensional matrices supported'); + } + + return Array.prototype.filter.call(array, function (entry) { + return regexp.test(entry); + }); +} +/** + * A safe join + * @param {Array} array + * @param {string} separator + */ + +function join(array, separator) { + return Array.prototype.join.call(array, separator); +} +/** + * Assign a numeric identifier to every element of a sorted array + * @param {Array} a An array + * @return {Array} An array of objects containing the original value and its identifier + */ + +function identify(a) { + if (!Array.isArray(a)) { + throw new TypeError('Array input expected'); + } + + if (a.length === 0) { + return a; + } + + var b = []; + var count = 0; + b[0] = { + value: a[0], + identifier: 0 + }; + + for (var i = 1; i < a.length; i++) { + if (a[i] === a[i - 1]) { + count++; + } else { + count = 0; + } + + b.push({ + value: a[i], + identifier: count + }); + } + + return b; +} +/** + * Remove the numeric identifier from the elements + * @param {array} a An array + * @return {array} An array of values without identifiers + */ + +function generalize(a) { + if (!Array.isArray(a)) { + throw new TypeError('Array input expected'); + } + + if (a.length === 0) { + return a; + } + + var b = []; + + for (var i = 0; i < a.length; i++) { + b.push(a[i].value); + } + + return b; +} +/** + * Check the datatype of a given object + * This is a low level implementation that should only be used by + * parent Matrix classes such as SparseMatrix or DenseMatrix + * This method does not validate Array Matrix shape + * @param {Array} array + * @param {function} typeOf Callback function to use to determine the type of a value + * @return string + */ + +function getArrayDataType(array, typeOf) { + var type; // to hold type info + + var length = 0; // to hold length value to ensure it has consistent sizes + + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var isArray = Array.isArray(item); // Saving the target matrix row size + + if (i === 0 && isArray) { + length = item.length; + } // If the current item is an array but the length does not equal the targetVectorSize + + + if (isArray && item.length !== length) { + return undefined; + } + + var itemType = isArray ? getArrayDataType(item, typeOf) // recurse into a nested array + : typeOf(item); + + if (type === undefined) { + type = itemType; // first item + } else if (type !== itemType) { + return 'mixed'; + } else {// we're good, everything has the same type so far + } + } + + return type; +} +/** + * Return the last item from an array + * @param array + * @returns {*} + */ + +function last(array) { + return array[array.length - 1]; +} +/** + * Get all but the last element of array. + */ + +function initial(array) { + return array.slice(0, array.length - 1); +} +/** + * Test whether an array or string contains an item + * @param {Array | string} array + * @param {*} item + * @return {boolean} + */ + +function contains(array, item) { + return array.indexOf(item) !== -1; +} + +/***/ }), +/* 3 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return clone; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return mapObject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return extend; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return deepExtend; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return deepStrictEqual; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return deepFlatten; }); +/* unused harmony export canDefineProperty */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return lazy; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return traverse; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return hasOwnProperty; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return isLegacyFactory; }); +/* unused harmony export get */ +/* unused harmony export set */ +/* unused harmony export pick */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return pickShallow; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return values; }); +/* harmony import */ var _is__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + + +/** + * Clone an object + * + * clone(x) + * + * Can clone any primitive type, array, and object. + * If x has a function clone, this function will be invoked to clone the object. + * + * @param {*} x + * @return {*} clone + */ + +function clone(x) { + var type = _typeof(x); // immutable primitive types + + + if (type === 'number' || type === 'string' || type === 'boolean' || x === null || x === undefined) { + return x; + } // use clone function of the object when available + + + if (typeof x.clone === 'function') { + return x.clone(); + } // array + + + if (Array.isArray(x)) { + return x.map(function (value) { + return clone(value); + }); + } + + if (x instanceof Date) return new Date(x.valueOf()); + if (Object(_is__WEBPACK_IMPORTED_MODULE_0__[/* isBigNumber */ "e"])(x)) return x; // bignumbers are immutable + + if (x instanceof RegExp) throw new TypeError('Cannot clone ' + x); // TODO: clone a RegExp + // object + + return mapObject(x, clone); +} +/** + * Apply map to all properties of an object + * @param {Object} object + * @param {function} callback + * @return {Object} Returns a copy of the object with mapped properties + */ + +function mapObject(object, callback) { + var clone = {}; + + for (var key in object) { + if (hasOwnProperty(object, key)) { + clone[key] = callback(object[key]); + } + } + + return clone; +} +/** + * Extend object a with the properties of object b + * @param {Object} a + * @param {Object} b + * @return {Object} a + */ + +function extend(a, b) { + for (var prop in b) { + if (hasOwnProperty(b, prop)) { + a[prop] = b[prop]; + } + } + + return a; +} +/** + * Deep extend an object a with the properties of object b + * @param {Object} a + * @param {Object} b + * @returns {Object} + */ + +function deepExtend(a, b) { + // TODO: add support for Arrays to deepExtend + if (Array.isArray(b)) { + throw new TypeError('Arrays are not supported by deepExtend'); + } + + for (var prop in b) { + if (hasOwnProperty(b, prop)) { + if (b[prop] && b[prop].constructor === Object) { + if (a[prop] === undefined) { + a[prop] = {}; + } + + if (a[prop] && a[prop].constructor === Object) { + deepExtend(a[prop], b[prop]); + } else { + a[prop] = b[prop]; + } + } else if (Array.isArray(b[prop])) { + throw new TypeError('Arrays are not supported by deepExtend'); + } else { + a[prop] = b[prop]; + } + } + } + + return a; +} +/** + * Deep test equality of all fields in two pairs of arrays or objects. + * Compares values and functions strictly (ie. 2 is not the same as '2'). + * @param {Array | Object} a + * @param {Array | Object} b + * @returns {boolean} + */ + +function deepStrictEqual(a, b) { + var prop, i, len; + + if (Array.isArray(a)) { + if (!Array.isArray(b)) { + return false; + } + + if (a.length !== b.length) { + return false; + } + + for (i = 0, len = a.length; i < len; i++) { + if (!deepStrictEqual(a[i], b[i])) { + return false; + } + } + + return true; + } else if (typeof a === 'function') { + return a === b; + } else if (a instanceof Object) { + if (Array.isArray(b) || !(b instanceof Object)) { + return false; + } + + for (prop in a) { + // noinspection JSUnfilteredForInLoop + if (!(prop in b) || !deepStrictEqual(a[prop], b[prop])) { + return false; + } + } + + for (prop in b) { + // noinspection JSUnfilteredForInLoop + if (!(prop in a) || !deepStrictEqual(a[prop], b[prop])) { + return false; + } + } + + return true; + } else { + return a === b; + } +} +/** + * Recursively flatten a nested object. + * @param {Object} nestedObject + * @return {Object} Returns the flattened object + */ + +function deepFlatten(nestedObject) { + var flattenedObject = {}; + + _deepFlatten(nestedObject, flattenedObject); + + return flattenedObject; +} // helper function used by deepFlatten + +function _deepFlatten(nestedObject, flattenedObject) { + for (var prop in nestedObject) { + if (hasOwnProperty(nestedObject, prop)) { + var value = nestedObject[prop]; + + if (_typeof(value) === 'object' && value !== null) { + _deepFlatten(value, flattenedObject); + } else { + flattenedObject[prop] = value; + } + } + } +} +/** + * Test whether the current JavaScript engine supports Object.defineProperty + * @returns {boolean} returns true if supported + */ + + +function canDefineProperty() { + // test needed for broken IE8 implementation + try { + if (Object.defineProperty) { + Object.defineProperty({}, 'x', { + get: function get() {} + }); + return true; + } + } catch (e) {} + + return false; +} +/** + * Attach a lazy loading property to a constant. + * The given function `fn` is called once when the property is first requested. + * + * @param {Object} object Object where to add the property + * @param {string} prop Property name + * @param {Function} valueResolver Function returning the property value. Called + * without arguments. + */ + +function lazy(object, prop, valueResolver) { + var _uninitialized = true; + + var _value; + + Object.defineProperty(object, prop, { + get: function get() { + if (_uninitialized) { + _value = valueResolver(); + _uninitialized = false; + } + + return _value; + }, + set: function set(value) { + _value = value; + _uninitialized = false; + }, + configurable: true, + enumerable: true + }); +} +/** + * Traverse a path into an object. + * When a namespace is missing, it will be created + * @param {Object} object + * @param {string | string[]} path A dot separated string like 'name.space' + * @return {Object} Returns the object at the end of the path + */ + +function traverse(object, path) { + if (path && typeof path === 'string') { + return traverse(object, path.split('.')); + } + + var obj = object; + + if (path) { + for (var i = 0; i < path.length; i++) { + var key = path[i]; + + if (!(key in obj)) { + obj[key] = {}; + } + + obj = obj[key]; + } + } + + return obj; +} +/** + * A safe hasOwnProperty + * @param {Object} object + * @param {string} property + */ + +function hasOwnProperty(object, property) { + return object && Object.hasOwnProperty.call(object, property); +} +/** + * Test whether an object is a factory. a factory has fields: + * + * - factory: function (type: Object, config: Object, load: function, typed: function [, math: Object]) (required) + * - name: string (optional) + * - path: string A dot separated path (optional) + * - math: boolean If true (false by default), the math namespace is passed + * as fifth argument of the factory function + * + * @param {*} object + * @returns {boolean} + */ + +function isLegacyFactory(object) { + return object && typeof object.factory === 'function'; +} +/** + * Get a nested property from an object + * @param {Object} object + * @param {string | string[]} path + * @returns {Object} + */ + +function get(object, path) { + if (typeof path === 'string') { + if (isPath(path)) { + return get(object, path.split('.')); + } else { + return object[path]; + } + } + + var child = object; + + for (var i = 0; i < path.length; i++) { + var key = path[i]; + child = child ? child[key] : undefined; + } + + return child; +} +/** + * Set a nested property in an object + * Mutates the object itself + * If the path doesn't exist, it will be created + * @param {Object} object + * @param {string | string[]} path + * @param {*} value + * @returns {Object} + */ + +function set(object, path, value) { + if (typeof path === 'string') { + if (isPath(path)) { + return set(object, path.split('.'), value); + } else { + object[path] = value; + return object; + } + } + + var child = object; + + for (var i = 0; i < path.length - 1; i++) { + var key = path[i]; + + if (child[key] === undefined) { + child[key] = {}; + } + + child = child[key]; + } + + if (path.length > 0) { + var lastKey = path[path.length - 1]; + child[lastKey] = value; + } + + return object; +} +/** + * Create an object composed of the picked object properties + * @param {Object} object + * @param {string[]} properties + * @param {function} [transform] Optional value to transform a value when picking it + * @return {Object} + */ + +function pick(object, properties, transform) { + var copy = {}; + + for (var i = 0; i < properties.length; i++) { + var key = properties[i]; + var value = get(object, key); + + if (value !== undefined) { + set(copy, key, transform ? transform(value, key) : value); + } + } + + return copy; +} +/** + * Shallow version of pick, creating an object composed of the picked object properties + * but not for nested properties + * @param {Object} object + * @param {string[]} properties + * @return {Object} + */ + +function pickShallow(object, properties) { + var copy = {}; + + for (var i = 0; i < properties.length; i++) { + var key = properties[i]; + var value = object[key]; + + if (value !== undefined) { + copy[key] = value; + } + } + + return copy; +} +function values(object) { + return Object.keys(object).map(function (key) { + return object[key]; + }); +} // helper function to test whether a string contains a path like 'user.name' + +function isPath(str) { + return str.indexOf('.') !== -1; +} + +/***/ }), +/* 4 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return isInteger; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return sign; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return log2; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return log10; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return log1p; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return cbrt; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return expm1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return format; }); +/* unused harmony export splitNumber */ +/* unused harmony export toEngineering */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return toFixed; }); +/* unused harmony export toExponential */ +/* unused harmony export toPrecision */ +/* unused harmony export roundDigits */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return digits; }); +/* unused harmony export DBL_EPSILON */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return nearlyEqual; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return acosh; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return asinh; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return atanh; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return cosh; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return sinh; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return tanh; }); +/* harmony import */ var _object__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); +/* harmony import */ var _is__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1); + + +/** + * @typedef {{sign: '+' | '-' | '', coefficients: number[], exponent: number}} SplitValue + */ + +/** + * Check if a number is integer + * @param {number | boolean} value + * @return {boolean} isInteger + */ + +function isInteger(value) { + if (typeof value === 'boolean') { + return true; + } + + return isFinite(value) ? value === Math.round(value) : false; // Note: we use ==, not ===, as we can have Booleans as well +} +/** + * Calculate the sign of a number + * @param {number} x + * @returns {number} + */ + +var sign = /* #__PURE__ */Math.sign || function (x) { + if (x > 0) { + return 1; + } else if (x < 0) { + return -1; + } else { + return 0; + } +}; +/** + * Calculate the base-2 logarithm of a number + * @param {number} x + * @returns {number} + */ + +var log2 = /* #__PURE__ */Math.log2 || function log2(x) { + return Math.log(x) / Math.LN2; +}; +/** + * Calculate the base-10 logarithm of a number + * @param {number} x + * @returns {number} + */ + +var log10 = /* #__PURE__ */Math.log10 || function log10(x) { + return Math.log(x) / Math.LN10; +}; +/** + * Calculate the natural logarithm of a number + 1 + * @param {number} x + * @returns {number} + */ + +var log1p = /* #__PURE__ */Math.log1p || function (x) { + return Math.log(x + 1); +}; +/** + * Calculate cubic root for a number + * + * Code from es6-shim.js: + * https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1564-L1577 + * + * @param {number} x + * @returns {number} Returns the cubic root of x + */ + +var cbrt = /* #__PURE__ */Math.cbrt || function cbrt(x) { + if (x === 0) { + return x; + } + + var negate = x < 0; + var result; + + if (negate) { + x = -x; + } + + if (isFinite(x)) { + result = Math.exp(Math.log(x) / 3); // from https://en.wikipedia.org/wiki/Cube_root#Numerical_methods + + result = (x / (result * result) + 2 * result) / 3; + } else { + result = x; + } + + return negate ? -result : result; +}; +/** + * Calculates exponentiation minus 1 + * @param {number} x + * @return {number} res + */ + +var expm1 = /* #__PURE__ */Math.expm1 || function expm1(x) { + return x >= 2e-4 || x <= -2e-4 ? Math.exp(x) - 1 : x + x * x / 2 + x * x * x / 6; +}; +/** + * Convert a number to a formatted string representation. + * + * Syntax: + * + * format(value) + * format(value, options) + * format(value, precision) + * format(value, fn) + * + * Where: + * + * {number} value The value to be formatted + * {Object} options An object with formatting options. Available options: + * {string} notation + * Number notation. Choose from: + * 'fixed' Always use regular number notation. + * For example '123.40' and '14000000' + * 'exponential' Always use exponential notation. + * For example '1.234e+2' and '1.4e+7' + * 'engineering' Always use engineering notation. + * For example '123.4e+0' and '14.0e+6' + * 'auto' (default) Regular number notation for numbers + * having an absolute value between + * `lowerExp` and `upperExp` bounds, and + * uses exponential notation elsewhere. + * Lower bound is included, upper bound + * is excluded. + * For example '123.4' and '1.4e7'. + * {number} precision A number between 0 and 16 to round + * the digits of the number. + * In case of notations 'exponential', + * 'engineering', and 'auto', + * `precision` defines the total + * number of significant digits returned. + * In case of notation 'fixed', + * `precision` defines the number of + * significant digits after the decimal + * point. + * `precision` is undefined by default, + * not rounding any digits. + * {number} lowerExp Exponent determining the lower boundary + * for formatting a value with an exponent + * when `notation='auto`. + * Default value is `-3`. + * {number} upperExp Exponent determining the upper boundary + * for formatting a value with an exponent + * when `notation='auto`. + * Default value is `5`. + * {Function} fn A custom formatting function. Can be used to override the + * built-in notations. Function `fn` is called with `value` as + * parameter and must return a string. Is useful for example to + * format all values inside a matrix in a particular way. + * + * Examples: + * + * format(6.4) // '6.4' + * format(1240000) // '1.24e6' + * format(1/3) // '0.3333333333333333' + * format(1/3, 3) // '0.333' + * format(21385, 2) // '21000' + * format(12.071, {notation: 'fixed'}) // '12' + * format(2.3, {notation: 'fixed', precision: 2}) // '2.30' + * format(52.8, {notation: 'exponential'}) // '5.28e+1' + * format(12345678, {notation: 'engineering'}) // '12.345678e+6' + * + * @param {number} value + * @param {Object | Function | number} [options] + * @return {string} str The formatted value + */ + +function format(value, options) { + if (typeof options === 'function') { + // handle format(value, fn) + return options(value); + } // handle special cases + + + if (value === Infinity) { + return 'Infinity'; + } else if (value === -Infinity) { + return '-Infinity'; + } else if (isNaN(value)) { + return 'NaN'; + } // default values for options + + + var notation = 'auto'; + var precision; + + if (options) { + // determine notation from options + if (options.notation) { + notation = options.notation; + } // determine precision from options + + + if (Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(options)) { + precision = options; + } else if (Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(options.precision)) { + precision = options.precision; + } + } // handle the various notations + + + switch (notation) { + case 'fixed': + return toFixed(value, precision); + + case 'exponential': + return toExponential(value, precision); + + case 'engineering': + return toEngineering(value, precision); + + case 'auto': + // TODO: clean up some day. Deprecated since: 2018-01-24 + // @deprecated upper and lower are replaced with upperExp and lowerExp since v4.0.0 + if (options && options.exponential && (options.exponential.lower !== undefined || options.exponential.upper !== undefined)) { + var fixedOptions = Object(_object__WEBPACK_IMPORTED_MODULE_0__[/* mapObject */ "i"])(options, function (x) { + return x; + }); + fixedOptions.exponential = undefined; + + if (options.exponential.lower !== undefined) { + fixedOptions.lowerExp = Math.round(Math.log(options.exponential.lower) / Math.LN10); + } + + if (options.exponential.upper !== undefined) { + fixedOptions.upperExp = Math.round(Math.log(options.exponential.upper) / Math.LN10); + } + + console.warn('Deprecation warning: Formatting options exponential.lower and exponential.upper ' + '(minimum and maximum value) ' + 'are replaced with exponential.lowerExp and exponential.upperExp ' + '(minimum and maximum exponent) since version 4.0.0. ' + 'Replace ' + JSON.stringify(options) + ' with ' + JSON.stringify(fixedOptions)); + return toPrecision(value, precision, fixedOptions); + } // remove trailing zeros after the decimal point + + + return toPrecision(value, precision, options && options).replace(/((\.\d*?)(0+))($|e)/, function () { + var digits = arguments[2]; + var e = arguments[4]; + return digits !== '.' ? digits + e : e; + }); + + default: + throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", or "fixed".'); + } +} +/** + * Split a number into sign, coefficients, and exponent + * @param {number | string} value + * @return {SplitValue} + * Returns an object containing sign, coefficients, and exponent + */ + +function splitNumber(value) { + // parse the input value + var match = String(value).toLowerCase().match(/^0*?(-?)(\d+\.?\d*)(e([+-]?\d+))?$/); + + if (!match) { + throw new SyntaxError('Invalid number ' + value); + } + + var sign = match[1]; + var digits = match[2]; + var exponent = parseFloat(match[4] || '0'); + var dot = digits.indexOf('.'); + exponent += dot !== -1 ? dot - 1 : digits.length - 1; + var coefficients = digits.replace('.', '') // remove the dot (must be removed before removing leading zeros) + .replace(/^0*/, function (zeros) { + // remove leading zeros, add their count to the exponent + exponent -= zeros.length; + return ''; + }).replace(/0*$/, '') // remove trailing zeros + .split('').map(function (d) { + return parseInt(d); + }); + + if (coefficients.length === 0) { + coefficients.push(0); + exponent++; + } + + return { + sign: sign, + coefficients: coefficients, + exponent: exponent + }; +} +/** + * Format a number in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3' + * @param {number | string} value + * @param {number} [precision] Optional number of significant figures to return. + */ + +function toEngineering(value, precision) { + if (isNaN(value) || !isFinite(value)) { + return String(value); + } + + var split = splitNumber(value); + var rounded = roundDigits(split, precision); + var e = rounded.exponent; + var c = rounded.coefficients; // find nearest lower multiple of 3 for exponent + + var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3; + + if (Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(precision)) { + // add zeroes to give correct sig figs + while (precision > c.length || e - newExp + 1 > c.length) { + c.push(0); + } + } else { + // concatenate coefficients with necessary zeros + // add zeros if necessary (for example: 1e+8 -> 100e+6) + var missingZeros = Math.abs(e - newExp) - (c.length - 1); + + for (var i = 0; i < missingZeros; i++) { + c.push(0); + } + } // find difference in exponents + + + var expDiff = Math.abs(e - newExp); + var decimalIdx = 1; // push decimal index over by expDiff times + + while (expDiff > 0) { + decimalIdx++; + expDiff--; + } // if all coefficient values are zero after the decimal point and precision is unset, don't add a decimal value. + // otherwise concat with the rest of the coefficients + + + var decimals = c.slice(decimalIdx).join(''); + var decimalVal = Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(precision) && decimals.length || decimals.match(/[1-9]/) ? '.' + decimals : ''; + var str = c.slice(0, decimalIdx).join('') + decimalVal + 'e' + (e >= 0 ? '+' : '') + newExp.toString(); + return rounded.sign + str; +} +/** + * Format a number with fixed notation. + * @param {number | string} value + * @param {number} [precision=undefined] Optional number of decimals after the + * decimal point. null by default. + */ + +function toFixed(value, precision) { + if (isNaN(value) || !isFinite(value)) { + return String(value); + } + + var splitValue = splitNumber(value); + var rounded = typeof precision === 'number' ? roundDigits(splitValue, splitValue.exponent + 1 + precision) : splitValue; + var c = rounded.coefficients; + var p = rounded.exponent + 1; // exponent may have changed + // append zeros if needed + + var pp = p + (precision || 0); + + if (c.length < pp) { + c = c.concat(zeros(pp - c.length)); + } // prepend zeros if needed + + + if (p < 0) { + c = zeros(-p + 1).concat(c); + p = 1; + } // insert a dot if needed + + + if (p < c.length) { + c.splice(p, 0, p === 0 ? '0.' : '.'); + } + + return rounded.sign + c.join(''); +} +/** + * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3' + * @param {number | string} value + * @param {number} [precision] Number of digits in formatted output. + * If not provided, the maximum available digits + * is used. + */ + +function toExponential(value, precision) { + if (isNaN(value) || !isFinite(value)) { + return String(value); + } // round if needed, else create a clone + + + var split = splitNumber(value); + var rounded = precision ? roundDigits(split, precision) : split; + var c = rounded.coefficients; + var e = rounded.exponent; // append zeros if needed + + if (c.length < precision) { + c = c.concat(zeros(precision - c.length)); + } // format as `C.CCCe+EEE` or `C.CCCe-EEE` + + + var first = c.shift(); + return rounded.sign + first + (c.length > 0 ? '.' + c.join('') : '') + 'e' + (e >= 0 ? '+' : '') + e; +} +/** + * Format a number with a certain precision + * @param {number | string} value + * @param {number} [precision=undefined] Optional number of digits. + * @param {{lowerExp: number | undefined, upperExp: number | undefined}} [options] + * By default: + * lowerExp = -3 (incl) + * upper = +5 (excl) + * @return {string} + */ + +function toPrecision(value, precision, options) { + if (isNaN(value) || !isFinite(value)) { + return String(value); + } // determine lower and upper bound for exponential notation. + + + var lowerExp = options && options.lowerExp !== undefined ? options.lowerExp : -3; + var upperExp = options && options.upperExp !== undefined ? options.upperExp : 5; + var split = splitNumber(value); + var rounded = precision ? roundDigits(split, precision) : split; + + if (rounded.exponent < lowerExp || rounded.exponent >= upperExp) { + // exponential notation + return toExponential(value, precision); + } else { + var c = rounded.coefficients; + var e = rounded.exponent; // append trailing zeros + + if (c.length < precision) { + c = c.concat(zeros(precision - c.length)); + } // append trailing zeros + // TODO: simplify the next statement + + + c = c.concat(zeros(e - c.length + 1 + (c.length < precision ? precision - c.length : 0))); // prepend zeros + + c = zeros(-e).concat(c); + var dot = e > 0 ? e : 0; + + if (dot < c.length - 1) { + c.splice(dot + 1, 0, '.'); + } + + return rounded.sign + c.join(''); + } +} +/** + * Round the number of digits of a number * + * @param {SplitValue} split A value split with .splitNumber(value) + * @param {number} precision A positive integer + * @return {SplitValue} + * Returns an object containing sign, coefficients, and exponent + * with rounded digits + */ + +function roundDigits(split, precision) { + // create a clone + var rounded = { + sign: split.sign, + coefficients: split.coefficients, + exponent: split.exponent + }; + var c = rounded.coefficients; // prepend zeros if needed + + while (precision <= 0) { + c.unshift(0); + rounded.exponent++; + precision++; + } + + if (c.length > precision) { + var removed = c.splice(precision, c.length - precision); + + if (removed[0] >= 5) { + var i = precision - 1; + c[i]++; + + while (c[i] === 10) { + c.pop(); + + if (i === 0) { + c.unshift(0); + rounded.exponent++; + i++; + } + + i--; + c[i]++; + } + } + } + + return rounded; +} +/** + * Create an array filled with zeros. + * @param {number} length + * @return {Array} + */ + +function zeros(length) { + var arr = []; + + for (var i = 0; i < length; i++) { + arr.push(0); + } + + return arr; +} +/** + * Count the number of significant digits of a number. + * + * For example: + * 2.34 returns 3 + * 0.0034 returns 2 + * 120.5e+30 returns 4 + * + * @param {number} value + * @return {number} digits Number of significant digits + */ + + +function digits(value) { + return value.toExponential().replace(/e.*$/, '') // remove exponential notation + .replace(/^0\.?0*|\./, '') // remove decimal point and leading zeros + .length; +} +/** + * Minimum number added to one that makes the result different than one + */ + +var DBL_EPSILON = Number.EPSILON || 2.2204460492503130808472633361816E-16; +/** + * Compares two floating point numbers. + * @param {number} x First value to compare + * @param {number} y Second value to compare + * @param {number} [epsilon] The maximum relative difference between x and y + * If epsilon is undefined or null, the function will + * test whether x and y are exactly equal. + * @return {boolean} whether the two numbers are nearly equal +*/ + +function nearlyEqual(x, y, epsilon) { + // if epsilon is null or undefined, test whether x and y are exactly equal + if (epsilon === null || epsilon === undefined) { + return x === y; + } + + if (x === y) { + return true; + } // NaN + + + if (isNaN(x) || isNaN(y)) { + return false; + } // at this point x and y should be finite + + + if (isFinite(x) && isFinite(y)) { + // check numbers are very close, needed when comparing numbers near zero + var diff = Math.abs(x - y); + + if (diff < DBL_EPSILON) { + return true; + } else { + // use relative error + return diff <= Math.max(Math.abs(x), Math.abs(y)) * epsilon; + } + } // Infinite and Number or negative Infinite and positive Infinite cases + + + return false; +} +/** + * Calculate the hyperbolic arccos of a number + * @param {number} x + * @return {number} + */ + +var acosh = Math.acosh || function (x) { + return Math.log(Math.sqrt(x * x - 1) + x); +}; +var asinh = Math.asinh || function (x) { + return Math.log(Math.sqrt(x * x + 1) + x); +}; +/** + * Calculate the hyperbolic arctangent of a number + * @param {number} x + * @return {number} + */ + +var atanh = Math.atanh || function (x) { + return Math.log((1 + x) / (1 - x)) / 2; +}; +/** + * Calculate the hyperbolic cosine of a number + * @param {number} x + * @returns {number} + */ + +var cosh = Math.cosh || function (x) { + return (Math.exp(x) + Math.exp(-x)) / 2; +}; +/** + * Calculate the hyperbolic sine of a number + * @param {number} x + * @returns {number} + */ + +var sinh = Math.sinh || function (x) { + return (Math.exp(x) - Math.exp(-x)) / 2; +}; +/** + * Calculate the hyperbolic tangent of a number + * @param {number} x + * @returns {number} + */ + +var tanh = Math.tanh || function (x) { + var e = Math.exp(2 * x); + return (e - 1) / (e + 1); +}; + +/***/ }), +/* 5 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ endsWith; }); +__webpack_require__.d(__webpack_exports__, "d", function() { return /* binding */ string_format; }); +__webpack_require__.d(__webpack_exports__, "e", function() { return /* binding */ stringify; }); +__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ string_escape; }); +__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ compareText; }); + +// EXTERNAL MODULE: ./src/utils/is.js +var is = __webpack_require__(1); + +// EXTERNAL MODULE: ./src/utils/number.js +var number = __webpack_require__(4); + +// EXTERNAL MODULE: ./src/utils/object.js +var object = __webpack_require__(3); + +// CONCATENATED MODULE: ./src/utils/bignumber/formatter.js + +/** + * Convert a BigNumber to a formatted string representation. + * + * Syntax: + * + * format(value) + * format(value, options) + * format(value, precision) + * format(value, fn) + * + * Where: + * + * {number} value The value to be formatted + * {Object} options An object with formatting options. Available options: + * {string} notation + * Number notation. Choose from: + * 'fixed' Always use regular number notation. + * For example '123.40' and '14000000' + * 'exponential' Always use exponential notation. + * For example '1.234e+2' and '1.4e+7' + * 'auto' (default) Regular number notation for numbers + * having an absolute value between + * `lower` and `upper` bounds, and uses + * exponential notation elsewhere. + * Lower bound is included, upper bound + * is excluded. + * For example '123.4' and '1.4e7'. + * {number} precision A number between 0 and 16 to round + * the digits of the number. + * In case of notations 'exponential', + * 'engineering', and 'auto', + * `precision` defines the total + * number of significant digits returned. + * In case of notation 'fixed', + * `precision` defines the number of + * significant digits after the decimal + * point. + * `precision` is undefined by default. + * {number} lowerExp Exponent determining the lower boundary + * for formatting a value with an exponent + * when `notation='auto`. + * Default value is `-3`. + * {number} upperExp Exponent determining the upper boundary + * for formatting a value with an exponent + * when `notation='auto`. + * Default value is `5`. + * {Function} fn A custom formatting function. Can be used to override the + * built-in notations. Function `fn` is called with `value` as + * parameter and must return a string. Is useful for example to + * format all values inside a matrix in a particular way. + * + * Examples: + * + * format(6.4) // '6.4' + * format(1240000) // '1.24e6' + * format(1/3) // '0.3333333333333333' + * format(1/3, 3) // '0.333' + * format(21385, 2) // '21000' + * format(12e8, {notation: 'fixed'}) // returns '1200000000' + * format(2.3, {notation: 'fixed', precision: 4}) // returns '2.3000' + * format(52.8, {notation: 'exponential'}) // returns '5.28e+1' + * format(12400, {notation: 'engineering'}) // returns '12.400e+3' + * + * @param {BigNumber} value + * @param {Object | Function | number} [options] + * @return {string} str The formatted value + */ + +function format(value, options) { + if (typeof options === 'function') { + // handle format(value, fn) + return options(value); + } // handle special cases + + + if (!value.isFinite()) { + return value.isNaN() ? 'NaN' : value.gt(0) ? 'Infinity' : '-Infinity'; + } // default values for options + + + var notation = 'auto'; + var precision; + + if (options !== undefined) { + // determine notation from options + if (options.notation) { + notation = options.notation; + } // determine precision from options + + + if (typeof options === 'number') { + precision = options; + } else if (options.precision) { + precision = options.precision; + } + } // handle the various notations + + + switch (notation) { + case 'fixed': + return toFixed(value, precision); + + case 'exponential': + return toExponential(value, precision); + + case 'engineering': + return toEngineering(value, precision); + + case 'auto': + { + // TODO: clean up some day. Deprecated since: 2018-01-24 + // @deprecated upper and lower are replaced with upperExp and lowerExp since v4.0.0 + if (options && options.exponential && (options.exponential.lower !== undefined || options.exponential.upper !== undefined)) { + var fixedOptions = Object(object["i" /* mapObject */])(options, function (x) { + return x; + }); + fixedOptions.exponential = undefined; + + if (options.exponential.lower !== undefined) { + fixedOptions.lowerExp = Math.round(Math.log(options.exponential.lower) / Math.LN10); + } + + if (options.exponential.upper !== undefined) { + fixedOptions.upperExp = Math.round(Math.log(options.exponential.upper) / Math.LN10); + } + + console.warn('Deprecation warning: Formatting options exponential.lower and exponential.upper ' + '(minimum and maximum value) ' + 'are replaced with exponential.lowerExp and exponential.upperExp ' + '(minimum and maximum exponent) since version 4.0.0. ' + 'Replace ' + JSON.stringify(options) + ' with ' + JSON.stringify(fixedOptions)); + return format(value, fixedOptions); + } // determine lower and upper bound for exponential notation. + // TODO: implement support for upper and lower to be BigNumbers themselves + + + var lowerExp = options && options.lowerExp !== undefined ? options.lowerExp : -3; + var upperExp = options && options.upperExp !== undefined ? options.upperExp : 5; // handle special case zero + + if (value.isZero()) return '0'; // determine whether or not to output exponential notation + + var str; + var rounded = value.toSignificantDigits(precision); + var exp = rounded.e; + + if (exp >= lowerExp && exp < upperExp) { + // normal number notation + str = rounded.toFixed(); + } else { + // exponential notation + str = toExponential(value, precision); + } // remove trailing zeros after the decimal point + + + return str.replace(/((\.\d*?)(0+))($|e)/, function () { + var digits = arguments[2]; + var e = arguments[4]; + return digits !== '.' ? digits + e : e; + }); + } + + default: + throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", or "fixed".'); + } +} +/** + * Format a BigNumber in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3' + * @param {BigNumber | string} value + * @param {number} [precision] Optional number of significant figures to return. + */ + +function toEngineering(value, precision) { + // find nearest lower multiple of 3 for exponent + var e = value.e; + var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3; // find difference in exponents, and calculate the value without exponent + + var valueWithoutExp = value.mul(Math.pow(10, -newExp)); + var valueStr = valueWithoutExp.toPrecision(precision); + + if (valueStr.indexOf('e') !== -1) { + valueStr = valueWithoutExp.toString(); + } + + return valueStr + 'e' + (e >= 0 ? '+' : '') + newExp.toString(); +} +/** + * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3' + * @param {BigNumber} value + * @param {number} [precision] Number of digits in formatted output. + * If not provided, the maximum available digits + * is used. + * @returns {string} str + */ + +function toExponential(value, precision) { + if (precision !== undefined) { + return value.toExponential(precision - 1); // Note the offset of one + } else { + return value.toExponential(); + } +} +/** + * Format a number with fixed notation. + * @param {BigNumber} value + * @param {number} [precision=undefined] Optional number of decimals after the + * decimal point. Undefined by default. + */ + +function toFixed(value, precision) { + return value.toFixed(precision); +} +// CONCATENATED MODULE: ./src/utils/string.js +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + + + + +/** + * Check if a text ends with a certain string. + * @param {string} text + * @param {string} search + */ + +function endsWith(text, search) { + var start = text.length - search.length; + var end = text.length; + return text.substring(start, end) === search; +} +/** + * Format a value of any type into a string. + * + * Usage: + * math.format(value) + * math.format(value, precision) + * + * When value is a function: + * + * - When the function has a property `syntax`, it returns this + * syntax description. + * - In other cases, a string `'function'` is returned. + * + * When `value` is an Object: + * + * - When the object contains a property `format` being a function, this + * function is invoked as `value.format(options)` and the result is returned. + * - When the object has its own `toString` method, this method is invoked + * and the result is returned. + * - In other cases the function will loop over all object properties and + * return JSON object notation like '{"a": 2, "b": 3}'. + * + * Example usage: + * math.format(2/7) // '0.2857142857142857' + * math.format(math.pi, 3) // '3.14' + * math.format(new Complex(2, 3)) // '2 + 3i' + * math.format('hello') // '"hello"' + * + * @param {*} value Value to be stringified + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @return {string} str + */ + +function string_format(value, options) { + if (typeof value === 'number') { + return Object(number["h" /* format */])(value, options); + } + + if (Object(is["e" /* isBigNumber */])(value)) { + return format(value, options); + } // note: we use unsafe duck-typing here to check for Fractions, this is + // ok here since we're only invoking toString or concatenating its values + + + if (looksLikeFraction(value)) { + if (!options || options.fraction !== 'decimal') { + // output as ratio, like '1/3' + return value.s * value.n + '/' + value.d; + } else { + // output as decimal, like '0.(3)' + return value.toString(); + } + } + + if (Array.isArray(value)) { + return formatArray(value, options); + } + + if (Object(is["I" /* isString */])(value)) { + return '"' + value + '"'; + } + + if (typeof value === 'function') { + return value.syntax ? String(value.syntax) : 'function'; + } + + if (value && _typeof(value) === 'object') { + if (typeof value.format === 'function') { + return value.format(options); + } else if (value && value.toString(options) !== {}.toString()) { + // this object has a non-native toString method, use that one + return value.toString(options); + } else { + var entries = Object.keys(value).map(function (key) { + return '"' + key + '": ' + string_format(value[key], options); + }); + return '{' + entries.join(', ') + '}'; + } + } + + return String(value); +} +/** + * Stringify a value into a string enclosed in double quotes. + * Unescaped double quotes and backslashes inside the value are escaped. + * @param {*} value + * @return {string} + */ + +function stringify(value) { + var text = String(value); + var escaped = ''; + var i = 0; + + while (i < text.length) { + var c = text.charAt(i); + + if (c === '\\') { + escaped += c; + i++; + c = text.charAt(i); + + if (c === '' || '"\\/bfnrtu'.indexOf(c) === -1) { + escaped += '\\'; // no valid escape character -> escape it + } + + escaped += c; + } else if (c === '"') { + escaped += '\\"'; + } else { + escaped += c; + } + + i++; + } + + return '"' + escaped + '"'; +} +/** + * Escape special HTML characters + * @param {*} value + * @return {string} + */ + +function string_escape(value) { + var text = String(value); + text = text.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>'); + return text; +} +/** + * Recursively format an n-dimensional matrix + * Example output: "[[1, 2], [3, 4]]" + * @param {Array} array + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @returns {string} str + */ + +function formatArray(array, options) { + if (Array.isArray(array)) { + var str = '['; + var len = array.length; + + for (var i = 0; i < len; i++) { + if (i !== 0) { + str += ', '; + } + + str += formatArray(array[i], options); + } + + str += ']'; + return str; + } else { + return string_format(array, options); + } +} +/** + * Check whether a value looks like a Fraction (unsafe duck-type check) + * @param {*} value + * @return {boolean} + */ + + +function looksLikeFraction(value) { + return value && _typeof(value) === 'object' && typeof value.s === 'number' && typeof value.n === 'number' && typeof value.d === 'number' || false; +} +/** + * Compare two strings + * @param {string} x + * @param {string} y + * @returns {number} + */ + + +function compareText(x, y) { + // we don't want to convert numbers to string, only accept string input + if (!Object(is["I" /* isString */])(x)) { + throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + Object(is["M" /* typeOf */])(x) + ', index: 0)'); + } + + if (!Object(is["I" /* isString */])(y)) { + throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + Object(is["M" /* typeOf */])(y) + ', index: 1)'); + } + + return x === y ? 0 : x > y ? 1 : -1; +} + +/***/ }), +/* 6 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DimensionError; }); +/** + * Create a range error with the message: + * 'Dimension mismatch ( != )' + * @param {number | number[]} actual The actual size + * @param {number | number[]} expected The expected size + * @param {string} [relation='!='] Optional relation between actual + * and expected size: '!=', '<', etc. + * @extends RangeError + */ +function DimensionError(actual, expected, relation) { + if (!(this instanceof DimensionError)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.actual = actual; + this.expected = expected; + this.relation = relation; + this.message = 'Dimension mismatch (' + (Array.isArray(actual) ? '[' + actual.join(', ') + ']' : actual) + ' ' + (this.relation || '!=') + ' ' + (Array.isArray(expected) ? '[' + expected.join(', ') + ']' : expected) + ')'; + this.stack = new Error().stack; +} +DimensionError.prototype = new RangeError(); +DimensionError.prototype.constructor = RangeError; +DimensionError.prototype.name = 'DimensionError'; +DimensionError.prototype.isDimensionError = true; + +/***/ }), +/* 7 */, +/* 8 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return warnOnce; }); +/** + * Log a console.warn message only once + */ +var warnOnce = function () { + var messages = {}; + return function warnOnce() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var message = args.join(', '); + + if (!messages[message]) { + var _console; + + messages[message] = true; + + (_console = console).warn.apply(_console, ['Warning:'].concat(args)); + } + }; +}(); + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/** + * @license Complex.js v2.0.11 11/02/2016 + * + * Copyright (c) 2016, Robert Eisele (robert@xarg.org) + * Dual licensed under the MIT or GPL Version 2 licenses. + **/ + +/** + * + * This class allows the manipulation of complex numbers. + * You can pass a complex number in different formats. Either as object, double, string or two integer parameters. + * + * Object form + * { re: , im: } + * { arg: , abs: } + * { phi: , r: } + * + * Array / Vector form + * [ real, imaginary ] + * + * Double form + * 99.3 - Single double value + * + * String form + * '23.1337' - Simple real number + * '15+3i' - a simple complex number + * '3-i' - a simple complex number + * + * Example: + * + * var c = new Complex('99.3+8i'); + * c.mul({r: 3, i: 9}).div(4.9).sub(3, 2); + * + */ + +(function(root) { + + 'use strict'; + + var cosh = function(x) { + return (Math.exp(x) + Math.exp(-x)) * 0.5; + }; + + var sinh = function(x) { + return (Math.exp(x) - Math.exp(-x)) * 0.5; + }; + + /** + * Calculates cos(x) - 1 using Taylor series if x is small. + * + * @param {number} x + * @returns {number} cos(x) - 1 + */ + + var cosm1 = function(x) { + var limit = Math.PI/4; + if (x < -limit || x > limit) { + return (Math.cos(x) - 1.0); + } + + var xx = x * x; + return xx * + (-0.5 + xx * + (1/24 + xx * + (-1/720 + xx * + (1/40320 + xx * + (-1/3628800 + xx * + (1/4790014600 + xx * + (-1/87178291200 + xx * + (1/20922789888000) + ) + ) + ) + ) + ) + ) + ) + }; + + var hypot = function(x, y) { + + var a = Math.abs(x); + var b = Math.abs(y); + + if (a < 3000 && b < 3000) { + return Math.sqrt(a * a + b * b); + } + + if (a < b) { + a = b; + b = x / y; + } else { + b = y / x; + } + return a * Math.sqrt(1 + b * b); + }; + + var parser_exit = function() { + throw SyntaxError('Invalid Param'); + }; + + /** + * Calculates log(sqrt(a^2+b^2)) in a way to avoid overflows + * + * @param {number} a + * @param {number} b + * @returns {number} + */ + function logHypot(a, b) { + + var _a = Math.abs(a); + var _b = Math.abs(b); + + if (a === 0) { + return Math.log(_b); + } + + if (b === 0) { + return Math.log(_a); + } + + if (_a < 3000 && _b < 3000) { + return Math.log(a * a + b * b) * 0.5; + } + + /* I got 4 ideas to compute this property without overflow: + * + * Testing 1000000 times with random samples for a,b ∈ [1, 1000000000] against a big decimal library to get an error estimate + * + * 1. Only eliminate the square root: (OVERALL ERROR: 3.9122483030951116e-11) + + Math.log(a * a + b * b) / 2 + + * + * + * 2. Try to use the non-overflowing pythagoras: (OVERALL ERROR: 8.889760039210159e-10) + + var fn = function(a, b) { + a = Math.abs(a); + b = Math.abs(b); + var t = Math.min(a, b); + a = Math.max(a, b); + t = t / a; + + return Math.log(a) + Math.log(1 + t * t) / 2; + }; + + * 3. Abuse the identity cos(atan(y/x) = x / sqrt(x^2+y^2): (OVERALL ERROR: 3.4780178737037204e-10) + + Math.log(a / Math.cos(Math.atan2(b, a))) + + * 4. Use 3. and apply log rules: (OVERALL ERROR: 1.2014087502620896e-9) + + Math.log(a) - Math.log(Math.cos(Math.atan2(b, a))) + + */ + + return Math.log(a / Math.cos(Math.atan2(b, a))); + } + + var parse = function(a, b) { + + var z = {'re': 0, 'im': 0}; + + if (a === undefined || a === null) { + z['re'] = + z['im'] = 0; + } else if (b !== undefined) { + z['re'] = a; + z['im'] = b; + } else + switch (typeof a) { + + case 'object': + + if ('im' in a && 're' in a) { + z['re'] = a['re']; + z['im'] = a['im']; + } else if ('abs' in a && 'arg' in a) { + if (!Number.isFinite(a['abs']) && Number.isFinite(a['arg'])) { + return Complex['INFINITY']; + } + z['re'] = a['abs'] * Math.cos(a['arg']); + z['im'] = a['abs'] * Math.sin(a['arg']); + } else if ('r' in a && 'phi' in a) { + if (!Number.isFinite(a['r']) && Number.isFinite(a['phi'])) { + return Complex['INFINITY']; + } + z['re'] = a['r'] * Math.cos(a['phi']); + z['im'] = a['r'] * Math.sin(a['phi']); + } else if (a.length === 2) { // Quick array check + z['re'] = a[0]; + z['im'] = a[1]; + } else { + parser_exit(); + } + break; + + case 'string': + + z['im'] = /* void */ + z['re'] = 0; + + var tokens = a.match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g); + var plus = 1; + var minus = 0; + + if (tokens === null) { + parser_exit(); + } + + for (var i = 0; i < tokens.length; i++) { + + var c = tokens[i]; + + if (c === ' ' || c === '\t' || c === '\n') { + /* void */ + } else if (c === '+') { + plus++; + } else if (c === '-') { + minus++; + } else if (c === 'i' || c === 'I') { + + if (plus + minus === 0) { + parser_exit(); + } + + if (tokens[i + 1] !== ' ' && !isNaN(tokens[i + 1])) { + z['im'] += parseFloat((minus % 2 ? '-' : '') + tokens[i + 1]); + i++; + } else { + z['im'] += parseFloat((minus % 2 ? '-' : '') + '1'); + } + plus = minus = 0; + + } else { + + if (plus + minus === 0 || isNaN(c)) { + parser_exit(); + } + + if (tokens[i + 1] === 'i' || tokens[i + 1] === 'I') { + z['im'] += parseFloat((minus % 2 ? '-' : '') + c); + i++; + } else { + z['re'] += parseFloat((minus % 2 ? '-' : '') + c); + } + plus = minus = 0; + } + } + + // Still something on the stack + if (plus + minus > 0) { + parser_exit(); + } + break; + + case 'number': + z['im'] = 0; + z['re'] = a; + break; + + default: + parser_exit(); + } + + if (isNaN(z['re']) || isNaN(z['im'])) { + // If a calculation is NaN, we treat it as NaN and don't throw + //parser_exit(); + } + + return z; + }; + + /** + * @constructor + * @returns {Complex} + */ + function Complex(a, b) { + + if (!(this instanceof Complex)) { + return new Complex(a, b); + } + + var z = parse(a, b); + + this['re'] = z['re']; + this['im'] = z['im']; + } + + Complex.prototype = { + + 're': 0, + 'im': 0, + + /** + * Calculates the sign of a complex number, which is a normalized complex + * + * @returns {Complex} + */ + 'sign': function() { + + var abs = this['abs'](); + + return new Complex( + this['re'] / abs, + this['im'] / abs); + }, + + /** + * Adds two complex numbers + * + * @returns {Complex} + */ + 'add': function(a, b) { + + var z = new Complex(a, b); + + // Infinity + Infinity = NaN + if (this['isInfinite']() && z['isInfinite']()) { + return Complex['NAN']; + } + + // Infinity + z = Infinity { where z != Infinity } + if (this['isInfinite']() || z['isInfinite']()) { + return Complex['INFINITY']; + } + + return new Complex( + this['re'] + z['re'], + this['im'] + z['im']); + }, + + /** + * Subtracts two complex numbers + * + * @returns {Complex} + */ + 'sub': function(a, b) { + + var z = new Complex(a, b); + + // Infinity - Infinity = NaN + if (this['isInfinite']() && z['isInfinite']()) { + return Complex['NAN']; + } + + // Infinity - z = Infinity { where z != Infinity } + if (this['isInfinite']() || z['isInfinite']()) { + return Complex['INFINITY']; + } + + return new Complex( + this['re'] - z['re'], + this['im'] - z['im']); + }, + + /** + * Multiplies two complex numbers + * + * @returns {Complex} + */ + 'mul': function(a, b) { + + var z = new Complex(a, b); + + // Infinity * 0 = NaN + if ((this['isInfinite']() && z['isZero']()) || (this['isZero']() && z['isInfinite']())) { + return Complex['NAN']; + } + + // Infinity * z = Infinity { where z != 0 } + if (this['isInfinite']() || z['isInfinite']()) { + return Complex['INFINITY']; + } + + // Short circuit for real values + if (z['im'] === 0 && this['im'] === 0) { + return new Complex(this['re'] * z['re'], 0); + } + + return new Complex( + this['re'] * z['re'] - this['im'] * z['im'], + this['re'] * z['im'] + this['im'] * z['re']); + }, + + /** + * Divides two complex numbers + * + * @returns {Complex} + */ + 'div': function(a, b) { + + var z = new Complex(a, b); + + // 0 / 0 = NaN and Infinity / Infinity = NaN + if ((this['isZero']() && z['isZero']()) || (this['isInfinite']() && z['isInfinite']())) { + return Complex['NAN']; + } + + // Infinity / 0 = Infinity + if (this['isInfinite']() || z['isZero']()) { + return Complex['INFINITY']; + } + + // 0 / Infinity = 0 + if (this['isZero']() || z['isInfinite']()) { + return Complex['ZERO']; + } + + a = this['re']; + b = this['im']; + + var c = z['re']; + var d = z['im']; + var t, x; + + if (0 === d) { + // Divisor is real + return new Complex(a / c, b / c); + } + + if (Math.abs(c) < Math.abs(d)) { + + x = c / d; + t = c * x + d; + + return new Complex( + (a * x + b) / t, + (b * x - a) / t); + + } else { + + x = d / c; + t = d * x + c; + + return new Complex( + (a + b * x) / t, + (b - a * x) / t); + } + }, + + /** + * Calculate the power of two complex numbers + * + * @returns {Complex} + */ + 'pow': function(a, b) { + + var z = new Complex(a, b); + + a = this['re']; + b = this['im']; + + if (z['isZero']()) { + return Complex['ONE']; + } + + // If the exponent is real + if (z['im'] === 0) { + + if (b === 0 && a >= 0) { + + return new Complex(Math.pow(a, z['re']), 0); + + } else if (a === 0) { // If base is fully imaginary + + switch ((z['re'] % 4 + 4) % 4) { + case 0: + return new Complex(Math.pow(b, z['re']), 0); + case 1: + return new Complex(0, Math.pow(b, z['re'])); + case 2: + return new Complex(-Math.pow(b, z['re']), 0); + case 3: + return new Complex(0, -Math.pow(b, z['re'])); + } + } + } + + /* I couldn't find a good formula, so here is a derivation and optimization + * + * z_1^z_2 = (a + bi)^(c + di) + * = exp((c + di) * log(a + bi) + * = pow(a^2 + b^2, (c + di) / 2) * exp(i(c + di)atan2(b, a)) + * =>... + * Re = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * cos(d * log(a^2 + b^2) / 2 + c * atan2(b, a)) + * Im = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * sin(d * log(a^2 + b^2) / 2 + c * atan2(b, a)) + * + * =>... + * Re = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * cos(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a)) + * Im = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * sin(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a)) + * + * => + * Re = exp(c * logsq2 - d * arg(z_1)) * cos(d * logsq2 + c * arg(z_1)) + * Im = exp(c * logsq2 - d * arg(z_1)) * sin(d * logsq2 + c * arg(z_1)) + * + */ + + if (a === 0 && b === 0 && z['re'] > 0 && z['im'] >= 0) { + return Complex['ZERO']; + } + + var arg = Math.atan2(b, a); + var loh = logHypot(a, b); + + a = Math.exp(z['re'] * loh - z['im'] * arg); + b = z['im'] * loh + z['re'] * arg; + return new Complex( + a * Math.cos(b), + a * Math.sin(b)); + }, + + /** + * Calculate the complex square root + * + * @returns {Complex} + */ + 'sqrt': function() { + + var a = this['re']; + var b = this['im']; + var r = this['abs'](); + + var re, im; + + if (a >= 0) { + + if (b === 0) { + return new Complex(Math.sqrt(a), 0); + } + + re = 0.5 * Math.sqrt(2.0 * (r + a)); + } else { + re = Math.abs(b) / Math.sqrt(2 * (r - a)); + } + + if (a <= 0) { + im = 0.5 * Math.sqrt(2.0 * (r - a)); + } else { + im = Math.abs(b) / Math.sqrt(2 * (r + a)); + } + + return new Complex(re, b < 0 ? -im : im); + }, + + /** + * Calculate the complex exponent + * + * @returns {Complex} + */ + 'exp': function() { + + var tmp = Math.exp(this['re']); + + if (this['im'] === 0) { + //return new Complex(tmp, 0); + } + return new Complex( + tmp * Math.cos(this['im']), + tmp * Math.sin(this['im'])); + }, + + /** + * Calculate the complex exponent and subtracts one. + * + * This may be more accurate than `Complex(x).exp().sub(1)` if + * `x` is small. + * + * @returns {Complex} + */ + 'expm1': function() { + + /** + * exp(a + i*b) - 1 + = exp(a) * (cos(b) + j*sin(b)) - 1 + = expm1(a)*cos(b) + cosm1(b) + j*exp(a)*sin(b) + */ + + var a = this['re']; + var b = this['im']; + + return new Complex( + Math.expm1(a) * Math.cos(b) + cosm1(b), + Math.exp(a) * Math.sin(b)); + }, + + /** + * Calculate the natural log + * + * @returns {Complex} + */ + 'log': function() { + + var a = this['re']; + var b = this['im']; + + if (b === 0 && a > 0) { + //return new Complex(Math.log(a), 0); + } + + return new Complex( + logHypot(a, b), + Math.atan2(b, a)); + }, + + /** + * Calculate the magnitude of the complex number + * + * @returns {number} + */ + 'abs': function() { + + return hypot(this['re'], this['im']); + }, + + /** + * Calculate the angle of the complex number + * + * @returns {number} + */ + 'arg': function() { + + return Math.atan2(this['im'], this['re']); + }, + + /** + * Calculate the sine of the complex number + * + * @returns {Complex} + */ + 'sin': function() { + + // sin(c) = (e^b - e^(-b)) / (2i) + + var a = this['re']; + var b = this['im']; + + return new Complex( + Math.sin(a) * cosh(b), + Math.cos(a) * sinh(b)); + }, + + /** + * Calculate the cosine + * + * @returns {Complex} + */ + 'cos': function() { + + // cos(z) = (e^b + e^(-b)) / 2 + + var a = this['re']; + var b = this['im']; + + return new Complex( + Math.cos(a) * cosh(b), + -Math.sin(a) * sinh(b)); + }, + + /** + * Calculate the tangent + * + * @returns {Complex} + */ + 'tan': function() { + + // tan(c) = (e^(ci) - e^(-ci)) / (i(e^(ci) + e^(-ci))) + + var a = 2 * this['re']; + var b = 2 * this['im']; + var d = Math.cos(a) + cosh(b); + + return new Complex( + Math.sin(a) / d, + sinh(b) / d); + }, + + /** + * Calculate the cotangent + * + * @returns {Complex} + */ + 'cot': function() { + + // cot(c) = i(e^(ci) + e^(-ci)) / (e^(ci) - e^(-ci)) + + var a = 2 * this['re']; + var b = 2 * this['im']; + var d = Math.cos(a) - cosh(b); + + return new Complex( + -Math.sin(a) / d, + sinh(b) / d); + }, + + /** + * Calculate the secant + * + * @returns {Complex} + */ + 'sec': function() { + + // sec(c) = 2 / (e^(ci) + e^(-ci)) + + var a = this['re']; + var b = this['im']; + var d = 0.5 * cosh(2 * b) + 0.5 * Math.cos(2 * a); + + return new Complex( + Math.cos(a) * cosh(b) / d, + Math.sin(a) * sinh(b) / d); + }, + + /** + * Calculate the cosecans + * + * @returns {Complex} + */ + 'csc': function() { + + // csc(c) = 2i / (e^(ci) - e^(-ci)) + + var a = this['re']; + var b = this['im']; + var d = 0.5 * cosh(2 * b) - 0.5 * Math.cos(2 * a); + + return new Complex( + Math.sin(a) * cosh(b) / d, + -Math.cos(a) * sinh(b) / d); + }, + + /** + * Calculate the complex arcus sinus + * + * @returns {Complex} + */ + 'asin': function() { + + // asin(c) = -i * log(ci + sqrt(1 - c^2)) + + var a = this['re']; + var b = this['im']; + + var t1 = new Complex( + b * b - a * a + 1, + -2 * a * b)['sqrt'](); + + var t2 = new Complex( + t1['re'] - b, + t1['im'] + a)['log'](); + + return new Complex(t2['im'], -t2['re']); + }, + + /** + * Calculate the complex arcus cosinus + * + * @returns {Complex} + */ + 'acos': function() { + + // acos(c) = i * log(c - i * sqrt(1 - c^2)) + + var a = this['re']; + var b = this['im']; + + var t1 = new Complex( + b * b - a * a + 1, + -2 * a * b)['sqrt'](); + + var t2 = new Complex( + t1['re'] - b, + t1['im'] + a)['log'](); + + return new Complex(Math.PI / 2 - t2['im'], t2['re']); + }, + + /** + * Calculate the complex arcus tangent + * + * @returns {Complex} + */ + 'atan': function() { + + // atan(c) = i / 2 log((i + x) / (i - x)) + + var a = this['re']; + var b = this['im']; + + if (a === 0) { + + if (b === 1) { + return new Complex(0, Infinity); + } + + if (b === -1) { + return new Complex(0, -Infinity); + } + } + + var d = a * a + (1.0 - b) * (1.0 - b); + + var t1 = new Complex( + (1 - b * b - a * a) / d, + -2 * a / d).log(); + + return new Complex(-0.5 * t1['im'], 0.5 * t1['re']); + }, + + /** + * Calculate the complex arcus cotangent + * + * @returns {Complex} + */ + 'acot': function() { + + // acot(c) = i / 2 log((c - i) / (c + i)) + + var a = this['re']; + var b = this['im']; + + if (b === 0) { + return new Complex(Math.atan2(1, a), 0); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).atan() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).atan(); + }, + + /** + * Calculate the complex arcus secant + * + * @returns {Complex} + */ + 'asec': function() { + + // asec(c) = -i * log(1 / c + sqrt(1 - i / c^2)) + + var a = this['re']; + var b = this['im']; + + if (a === 0 && b === 0) { + return new Complex(0, Infinity); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).acos() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).acos(); + }, + + /** + * Calculate the complex arcus cosecans + * + * @returns {Complex} + */ + 'acsc': function() { + + // acsc(c) = -i * log(i / c + sqrt(1 - 1 / c^2)) + + var a = this['re']; + var b = this['im']; + + if (a === 0 && b === 0) { + return new Complex(Math.PI / 2, Infinity); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).asin() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).asin(); + }, + + /** + * Calculate the complex sinh + * + * @returns {Complex} + */ + 'sinh': function() { + + // sinh(c) = (e^c - e^-c) / 2 + + var a = this['re']; + var b = this['im']; + + return new Complex( + sinh(a) * Math.cos(b), + cosh(a) * Math.sin(b)); + }, + + /** + * Calculate the complex cosh + * + * @returns {Complex} + */ + 'cosh': function() { + + // cosh(c) = (e^c + e^-c) / 2 + + var a = this['re']; + var b = this['im']; + + return new Complex( + cosh(a) * Math.cos(b), + sinh(a) * Math.sin(b)); + }, + + /** + * Calculate the complex tanh + * + * @returns {Complex} + */ + 'tanh': function() { + + // tanh(c) = (e^c - e^-c) / (e^c + e^-c) + + var a = 2 * this['re']; + var b = 2 * this['im']; + var d = cosh(a) + Math.cos(b); + + return new Complex( + sinh(a) / d, + Math.sin(b) / d); + }, + + /** + * Calculate the complex coth + * + * @returns {Complex} + */ + 'coth': function() { + + // coth(c) = (e^c + e^-c) / (e^c - e^-c) + + var a = 2 * this['re']; + var b = 2 * this['im']; + var d = cosh(a) - Math.cos(b); + + return new Complex( + sinh(a) / d, + -Math.sin(b) / d); + }, + + /** + * Calculate the complex coth + * + * @returns {Complex} + */ + 'csch': function() { + + // csch(c) = 2 / (e^c - e^-c) + + var a = this['re']; + var b = this['im']; + var d = Math.cos(2 * b) - cosh(2 * a); + + return new Complex( + -2 * sinh(a) * Math.cos(b) / d, + 2 * cosh(a) * Math.sin(b) / d); + }, + + /** + * Calculate the complex sech + * + * @returns {Complex} + */ + 'sech': function() { + + // sech(c) = 2 / (e^c + e^-c) + + var a = this['re']; + var b = this['im']; + var d = Math.cos(2 * b) + cosh(2 * a); + + return new Complex( + 2 * cosh(a) * Math.cos(b) / d, + -2 * sinh(a) * Math.sin(b) / d); + }, + + /** + * Calculate the complex asinh + * + * @returns {Complex} + */ + 'asinh': function() { + + // asinh(c) = log(c + sqrt(c^2 + 1)) + + var tmp = this['im']; + this['im'] = -this['re']; + this['re'] = tmp; + var res = this['asin'](); + + this['re'] = -this['im']; + this['im'] = tmp; + tmp = res['re']; + + res['re'] = -res['im']; + res['im'] = tmp; + return res; + }, + + /** + * Calculate the complex asinh + * + * @returns {Complex} + */ + 'acosh': function() { + + // acosh(c) = log(c + sqrt(c^2 - 1)) + + var res = this['acos'](); + if (res['im'] <= 0) { + var tmp = res['re']; + res['re'] = -res['im']; + res['im'] = tmp; + } else { + var tmp = res['im']; + res['im'] = -res['re']; + res['re'] = tmp; + } + return res; + }, + + /** + * Calculate the complex atanh + * + * @returns {Complex} + */ + 'atanh': function() { + + // atanh(c) = log((1+c) / (1-c)) / 2 + + var a = this['re']; + var b = this['im']; + + var noIM = a > 1 && b === 0; + var oneMinus = 1 - a; + var onePlus = 1 + a; + var d = oneMinus * oneMinus + b * b; + + var x = (d !== 0) + ? new Complex( + (onePlus * oneMinus - b * b) / d, + (b * oneMinus + onePlus * b) / d) + : new Complex( + (a !== -1) ? (a / 0) : 0, + (b !== 0) ? (b / 0) : 0); + + var temp = x['re']; + x['re'] = logHypot(x['re'], x['im']) / 2; + x['im'] = Math.atan2(x['im'], temp) / 2; + if (noIM) { + x['im'] = -x['im']; + } + return x; + }, + + /** + * Calculate the complex acoth + * + * @returns {Complex} + */ + 'acoth': function() { + + // acoth(c) = log((c+1) / (c-1)) / 2 + + var a = this['re']; + var b = this['im']; + + if (a === 0 && b === 0) { + return new Complex(0, Math.PI / 2); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).atanh() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).atanh(); + }, + + /** + * Calculate the complex acsch + * + * @returns {Complex} + */ + 'acsch': function() { + + // acsch(c) = log((1+sqrt(1+c^2))/c) + + var a = this['re']; + var b = this['im']; + + if (b === 0) { + + return new Complex( + (a !== 0) + ? Math.log(a + Math.sqrt(a * a + 1)) + : Infinity, 0); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).asinh() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).asinh(); + }, + + /** + * Calculate the complex asech + * + * @returns {Complex} + */ + 'asech': function() { + + // asech(c) = log((1+sqrt(1-c^2))/c) + + var a = this['re']; + var b = this['im']; + + if (this['isZero']()) { + return Complex['INFINITY']; + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).acosh() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).acosh(); + }, + + /** + * Calculate the complex inverse 1/z + * + * @returns {Complex} + */ + 'inverse': function() { + + // 1 / 0 = Infinity and 1 / Infinity = 0 + if (this['isZero']()) { + return Complex['INFINITY']; + } + + if (this['isInfinite']()) { + return Complex['ZERO']; + } + + var a = this['re']; + var b = this['im']; + + var d = a * a + b * b; + + return new Complex(a / d, -b / d); + }, + + /** + * Returns the complex conjugate + * + * @returns {Complex} + */ + 'conjugate': function() { + + return new Complex(this['re'], -this['im']); + }, + + /** + * Gets the negated complex number + * + * @returns {Complex} + */ + 'neg': function() { + + return new Complex(-this['re'], -this['im']); + }, + + /** + * Ceils the actual complex number + * + * @returns {Complex} + */ + 'ceil': function(places) { + + places = Math.pow(10, places || 0); + + return new Complex( + Math.ceil(this['re'] * places) / places, + Math.ceil(this['im'] * places) / places); + }, + + /** + * Floors the actual complex number + * + * @returns {Complex} + */ + 'floor': function(places) { + + places = Math.pow(10, places || 0); + + return new Complex( + Math.floor(this['re'] * places) / places, + Math.floor(this['im'] * places) / places); + }, + + /** + * Ceils the actual complex number + * + * @returns {Complex} + */ + 'round': function(places) { + + places = Math.pow(10, places || 0); + + return new Complex( + Math.round(this['re'] * places) / places, + Math.round(this['im'] * places) / places); + }, + + /** + * Compares two complex numbers + * + * **Note:** new Complex(Infinity).equals(Infinity) === false + * + * @returns {boolean} + */ + 'equals': function(a, b) { + + var z = new Complex(a, b); + + return Math.abs(z['re'] - this['re']) <= Complex['EPSILON'] && + Math.abs(z['im'] - this['im']) <= Complex['EPSILON']; + }, + + /** + * Clones the actual object + * + * @returns {Complex} + */ + 'clone': function() { + + return new Complex(this['re'], this['im']); + }, + + /** + * Gets a string of the actual complex number + * + * @returns {string} + */ + 'toString': function() { + + var a = this['re']; + var b = this['im']; + var ret = ''; + + if (this['isNaN']()) { + return 'NaN'; + } + + if (this['isZero']()) { + return '0'; + } + + if (this['isInfinite']()) { + return 'Infinity'; + } + + if (a !== 0) { + ret += a; + } + + if (b !== 0) { + + if (a !== 0) { + ret += b < 0 ? ' - ' : ' + '; + } else if (b < 0) { + ret += '-'; + } + + b = Math.abs(b); + + if (1 !== b) { + ret += b; + } + ret += 'i'; + } + + if (!ret) + return '0'; + + return ret; + }, + + /** + * Returns the actual number as a vector + * + * @returns {Array} + */ + 'toVector': function() { + + return [this['re'], this['im']]; + }, + + /** + * Returns the actual real value of the current object + * + * @returns {number|null} + */ + 'valueOf': function() { + + if (this['im'] === 0) { + return this['re']; + } + return null; + }, + + /** + * Determines whether a complex number is not on the Riemann sphere. + * + * @returns {boolean} + */ + 'isNaN': function() { + return isNaN(this['re']) || isNaN(this['im']); + }, + + /** + * Determines whether or not a complex number is at the zero pole of the + * Riemann sphere. + * + * @returns {boolean} + */ + 'isZero': function() { + return ( + (this['re'] === 0 || this['re'] === -0) && + (this['im'] === 0 || this['im'] === -0) + ); + }, + + /** + * Determines whether a complex number is not at the infinity pole of the + * Riemann sphere. + * + * @returns {boolean} + */ + 'isFinite': function() { + return isFinite(this['re']) && isFinite(this['im']); + }, + + /** + * Determines whether or not a complex number is at the infinity pole of the + * Riemann sphere. + * + * @returns {boolean} + */ + 'isInfinite': function() { + return !(this['isNaN']() || this['isFinite']()); + } + }; + + Complex['ZERO'] = new Complex(0, 0); + Complex['ONE'] = new Complex(1, 0); + Complex['I'] = new Complex(0, 1); + Complex['PI'] = new Complex(Math.PI, 0); + Complex['E'] = new Complex(Math.E, 0); + Complex['INFINITY'] = new Complex(Infinity, Infinity); + Complex['NAN'] = new Complex(NaN, NaN); + Complex['EPSILON'] = 1e-16; + + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { + return Complex; + }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} + +})(this); + + +/***/ }), +/* 10 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return IndexError; }); +/** + * Create a range error with the message: + * 'Index out of range (index < min)' + * 'Index out of range (index < max)' + * + * @param {number} index The actual index + * @param {number} [min=0] Minimum index (included) + * @param {number} [max] Maximum index (excluded) + * @extends RangeError + */ +function IndexError(index, min, max) { + if (!(this instanceof IndexError)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.index = index; + + if (arguments.length < 3) { + this.min = 0; + this.max = min; + } else { + this.min = min; + this.max = max; + } + + if (this.min !== undefined && this.index < this.min) { + this.message = 'Index out of range (' + this.index + ' < ' + this.min + ')'; + } else if (this.max !== undefined && this.index >= this.max) { + this.message = 'Index out of range (' + this.index + ' > ' + (this.max - 1) + ')'; + } else { + this.message = 'Index out of range (' + this.index + ')'; + } + + this.stack = new Error().stack; +} +IndexError.prototype = new RangeError(); +IndexError.prototype.constructor = RangeError; +IndexError.prototype.name = 'IndexError'; +IndexError.prototype.isIndexError = true; + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/** + * @license Fraction.js v4.0.12 09/09/2015 + * http://www.xarg.org/2014/03/rational-numbers-in-javascript/ + * + * Copyright (c) 2015, Robert Eisele (robert@xarg.org) + * Dual licensed under the MIT or GPL Version 2 licenses. + **/ + + +/** + * + * This class offers the possibility to calculate fractions. + * You can pass a fraction in different formats. Either as array, as double, as string or as an integer. + * + * Array/Object form + * [ 0 => , 1 => ] + * [ n => , d => ] + * + * Integer form + * - Single integer value + * + * Double form + * - Single double value + * + * String form + * 123.456 - a simple double + * 123/456 - a string fraction + * 123.'456' - a double with repeating decimal places + * 123.(456) - synonym + * 123.45'6' - a double with repeating last place + * 123.45(6) - synonym + * + * Example: + * + * var f = new Fraction("9.4'31'"); + * f.mul([-4, 3]).div(4.9); + * + */ + +(function(root) { + + "use strict"; + + // Maximum search depth for cyclic rational numbers. 2000 should be more than enough. + // Example: 1/7 = 0.(142857) has 6 repeating decimal places. + // If MAX_CYCLE_LEN gets reduced, long cycles will not be detected and toString() only gets the first 10 digits + var MAX_CYCLE_LEN = 2000; + + // Parsed data to avoid calling "new" all the time + var P = { + "s": 1, + "n": 0, + "d": 1 + }; + + function createError(name) { + + function errorConstructor() { + var temp = Error.apply(this, arguments); + temp['name'] = this['name'] = name; + this['stack'] = temp['stack']; + this['message'] = temp['message']; + } + + /** + * Error constructor + * + * @constructor + */ + function IntermediateInheritor() {} + IntermediateInheritor.prototype = Error.prototype; + errorConstructor.prototype = new IntermediateInheritor(); + + return errorConstructor; + } + + var DivisionByZero = Fraction['DivisionByZero'] = createError('DivisionByZero'); + var InvalidParameter = Fraction['InvalidParameter'] = createError('InvalidParameter'); + + function assign(n, s) { + + if (isNaN(n = parseInt(n, 10))) { + throwInvalidParam(); + } + return n * s; + } + + function throwInvalidParam() { + throw new InvalidParameter(); + } + + var parse = function(p1, p2) { + + var n = 0, d = 1, s = 1; + var v = 0, w = 0, x = 0, y = 1, z = 1; + + var A = 0, B = 1; + var C = 1, D = 1; + + var N = 10000000; + var M; + + if (p1 === undefined || p1 === null) { + /* void */ + } else if (p2 !== undefined) { + n = p1; + d = p2; + s = n * d; + } else + switch (typeof p1) { + + case "object": + { + if ("d" in p1 && "n" in p1) { + n = p1["n"]; + d = p1["d"]; + if ("s" in p1) + n *= p1["s"]; + } else if (0 in p1) { + n = p1[0]; + if (1 in p1) + d = p1[1]; + } else { + throwInvalidParam(); + } + s = n * d; + break; + } + case "number": + { + if (p1 < 0) { + s = p1; + p1 = -p1; + } + + if (p1 % 1 === 0) { + n = p1; + } else if (p1 > 0) { // check for != 0, scale would become NaN (log(0)), which converges really slow + + if (p1 >= 1) { + z = Math.pow(10, Math.floor(1 + Math.log(p1) / Math.LN10)); + p1 /= z; + } + + // Using Farey Sequences + // http://www.johndcook.com/blog/2010/10/20/best-rational-approximation/ + + while (B <= N && D <= N) { + M = (A + C) / (B + D); + + if (p1 === M) { + if (B + D <= N) { + n = A + C; + d = B + D; + } else if (D > B) { + n = C; + d = D; + } else { + n = A; + d = B; + } + break; + + } else { + + if (p1 > M) { + A += C; + B += D; + } else { + C += A; + D += B; + } + + if (B > N) { + n = C; + d = D; + } else { + n = A; + d = B; + } + } + } + n *= z; + } else if (isNaN(p1) || isNaN(p2)) { + d = n = NaN; + } + break; + } + case "string": + { + B = p1.match(/\d+|./g); + + if (B === null) + throwInvalidParam(); + + if (B[A] === '-') {// Check for minus sign at the beginning + s = -1; + A++; + } else if (B[A] === '+') {// Check for plus sign at the beginning + A++; + } + + if (B.length === A + 1) { // Check if it's just a simple number "1234" + w = assign(B[A++], s); + } else if (B[A + 1] === '.' || B[A] === '.') { // Check if it's a decimal number + + if (B[A] !== '.') { // Handle 0.5 and .5 + v = assign(B[A++], s); + } + A++; + + // Check for decimal places + if (A + 1 === B.length || B[A + 1] === '(' && B[A + 3] === ')' || B[A + 1] === "'" && B[A + 3] === "'") { + w = assign(B[A], s); + y = Math.pow(10, B[A].length); + A++; + } + + // Check for repeating places + if (B[A] === '(' && B[A + 2] === ')' || B[A] === "'" && B[A + 2] === "'") { + x = assign(B[A + 1], s); + z = Math.pow(10, B[A + 1].length) - 1; + A += 3; + } + + } else if (B[A + 1] === '/' || B[A + 1] === ':') { // Check for a simple fraction "123/456" or "123:456" + w = assign(B[A], s); + y = assign(B[A + 2], 1); + A += 3; + } else if (B[A + 3] === '/' && B[A + 1] === ' ') { // Check for a complex fraction "123 1/2" + v = assign(B[A], s); + w = assign(B[A + 2], s); + y = assign(B[A + 4], 1); + A += 5; + } + + if (B.length <= A) { // Check for more tokens on the stack + d = y * z; + s = /* void */ + n = x + d * v + z * w; + break; + } + + /* Fall through on error */ + } + default: + throwInvalidParam(); + } + + if (d === 0) { + throw new DivisionByZero(); + } + + P["s"] = s < 0 ? -1 : 1; + P["n"] = Math.abs(n); + P["d"] = Math.abs(d); + }; + + function modpow(b, e, m) { + + var r = 1; + for (; e > 0; b = (b * b) % m, e >>= 1) { + + if (e & 1) { + r = (r * b) % m; + } + } + return r; + } + + + function cycleLen(n, d) { + + for (; d % 2 === 0; + d /= 2) { + } + + for (; d % 5 === 0; + d /= 5) { + } + + if (d === 1) // Catch non-cyclic numbers + return 0; + + // If we would like to compute really large numbers quicker, we could make use of Fermat's little theorem: + // 10^(d-1) % d == 1 + // However, we don't need such large numbers and MAX_CYCLE_LEN should be the capstone, + // as we want to translate the numbers to strings. + + var rem = 10 % d; + var t = 1; + + for (; rem !== 1; t++) { + rem = rem * 10 % d; + + if (t > MAX_CYCLE_LEN) + return 0; // Returning 0 here means that we don't print it as a cyclic number. It's likely that the answer is `d-1` + } + return t; + } + + + function cycleStart(n, d, len) { + + var rem1 = 1; + var rem2 = modpow(10, len, d); + + for (var t = 0; t < 300; t++) { // s < ~log10(Number.MAX_VALUE) + // Solve 10^s == 10^(s+t) (mod d) + + if (rem1 === rem2) + return t; + + rem1 = rem1 * 10 % d; + rem2 = rem2 * 10 % d; + } + return 0; + } + + function gcd(a, b) { + + if (!a) + return b; + if (!b) + return a; + + while (1) { + a %= b; + if (!a) + return b; + b %= a; + if (!b) + return a; + } + }; + + /** + * Module constructor + * + * @constructor + * @param {number|Fraction=} a + * @param {number=} b + */ + function Fraction(a, b) { + + if (!(this instanceof Fraction)) { + return new Fraction(a, b); + } + + parse(a, b); + + if (Fraction['REDUCE']) { + a = gcd(P["d"], P["n"]); // Abuse a + } else { + a = 1; + } + + this["s"] = P["s"]; + this["n"] = P["n"] / a; + this["d"] = P["d"] / a; + } + + /** + * Boolean global variable to be able to disable automatic reduction of the fraction + * + */ + Fraction['REDUCE'] = 1; + + Fraction.prototype = { + + "s": 1, + "n": 0, + "d": 1, + + /** + * Calculates the absolute value + * + * Ex: new Fraction(-4).abs() => 4 + **/ + "abs": function() { + + return new Fraction(this["n"], this["d"]); + }, + + /** + * Inverts the sign of the current fraction + * + * Ex: new Fraction(-4).neg() => 4 + **/ + "neg": function() { + + return new Fraction(-this["s"] * this["n"], this["d"]); + }, + + /** + * Adds two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => 467 / 30 + **/ + "add": function(a, b) { + + parse(a, b); + return new Fraction( + this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Subtracts two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => -427 / 30 + **/ + "sub": function(a, b) { + + parse(a, b); + return new Fraction( + this["s"] * this["n"] * P["d"] - P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Multiplies two rational numbers + * + * Ex: new Fraction("-17.(345)").mul(3) => 5776 / 111 + **/ + "mul": function(a, b) { + + parse(a, b); + return new Fraction( + this["s"] * P["s"] * this["n"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Divides two rational numbers + * + * Ex: new Fraction("-17.(345)").inverse().div(3) + **/ + "div": function(a, b) { + + parse(a, b); + return new Fraction( + this["s"] * P["s"] * this["n"] * P["d"], + this["d"] * P["n"] + ); + }, + + /** + * Clones the actual object + * + * Ex: new Fraction("-17.(345)").clone() + **/ + "clone": function() { + return new Fraction(this); + }, + + /** + * Calculates the modulo of two rational numbers - a more precise fmod + * + * Ex: new Fraction('4.(3)').mod([7, 8]) => (13/3) % (7/8) = (5/6) + **/ + "mod": function(a, b) { + + if (isNaN(this['n']) || isNaN(this['d'])) { + return new Fraction(NaN); + } + + if (a === undefined) { + return new Fraction(this["s"] * this["n"] % this["d"], 1); + } + + parse(a, b); + if (0 === P["n"] && 0 === this["d"]) { + Fraction(0, 0); // Throw DivisionByZero + } + + /* + * First silly attempt, kinda slow + * + return that["sub"]({ + "n": num["n"] * Math.floor((this.n / this.d) / (num.n / num.d)), + "d": num["d"], + "s": this["s"] + });*/ + + /* + * New attempt: a1 / b1 = a2 / b2 * q + r + * => b2 * a1 = a2 * b1 * q + b1 * b2 * r + * => (b2 * a1 % a2 * b1) / (b1 * b2) + */ + return new Fraction( + this["s"] * (P["d"] * this["n"]) % (P["n"] * this["d"]), + P["d"] * this["d"] + ); + }, + + /** + * Calculates the fractional gcd of two rational numbers + * + * Ex: new Fraction(5,8).gcd(3,7) => 1/56 + */ + "gcd": function(a, b) { + + parse(a, b); + + // gcd(a / b, c / d) = gcd(a, c) / lcm(b, d) + + return new Fraction(gcd(P["n"], this["n"]) * gcd(P["d"], this["d"]), P["d"] * this["d"]); + }, + + /** + * Calculates the fractional lcm of two rational numbers + * + * Ex: new Fraction(5,8).lcm(3,7) => 15 + */ + "lcm": function(a, b) { + + parse(a, b); + + // lcm(a / b, c / d) = lcm(a, c) / gcd(b, d) + + if (P["n"] === 0 && this["n"] === 0) { + return new Fraction; + } + return new Fraction(P["n"] * this["n"], gcd(P["n"], this["n"]) * gcd(P["d"], this["d"])); + }, + + /** + * Calculates the ceil of a rational number + * + * Ex: new Fraction('4.(3)').ceil() => (5 / 1) + **/ + "ceil": function(places) { + + places = Math.pow(10, places || 0); + + if (isNaN(this["n"]) || isNaN(this["d"])) { + return new Fraction(NaN); + } + return new Fraction(Math.ceil(places * this["s"] * this["n"] / this["d"]), places); + }, + + /** + * Calculates the floor of a rational number + * + * Ex: new Fraction('4.(3)').floor() => (4 / 1) + **/ + "floor": function(places) { + + places = Math.pow(10, places || 0); + + if (isNaN(this["n"]) || isNaN(this["d"])) { + return new Fraction(NaN); + } + return new Fraction(Math.floor(places * this["s"] * this["n"] / this["d"]), places); + }, + + /** + * Rounds a rational numbers + * + * Ex: new Fraction('4.(3)').round() => (4 / 1) + **/ + "round": function(places) { + + places = Math.pow(10, places || 0); + + if (isNaN(this["n"]) || isNaN(this["d"])) { + return new Fraction(NaN); + } + return new Fraction(Math.round(places * this["s"] * this["n"] / this["d"]), places); + }, + + /** + * Gets the inverse of the fraction, means numerator and denumerator are exchanged + * + * Ex: new Fraction([-3, 4]).inverse() => -4 / 3 + **/ + "inverse": function() { + + return new Fraction(this["s"] * this["d"], this["n"]); + }, + + /** + * Calculates the fraction to some integer exponent + * + * Ex: new Fraction(-1,2).pow(-3) => -8 + */ + "pow": function(m) { + + if (m < 0) { + return new Fraction(Math.pow(this['s'] * this["d"], -m), Math.pow(this["n"], -m)); + } else { + return new Fraction(Math.pow(this['s'] * this["n"], m), Math.pow(this["d"], m)); + } + }, + + /** + * Check if two rational numbers are the same + * + * Ex: new Fraction(19.6).equals([98, 5]); + **/ + "equals": function(a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] === P["s"] * P["n"] * this["d"]; // Same as compare() === 0 + }, + + /** + * Check if two rational numbers are the same + * + * Ex: new Fraction(19.6).equals([98, 5]); + **/ + "compare": function(a, b) { + + parse(a, b); + var t = (this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]); + return (0 < t) - (t < 0); + }, + + "simplify": function(eps) { + + // First naive implementation, needs improvement + + if (isNaN(this['n']) || isNaN(this['d'])) { + return this; + } + + var cont = this['abs']()['toContinued'](); + + eps = eps || 0.001; + + function rec(a) { + if (a.length === 1) + return new Fraction(a[0]); + return rec(a.slice(1))['inverse']()['add'](a[0]); + } + + for (var i = 0; i < cont.length; i++) { + var tmp = rec(cont.slice(0, i + 1)); + if (tmp['sub'](this['abs']())['abs']().valueOf() < eps) { + return tmp['mul'](this['s']); + } + } + return this; + }, + + /** + * Check if two rational numbers are divisible + * + * Ex: new Fraction(19.6).divisible(1.5); + */ + "divisible": function(a, b) { + + parse(a, b); + return !(!(P["n"] * this["d"]) || ((this["n"] * P["d"]) % (P["n"] * this["d"]))); + }, + + /** + * Returns a decimal representation of the fraction + * + * Ex: new Fraction("100.'91823'").valueOf() => 100.91823918239183 + **/ + 'valueOf': function() { + + return this["s"] * this["n"] / this["d"]; + }, + + /** + * Returns a string-fraction representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toFraction() => "4 1/3" + **/ + 'toFraction': function(excludeWhole) { + + var whole, str = ""; + var n = this["n"]; + var d = this["d"]; + if (this["s"] < 0) { + str += '-'; + } + + if (d === 1) { + str += n; + } else { + + if (excludeWhole && (whole = Math.floor(n / d)) > 0) { + str += whole; + str += " "; + n %= d; + } + + str += n; + str += '/'; + str += d; + } + return str; + }, + + /** + * Returns a latex representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toLatex() => "\frac{4}{3}" + **/ + 'toLatex': function(excludeWhole) { + + var whole, str = ""; + var n = this["n"]; + var d = this["d"]; + if (this["s"] < 0) { + str += '-'; + } + + if (d === 1) { + str += n; + } else { + + if (excludeWhole && (whole = Math.floor(n / d)) > 0) { + str += whole; + n %= d; + } + + str += "\\frac{"; + str += n; + str += '}{'; + str += d; + str += '}'; + } + return str; + }, + + /** + * Returns an array of continued fraction elements + * + * Ex: new Fraction("7/8").toContinued() => [0,1,7] + */ + 'toContinued': function() { + + var t; + var a = this['n']; + var b = this['d']; + var res = []; + + if (isNaN(this['n']) || isNaN(this['d'])) { + return res; + } + + do { + res.push(Math.floor(a / b)); + t = a % b; + a = b; + b = t; + } while (a !== 1); + + return res; + }, + + /** + * Creates a string representation of a fraction with all digits + * + * Ex: new Fraction("100.'91823'").toString() => "100.(91823)" + **/ + 'toString': function(dec) { + + var g; + var N = this["n"]; + var D = this["d"]; + + if (isNaN(N) || isNaN(D)) { + return "NaN"; + } + + if (!Fraction['REDUCE']) { + g = gcd(N, D); + N /= g; + D /= g; + } + + dec = dec || 15; // 15 = decimal places when no repitation + + var cycLen = cycleLen(N, D); // Cycle length + var cycOff = cycleStart(N, D, cycLen); // Cycle start + + var str = this['s'] === -1 ? "-" : ""; + + str += N / D | 0; + + N %= D; + N *= 10; + + if (N) + str += "."; + + if (cycLen) { + + for (var i = cycOff; i--; ) { + str += N / D | 0; + N %= D; + N *= 10; + } + str += "("; + for (var i = cycLen; i--; ) { + str += N / D | 0; + N %= D; + N *= 10; + } + str += ")"; + } else { + for (var i = dec; N && i--; ) { + str += N / D | 0; + N %= D; + N *= 10; + } + } + return str; + } + }; + + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { + return Fraction; + }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} + +})(this); + + +/***/ }), +/* 12 */ +/***/ (function(module, exports) { + +/* + * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license + * Author: Jim Palmer (based on chunking idea from Dave Koelle) + */ +/*jshint unused:false */ +module.exports = function naturalSort (a, b) { + "use strict"; + var re = /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi, + sre = /(^[ ]*|[ ]*$)/g, + dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/, + hre = /^0x[0-9a-f]+$/i, + ore = /^0/, + i = function(s) { return naturalSort.insensitive && ('' + s).toLowerCase() || '' + s; }, + // convert all to strings strip whitespace + x = i(a).replace(sre, '') || '', + y = i(b).replace(sre, '') || '', + // chunk/tokenize + xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), + yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), + // numeric, hex or date detection + xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && x.match(dre) && Date.parse(x)), + yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null, + oFxNcL, oFyNcL; + // first try and sort Hex codes or Dates + if (yD) { + if ( xD < yD ) { return -1; } + else if ( xD > yD ) { return 1; } + } + // natural sorting through split numeric strings and default strings + for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) { + // find floats not starting with '0', string or 0 if not defined (Clint Priest) + oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0; + oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0; + // handle numeric vs string comparison - number < string - (Kyle Adams) + if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; } + // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2' + else if (typeof oFxNcL !== typeof oFyNcL) { + oFxNcL += ''; + oFyNcL += ''; + } + if (oFxNcL < oFyNcL) { return -1; } + if (oFxNcL > oFyNcL) { return 1; } + } + return 0; +}; + + +/***/ }), +/* 13 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ArgumentsError; }); +/** + * Create a syntax error with the message: + * 'Wrong number of arguments in function ( provided, - expected)' + * @param {string} fn Function name + * @param {number} count Actual argument count + * @param {number} min Minimum required argument count + * @param {number} [max] Maximum required argument count + * @extends Error + */ +function ArgumentsError(fn, count, min, max) { + if (!(this instanceof ArgumentsError)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.fn = fn; + this.count = count; + this.min = min; + this.max = max; + this.message = 'Wrong number of arguments in function ' + fn + ' (' + count + ' provided, ' + min + (max !== undefined && max !== null ? '-' + max : '') + ' expected)'; + this.stack = new Error().stack; +} +ArgumentsError.prototype = new Error(); +ArgumentsError.prototype.constructor = Error; +ArgumentsError.prototype.name = 'ArgumentsError'; +ArgumentsError.prototype.isArgumentsError = true; + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/** + * typed-function + * + * Type checking for JavaScript functions + * + * https://github.com/josdejong/typed-function + */ + + +(function (root, factory) { + if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function () { + + function ok () { + return true; + } + + function notOk () { + return false; + } + + function undef () { + return undefined; + } + + /** + * @typedef {{ + * params: Param[], + * fn: function + * }} Signature + * + * @typedef {{ + * types: Type[], + * restParam: boolean + * }} Param + * + * @typedef {{ + * name: string, + * typeIndex: number, + * test: function, + * conversion?: ConversionDef, + * conversionIndex: number, + * }} Type + * + * @typedef {{ + * from: string, + * to: string, + * convert: function (*) : * + * }} ConversionDef + * + * @typedef {{ + * name: string, + * test: function(*) : boolean + * }} TypeDef + */ + + // create a new instance of typed-function + function create () { + // data type tests + var _types = [ + { name: 'number', test: function (x) { return typeof x === 'number' } }, + { name: 'string', test: function (x) { return typeof x === 'string' } }, + { name: 'boolean', test: function (x) { return typeof x === 'boolean' } }, + { name: 'Function', test: function (x) { return typeof x === 'function'} }, + { name: 'Array', test: Array.isArray }, + { name: 'Date', test: function (x) { return x instanceof Date } }, + { name: 'RegExp', test: function (x) { return x instanceof RegExp } }, + { name: 'Object', test: function (x) { + return typeof x === 'object' && x !== null && x.constructor === Object + }}, + { name: 'null', test: function (x) { return x === null } }, + { name: 'undefined', test: function (x) { return x === undefined } } + ]; + + var anyType = { + name: 'any', + test: ok + } + + // types which need to be ignored + var _ignore = []; + + // type conversions + var _conversions = []; + + // This is a temporary object, will be replaced with a typed function at the end + var typed = { + types: _types, + conversions: _conversions, + ignore: _ignore + }; + + /** + * Find the test function for a type + * @param {String} typeName + * @return {TypeDef} Returns the type definition when found, + * Throws a TypeError otherwise + */ + function findTypeByName (typeName) { + var entry = findInArray(typed.types, function (entry) { + return entry.name === typeName; + }); + + if (entry) { + return entry; + } + + if (typeName === 'any') { // special baked-in case 'any' + return anyType; + } + + var hint = findInArray(typed.types, function (entry) { + return entry.name.toLowerCase() === typeName.toLowerCase(); + }); + + throw new TypeError('Unknown type "' + typeName + '"' + + (hint ? ('. Did you mean "' + hint.name + '"?') : '')); + } + + /** + * Find the index of a type definition. Handles special case 'any' + * @param {TypeDef} type + * @return {number} + */ + function findTypeIndex(type) { + if (type === anyType) { + return 999; + } + + return typed.types.indexOf(type); + } + + /** + * Find a type that matches a value. + * @param {*} value + * @return {string} Returns the name of the first type for which + * the type test matches the value. + */ + function findTypeName(value) { + var entry = findInArray(typed.types, function (entry) { + return entry.test(value); + }); + + if (entry) { + return entry.name; + } + + throw new TypeError('Value has unknown type. Value: ' + value); + } + + /** + * Find a specific signature from a (composed) typed function, for example: + * + * typed.find(fn, ['number', 'string']) + * typed.find(fn, 'number, string') + * + * Function find only only works for exact matches. + * + * @param {Function} fn A typed-function + * @param {string | string[]} signature Signature to be found, can be + * an array or a comma separated string. + * @return {Function} Returns the matching signature, or + * throws an error when no signature + * is found. + */ + function find (fn, signature) { + if (!fn.signatures) { + throw new TypeError('Function is no typed-function'); + } + + // normalize input + var arr; + if (typeof signature === 'string') { + arr = signature.split(','); + for (var i = 0; i < arr.length; i++) { + arr[i] = arr[i].trim(); + } + } + else if (Array.isArray(signature)) { + arr = signature; + } + else { + throw new TypeError('String array or a comma separated string expected'); + } + + var str = arr.join(','); + + // find an exact match + var match = fn.signatures[str]; + if (match) { + return match; + } + + // TODO: extend find to match non-exact signatures + + throw new TypeError('Signature not found (signature: ' + (fn.name || 'unnamed') + '(' + arr.join(', ') + '))'); + } + + /** + * Convert a given value to another data type. + * @param {*} value + * @param {string} type + */ + function convert (value, type) { + var from = findTypeName(value); + + // check conversion is needed + if (type === from) { + return value; + } + + for (var i = 0; i < typed.conversions.length; i++) { + var conversion = typed.conversions[i]; + if (conversion.from === from && conversion.to === type) { + return conversion.convert(value); + } + } + + throw new Error('Cannot convert from ' + from + ' to ' + type); + } + + /** + * Stringify parameters in a normalized way + * @param {Param[]} params + * @return {string} + */ + function stringifyParams (params) { + return params + .map(function (param) { + var typeNames = param.types.map(getTypeName); + + return (param.restParam ? '...' : '') + typeNames.join('|'); + }) + .join(','); + } + + /** + * Parse a parameter, like "...number | boolean" + * @param {string} param + * @param {ConversionDef[]} conversions + * @return {Param} param + */ + function parseParam (param, conversions) { + var restParam = param.indexOf('...') === 0; + var types = (!restParam) + ? param + : (param.length > 3) + ? param.slice(3) + : 'any'; + + var typeNames = types.split('|').map(trim) + .filter(notEmpty) + .filter(notIgnore); + + var matchingConversions = filterConversions(conversions, typeNames); + + var exactTypes = typeNames.map(function (typeName) { + var type = findTypeByName(typeName); + + return { + name: typeName, + typeIndex: findTypeIndex(type), + test: type.test, + conversion: null, + conversionIndex: -1 + }; + }); + + var convertibleTypes = matchingConversions.map(function (conversion) { + var type = findTypeByName(conversion.from); + + return { + name: conversion.from, + typeIndex: findTypeIndex(type), + test: type.test, + conversion: conversion, + conversionIndex: conversions.indexOf(conversion) + }; + }); + + return { + types: exactTypes.concat(convertibleTypes), + restParam: restParam + }; + } + + /** + * Parse a signature with comma separated parameters, + * like "number | boolean, ...string" + * @param {string} signature + * @param {function} fn + * @param {ConversionDef[]} conversions + * @return {Signature | null} signature + */ + function parseSignature (signature, fn, conversions) { + var params = []; + + if (signature.trim() !== '') { + params = signature + .split(',') + .map(trim) + .map(function (param, index, array) { + var parsedParam = parseParam(param, conversions); + + if (parsedParam.restParam && (index !== array.length - 1)) { + throw new SyntaxError('Unexpected rest parameter "' + param + '": ' + + 'only allowed for the last parameter'); + } + + return parsedParam; + }); + } + + if (params.some(isInvalidParam)) { + // invalid signature: at least one parameter has no types + // (they may have been filtered) + return null; + } + + return { + params: params, + fn: fn + }; + } + + /** + * Test whether a set of params contains a restParam + * @param {Param[]} params + * @return {boolean} Returns true when the last parameter is a restParam + */ + function hasRestParam(params) { + var param = last(params) + return param ? param.restParam : false; + } + + /** + * Test whether a parameter contains conversions + * @param {Param} param + * @return {boolean} Returns true when at least one of the parameters + * contains a conversion. + */ + function hasConversions(param) { + return param.types.some(function (type) { + return type.conversion != null; + }); + } + + /** + * Create a type test for a single parameter, which can have one or multiple + * types. + * @param {Param} param + * @return {function(x: *) : boolean} Returns a test function + */ + function compileTest(param) { + if (!param || param.types.length === 0) { + // nothing to do + return ok; + } + else if (param.types.length === 1) { + return findTypeByName(param.types[0].name).test; + } + else if (param.types.length === 2) { + var test0 = findTypeByName(param.types[0].name).test; + var test1 = findTypeByName(param.types[1].name).test; + return function or(x) { + return test0(x) || test1(x); + } + } + else { // param.types.length > 2 + var tests = param.types.map(function (type) { + return findTypeByName(type.name).test; + }) + return function or(x) { + for (var i = 0; i < tests.length; i++) { + if (tests[i](x)) { + return true; + } + } + return false; + } + } + } + + /** + * Create a test for all parameters of a signature + * @param {Param[]} params + * @return {function(args: Array<*>) : boolean} + */ + function compileTests(params) { + var tests, test0, test1; + + if (hasRestParam(params)) { + // variable arguments like '...number' + tests = initial(params).map(compileTest); + var varIndex = tests.length; + var lastTest = compileTest(last(params)); + var testRestParam = function (args) { + for (var i = varIndex; i < args.length; i++) { + if (!lastTest(args[i])) { + return false; + } + } + return true; + } + + return function testArgs(args) { + for (var i = 0; i < tests.length; i++) { + if (!tests[i](args[i])) { + return false; + } + } + return testRestParam(args) && (args.length >= varIndex + 1); + }; + } + else { + // no variable arguments + if (params.length === 0) { + return function testArgs(args) { + return args.length === 0; + }; + } + else if (params.length === 1) { + test0 = compileTest(params[0]); + return function testArgs(args) { + return test0(args[0]) && args.length === 1; + }; + } + else if (params.length === 2) { + test0 = compileTest(params[0]); + test1 = compileTest(params[1]); + return function testArgs(args) { + return test0(args[0]) && test1(args[1]) && args.length === 2; + }; + } + else { // arguments.length > 2 + tests = params.map(compileTest); + return function testArgs(args) { + for (var i = 0; i < tests.length; i++) { + if (!tests[i](args[i])) { + return false; + } + } + return args.length === tests.length; + }; + } + } + } + + /** + * Find the parameter at a specific index of a signature. + * Handles rest parameters. + * @param {Signature} signature + * @param {number} index + * @return {Param | null} Returns the matching parameter when found, + * null otherwise. + */ + function getParamAtIndex(signature, index) { + return index < signature.params.length + ? signature.params[index] + : hasRestParam(signature.params) + ? last(signature.params) + : null + } + + /** + * Get all type names of a parameter + * @param {Signature} signature + * @param {number} index + * @param {boolean} excludeConversions + * @return {string[]} Returns an array with type names + */ + function getExpectedTypeNames (signature, index, excludeConversions) { + var param = getParamAtIndex(signature, index); + var types = param + ? excludeConversions + ? param.types.filter(isExactType) + : param.types + : []; + + return types.map(getTypeName); + } + + /** + * Returns the name of a type + * @param {Type} type + * @return {string} Returns the type name + */ + function getTypeName(type) { + return type.name; + } + + /** + * Test whether a type is an exact type or conversion + * @param {Type} type + * @return {boolean} Returns true when + */ + function isExactType(type) { + return type.conversion === null || type.conversion === undefined; + } + + /** + * Helper function for creating error messages: create an array with + * all available types on a specific argument index. + * @param {Signature[]} signatures + * @param {number} index + * @return {string[]} Returns an array with available types + */ + function mergeExpectedParams(signatures, index) { + var typeNames = uniq(flatMap(signatures, function (signature) { + return getExpectedTypeNames(signature, index, false); + })); + + return (typeNames.indexOf('any') !== -1) ? ['any'] : typeNames; + } + + /** + * Create + * @param {string} name The name of the function + * @param {array.<*>} args The actual arguments passed to the function + * @param {Signature[]} signatures A list with available signatures + * @return {TypeError} Returns a type error with additional data + * attached to it in the property `data` + */ + function createError(name, args, signatures) { + var err, expected; + var _name = name || 'unnamed'; + + // test for wrong type at some index + var matchingSignatures = signatures; + var index; + for (index = 0; index < args.length; index++) { + var nextMatchingDefs = matchingSignatures.filter(function (signature) { + var test = compileTest(getParamAtIndex(signature, index)); + return (index < signature.params.length || hasRestParam(signature.params)) && + test(args[index]); + }); + + if (nextMatchingDefs.length === 0) { + // no matching signatures anymore, throw error "wrong type" + expected = mergeExpectedParams(matchingSignatures, index); + if (expected.length > 0) { + var actualType = findTypeName(args[index]); + + err = new TypeError('Unexpected type of argument in function ' + _name + + ' (expected: ' + expected.join(' or ') + + ', actual: ' + actualType + ', index: ' + index + ')'); + err.data = { + category: 'wrongType', + fn: _name, + index: index, + actual: actualType, + expected: expected + } + return err; + } + } + else { + matchingSignatures = nextMatchingDefs; + } + } + + // test for too few arguments + var lengths = matchingSignatures.map(function (signature) { + return hasRestParam(signature.params) ? Infinity : signature.params.length; + }); + if (args.length < Math.min.apply(null, lengths)) { + expected = mergeExpectedParams(matchingSignatures, index); + err = new TypeError('Too few arguments in function ' + _name + + ' (expected: ' + expected.join(' or ') + + ', index: ' + args.length + ')'); + err.data = { + category: 'tooFewArgs', + fn: _name, + index: args.length, + expected: expected + } + return err; + } + + // test for too many arguments + var maxLength = Math.max.apply(null, lengths); + if (args.length > maxLength) { + err = new TypeError('Too many arguments in function ' + _name + + ' (expected: ' + maxLength + ', actual: ' + args.length + ')'); + err.data = { + category: 'tooManyArgs', + fn: _name, + index: args.length, + expectedLength: maxLength + } + return err; + } + + err = new TypeError('Arguments of type "' + args.join(', ') + + '" do not match any of the defined signatures of function ' + _name + '.'); + err.data = { + category: 'mismatch', + actual: args.map(findTypeName) + } + return err; + } + + /** + * Find the lowest index of all exact types of a parameter (no conversions) + * @param {Param} param + * @return {number} Returns the index of the lowest type in typed.types + */ + function getLowestTypeIndex (param) { + var min = 999; + + for (var i = 0; i < param.types.length; i++) { + if (isExactType(param.types[i])) { + min = Math.min(min, param.types[i].typeIndex); + } + } + + return min; + } + + /** + * Find the lowest index of the conversion of all types of the parameter + * having a conversion + * @param {Param} param + * @return {number} Returns the lowest index of the conversions of this type + */ + function getLowestConversionIndex (param) { + var min = 999; + + for (var i = 0; i < param.types.length; i++) { + if (!isExactType(param.types[i])) { + min = Math.min(min, param.types[i].conversionIndex); + } + } + + return min; + } + + /** + * Compare two params + * @param {Param} param1 + * @param {Param} param2 + * @return {number} returns a negative number when param1 must get a lower + * index than param2, a positive number when the opposite, + * or zero when both are equal + */ + function compareParams (param1, param2) { + var c; + + // compare having a rest parameter or not + c = param1.restParam - param2.restParam; + if (c !== 0) { + return c; + } + + // compare having conversions or not + c = hasConversions(param1) - hasConversions(param2); + if (c !== 0) { + return c; + } + + // compare the index of the types + c = getLowestTypeIndex(param1) - getLowestTypeIndex(param2); + if (c !== 0) { + return c; + } + + // compare the index of any conversion + return getLowestConversionIndex(param1) - getLowestConversionIndex(param2); + } + + /** + * Compare two signatures + * @param {Signature} signature1 + * @param {Signature} signature2 + * @return {number} returns a negative number when param1 must get a lower + * index than param2, a positive number when the opposite, + * or zero when both are equal + */ + function compareSignatures (signature1, signature2) { + var len = Math.min(signature1.params.length, signature2.params.length); + var i; + var c; + + // compare whether the params have conversions at all or not + c = signature1.params.some(hasConversions) - signature2.params.some(hasConversions) + if (c !== 0) { + return c; + } + + // next compare whether the params have conversions one by one + for (i = 0; i < len; i++) { + c = hasConversions(signature1.params[i]) - hasConversions(signature2.params[i]); + if (c !== 0) { + return c; + } + } + + // compare the types of the params one by one + for (i = 0; i < len; i++) { + c = compareParams(signature1.params[i], signature2.params[i]); + if (c !== 0) { + return c; + } + } + + // compare the number of params + return signature1.params.length - signature2.params.length; + } + + /** + * Get params containing all types that can be converted to the defined types. + * + * @param {ConversionDef[]} conversions + * @param {string[]} typeNames + * @return {ConversionDef[]} Returns the conversions that are available + * for every type (if any) + */ + function filterConversions(conversions, typeNames) { + var matches = {}; + + conversions.forEach(function (conversion) { + if (typeNames.indexOf(conversion.from) === -1 && + typeNames.indexOf(conversion.to) !== -1 && + !matches[conversion.from]) { + matches[conversion.from] = conversion; + } + }); + + return Object.keys(matches).map(function (from) { + return matches[from]; + }); + } + + /** + * Preprocess arguments before calling the original function: + * - if needed convert the parameters + * - in case of rest parameters, move the rest parameters into an Array + * @param {Param[]} params + * @param {function} fn + * @return {function} Returns a wrapped function + */ + function compileArgsPreprocessing(params, fn) { + var fnConvert = fn; + + // TODO: can we make this wrapper function smarter/simpler? + + if (params.some(hasConversions)) { + var restParam = hasRestParam(params); + var compiledConversions = params.map(compileArgConversion) + + fnConvert = function convertArgs() { + var args = []; + var last = restParam ? arguments.length - 1 : arguments.length; + for (var i = 0; i < last; i++) { + args[i] = compiledConversions[i](arguments[i]); + } + if (restParam) { + args[last] = arguments[last].map(compiledConversions[last]); + } + + return fn.apply(null, args); + } + } + + var fnPreprocess = fnConvert; + if (hasRestParam(params)) { + var offset = params.length - 1; + + fnPreprocess = function preprocessRestParams () { + return fnConvert.apply(null, + slice(arguments, 0, offset).concat([slice(arguments, offset)])); + } + } + + return fnPreprocess; + } + + /** + * Compile conversion for a parameter to the right type + * @param {Param} param + * @return {function} Returns the wrapped function that will convert arguments + * + */ + function compileArgConversion(param) { + var test0, test1, conversion0, conversion1; + var tests = []; + var conversions = []; + + param.types.forEach(function (type) { + if (type.conversion) { + tests.push(findTypeByName(type.conversion.from).test); + conversions.push(type.conversion.convert); + } + }); + + // create optimized conversion functions depending on the number of conversions + switch (conversions.length) { + case 0: + return function convertArg(arg) { + return arg; + } + + case 1: + test0 = tests[0] + conversion0 = conversions[0]; + return function convertArg(arg) { + if (test0(arg)) { + return conversion0(arg) + } + return arg; + } + + case 2: + test0 = tests[0] + test1 = tests[1] + conversion0 = conversions[0]; + conversion1 = conversions[1]; + return function convertArg(arg) { + if (test0(arg)) { + return conversion0(arg) + } + if (test1(arg)) { + return conversion1(arg) + } + return arg; + } + + default: + return function convertArg(arg) { + for (var i = 0; i < conversions.length; i++) { + if (tests[i](arg)) { + return conversions[i](arg); + } + } + return arg; + } + } + } + + /** + * Convert an array with signatures into a map with signatures, + * where signatures with union types are split into separate signatures + * + * Throws an error when there are conflicting types + * + * @param {Signature[]} signatures + * @return {Object.} Returns a map with signatures + * as key and the original function + * of this signature as value. + */ + function createSignaturesMap(signatures) { + var signaturesMap = {}; + signatures.forEach(function (signature) { + if (!signature.params.some(hasConversions)) { + splitParams(signature.params, true).forEach(function (params) { + signaturesMap[stringifyParams(params)] = signature.fn; + }); + } + }); + + return signaturesMap; + } + + /** + * Split params with union types in to separate params. + * + * For example: + * + * splitParams([['Array', 'Object'], ['string', 'RegExp']) + * // returns: + * // [ + * // ['Array', 'string'], + * // ['Array', 'RegExp'], + * // ['Object', 'string'], + * // ['Object', 'RegExp'] + * // ] + * + * @param {Param[]} params + * @param {boolean} ignoreConversionTypes + * @return {Param[]} + */ + function splitParams(params, ignoreConversionTypes) { + function _splitParams(params, index, types) { + if (index < params.length) { + var param = params[index] + var filteredTypes = ignoreConversionTypes + ? param.types.filter(isExactType) + : param.types; + var typeGroups + + if (param.restParam) { + // split the types of a rest parameter in two: + // one with only exact types, and one with exact types and conversions + var exactTypes = filteredTypes.filter(isExactType) + typeGroups = exactTypes.length < filteredTypes.length + ? [exactTypes, filteredTypes] + : [filteredTypes] + + } + else { + // split all the types of a regular parameter into one type per group + typeGroups = filteredTypes.map(function (type) { + return [type] + }) + } + + // recurse over the groups with types + return flatMap(typeGroups, function (typeGroup) { + return _splitParams(params, index + 1, types.concat([typeGroup])); + }); + + } + else { + // we've reached the end of the parameters. Now build a new Param + var splittedParams = types.map(function (type, typeIndex) { + return { + types: type, + restParam: (typeIndex === params.length - 1) && hasRestParam(params) + } + }); + + return [splittedParams]; + } + } + + return _splitParams(params, 0, []); + } + + /** + * Test whether two signatures have a conflicting signature + * @param {Signature} signature1 + * @param {Signature} signature2 + * @return {boolean} Returns true when the signatures conflict, false otherwise. + */ + function hasConflictingParams(signature1, signature2) { + var ii = Math.max(signature1.params.length, signature2.params.length); + + for (var i = 0; i < ii; i++) { + var typesNames1 = getExpectedTypeNames(signature1, i, true); + var typesNames2 = getExpectedTypeNames(signature2, i, true); + + if (!hasOverlap(typesNames1, typesNames2)) { + return false; + } + } + + var len1 = signature1.params.length; + var len2 = signature2.params.length; + var restParam1 = hasRestParam(signature1.params); + var restParam2 = hasRestParam(signature2.params); + + return restParam1 + ? restParam2 ? (len1 === len2) : (len2 >= len1) + : restParam2 ? (len1 >= len2) : (len1 === len2) + } + + /** + * Create a typed function + * @param {String} name The name for the typed function + * @param {Object.} signaturesMap + * An object with one or + * multiple signatures as key, and the + * function corresponding to the + * signature as value. + * @return {function} Returns the created typed function. + */ + function createTypedFunction(name, signaturesMap) { + if (Object.keys(signaturesMap).length === 0) { + throw new SyntaxError('No signatures provided'); + } + + // parse the signatures, and check for conflicts + var parsedSignatures = []; + Object.keys(signaturesMap) + .map(function (signature) { + return parseSignature(signature, signaturesMap[signature], typed.conversions); + }) + .filter(notNull) + .forEach(function (parsedSignature) { + // check whether this parameter conflicts with already parsed signatures + var conflictingSignature = findInArray(parsedSignatures, function (s) { + return hasConflictingParams(s, parsedSignature) + }); + if (conflictingSignature) { + throw new TypeError('Conflicting signatures "' + + stringifyParams(conflictingSignature.params) + '" and "' + + stringifyParams(parsedSignature.params) + '".'); + } + + parsedSignatures.push(parsedSignature); + }); + + // split and filter the types of the signatures, and then order them + var signatures = flatMap(parsedSignatures, function (parsedSignature) { + var params = parsedSignature ? splitParams(parsedSignature.params, false) : [] + + return params.map(function (params) { + return { + params: params, + fn: parsedSignature.fn + }; + }); + }).filter(notNull); + + signatures.sort(compareSignatures); + + // we create a highly optimized checks for the first couple of signatures with max 2 arguments + var ok0 = signatures[0] && signatures[0].params.length <= 2 && !hasRestParam(signatures[0].params); + var ok1 = signatures[1] && signatures[1].params.length <= 2 && !hasRestParam(signatures[1].params); + var ok2 = signatures[2] && signatures[2].params.length <= 2 && !hasRestParam(signatures[2].params); + var ok3 = signatures[3] && signatures[3].params.length <= 2 && !hasRestParam(signatures[3].params); + var ok4 = signatures[4] && signatures[4].params.length <= 2 && !hasRestParam(signatures[4].params); + var ok5 = signatures[5] && signatures[5].params.length <= 2 && !hasRestParam(signatures[5].params); + var allOk = ok0 && ok1 && ok2 && ok3 && ok4 && ok5; + + // compile the tests + var tests = signatures.map(function (signature) { + return compileTests(signature.params); + }); + + var test00 = ok0 ? compileTest(signatures[0].params[0]) : notOk; + var test10 = ok1 ? compileTest(signatures[1].params[0]) : notOk; + var test20 = ok2 ? compileTest(signatures[2].params[0]) : notOk; + var test30 = ok3 ? compileTest(signatures[3].params[0]) : notOk; + var test40 = ok4 ? compileTest(signatures[4].params[0]) : notOk; + var test50 = ok5 ? compileTest(signatures[5].params[0]) : notOk; + + var test01 = ok0 ? compileTest(signatures[0].params[1]) : notOk; + var test11 = ok1 ? compileTest(signatures[1].params[1]) : notOk; + var test21 = ok2 ? compileTest(signatures[2].params[1]) : notOk; + var test31 = ok3 ? compileTest(signatures[3].params[1]) : notOk; + var test41 = ok4 ? compileTest(signatures[4].params[1]) : notOk; + var test51 = ok5 ? compileTest(signatures[5].params[1]) : notOk; + + // compile the functions + var fns = signatures.map(function(signature) { + return compileArgsPreprocessing(signature.params, signature.fn) + }); + + var fn0 = ok0 ? fns[0] : undef; + var fn1 = ok1 ? fns[1] : undef; + var fn2 = ok2 ? fns[2] : undef; + var fn3 = ok3 ? fns[3] : undef; + var fn4 = ok4 ? fns[4] : undef; + var fn5 = ok5 ? fns[5] : undef; + + var len0 = ok0 ? signatures[0].params.length : -1; + var len1 = ok1 ? signatures[1].params.length : -1; + var len2 = ok2 ? signatures[2].params.length : -1; + var len3 = ok3 ? signatures[3].params.length : -1; + var len4 = ok4 ? signatures[4].params.length : -1; + var len5 = ok5 ? signatures[5].params.length : -1; + + // simple and generic, but also slow + var iStart = allOk ? 6 : 0; + var iEnd = signatures.length; + var generic = function generic() { + 'use strict'; + + for (var i = iStart; i < iEnd; i++) { + if (tests[i](arguments)) { + return fns[i].apply(null, arguments); + } + } + + throw createError(name, arguments, signatures); + } + + // create the typed function + // fast, specialized version. Falls back to the slower, generic one if needed + var fn = function fn(arg0, arg1) { + 'use strict'; + + if (arguments.length === len0 && test00(arg0) && test01(arg1)) { return fn0.apply(null, arguments); } + if (arguments.length === len1 && test10(arg0) && test11(arg1)) { return fn1.apply(null, arguments); } + if (arguments.length === len2 && test20(arg0) && test21(arg1)) { return fn2.apply(null, arguments); } + if (arguments.length === len3 && test30(arg0) && test31(arg1)) { return fn3.apply(null, arguments); } + if (arguments.length === len4 && test40(arg0) && test41(arg1)) { return fn4.apply(null, arguments); } + if (arguments.length === len5 && test50(arg0) && test51(arg1)) { return fn5.apply(null, arguments); } + + return generic.apply(null, arguments); + } + + // attach name the typed function + try { + Object.defineProperty(fn, 'name', {value: name}); + } + catch (err) { + // old browsers do not support Object.defineProperty and some don't support setting the name property + // the function name is not essential for the functioning, it's mostly useful for debugging, + // so it's fine to have unnamed functions. + } + + // attach signatures to the function + fn.signatures = createSignaturesMap(signatures); + + return fn; + } + + /** + * Test whether a type should be NOT be ignored + * @param {string} typeName + * @return {boolean} + */ + function notIgnore(typeName) { + return typed.ignore.indexOf(typeName) === -1; + } + + /** + * trim a string + * @param {string} str + * @return {string} + */ + function trim(str) { + return str.trim(); + } + + /** + * Test whether a string is not empty + * @param {string} str + * @return {boolean} + */ + function notEmpty(str) { + return !!str; + } + + /** + * test whether a value is not strict equal to null + * @param {*} value + * @return {boolean} + */ + function notNull(value) { + return value !== null; + } + + /** + * Test whether a parameter has no types defined + * @param {Param} param + * @return {boolean} + */ + function isInvalidParam (param) { + return param.types.length === 0; + } + + /** + * Return all but the last items of an array + * @param {Array} arr + * @return {Array} + */ + function initial(arr) { + return arr.slice(0, arr.length - 1); + } + + /** + * return the last item of an array + * @param {Array} arr + * @return {*} + */ + function last(arr) { + return arr[arr.length - 1]; + } + + /** + * Slice an array or function Arguments + * @param {Array | Arguments | IArguments} arr + * @param {number} start + * @param {number} [end] + * @return {Array} + */ + function slice(arr, start, end) { + return Array.prototype.slice.call(arr, start, end); + } + + /** + * Test whether an array contains some item + * @param {Array} array + * @param {*} item + * @return {boolean} Returns true if array contains item, false if not. + */ + function contains(array, item) { + return array.indexOf(item) !== -1; + } + + /** + * Test whether two arrays have overlapping items + * @param {Array} array1 + * @param {Array} array2 + * @return {boolean} Returns true when at least one item exists in both arrays + */ + function hasOverlap(array1, array2) { + for (var i = 0; i < array1.length; i++) { + if (contains(array2, array1[i])) { + return true; + } + } + + return false; + } + + /** + * Return the first item from an array for which test(arr[i]) returns true + * @param {Array} arr + * @param {function} test + * @return {* | undefined} Returns the first matching item + * or undefined when there is no match + */ + function findInArray(arr, test) { + for (var i = 0; i < arr.length; i++) { + if (test(arr[i])) { + return arr[i]; + } + } + return undefined; + } + + /** + * Filter unique items of an array with strings + * @param {string[]} arr + * @return {string[]} + */ + function uniq(arr) { + var entries = {} + for (var i = 0; i < arr.length; i++) { + entries[arr[i]] = true; + } + return Object.keys(entries); + } + + /** + * Flat map the result invoking a callback for every item in an array. + * https://gist.github.com/samgiles/762ee337dff48623e729 + * @param {Array} arr + * @param {function} callback + * @return {Array} + */ + function flatMap(arr, callback) { + return Array.prototype.concat.apply([], arr.map(callback)); + } + + /** + * Retrieve the function name from a set of typed functions, + * and check whether the name of all functions match (if given) + * @param {function[]} fns + */ + function getName (fns) { + var name = ''; + + for (var i = 0; i < fns.length; i++) { + var fn = fns[i]; + + // check whether the names are the same when defined + if ((typeof fn.signatures === 'object' || typeof fn.signature === 'string') && fn.name !== '') { + if (name === '') { + name = fn.name; + } + else if (name !== fn.name) { + var err = new Error('Function names do not match (expected: ' + name + ', actual: ' + fn.name + ')'); + err.data = { + actual: fn.name, + expected: name + }; + throw err; + } + } + } + + return name; + } + + // extract and merge all signatures of a list with typed functions + function extractSignatures(fns) { + var err; + var signaturesMap = {}; + + function validateUnique(_signature, _fn) { + if (signaturesMap.hasOwnProperty(_signature) && _fn !== signaturesMap[_signature]) { + err = new Error('Signature "' + _signature + '" is defined twice'); + err.data = {signature: _signature}; + throw err; + // else: both signatures point to the same function, that's fine + } + } + + for (var i = 0; i < fns.length; i++) { + var fn = fns[i]; + + // test whether this is a typed-function + if (typeof fn.signatures === 'object') { + // merge the signatures + for (var signature in fn.signatures) { + if (fn.signatures.hasOwnProperty(signature)) { + validateUnique(signature, fn.signatures[signature]); + signaturesMap[signature] = fn.signatures[signature]; + } + } + } + else if (typeof fn.signature === 'string') { + validateUnique(fn.signature, fn); + signaturesMap[fn.signature] = fn; + } + else { + err = new TypeError('Function is no typed-function (index: ' + i + ')'); + err.data = {index: i}; + throw err; + } + } + + return signaturesMap; + } + + typed = createTypedFunction('typed', { + 'string, Object': createTypedFunction, + 'Object': function (signaturesMap) { + // find existing name + var fns = []; + for (var signature in signaturesMap) { + if (signaturesMap.hasOwnProperty(signature)) { + fns.push(signaturesMap[signature]); + } + } + var name = getName(fns); + return createTypedFunction(name, signaturesMap); + }, + '...Function': function (fns) { + return createTypedFunction(getName(fns), extractSignatures(fns)); + }, + 'string, ...Function': function (name, fns) { + return createTypedFunction(name, extractSignatures(fns)); + } + }); + + typed.create = create; + typed.types = _types; + typed.conversions = _conversions; + typed.ignore = _ignore; + typed.convert = convert; + typed.find = find; + + /** + * add a type + * @param {{name: string, test: function}} type + * @param {boolean} [beforeObjectTest=true] + * If true, the new test will be inserted before + * the test with name 'Object' (if any), since + * tests for Object match Array and classes too. + */ + typed.addType = function (type, beforeObjectTest) { + if (!type || typeof type.name !== 'string' || typeof type.test !== 'function') { + throw new TypeError('Object with properties {name: string, test: function} expected'); + } + + if (beforeObjectTest !== false) { + for (var i = 0; i < typed.types.length; i++) { + if (typed.types[i].name === 'Object') { + typed.types.splice(i, 0, type); + return + } + } + } + + typed.types.push(type); + }; + + // add a conversion + typed.addConversion = function (conversion) { + if (!conversion + || typeof conversion.from !== 'string' + || typeof conversion.to !== 'string' + || typeof conversion.convert !== 'function') { + throw new TypeError('Object with properties {from: string, to: string, convert: function} expected'); + } + + typed.conversions.push(conversion); + }; + + return typed; + } + + return create(); +})); + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +var width = 256;// each RC4 output is 0 <= x < 256 +var chunks = 6;// at least six RC4 outputs for each double +var digits = 52;// there are 52 significant digits in a double +var pool = [];// pool: entropy pool starts empty +var GLOBAL = typeof global === 'undefined' ? window : global; + +// +// The following constants are related to IEEE 754 limits. +// +var startdenom = Math.pow(width, chunks), + significance = Math.pow(2, digits), + overflow = significance * 2, + mask = width - 1; + + +var oldRandom = Math.random; + +// +// seedrandom() +// This is the seedrandom function described above. +// +module.exports = function(seed, options) { + if (options && options.global === true) { + options.global = false; + Math.random = module.exports(seed, options); + options.global = true; + return Math.random; + } + var use_entropy = (options && options.entropy) || false; + var key = []; + + // Flatten the seed string or build one from local entropy if needed. + var shortseed = mixkey(flatten( + use_entropy ? [seed, tostring(pool)] : + 0 in arguments ? seed : autoseed(), 3), key); + + // Use the seed to initialize an ARC4 generator. + var arc4 = new ARC4(key); + + // Mix the randomness into accumulated entropy. + mixkey(tostring(arc4.S), pool); + + // Override Math.random + + // This function returns a random double in [0, 1) that contains + // randomness in every bit of the mantissa of the IEEE 754 value. + + return function() { // Closure to return a random double: + var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48 + d = startdenom, // and denominator d = 2 ^ 48. + x = 0; // and no 'extra last byte'. + while (n < significance) { // Fill up all significant digits by + n = (n + x) * width; // shifting numerator and + d *= width; // denominator and generating a + x = arc4.g(1); // new least-significant-byte. + } + while (n >= overflow) { // To avoid rounding up, before adding + n /= 2; // last byte, shift everything + d /= 2; // right using integer Math until + x >>>= 1; // we have exactly the desired bits. + } + return (n + x) / d; // Form the number within [0, 1). + }; +}; + +module.exports.resetGlobal = function () { + Math.random = oldRandom; +}; + +// +// ARC4 +// +// An ARC4 implementation. The constructor takes a key in the form of +// an array of at most (width) integers that should be 0 <= x < (width). +// +// The g(count) method returns a pseudorandom integer that concatenates +// the next (count) outputs from ARC4. Its return value is a number x +// that is in the range 0 <= x < (width ^ count). +// +/** @constructor */ +function ARC4(key) { + var t, keylen = key.length, + me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; + + // The empty key [] is treated as [0]. + if (!keylen) { key = [keylen++]; } + + // Set up S using the standard key scheduling algorithm. + while (i < width) { + s[i] = i++; + } + for (i = 0; i < width; i++) { + s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))]; + s[j] = t; + } + + // The "g" method returns the next (count) outputs as one number. + (me.g = function(count) { + // Using instance members instead of closure state nearly doubles speed. + var t, r = 0, + i = me.i, j = me.j, s = me.S; + while (count--) { + t = s[i = mask & (i + 1)]; + r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))]; + } + me.i = i; me.j = j; + return r; + // For robust unpredictability discard an initial batch of values. + // See http://www.rsa.com/rsalabs/node.asp?id=2009 + })(width); +} + +// +// flatten() +// Converts an object tree to nested arrays of strings. +// +function flatten(obj, depth) { + var result = [], typ = (typeof obj)[0], prop; + if (depth && typ == 'o') { + for (prop in obj) { + try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} + } + } + return (result.length ? result : typ == 's' ? obj : obj + '\0'); +} + +// +// mixkey() +// Mixes a string seed into a key that is an array of integers, and +// returns a shortened string seed that is equivalent to the result key. +// +function mixkey(seed, key) { + var stringseed = seed + '', smear, j = 0; + while (j < stringseed.length) { + key[mask & j] = + mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++)); + } + return tostring(key); +} + +// +// autoseed() +// Returns an object for autoseeding, using window.crypto if available. +// +/** @param {Uint8Array=} seed */ +function autoseed(seed) { + try { + GLOBAL.crypto.getRandomValues(seed = new Uint8Array(width)); + return tostring(seed); + } catch (e) { + return [+new Date, GLOBAL, GLOBAL.navigator && GLOBAL.navigator.plugins, + GLOBAL.screen, tostring(pool)]; + } +} + +// +// tostring() +// Converts an array of charcodes to a string +// +function tostring(a) { + return String.fromCharCode.apply(0, a); +} + +// +// When seedrandom.js is loaded, we immediately mix a few bits +// from the built-in RNG into the entropy pool. Because we do +// not want to intefere with determinstic PRNG state later, +// seedrandom will not call Math.random on its own again after +// initialization. +// +mixkey(Math.random(), pool); + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(20))) + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_RESULT__;;(function (globalScope) { + 'use strict'; + + + /* + * decimal.js v10.2.0 + * An arbitrary-precision Decimal type for JavaScript. + * https://github.com/MikeMcl/decimal.js + * Copyright (c) 2019 Michael Mclaughlin + * MIT Licence + */ + + + // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ // + + + // The maximum exponent magnitude. + // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`. + var EXP_LIMIT = 9e15, // 0 to 9e15 + + // The limit on the value of `precision`, and on the value of the first argument to + // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`. + MAX_DIGITS = 1e9, // 0 to 1e9 + + // Base conversion alphabet. + NUMERALS = '0123456789abcdef', + + // The natural logarithm of 10 (1025 digits). + LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058', + + // Pi (1025 digits). + PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789', + + + // The initial configuration properties of the Decimal constructor. + DEFAULTS = { + + // These values must be integers within the stated ranges (inclusive). + // Most of these values can be changed at run-time using the `Decimal.config` method. + + // The maximum number of significant digits of the result of a calculation or base conversion. + // E.g. `Decimal.config({ precision: 20 });` + precision: 20, // 1 to MAX_DIGITS + + // The rounding mode used when rounding to `precision`. + // + // ROUND_UP 0 Away from zero. + // ROUND_DOWN 1 Towards zero. + // ROUND_CEIL 2 Towards +Infinity. + // ROUND_FLOOR 3 Towards -Infinity. + // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + // + // E.g. + // `Decimal.rounding = 4;` + // `Decimal.rounding = Decimal.ROUND_HALF_UP;` + rounding: 4, // 0 to 8 + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend (JavaScript %). + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 The IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive. + // + // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian + // division (9) are commonly used for the modulus operation. The other rounding modes can also + // be used, but they may not give useful results. + modulo: 1, // 0 to 9 + + // The exponent value at and beneath which `toString` returns exponential notation. + // JavaScript numbers: -7 + toExpNeg: -7, // 0 to -EXP_LIMIT + + // The exponent value at and above which `toString` returns exponential notation. + // JavaScript numbers: 21 + toExpPos: 21, // 0 to EXP_LIMIT + + // The minimum exponent value, beneath which underflow to zero occurs. + // JavaScript numbers: -324 (5e-324) + minE: -EXP_LIMIT, // -1 to -EXP_LIMIT + + // The maximum exponent value, above which overflow to Infinity occurs. + // JavaScript numbers: 308 (1.7976931348623157e+308) + maxE: EXP_LIMIT, // 1 to EXP_LIMIT + + // Whether to use cryptographically-secure random number generation, if available. + crypto: false // true/false + }, + + + // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- // + + + Decimal, inexact, noConflict, quadrant, + external = true, + + decimalError = '[DecimalError] ', + invalidArgument = decimalError + 'Invalid argument: ', + precisionLimitExceeded = decimalError + 'Precision limit exceeded', + cryptoUnavailable = decimalError + 'crypto unavailable', + + mathfloor = Math.floor, + mathpow = Math.pow, + + isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i, + isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i, + isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i, + isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, + + BASE = 1e7, + LOG_BASE = 7, + MAX_SAFE_INTEGER = 9007199254740991, + + LN10_PRECISION = LN10.length - 1, + PI_PRECISION = PI.length - 1, + + // Decimal.prototype object + P = { name: '[object Decimal]' }; + + + // Decimal prototype methods + + + /* + * absoluteValue abs + * ceil + * comparedTo cmp + * cosine cos + * cubeRoot cbrt + * decimalPlaces dp + * dividedBy div + * dividedToIntegerBy divToInt + * equals eq + * floor + * greaterThan gt + * greaterThanOrEqualTo gte + * hyperbolicCosine cosh + * hyperbolicSine sinh + * hyperbolicTangent tanh + * inverseCosine acos + * inverseHyperbolicCosine acosh + * inverseHyperbolicSine asinh + * inverseHyperbolicTangent atanh + * inverseSine asin + * inverseTangent atan + * isFinite + * isInteger isInt + * isNaN + * isNegative isNeg + * isPositive isPos + * isZero + * lessThan lt + * lessThanOrEqualTo lte + * logarithm log + * [maximum] [max] + * [minimum] [min] + * minus sub + * modulo mod + * naturalExponential exp + * naturalLogarithm ln + * negated neg + * plus add + * precision sd + * round + * sine sin + * squareRoot sqrt + * tangent tan + * times mul + * toBinary + * toDecimalPlaces toDP + * toExponential + * toFixed + * toFraction + * toHexadecimal toHex + * toNearest + * toNumber + * toOctal + * toPower pow + * toPrecision + * toSignificantDigits toSD + * toString + * truncated trunc + * valueOf toJSON + */ + + + /* + * Return a new Decimal whose value is the absolute value of this Decimal. + * + */ + P.absoluteValue = P.abs = function () { + var x = new this.constructor(this); + if (x.s < 0) x.s = 1; + return finalise(x); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the + * direction of positive Infinity. + * + */ + P.ceil = function () { + return finalise(new this.constructor(this), this.e + 1, 2); + }; + + + /* + * Return + * 1 if the value of this Decimal is greater than the value of `y`, + * -1 if the value of this Decimal is less than the value of `y`, + * 0 if they have the same value, + * NaN if the value of either Decimal is NaN. + * + */ + P.comparedTo = P.cmp = function (y) { + var i, j, xdL, ydL, + x = this, + xd = x.d, + yd = (y = new x.constructor(y)).d, + xs = x.s, + ys = y.s; + + // Either NaN or ±Infinity? + if (!xd || !yd) { + return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1; + } + + // Either zero? + if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0; + + // Signs differ? + if (xs !== ys) return xs; + + // Compare exponents. + if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1; + + xdL = xd.length; + ydL = yd.length; + + // Compare digit by digit. + for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) { + if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1; + } + + // Compare lengths. + return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1; + }; + + + /* + * Return a new Decimal whose value is the cosine of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * cos(0) = 1 + * cos(-0) = 1 + * cos(Infinity) = NaN + * cos(-Infinity) = NaN + * cos(NaN) = NaN + * + */ + P.cosine = P.cos = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.d) return new Ctor(NaN); + + // cos(0) = cos(-0) = 1 + if (!x.d[0]) return new Ctor(1); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; + Ctor.rounding = 1; + + x = cosine(Ctor, toLessThanHalfPi(Ctor, x)); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true); + }; + + + /* + * + * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * cbrt(0) = 0 + * cbrt(-0) = -0 + * cbrt(1) = 1 + * cbrt(-1) = -1 + * cbrt(N) = N + * cbrt(-I) = -I + * cbrt(I) = I + * + * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3)) + * + */ + P.cubeRoot = P.cbrt = function () { + var e, m, n, r, rep, s, sd, t, t3, t3plusx, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + external = false; + + // Initial estimate. + s = x.s * mathpow(x.s * x, 1 / 3); + + // Math.cbrt underflow/overflow? + // Pass x to Math.pow as integer, then adjust the exponent of the result. + if (!s || Math.abs(s) == 1 / 0) { + n = digitsToString(x.d); + e = x.e; + + // Adjust n exponent so it is a multiple of 3 away from x exponent. + if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00'); + s = mathpow(n, 1 / 3); + + // Rarely, e may be one less than the result exponent value. + e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new Ctor(n); + r.s = x.s; + } else { + r = new Ctor(s.toString()); + } + + sd = (e = Ctor.precision) + 3; + + // Halley's method. + // TODO? Compare Newton's method. + for (;;) { + t = r; + t3 = t.times(t).times(t); + t3plusx = t3.plus(x); + r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1); + + // TODO? Replace with for-loop and checkRoundingDigits. + if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { + n = n.slice(sd - 3, sd + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999 + // , i.e. approaching a rounding boundary, continue the iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the exact result as the + // nines may infinitely repeat. + if (!rep) { + finalise(t, e + 1, 0); + + if (t.times(t).times(t).eq(x)) { + r = t; + break; + } + } + + sd += 4; + rep = 1; + } else { + + // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. + // If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + finalise(r, e + 1, 1); + m = !r.times(r).times(r).eq(x); + } + + break; + } + } + } + + external = true; + + return finalise(r, e, Ctor.rounding, m); + }; + + + /* + * Return the number of decimal places of the value of this Decimal. + * + */ + P.decimalPlaces = P.dp = function () { + var w, + d = this.d, + n = NaN; + + if (d) { + w = d.length - 1; + n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last word. + w = d[w]; + if (w) for (; w % 10 == 0; w /= 10) n--; + if (n < 0) n = 0; + } + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + */ + P.dividedBy = P.div = function (y) { + return divide(this, new this.constructor(y)); + }; + + + /* + * Return a new Decimal whose value is the integer part of dividing the value of this Decimal + * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`. + * + */ + P.dividedToIntegerBy = P.divToInt = function (y) { + var x = this, + Ctor = x.constructor; + return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding); + }; + + + /* + * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. + * + */ + P.equals = P.eq = function (y) { + return this.cmp(y) === 0; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the + * direction of negative Infinity. + * + */ + P.floor = function () { + return finalise(new this.constructor(this), this.e + 1, 3); + }; + + + /* + * Return true if the value of this Decimal is greater than the value of `y`, otherwise return + * false. + * + */ + P.greaterThan = P.gt = function (y) { + return this.cmp(y) > 0; + }; + + + /* + * Return true if the value of this Decimal is greater than or equal to the value of `y`, + * otherwise return false. + * + */ + P.greaterThanOrEqualTo = P.gte = function (y) { + var k = this.cmp(y); + return k == 1 || k === 0; + }; + + + /* + * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [1, Infinity] + * + * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ... + * + * cosh(0) = 1 + * cosh(-0) = 1 + * cosh(Infinity) = Infinity + * cosh(-Infinity) = Infinity + * cosh(NaN) = NaN + * + * x time taken (ms) result + * 1000 9 9.8503555700852349694e+433 + * 10000 25 4.4034091128314607936e+4342 + * 100000 171 1.4033316802130615897e+43429 + * 1000000 3817 1.5166076984010437725e+434294 + * 10000000 abandoned after 2 minute wait + * + * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x)) + * + */ + P.hyperbolicCosine = P.cosh = function () { + var k, n, pr, rm, len, + x = this, + Ctor = x.constructor, + one = new Ctor(1); + + if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN); + if (x.isZero()) return one; + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; + Ctor.rounding = 1; + len = x.d.length; + + // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1 + // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4)) + + // Estimate the optimum number of times to use the argument reduction. + // TODO? Estimation reused from cosine() and may not be optimal here. + if (len < 32) { + k = Math.ceil(len / 3); + n = (1 / tinyPow(4, k)).toString(); + } else { + k = 16; + n = '2.3283064365386962890625e-10'; + } + + x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true); + + // Reverse argument reduction + var cosh2_x, + i = k, + d8 = new Ctor(8); + for (; i--;) { + cosh2_x = x.times(x); + x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8)))); + } + + return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true); + }; + + + /* + * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ... + * + * sinh(0) = 0 + * sinh(-0) = -0 + * sinh(Infinity) = Infinity + * sinh(-Infinity) = -Infinity + * sinh(NaN) = NaN + * + * x time taken (ms) + * 10 2 ms + * 100 5 ms + * 1000 14 ms + * 10000 82 ms + * 100000 886 ms 1.4033316802130615897e+43429 + * 200000 2613 ms + * 300000 5407 ms + * 400000 8824 ms + * 500000 13026 ms 8.7080643612718084129e+217146 + * 1000000 48543 ms + * + * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x)) + * + */ + P.hyperbolicSine = P.sinh = function () { + var k, pr, rm, len, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; + Ctor.rounding = 1; + len = x.d.length; + + if (len < 3) { + x = taylorSeries(Ctor, 2, x, x, true); + } else { + + // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x)) + // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3)) + // 3 multiplications and 1 addition + + // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x))) + // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5))) + // 4 multiplications and 2 additions + + // Estimate the optimum number of times to use the argument reduction. + k = 1.4 * Math.sqrt(len); + k = k > 16 ? 16 : k | 0; + + x = x.times(1 / tinyPow(5, k)); + x = taylorSeries(Ctor, 2, x, x, true); + + // Reverse argument reduction + var sinh2_x, + d5 = new Ctor(5), + d16 = new Ctor(16), + d20 = new Ctor(20); + for (; k--;) { + sinh2_x = x.times(x); + x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20)))); + } + } + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(x, pr, rm, true); + }; + + + /* + * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * tanh(x) = sinh(x) / cosh(x) + * + * tanh(0) = 0 + * tanh(-0) = -0 + * tanh(Infinity) = 1 + * tanh(-Infinity) = -1 + * tanh(NaN) = NaN + * + */ + P.hyperbolicTangent = P.tanh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(x.s); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 7; + Ctor.rounding = 1; + + return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm); + }; + + + /* + * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of + * this Decimal. + * + * Domain: [-1, 1] + * Range: [0, pi] + * + * acos(x) = pi/2 - asin(x) + * + * acos(0) = pi/2 + * acos(-0) = pi/2 + * acos(1) = 0 + * acos(-1) = pi + * acos(1/2) = pi/3 + * acos(-1/2) = 2*pi/3 + * acos(|x| > 1) = NaN + * acos(NaN) = NaN + * + */ + P.inverseCosine = P.acos = function () { + var halfPi, + x = this, + Ctor = x.constructor, + k = x.abs().cmp(1), + pr = Ctor.precision, + rm = Ctor.rounding; + + if (k !== -1) { + return k === 0 + // |x| is 1 + ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0) + // |x| > 1 or x is NaN + : new Ctor(NaN); + } + + if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5); + + // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3 + + Ctor.precision = pr + 6; + Ctor.rounding = 1; + + x = x.asin(); + halfPi = getPi(Ctor, pr + 4, rm).times(0.5); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return halfPi.minus(x); + }; + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the + * value of this Decimal. + * + * Domain: [1, Infinity] + * Range: [0, Infinity] + * + * acosh(x) = ln(x + sqrt(x^2 - 1)) + * + * acosh(x < 1) = NaN + * acosh(NaN) = NaN + * acosh(Infinity) = Infinity + * acosh(-Infinity) = NaN + * acosh(0) = NaN + * acosh(-0) = NaN + * acosh(1) = 0 + * acosh(-1) = NaN + * + */ + P.inverseHyperbolicCosine = P.acosh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN); + if (!x.isFinite()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4; + Ctor.rounding = 1; + external = false; + + x = x.times(x).minus(1).sqrt().plus(x); + + external = true; + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.ln(); + }; + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value + * of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * asinh(x) = ln(x + sqrt(x^2 + 1)) + * + * asinh(NaN) = NaN + * asinh(Infinity) = Infinity + * asinh(-Infinity) = -Infinity + * asinh(0) = 0 + * asinh(-0) = -0 + * + */ + P.inverseHyperbolicSine = P.asinh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6; + Ctor.rounding = 1; + external = false; + + x = x.times(x).plus(1).sqrt().plus(x); + + external = true; + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.ln(); + }; + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the + * value of this Decimal. + * + * Domain: [-1, 1] + * Range: [-Infinity, Infinity] + * + * atanh(x) = 0.5 * ln((1 + x) / (1 - x)) + * + * atanh(|x| > 1) = NaN + * atanh(NaN) = NaN + * atanh(Infinity) = NaN + * atanh(-Infinity) = NaN + * atanh(0) = 0 + * atanh(-0) = -0 + * atanh(1) = Infinity + * atanh(-1) = -Infinity + * + */ + P.inverseHyperbolicTangent = P.atanh = function () { + var pr, rm, wpr, xsd, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN); + + pr = Ctor.precision; + rm = Ctor.rounding; + xsd = x.sd(); + + if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true); + + Ctor.precision = wpr = xsd - x.e; + + x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1); + + Ctor.precision = pr + 4; + Ctor.rounding = 1; + + x = x.ln(); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.times(0.5); + }; + + + /* + * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi/2, pi/2] + * + * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2))) + * + * asin(0) = 0 + * asin(-0) = -0 + * asin(1/2) = pi/6 + * asin(-1/2) = -pi/6 + * asin(1) = pi/2 + * asin(-1) = -pi/2 + * asin(|x| > 1) = NaN + * asin(NaN) = NaN + * + * TODO? Compare performance of Taylor series. + * + */ + P.inverseSine = P.asin = function () { + var halfPi, k, + pr, rm, + x = this, + Ctor = x.constructor; + + if (x.isZero()) return new Ctor(x); + + k = x.abs().cmp(1); + pr = Ctor.precision; + rm = Ctor.rounding; + + if (k !== -1) { + + // |x| is 1 + if (k === 0) { + halfPi = getPi(Ctor, pr + 4, rm).times(0.5); + halfPi.s = x.s; + return halfPi; + } + + // |x| > 1 or x is NaN + return new Ctor(NaN); + } + + // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6 + + Ctor.precision = pr + 6; + Ctor.rounding = 1; + + x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan(); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.times(2); + }; + + + /* + * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value + * of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi/2, pi/2] + * + * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... + * + * atan(0) = 0 + * atan(-0) = -0 + * atan(1) = pi/4 + * atan(-1) = -pi/4 + * atan(Infinity) = pi/2 + * atan(-Infinity) = -pi/2 + * atan(NaN) = NaN + * + */ + P.inverseTangent = P.atan = function () { + var i, j, k, n, px, t, r, wpr, x2, + x = this, + Ctor = x.constructor, + pr = Ctor.precision, + rm = Ctor.rounding; + + if (!x.isFinite()) { + if (!x.s) return new Ctor(NaN); + if (pr + 4 <= PI_PRECISION) { + r = getPi(Ctor, pr + 4, rm).times(0.5); + r.s = x.s; + return r; + } + } else if (x.isZero()) { + return new Ctor(x); + } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) { + r = getPi(Ctor, pr + 4, rm).times(0.25); + r.s = x.s; + return r; + } + + Ctor.precision = wpr = pr + 10; + Ctor.rounding = 1; + + // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x); + + // Argument reduction + // Ensure |x| < 0.42 + // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2))) + + k = Math.min(28, wpr / LOG_BASE + 2 | 0); + + for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1)); + + external = false; + + j = Math.ceil(wpr / LOG_BASE); + n = 1; + x2 = x.times(x); + r = new Ctor(x); + px = x; + + // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... + for (; i !== -1;) { + px = px.times(x2); + t = r.minus(px.div(n += 2)); + + px = px.times(x2); + r = t.plus(px.div(n += 2)); + + if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;); + } + + if (k) r = r.times(2 << (k - 1)); + + external = true; + + return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true); + }; + + + /* + * Return true if the value of this Decimal is a finite number, otherwise return false. + * + */ + P.isFinite = function () { + return !!this.d; + }; + + + /* + * Return true if the value of this Decimal is an integer, otherwise return false. + * + */ + P.isInteger = P.isInt = function () { + return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2; + }; + + + /* + * Return true if the value of this Decimal is NaN, otherwise return false. + * + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this Decimal is negative, otherwise return false. + * + */ + P.isNegative = P.isNeg = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this Decimal is positive, otherwise return false. + * + */ + P.isPositive = P.isPos = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this Decimal is 0 or -0, otherwise return false. + * + */ + P.isZero = function () { + return !!this.d && this.d[0] === 0; + }; + + + /* + * Return true if the value of this Decimal is less than `y`, otherwise return false. + * + */ + P.lessThan = P.lt = function (y) { + return this.cmp(y) < 0; + }; + + + /* + * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. + * + */ + P.lessThanOrEqualTo = P.lte = function (y) { + return this.cmp(y) < 1; + }; + + + /* + * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * If no base is specified, return log[10](arg). + * + * log[base](arg) = ln(arg) / ln(base) + * + * The result will always be correctly rounded if the base of the log is 10, and 'almost always' + * otherwise: + * + * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen + * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error + * between the result and the correctly rounded result will be one ulp (unit in the last place). + * + * log[-b](a) = NaN + * log[0](a) = NaN + * log[1](a) = NaN + * log[NaN](a) = NaN + * log[Infinity](a) = NaN + * log[b](0) = -Infinity + * log[b](-0) = -Infinity + * log[b](-a) = NaN + * log[b](1) = 0 + * log[b](Infinity) = Infinity + * log[b](NaN) = NaN + * + * [base] {number|string|Decimal} The base of the logarithm. + * + */ + P.logarithm = P.log = function (base) { + var isBase10, d, denominator, k, inf, num, sd, r, + arg = this, + Ctor = arg.constructor, + pr = Ctor.precision, + rm = Ctor.rounding, + guard = 5; + + // Default base is 10. + if (base == null) { + base = new Ctor(10); + isBase10 = true; + } else { + base = new Ctor(base); + d = base.d; + + // Return NaN if base is negative, or non-finite, or is 0 or 1. + if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN); + + isBase10 = base.eq(10); + } + + d = arg.d; + + // Is arg negative, non-finite, 0 or 1? + if (arg.s < 0 || !d || !d[0] || arg.eq(1)) { + return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0); + } + + // The result will have a non-terminating decimal expansion if base is 10 and arg is not an + // integer power of 10. + if (isBase10) { + if (d.length > 1) { + inf = true; + } else { + for (k = d[0]; k % 10 === 0;) k /= 10; + inf = k !== 1; + } + } + + external = false; + sd = pr + guard; + num = naturalLogarithm(arg, sd); + denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); + + // The result will have 5 rounding digits. + r = divide(num, denominator, sd, 1); + + // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000, + // calculate 10 further digits. + // + // If the result is known to have an infinite decimal expansion, repeat this until it is clear + // that the result is above or below the boundary. Otherwise, if after calculating the 10 + // further digits, the last 14 are nines, round up and assume the result is exact. + // Also assume the result is exact if the last 14 are zero. + // + // Example of a result that will be incorrectly rounded: + // log[1048576](4503599627370502) = 2.60000000000000009610279511444746... + // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it + // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so + // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal + // place is still 2.6. + if (checkRoundingDigits(r.d, k = pr, rm)) { + + do { + sd += 10; + num = naturalLogarithm(arg, sd); + denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); + r = divide(num, denominator, sd, 1); + + if (!inf) { + + // Check for 14 nines from the 2nd rounding digit, as the first may be 4. + if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) { + r = finalise(r, pr + 1, 0); + } + + break; + } + } while (checkRoundingDigits(r.d, k += 10, rm)); + } + + external = true; + + return finalise(r, pr, rm); + }; + + + /* + * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal. + * + * arguments {number|string|Decimal} + * + P.max = function () { + Array.prototype.push.call(arguments, this); + return maxOrMin(this.constructor, arguments, 'lt'); + }; + */ + + + /* + * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal. + * + * arguments {number|string|Decimal} + * + P.min = function () { + Array.prototype.push.call(arguments, this); + return maxOrMin(this.constructor, arguments, 'gt'); + }; + */ + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.minus = P.sub = function (y) { + var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // If either is not finite... + if (!x.d || !y.d) { + + // Return NaN if either is NaN. + if (!x.s || !y.s) y = new Ctor(NaN); + + // Return y negated if x is finite and y is ±Infinity. + else if (x.d) y.s = -y.s; + + // Return x if y is finite and x is ±Infinity. + // Return x if both are ±Infinity with different signs. + // Return NaN if both are ±Infinity with the same sign. + else y = new Ctor(y.d || x.s !== y.s ? x : NaN); + + return y; + } + + // If signs differ... + if (x.s != y.s) { + y.s = -y.s; + return x.plus(y); + } + + xd = x.d; + yd = y.d; + pr = Ctor.precision; + rm = Ctor.rounding; + + // If either is zero... + if (!xd[0] || !yd[0]) { + + // Return y negated if x is zero and y is non-zero. + if (yd[0]) y.s = -y.s; + + // Return x if y is zero and x is non-zero. + else if (xd[0]) y = new Ctor(x); + + // Return zero if both are zero. + // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity. + else return new Ctor(rm === 3 ? -0 : 0); + + return external ? finalise(y, pr, rm) : y; + } + + // x and y are finite, non-zero numbers with the same sign. + + // Calculate base 1e7 exponents. + e = mathfloor(y.e / LOG_BASE); + xe = mathfloor(x.e / LOG_BASE); + + xd = xd.slice(); + k = xe - e; + + // If base 1e7 exponents differ... + if (k) { + xLTy = k < 0; + + if (xLTy) { + d = xd; + k = -k; + len = yd.length; + } else { + d = yd; + e = xe; + len = xd.length; + } + + // Numbers with massively different exponents would result in a very high number of + // zeros needing to be prepended, but this can be avoided while still ensuring correct + // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`. + i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2; + + if (k > i) { + k = i; + d.length = 1; + } + + // Prepend zeros to equalise exponents. + d.reverse(); + for (i = k; i--;) d.push(0); + d.reverse(); + + // Base 1e7 exponents equal. + } else { + + // Check digits to determine which is the bigger number. + + i = xd.length; + len = yd.length; + xLTy = i < len; + if (xLTy) len = i; + + for (i = 0; i < len; i++) { + if (xd[i] != yd[i]) { + xLTy = xd[i] < yd[i]; + break; + } + } + + k = 0; + } + + if (xLTy) { + d = xd; + xd = yd; + yd = d; + y.s = -y.s; + } + + len = xd.length; + + // Append zeros to `xd` if shorter. + // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length. + for (i = yd.length - len; i > 0; --i) xd[len++] = 0; + + // Subtract yd from xd. + for (i = yd.length; i > k;) { + + if (xd[--i] < yd[i]) { + for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1; + --xd[j]; + xd[i] += BASE; + } + + xd[i] -= yd[i]; + } + + // Remove trailing zeros. + for (; xd[--len] === 0;) xd.pop(); + + // Remove leading zeros and adjust exponent accordingly. + for (; xd[0] === 0; xd.shift()) --e; + + // Zero? + if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0); + + y.d = xd; + y.e = getBase10Exponent(xd, e); + + return external ? finalise(y, pr, rm) : y; + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * The result depends on the modulo mode. + * + */ + P.modulo = P.mod = function (y) { + var q, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0. + if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN); + + // Return x if y is ±Infinity or x is ±0. + if (!y.d || x.d && !x.d[0]) { + return finalise(new Ctor(x), Ctor.precision, Ctor.rounding); + } + + // Prevent rounding of intermediate calculations. + external = false; + + if (Ctor.modulo == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // result = x - q * y where 0 <= result < abs(y) + q = divide(x, y.abs(), 0, 3, 1); + q.s *= y.s; + } else { + q = divide(x, y, 0, Ctor.modulo, 1); + } + + q = q.times(y); + + external = true; + + return x.minus(q); + }; + + + /* + * Return a new Decimal whose value is the natural exponential of the value of this Decimal, + * i.e. the base e raised to the power the value of this Decimal, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.naturalExponential = P.exp = function () { + return naturalExponential(this); + }; + + + /* + * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, + * rounded to `precision` significant digits using rounding mode `rounding`. + * + */ + P.naturalLogarithm = P.ln = function () { + return naturalLogarithm(this); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by + * -1. + * + */ + P.negated = P.neg = function () { + var x = new this.constructor(this); + x.s = -x.s; + return finalise(x); + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.plus = P.add = function (y) { + var carry, d, e, i, k, len, pr, rm, xd, yd, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // If either is not finite... + if (!x.d || !y.d) { + + // Return NaN if either is NaN. + if (!x.s || !y.s) y = new Ctor(NaN); + + // Return x if y is finite and x is ±Infinity. + // Return x if both are ±Infinity with the same sign. + // Return NaN if both are ±Infinity with different signs. + // Return y if x is finite and y is ±Infinity. + else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN); + + return y; + } + + // If signs differ... + if (x.s != y.s) { + y.s = -y.s; + return x.minus(y); + } + + xd = x.d; + yd = y.d; + pr = Ctor.precision; + rm = Ctor.rounding; + + // If either is zero... + if (!xd[0] || !yd[0]) { + + // Return x if y is zero. + // Return y if y is non-zero. + if (!yd[0]) y = new Ctor(x); + + return external ? finalise(y, pr, rm) : y; + } + + // x and y are finite, non-zero numbers with the same sign. + + // Calculate base 1e7 exponents. + k = mathfloor(x.e / LOG_BASE); + e = mathfloor(y.e / LOG_BASE); + + xd = xd.slice(); + i = k - e; + + // If base 1e7 exponents differ... + if (i) { + + if (i < 0) { + d = xd; + i = -i; + len = yd.length; + } else { + d = yd; + e = k; + len = xd.length; + } + + // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1. + k = Math.ceil(pr / LOG_BASE); + len = k > len ? k + 1 : len + 1; + + if (i > len) { + i = len; + d.length = 1; + } + + // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts. + d.reverse(); + for (; i--;) d.push(0); + d.reverse(); + } + + len = xd.length; + i = yd.length; + + // If yd is longer than xd, swap xd and yd so xd points to the longer array. + if (len - i < 0) { + i = len; + d = yd; + yd = xd; + xd = d; + } + + // Only start adding at yd.length - 1 as the further digits of xd can be left as they are. + for (carry = 0; i;) { + carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0; + xd[i] %= BASE; + } + + if (carry) { + xd.unshift(carry); + ++e; + } + + // Remove trailing zeros. + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + for (len = xd.length; xd[--len] == 0;) xd.pop(); + + y.d = xd; + y.e = getBase10Exponent(xd, e); + + return external ? finalise(y, pr, rm) : y; + }; + + + /* + * Return the number of significant digits of the value of this Decimal. + * + * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. + * + */ + P.precision = P.sd = function (z) { + var k, + x = this; + + if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z); + + if (x.d) { + k = getPrecision(x.d); + if (z && x.e + 1 > k) k = x.e + 1; + } else { + k = NaN; + } + + return k; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using + * rounding mode `rounding`. + * + */ + P.round = function () { + var x = this, + Ctor = x.constructor; + + return finalise(new Ctor(x), x.e + 1, Ctor.rounding); + }; + + + /* + * Return a new Decimal whose value is the sine of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * sin(x) = x - x^3/3! + x^5/5! - ... + * + * sin(0) = 0 + * sin(-0) = -0 + * sin(Infinity) = NaN + * sin(-Infinity) = NaN + * sin(NaN) = NaN + * + */ + P.sine = P.sin = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; + Ctor.rounding = 1; + + x = sine(Ctor, toLessThanHalfPi(Ctor, x)); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true); + }; + + + /* + * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + */ + P.squareRoot = P.sqrt = function () { + var m, n, sd, r, rep, t, + x = this, + d = x.d, + e = x.e, + s = x.s, + Ctor = x.constructor; + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !d || !d[0]) { + return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0); + } + + external = false; + + // Initial estimate. + s = Math.sqrt(+x); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = digitsToString(d); + + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(n); + e = mathfloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '1e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new Ctor(n); + } else { + r = new Ctor(s.toString()); + } + + sd = (e = Ctor.precision) + 3; + + // Newton-Raphson iteration. + for (;;) { + t = r; + r = t.plus(divide(x, t, sd + 2, 1)).times(0.5); + + // TODO? Replace with for-loop and checkRoundingDigits. + if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { + n = n.slice(sd - 3, sd + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or + // 4999, i.e. approaching a rounding boundary, continue the iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the exact result as the + // nines may infinitely repeat. + if (!rep) { + finalise(t, e + 1, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + sd += 4; + rep = 1; + } else { + + // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. + // If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + finalise(r, e + 1, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + + external = true; + + return finalise(r, e, Ctor.rounding, m); + }; + + + /* + * Return a new Decimal whose value is the tangent of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * tan(0) = 0 + * tan(-0) = -0 + * tan(Infinity) = NaN + * tan(-Infinity) = NaN + * tan(NaN) = NaN + * + */ + P.tangent = P.tan = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 10; + Ctor.rounding = 1; + + x = x.sin(); + x.s = 1; + x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true); + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + */ + P.times = P.mul = function (y) { + var carry, e, i, k, r, rL, t, xdL, ydL, + x = this, + Ctor = x.constructor, + xd = x.d, + yd = (y = new Ctor(y)).d; + + y.s *= x.s; + + // If either is NaN, ±Infinity or ±0... + if (!xd || !xd[0] || !yd || !yd[0]) { + + return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd + + // Return NaN if either is NaN. + // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity. + ? NaN + + // Return ±Infinity if either is ±Infinity. + // Return ±0 if either is ±0. + : !xd || !yd ? y.s / 0 : y.s * 0); + } + + e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE); + xdL = xd.length; + ydL = yd.length; + + // Ensure xd points to the longer array. + if (xdL < ydL) { + r = xd; + xd = yd; + yd = r; + rL = xdL; + xdL = ydL; + ydL = rL; + } + + // Initialise the result array with zeros. + r = []; + rL = xdL + ydL; + for (i = rL; i--;) r.push(0); + + // Multiply! + for (i = ydL; --i >= 0;) { + carry = 0; + for (k = xdL + i; k > i;) { + t = r[k] + yd[i] * xd[k - i - 1] + carry; + r[k--] = t % BASE | 0; + carry = t / BASE | 0; + } + + r[k] = (r[k] + carry) % BASE | 0; + } + + // Remove trailing zeros. + for (; !r[--rL];) r.pop(); + + if (carry) ++e; + else r.shift(); + + y.d = r; + y.e = getBase10Exponent(r, e); + + return external ? finalise(y, Ctor.precision, Ctor.rounding) : y; + }; + + + /* + * Return a string representing the value of this Decimal in base 2, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toBinary = function (sd, rm) { + return toStringBinary(this, 2, sd, rm); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` + * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. + * + * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toDecimalPlaces = P.toDP = function (dp, rm) { + var x = this, + Ctor = x.constructor; + + x = new Ctor(x); + if (dp === void 0) return x; + + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + return finalise(x, dp + x.e + 1, rm); + }; + + + /* + * Return a string representing the value of this Decimal in exponential notation rounded to + * `dp` fixed decimal places using rounding mode `rounding`. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toExponential = function (dp, rm) { + var str, + x = this, + Ctor = x.constructor; + + if (dp === void 0) { + str = finiteToString(x, true); + } else { + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + x = finalise(new Ctor(x), dp + 1, rm); + str = finiteToString(x, true, dp + 1); + } + + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a string representing the value of this Decimal in normal (fixed-point) notation to + * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is + * omitted. + * + * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. + * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. + * (-0).toFixed(3) is '0.000'. + * (-0.5).toFixed(0) is '-0'. + * + */ + P.toFixed = function (dp, rm) { + var str, y, + x = this, + Ctor = x.constructor; + + if (dp === void 0) { + str = finiteToString(x); + } else { + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + y = finalise(new Ctor(x), dp + x.e + 1, rm); + str = finiteToString(y, false, dp + y.e + 1); + } + + // To determine whether to add the minus sign look at the value before it was rounded, + // i.e. look at `x` rather than `y`. + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return an array representing the value of this Decimal as a simple fraction with an integer + * numerator and an integer denominator. + * + * The denominator will be a positive non-zero value less than or equal to the specified maximum + * denominator. If a maximum denominator is not specified, the denominator will be the lowest + * value necessary to represent the number exactly. + * + * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity. + * + */ + P.toFraction = function (maxD) { + var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r, + x = this, + xd = x.d, + Ctor = x.constructor; + + if (!xd) return new Ctor(x); + + n1 = d0 = new Ctor(1); + d1 = n0 = new Ctor(0); + + d = new Ctor(d1); + e = d.e = getPrecision(xd) - x.e - 1; + k = e % LOG_BASE; + d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k); + + if (maxD == null) { + + // d is 10**e, the minimum max-denominator needed. + maxD = e > 0 ? d : n1; + } else { + n = new Ctor(maxD); + if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n); + maxD = n.gt(d) ? (e > 0 ? d : n1) : n; + } + + external = false; + n = new Ctor(digitsToString(xd)); + pr = Ctor.precision; + Ctor.precision = e = xd.length * LOG_BASE * 2; + + for (;;) { + q = divide(n, d, 0, 1, 1); + d2 = d0.plus(q.times(d1)); + if (d2.cmp(maxD) == 1) break; + d0 = d1; + d1 = d2; + d2 = n1; + n1 = n0.plus(q.times(d2)); + n0 = d2; + d2 = d; + d = n.minus(q.times(d2)); + n = d2; + } + + d2 = divide(maxD.minus(d0), d1, 0, 1, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + + // Determine which fraction is closer to x, n0/d0 or n1/d1? + r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1 + ? [n1, d1] : [n0, d0]; + + Ctor.precision = pr; + external = true; + + return r; + }; + + + /* + * Return a string representing the value of this Decimal in base 16, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toHexadecimal = P.toHex = function (sd, rm) { + return toStringBinary(this, 16, sd, rm); + }; + + + /* + * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding + * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal. + * + * The return value will always have the same sign as this Decimal, unless either this Decimal + * or `y` is NaN, in which case the return value will be also be NaN. + * + * The return value is not affected by the value of `precision`. + * + * y {number|string|Decimal} The magnitude to round to a multiple of. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toNearest() rounding mode not an integer: {rm}' + * 'toNearest() rounding mode out of range: {rm}' + * + */ + P.toNearest = function (y, rm) { + var x = this, + Ctor = x.constructor; + + x = new Ctor(x); + + if (y == null) { + + // If x is not finite, return x. + if (!x.d) return x; + + y = new Ctor(1); + rm = Ctor.rounding; + } else { + y = new Ctor(y); + if (rm === void 0) { + rm = Ctor.rounding; + } else { + checkInt32(rm, 0, 8); + } + + // If x is not finite, return x if y is not NaN, else NaN. + if (!x.d) return y.s ? x : y; + + // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN. + if (!y.d) { + if (y.s) y.s = x.s; + return y; + } + } + + // If y is not zero, calculate the nearest multiple of y to x. + if (y.d[0]) { + external = false; + x = divide(x, y, 0, rm, 1).times(y); + external = true; + finalise(x); + + // If y is zero, return zero with the sign of x. + } else { + y.s = x.s; + x = y; + } + + return x; + }; + + + /* + * Return the value of this Decimal converted to a number primitive. + * Zero keeps its sign. + * + */ + P.toNumber = function () { + return +this; + }; + + + /* + * Return a string representing the value of this Decimal in base 8, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toOctal = function (sd, rm) { + return toStringBinary(this, 8, sd, rm); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded + * to `precision` significant digits using rounding mode `rounding`. + * + * ECMAScript compliant. + * + * pow(x, NaN) = NaN + * pow(x, ±0) = 1 + + * pow(NaN, non-zero) = NaN + * pow(abs(x) > 1, +Infinity) = +Infinity + * pow(abs(x) > 1, -Infinity) = +0 + * pow(abs(x) == 1, ±Infinity) = NaN + * pow(abs(x) < 1, +Infinity) = +0 + * pow(abs(x) < 1, -Infinity) = +Infinity + * pow(+Infinity, y > 0) = +Infinity + * pow(+Infinity, y < 0) = +0 + * pow(-Infinity, odd integer > 0) = -Infinity + * pow(-Infinity, even integer > 0) = +Infinity + * pow(-Infinity, odd integer < 0) = -0 + * pow(-Infinity, even integer < 0) = +0 + * pow(+0, y > 0) = +0 + * pow(+0, y < 0) = +Infinity + * pow(-0, odd integer > 0) = -0 + * pow(-0, even integer > 0) = +0 + * pow(-0, odd integer < 0) = -Infinity + * pow(-0, even integer < 0) = +Infinity + * pow(finite x < 0, finite non-integer) = NaN + * + * For non-integer or very large exponents pow(x, y) is calculated using + * + * x^y = exp(y*ln(x)) + * + * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the + * probability of an incorrectly rounded result + * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14 + * i.e. 1 in 250,000,000,000,000 + * + * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place). + * + * y {number|string|Decimal} The power to which to raise this Decimal. + * + */ + P.toPower = P.pow = function (y) { + var e, k, pr, r, rm, s, + x = this, + Ctor = x.constructor, + yn = +(y = new Ctor(y)); + + // Either ±Infinity, NaN or ±0? + if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn)); + + x = new Ctor(x); + + if (x.eq(1)) return x; + + pr = Ctor.precision; + rm = Ctor.rounding; + + if (y.eq(1)) return finalise(x, pr, rm); + + // y exponent + e = mathfloor(y.e / LOG_BASE); + + // If y is a small integer use the 'exponentiation by squaring' algorithm. + if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) { + r = intPow(Ctor, x, k, pr); + return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm); + } + + s = x.s; + + // if x is negative + if (s < 0) { + + // if y is not an integer + if (e < y.d.length - 1) return new Ctor(NaN); + + // Result is positive if x is negative and the last digit of integer y is even. + if ((y.d[e] & 1) == 0) s = 1; + + // if x.eq(-1) + if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) { + x.s = s; + return x; + } + } + + // Estimate result exponent. + // x^y = 10^e, where e = y * log10(x) + // log10(x) = log10(x_significand) + x_exponent + // log10(x_significand) = ln(x_significand) / ln(10) + k = mathpow(+x, yn); + e = k == 0 || !isFinite(k) + ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1)) + : new Ctor(k + '').e; + + // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1. + + // Overflow/underflow? + if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0); + + external = false; + Ctor.rounding = x.s = 1; + + // Estimate the extra guard digits needed to ensure five correct rounding digits from + // naturalLogarithm(x). Example of failure without these extra digits (precision: 10): + // new Decimal(2.32456).pow('2087987436534566.46411') + // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815 + k = Math.min(12, (e + '').length); + + // r = x^y = exp(y*ln(x)) + r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr); + + // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40) + if (r.d) { + + // Truncate to the required precision plus five rounding digits. + r = finalise(r, pr + 5, 1); + + // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate + // the result. + if (checkRoundingDigits(r.d, pr, rm)) { + e = pr + 10; + + // Truncate to the increased precision plus five rounding digits. + r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1); + + // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9). + if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) { + r = finalise(r, pr + 1, 0); + } + } + } + + r.s = s; + external = true; + Ctor.rounding = rm; + + return finalise(r, pr, rm); + }; + + + /* + * Return a string representing the value of this Decimal rounded to `sd` significant digits + * using rounding mode `rounding`. + * + * Return exponential notation if `sd` is less than the number of digits necessary to represent + * the integer part of the value in normal notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toPrecision = function (sd, rm) { + var str, + x = this, + Ctor = x.constructor; + + if (sd === void 0) { + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + } else { + checkInt32(sd, 1, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + x = finalise(new Ctor(x), sd, rm); + str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd); + } + + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` + * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if + * omitted. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toSD() digits out of range: {sd}' + * 'toSD() digits not an integer: {sd}' + * 'toSD() rounding mode not an integer: {rm}' + * 'toSD() rounding mode out of range: {rm}' + * + */ + P.toSignificantDigits = P.toSD = function (sd, rm) { + var x = this, + Ctor = x.constructor; + + if (sd === void 0) { + sd = Ctor.precision; + rm = Ctor.rounding; + } else { + checkInt32(sd, 1, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + } + + return finalise(new Ctor(x), sd, rm); + }; + + + /* + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + P.toString = function () { + var x = this, + Ctor = x.constructor, + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal truncated to a whole number. + * + */ + P.truncated = P.trunc = function () { + return finalise(new this.constructor(this), this.e + 1, 1); + }; + + + /* + * Return a string representing the value of this Decimal. + * Unlike `toString`, negative zero will include the minus sign. + * + */ + P.valueOf = P.toJSON = function () { + var x = this, + Ctor = x.constructor, + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + + return x.isNeg() ? '-' + str : str; + }; + + + /* + // Add aliases to match BigDecimal method names. + // P.add = P.plus; + P.subtract = P.minus; + P.multiply = P.times; + P.divide = P.div; + P.remainder = P.mod; + P.compareTo = P.cmp; + P.negate = P.neg; + */ + + + // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers. + + + /* + * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower, + * finiteToString, naturalExponential, naturalLogarithm + * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest, + * P.toPrecision, P.toSignificantDigits, toStringBinary, random + * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm + * convertBase toStringBinary, parseOther + * cos P.cos + * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy, + * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction, + * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm, + * taylorSeries, atan2, parseOther + * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh, + * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus, + * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot, + * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed, + * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits, + * P.truncated, divide, getLn10, getPi, naturalExponential, + * naturalLogarithm, ceil, floor, round, trunc + * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf, + * toStringBinary + * getBase10Exponent P.minus, P.plus, P.times, parseOther + * getLn10 P.logarithm, naturalLogarithm + * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2 + * getPrecision P.precision, P.toFraction + * getZeroString digitsToString, finiteToString + * intPow P.toPower, parseOther + * isOdd toLessThanHalfPi + * maxOrMin max, min + * naturalExponential P.naturalExponential, P.toPower + * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm, + * P.toPower, naturalExponential + * nonFiniteToString finiteToString, toStringBinary + * parseDecimal Decimal + * parseOther Decimal + * sin P.sin + * taylorSeries P.cosh, P.sinh, cos, sin + * toLessThanHalfPi P.cos, P.sin + * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal + * truncate intPow + * + * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi, + * naturalLogarithm, config, parseOther, random, Decimal + */ + + + function digitsToString(d) { + var i, k, ws, + indexOfLastWord = d.length - 1, + str = '', + w = d[0]; + + if (indexOfLastWord > 0) { + str += w; + for (i = 1; i < indexOfLastWord; i++) { + ws = d[i] + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + str += ws; + } + + w = d[i]; + ws = w + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + } else if (w === 0) { + return '0'; + } + + // Remove trailing zeros of last w. + for (; w % 10 === 0;) w /= 10; + + return str + w; + } + + + function checkInt32(i, min, max) { + if (i !== ~~i || i < min || i > max) { + throw Error(invalidArgument + i); + } + } + + + /* + * Check 5 rounding digits if `repeating` is null, 4 otherwise. + * `repeating == null` if caller is `log` or `pow`, + * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`. + */ + function checkRoundingDigits(d, i, rm, repeating) { + var di, k, r, rd; + + // Get the length of the first word of the array d. + for (k = d[0]; k >= 10; k /= 10) --i; + + // Is the rounding digit in the first word of d? + if (--i < 0) { + i += LOG_BASE; + di = 0; + } else { + di = Math.ceil((i + 1) / LOG_BASE); + i %= LOG_BASE; + } + + // i is the index (0 - 6) of the rounding digit. + // E.g. if within the word 3487563 the first rounding digit is 5, + // then i = 4, k = 1000, rd = 3487563 % 1000 = 563 + k = mathpow(10, LOG_BASE - i); + rd = d[di] % k | 0; + + if (repeating == null) { + if (i < 3) { + if (i == 0) rd = rd / 100 | 0; + else if (i == 1) rd = rd / 10 | 0; + r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0; + } else { + r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) && + (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 || + (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0; + } + } else { + if (i < 4) { + if (i == 0) rd = rd / 1000 | 0; + else if (i == 1) rd = rd / 100 | 0; + else if (i == 2) rd = rd / 10 | 0; + r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999; + } else { + r = ((repeating || rm < 4) && rd + 1 == k || + (!repeating && rm > 3) && rd + 1 == k / 2) && + (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1; + } + } + + return r; + } + + + // Convert string of `baseIn` to an array of numbers of `baseOut`. + // Eg. convertBase('255', 10, 16) returns [15, 15]. + // Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. + function convertBase(str, baseIn, baseOut) { + var j, + arr = [0], + arrL, + i = 0, + strL = str.length; + + for (; i < strL;) { + for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn; + arr[0] += NUMERALS.indexOf(str.charAt(i++)); + for (j = 0; j < arr.length; j++) { + if (arr[j] > baseOut - 1) { + if (arr[j + 1] === void 0) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + + /* + * cos(x) = 1 - x^2/2! + x^4/4! - ... + * |x| < pi/2 + * + */ + function cosine(Ctor, x) { + var k, y, + len = x.d.length; + + // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1 + // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1 + + // Estimate the optimum number of times to use the argument reduction. + if (len < 32) { + k = Math.ceil(len / 3); + y = (1 / tinyPow(4, k)).toString(); + } else { + k = 16; + y = '2.3283064365386962890625e-10'; + } + + Ctor.precision += k; + + x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1)); + + // Reverse argument reduction + for (var i = k; i--;) { + var cos2x = x.times(x); + x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1); + } + + Ctor.precision -= k; + + return x; + } + + + /* + * Perform division in the specified base. + */ + var divide = (function () { + + // Assumes non-zero x and k, and hence non-zero result. + function multiplyInteger(x, k, base) { + var temp, + carry = 0, + i = x.length; + + for (x = x.slice(); i--;) { + temp = x[i] * k + carry; + x[i] = temp % base | 0; + carry = temp / base | 0; + } + + if (carry) x.unshift(carry); + + return x; + } + + function compare(a, b, aL, bL) { + var i, r; + + if (aL != bL) { + r = aL > bL ? 1 : -1; + } else { + for (i = r = 0; i < aL; i++) { + if (a[i] != b[i]) { + r = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return r; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1;) a.shift(); + } + + return function (x, y, pr, rm, dp, base) { + var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, + yL, yz, + Ctor = x.constructor, + sign = x.s == y.s ? 1 : -1, + xd = x.d, + yd = y.d; + + // Either NaN, Infinity or 0? + if (!xd || !xd[0] || !yd || !yd[0]) { + + return new Ctor(// Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN : + + // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0. + xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0); + } + + if (base) { + logBase = 1; + e = x.e - y.e; + } else { + base = BASE; + logBase = LOG_BASE; + e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase); + } + + yL = yd.length; + xL = xd.length; + q = new Ctor(sign); + qd = q.d = []; + + // Result exponent may be one less than e. + // The digit array of a Decimal from toStringBinary may have trailing zeros. + for (i = 0; yd[i] == (xd[i] || 0); i++); + + if (yd[i] > (xd[i] || 0)) e--; + + if (pr == null) { + sd = pr = Ctor.precision; + rm = Ctor.rounding; + } else if (dp) { + sd = pr + (x.e - y.e) + 1; + } else { + sd = pr; + } + + if (sd < 0) { + qd.push(1); + more = true; + } else { + + // Convert precision in number of base 10 digits to base 1e7 digits. + sd = sd / logBase + 2 | 0; + i = 0; + + // divisor < 1e7 + if (yL == 1) { + k = 0; + yd = yd[0]; + sd++; + + // k is the carry. + for (; (i < xL || k) && sd--; i++) { + t = k * base + (xd[i] || 0); + qd[i] = t / yd | 0; + k = t % yd | 0; + } + + more = k || i < xL; + + // divisor >= 1e7 + } else { + + // Normalise xd and yd so highest order digit of yd is >= base/2 + k = base / (yd[0] + 1) | 0; + + if (k > 1) { + yd = multiplyInteger(yd, k, base); + xd = multiplyInteger(xd, k, base); + yL = yd.length; + xL = xd.length; + } + + xi = yL; + rem = xd.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL;) rem[remL++] = 0; + + yz = yd.slice(); + yz.unshift(0); + yd0 = yd[0]; + + if (yd[1] >= base / 2) ++yd0; + + do { + k = 0; + + // Compare divisor and remainder. + cmp = compare(yd, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, k. + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // k will be how many times the divisor goes into the current remainder. + k = rem0 / yd0 | 0; + + // Algorithm: + // 1. product = divisor * trial digit (k) + // 2. if product > remainder: product -= divisor, k-- + // 3. remainder -= product + // 4. if product was < remainder at 2: + // 5. compare new remainder and divisor + // 6. If remainder > divisor: remainder -= divisor, k++ + + if (k > 1) { + if (k >= base) k = base - 1; + + // product = divisor * trial digit. + prod = multiplyInteger(yd, k, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + cmp = compare(prod, rem, prodL, remL); + + // product > remainder. + if (cmp == 1) { + k--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yd, prodL, base); + } + } else { + + // cmp is -1. + // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1 + // to avoid it. If k is 1 there is a need to compare yd and rem again below. + if (k == 0) cmp = k = 1; + prod = yd.slice(); + } + + prodL = prod.length; + if (prodL < remL) prod.unshift(0); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + + // If product was < previous remainder. + if (cmp == -1) { + remL = rem.length; + + // Compare divisor and new remainder. + cmp = compare(yd, rem, yL, remL); + + // If divisor < new remainder, subtract divisor from remainder. + if (cmp < 1) { + k++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yd, remL, base); + } + } + + remL = rem.length; + } else if (cmp === 0) { + k++; + rem = [0]; + } // if cmp === 1, k will be 0 + + // Add the next digit, k, to the result array. + qd[i++] = k; + + // Update the remainder. + if (cmp && rem[0]) { + rem[remL++] = xd[xi] || 0; + } else { + rem = [xd[xi]]; + remL = 1; + } + + } while ((xi++ < xL || rem[0] !== void 0) && sd--); + + more = rem[0] !== void 0; + } + + // Leading zero? + if (!qd[0]) qd.shift(); + } + + // logBase is 1 when divide is being used for base conversion. + if (logBase == 1) { + q.e = e; + inexact = more; + } else { + + // To calculate q.e, first get the number of digits of qd[0]. + for (i = 1, k = qd[0]; k >= 10; k /= 10) i++; + q.e = i + e * logBase - 1; + + finalise(q, dp ? pr + q.e + 1 : pr, rm, more); + } + + return q; + }; + })(); + + + /* + * Round `x` to `sd` significant digits using rounding mode `rm`. + * Check for over/under-flow. + */ + function finalise(x, sd, rm, isTruncated) { + var digits, i, j, k, rd, roundUp, w, xd, xdi, + Ctor = x.constructor; + + // Don't round if sd is null or undefined. + out: if (sd != null) { + xd = x.d; + + // Infinity/NaN. + if (!xd) return x; + + // rd: the rounding digit, i.e. the digit after the digit that may be rounded up. + // w: the word of xd containing rd, a base 1e7 number. + // xdi: the index of w within xd. + // digits: the number of digits of w. + // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if + // they had leading zeros) + // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero). + + // Get the length of the first word of the digits array xd. + for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++; + i = sd - digits; + + // Is the rounding digit in the first word of xd? + if (i < 0) { + i += LOG_BASE; + j = sd; + w = xd[xdi = 0]; + + // Get the rounding digit at index j of w. + rd = w / mathpow(10, digits - j - 1) % 10 | 0; + } else { + xdi = Math.ceil((i + 1) / LOG_BASE); + k = xd.length; + if (xdi >= k) { + if (isTruncated) { + + // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`. + for (; k++ <= xdi;) xd.push(0); + w = rd = 0; + digits = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + w = k = xd[xdi]; + + // Get the number of digits of w. + for (digits = 1; k >= 10; k /= 10) digits++; + + // Get the index of rd within w. + i %= LOG_BASE; + + // Get the index of rd within w, adjusted for leading zeros. + // The number of leading zeros of w is given by LOG_BASE - digits. + j = i - LOG_BASE + digits; + + // Get the rounding digit at index j of w. + rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0; + } + } + + // Are there any non-zero digits after the rounding digit? + isTruncated = isTruncated || sd < 0 || + xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1)); + + // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right + // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression + // will give 714. + + roundUp = rm < 4 + ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xd[0]) { + xd.length = 0; + if (roundUp) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE); + x.e = -sd || 0; + } else { + + // Zero. + xd[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xd.length = xdi; + k = 1; + xdi--; + } else { + xd.length = xdi + 1; + k = mathpow(10, LOG_BASE - i); + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of w. + xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0; + } + + if (roundUp) { + for (;;) { + + // Is the digit to be rounded up in the first word of xd? + if (xdi == 0) { + + // i will be the length of xd[0] before k is added. + for (i = 1, j = xd[0]; j >= 10; j /= 10) i++; + j = xd[0] += k; + for (k = 1; j >= 10; j /= 10) k++; + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xd[0] == BASE) xd[0] = 1; + } + + break; + } else { + xd[xdi] += k; + if (xd[xdi] != BASE) break; + xd[xdi--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xd.length; xd[--i] === 0;) xd.pop(); + } + + if (external) { + + // Overflow? + if (x.e > Ctor.maxE) { + + // Infinity. + x.d = null; + x.e = NaN; + + // Underflow? + } else if (x.e < Ctor.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + // Ctor.underflow = true; + } // else Ctor.underflow = false; + } + + return x; + } + + + function finiteToString(x, isExp, sd) { + if (!x.isFinite()) return nonFiniteToString(x); + var k, + e = x.e, + str = digitsToString(x.d), + len = str.length; + + if (isExp) { + if (sd && (k = sd - len) > 0) { + str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k); + } else if (len > 1) { + str = str.charAt(0) + '.' + str.slice(1); + } + + str = str + (x.e < 0 ? 'e' : 'e+') + x.e; + } else if (e < 0) { + str = '0.' + getZeroString(-e - 1) + str; + if (sd && (k = sd - len) > 0) str += getZeroString(k); + } else if (e >= len) { + str += getZeroString(e + 1 - len); + if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k); + } else { + if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k); + if (sd && (k = sd - len) > 0) { + if (e + 1 === len) str += '.'; + str += getZeroString(k); + } + } + + return str; + } + + + // Calculate the base 10 exponent from the base 1e7 exponent. + function getBase10Exponent(digits, e) { + var w = digits[0]; + + // Add the number of digits of the first word of the digits array. + for ( e *= LOG_BASE; w >= 10; w /= 10) e++; + return e; + } + + + function getLn10(Ctor, sd, pr) { + if (sd > LN10_PRECISION) { + + // Reset global state in case the exception is caught. + external = true; + if (pr) Ctor.precision = pr; + throw Error(precisionLimitExceeded); + } + return finalise(new Ctor(LN10), sd, 1, true); + } + + + function getPi(Ctor, sd, rm) { + if (sd > PI_PRECISION) throw Error(precisionLimitExceeded); + return finalise(new Ctor(PI), sd, rm, true); + } + + + function getPrecision(digits) { + var w = digits.length - 1, + len = w * LOG_BASE + 1; + + w = digits[w]; + + // If non-zero... + if (w) { + + // Subtract the number of trailing zeros of the last word. + for (; w % 10 == 0; w /= 10) len--; + + // Add the number of digits of the first word. + for (w = digits[0]; w >= 10; w /= 10) len++; + } + + return len; + } + + + function getZeroString(k) { + var zs = ''; + for (; k--;) zs += '0'; + return zs; + } + + + /* + * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an + * integer of type number. + * + * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`. + * + */ + function intPow(Ctor, x, n, pr) { + var isTruncated, + r = new Ctor(1), + + // Max n of 9007199254740991 takes 53 loop iterations. + // Maximum digits array length; leaves [28, 34] guard digits. + k = Math.ceil(pr / LOG_BASE + 4); + + external = false; + + for (;;) { + if (n % 2) { + r = r.times(x); + if (truncate(r.d, k)) isTruncated = true; + } + + n = mathfloor(n / 2); + if (n === 0) { + + // To ensure correct rounding when r.d is truncated, increment the last word if it is zero. + n = r.d.length - 1; + if (isTruncated && r.d[n] === 0) ++r.d[n]; + break; + } + + x = x.times(x); + truncate(x.d, k); + } + + external = true; + + return r; + } + + + function isOdd(n) { + return n.d[n.d.length - 1] & 1; + } + + + /* + * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'. + */ + function maxOrMin(Ctor, args, ltgt) { + var y, + x = new Ctor(args[0]), + i = 0; + + for (; ++i < args.length;) { + y = new Ctor(args[i]); + if (!y.s) { + x = y; + break; + } else if (x[ltgt](y)) { + x = y; + } + } + + return x; + } + + + /* + * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant + * digits. + * + * Taylor/Maclaurin series. + * + * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ... + * + * Argument reduction: + * Repeat x = x / 32, k += 5, until |x| < 0.1 + * exp(x) = exp(x / 2^k)^(2^k) + * + * Previously, the argument was initially reduced by + * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10) + * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was + * found to be slower than just dividing repeatedly by 32 as above. + * + * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000 + * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000 + * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324) + * + * exp(Infinity) = Infinity + * exp(-Infinity) = 0 + * exp(NaN) = NaN + * exp(±0) = 1 + * + * exp(x) is non-terminating for any finite, non-zero x. + * + * The result will always be correctly rounded. + * + */ + function naturalExponential(x, sd) { + var denominator, guard, j, pow, sum, t, wpr, + rep = 0, + i = 0, + k = 0, + Ctor = x.constructor, + rm = Ctor.rounding, + pr = Ctor.precision; + + // 0/NaN/Infinity? + if (!x.d || !x.d[0] || x.e > 17) { + + return new Ctor(x.d + ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0 + : x.s ? x.s < 0 ? 0 : x : 0 / 0); + } + + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } + + t = new Ctor(0.03125); + + // while abs(x) >= 0.1 + while (x.e > -2) { + + // x = x / 2^5 + x = x.times(t); + k += 5; + } + + // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision + // necessary to ensure the first 4 rounding digits are correct. + guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0; + wpr += guard; + denominator = pow = sum = new Ctor(1); + Ctor.precision = wpr; + + for (;;) { + pow = finalise(pow.times(x), wpr, 1); + denominator = denominator.times(++i); + t = sum.plus(divide(pow, denominator, wpr, 1)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + j = k; + while (j--) sum = finalise(sum.times(sum), wpr, 1); + + // Check to see if the first 4 rounding digits are [49]999. + // If so, repeat the summation with a higher precision, otherwise + // e.g. with precision: 18, rounding: 1 + // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123) + // `wpr - guard` is the index of first rounding digit. + if (sd == null) { + + if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { + Ctor.precision = wpr += 10; + denominator = pow = t = new Ctor(1); + i = 0; + rep++; + } else { + return finalise(sum, Ctor.precision = pr, rm, external = true); + } + } else { + Ctor.precision = pr; + return sum; + } + } + + sum = t; + } + } + + + /* + * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant + * digits. + * + * ln(-n) = NaN + * ln(0) = -Infinity + * ln(-0) = -Infinity + * ln(1) = 0 + * ln(Infinity) = Infinity + * ln(-Infinity) = NaN + * ln(NaN) = NaN + * + * ln(n) (n != 1) is non-terminating. + * + */ + function naturalLogarithm(y, sd) { + var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2, + n = 1, + guard = 10, + x = y, + xd = x.d, + Ctor = x.constructor, + rm = Ctor.rounding, + pr = Ctor.precision; + + // Is x negative or Infinity, NaN, 0 or 1? + if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) { + return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x); + } + + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } + + Ctor.precision = wpr += guard; + c = digitsToString(xd); + c0 = c.charAt(0); + + if (Math.abs(e = x.e) < 1.5e15) { + + // Argument reduction. + // The series converges faster the closer the argument is to 1, so using + // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b + // multiply the argument by itself until the leading digits of the significand are 7, 8, 9, + // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can + // later be divided by this number, then separate out the power of 10 using + // ln(a*10^b) = ln(a) + b*ln(10). + + // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14). + //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) { + // max n is 6 (gives 0.7 - 1.3) + while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) { + x = x.times(y); + c = digitsToString(x.d); + c0 = c.charAt(0); + n++; + } + + e = x.e; + + if (c0 > 1) { + x = new Ctor('0.' + c); + e++; + } else { + x = new Ctor(c0 + '.' + c.slice(1)); + } + } else { + + // The argument reduction method above may result in overflow if the argument y is a massive + // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this + // function using ln(x*10^e) = ln(x) + e*ln(10). + t = getLn10(Ctor, wpr + 2, pr).times(e + ''); + x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t); + Ctor.precision = pr; + + return sd == null ? finalise(x, pr, rm, external = true) : x; + } + + // x1 is x reduced to a value near 1. + x1 = x; + + // Taylor series. + // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...) + // where x = (y - 1)/(y + 1) (|x| < 1) + sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1); + x2 = finalise(x.times(x), wpr, 1); + denominator = 3; + + for (;;) { + numerator = finalise(numerator.times(x2), wpr, 1); + t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + sum = sum.times(2); + + // Reverse the argument reduction. Check that e is not 0 because, besides preventing an + // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0. + if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + '')); + sum = divide(sum, new Ctor(n), wpr, 1); + + // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has + // been repeated previously) and the first 4 rounding digits 9999? + // If so, restart the summation with a higher precision, otherwise + // e.g. with precision: 12, rounding: 1 + // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463. + // `wpr - guard` is the index of first rounding digit. + if (sd == null) { + if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { + Ctor.precision = wpr += guard; + t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1); + x2 = finalise(x.times(x), wpr, 1); + denominator = rep = 1; + } else { + return finalise(sum, Ctor.precision = pr, rm, external = true); + } + } else { + Ctor.precision = pr; + return sum; + } + } + + sum = t; + denominator += 2; + } + } + + + // ±Infinity, NaN. + function nonFiniteToString(x) { + // Unsigned. + return String(x.s * x.s / 0); + } + + + /* + * Parse the value of a new Decimal `x` from string `str`. + */ + function parseDecimal(x, str) { + var e, i, len; + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(len - 1) === 48; --len); + str = str.slice(i, len); + + if (str) { + len -= i; + x.e = e = e - i - 1; + x.d = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first word of the digits array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; + + if (i < len) { + if (i) x.d.push(+str.slice(0, i)); + for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE)); + str = str.slice(i); + i = LOG_BASE - str.length; + } else { + i -= len; + } + + for (; i--;) str += '0'; + x.d.push(+str); + + if (external) { + + // Overflow? + if (x.e > x.constructor.maxE) { + + // Infinity. + x.d = null; + x.e = NaN; + + // Underflow? + } else if (x.e < x.constructor.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + // x.constructor.underflow = true; + } // else x.constructor.underflow = false; + } + } else { + + // Zero. + x.e = 0; + x.d = [0]; + } + + return x; + } + + + /* + * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value. + */ + function parseOther(x, str) { + var base, Ctor, divisor, i, isFloat, len, p, xd, xe; + + if (str === 'Infinity' || str === 'NaN') { + if (!+str) x.s = NaN; + x.e = NaN; + x.d = null; + return x; + } + + if (isHex.test(str)) { + base = 16; + str = str.toLowerCase(); + } else if (isBinary.test(str)) { + base = 2; + } else if (isOctal.test(str)) { + base = 8; + } else { + throw Error(invalidArgument + str); + } + + // Is there a binary exponent part? + i = str.search(/p/i); + + if (i > 0) { + p = +str.slice(i + 1); + str = str.substring(2, i); + } else { + str = str.slice(2); + } + + // Convert `str` as an integer then divide the result by `base` raised to a power such that the + // fraction part will be restored. + i = str.indexOf('.'); + isFloat = i >= 0; + Ctor = x.constructor; + + if (isFloat) { + str = str.replace('.', ''); + len = str.length; + i = len - i; + + // log[10](16) = 1.2041... , log[10](88) = 1.9444.... + divisor = intPow(Ctor, new Ctor(base), i, i * 2); + } + + xd = convertBase(str, base, BASE); + xe = xd.length - 1; + + // Remove trailing zeros. + for (i = xe; xd[i] === 0; --i) xd.pop(); + if (i < 0) return new Ctor(x.s * 0); + x.e = getBase10Exponent(xd, xe); + x.d = xd; + external = false; + + // At what precision to perform the division to ensure exact conversion? + // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount) + // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412 + // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits. + // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount + // Therefore using 4 * the number of digits of str will always be enough. + if (isFloat) x = divide(x, divisor, len * 4); + + // Multiply by the binary exponent part if present. + if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p)); + external = true; + + return x; + } + + + /* + * sin(x) = x - x^3/3! + x^5/5! - ... + * |x| < pi/2 + * + */ + function sine(Ctor, x) { + var k, + len = x.d.length; + + if (len < 3) return taylorSeries(Ctor, 2, x, x); + + // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x) + // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5) + // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20)) + + // Estimate the optimum number of times to use the argument reduction. + k = 1.4 * Math.sqrt(len); + k = k > 16 ? 16 : k | 0; + + x = x.times(1 / tinyPow(5, k)); + x = taylorSeries(Ctor, 2, x, x); + + // Reverse argument reduction + var sin2_x, + d5 = new Ctor(5), + d16 = new Ctor(16), + d20 = new Ctor(20); + for (; k--;) { + sin2_x = x.times(x); + x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20)))); + } + + return x; + } + + + // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`. + function taylorSeries(Ctor, n, x, y, isHyperbolic) { + var j, t, u, x2, + i = 1, + pr = Ctor.precision, + k = Math.ceil(pr / LOG_BASE); + + external = false; + x2 = x.times(x); + u = new Ctor(y); + + for (;;) { + t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1); + u = isHyperbolic ? y.plus(t) : y.minus(t); + y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1); + t = u.plus(y); + + if (t.d[k] !== void 0) { + for (j = k; t.d[j] === u.d[j] && j--;); + if (j == -1) break; + } + + j = u; + u = y; + y = t; + t = j; + i++; + } + + external = true; + t.d.length = k + 1; + + return t; + } + + + // Exponent e must be positive and non-zero. + function tinyPow(b, e) { + var n = b; + while (--e) n *= b; + return n; + } + + + // Return the absolute value of `x` reduced to less than or equal to half pi. + function toLessThanHalfPi(Ctor, x) { + var t, + isNeg = x.s < 0, + pi = getPi(Ctor, Ctor.precision, 1), + halfPi = pi.times(0.5); + + x = x.abs(); + + if (x.lte(halfPi)) { + quadrant = isNeg ? 4 : 1; + return x; + } + + t = x.divToInt(pi); + + if (t.isZero()) { + quadrant = isNeg ? 3 : 2; + } else { + x = x.minus(t.times(pi)); + + // 0 <= x < pi + if (x.lte(halfPi)) { + quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1); + return x; + } + + quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2); + } + + return x.minus(pi).abs(); + } + + + /* + * Return the value of Decimal `x` as a string in base `baseOut`. + * + * If the optional `sd` argument is present include a binary exponent suffix. + */ + function toStringBinary(x, baseOut, sd, rm) { + var base, e, i, k, len, roundUp, str, xd, y, + Ctor = x.constructor, + isExp = sd !== void 0; + + if (isExp) { + checkInt32(sd, 1, MAX_DIGITS); + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + } else { + sd = Ctor.precision; + rm = Ctor.rounding; + } + + if (!x.isFinite()) { + str = nonFiniteToString(x); + } else { + str = finiteToString(x); + i = str.indexOf('.'); + + // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required: + // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10)) + // minBinaryExponent = floor(decimalExponent * log[2](10)) + // log[2](10) = 3.321928094887362347870319429489390175864 + + if (isExp) { + base = 2; + if (baseOut == 16) { + sd = sd * 4 - 3; + } else if (baseOut == 8) { + sd = sd * 3 - 2; + } + } else { + base = baseOut; + } + + // Convert the number as an integer then divide the result by its base raised to a power such + // that the fraction part will be restored. + + // Non-integer. + if (i >= 0) { + str = str.replace('.', ''); + y = new Ctor(1); + y.e = str.length - i; + y.d = convertBase(finiteToString(y), 10, base); + y.e = y.d.length; + } + + xd = convertBase(str, 10, base); + e = len = xd.length; + + // Remove trailing zeros. + for (; xd[--len] == 0;) xd.pop(); + + if (!xd[0]) { + str = isExp ? '0p+0' : '0'; + } else { + if (i < 0) { + e--; + } else { + x = new Ctor(x); + x.d = xd; + x.e = e; + x = divide(x, y, sd, rm, 0, base); + xd = x.d; + e = x.e; + roundUp = inexact; + } + + // The rounding digit, i.e. the digit after the digit that may be rounded up. + i = xd[sd]; + k = base / 2; + roundUp = roundUp || xd[sd + 1] !== void 0; + + roundUp = rm < 4 + ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2)) + : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 || + rm === (x.s < 0 ? 8 : 7)); + + xd.length = sd; + + if (roundUp) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (; ++xd[--sd] > base - 1;) { + xd[sd] = 0; + if (!sd) { + ++e; + xd.unshift(1); + } + } + } + + // Determine trailing zeros. + for (len = xd.length; !xd[len - 1]; --len); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]); + + // Add binary exponent suffix? + if (isExp) { + if (len > 1) { + if (baseOut == 16 || baseOut == 8) { + i = baseOut == 16 ? 4 : 3; + for (--len; len % i; len++) str += '0'; + xd = convertBase(str, base, baseOut); + for (len = xd.length; !xd[len - 1]; --len); + + // xd[0] will always be be 1 + for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]); + } else { + str = str.charAt(0) + '.' + str.slice(1); + } + } + + str = str + (e < 0 ? 'p' : 'p+') + e; + } else if (e < 0) { + for (; ++e;) str = '0' + str; + str = '0.' + str; + } else { + if (++e > len) for (e -= len; e-- ;) str += '0'; + else if (e < len) str = str.slice(0, e) + '.' + str.slice(e); + } + } + + str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str; + } + + return x.s < 0 ? '-' + str : str; + } + + + // Does not strip trailing zeros. + function truncate(arr, len) { + if (arr.length > len) { + arr.length = len; + return true; + } + } + + + // Decimal methods + + + /* + * abs + * acos + * acosh + * add + * asin + * asinh + * atan + * atanh + * atan2 + * cbrt + * ceil + * clone + * config + * cos + * cosh + * div + * exp + * floor + * hypot + * ln + * log + * log2 + * log10 + * max + * min + * mod + * mul + * pow + * random + * round + * set + * sign + * sin + * sinh + * sqrt + * sub + * tan + * tanh + * trunc + */ + + + /* + * Return a new Decimal whose value is the absolute value of `x`. + * + * x {number|string|Decimal} + * + */ + function abs(x) { + return new this(x).abs(); + } + + + /* + * Return a new Decimal whose value is the arccosine in radians of `x`. + * + * x {number|string|Decimal} + * + */ + function acos(x) { + return new this(x).acos(); + } + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function acosh(x) { + return new this(x).acosh(); + } + + + /* + * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function add(x, y) { + return new this(x).plus(y); + } + + + /* + * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function asin(x) { + return new this(x).asin(); + } + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function asinh(x) { + return new this(x).asinh(); + } + + + /* + * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function atan(x) { + return new this(x).atan(); + } + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function atanh(x) { + return new this(x).atanh(); + } + + + /* + * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi + * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi, pi] + * + * y {number|string|Decimal} The y-coordinate. + * x {number|string|Decimal} The x-coordinate. + * + * atan2(±0, -0) = ±pi + * atan2(±0, +0) = ±0 + * atan2(±0, -x) = ±pi for x > 0 + * atan2(±0, x) = ±0 for x > 0 + * atan2(-y, ±0) = -pi/2 for y > 0 + * atan2(y, ±0) = pi/2 for y > 0 + * atan2(±y, -Infinity) = ±pi for finite y > 0 + * atan2(±y, +Infinity) = ±0 for finite y > 0 + * atan2(±Infinity, x) = ±pi/2 for finite x + * atan2(±Infinity, -Infinity) = ±3*pi/4 + * atan2(±Infinity, +Infinity) = ±pi/4 + * atan2(NaN, x) = NaN + * atan2(y, NaN) = NaN + * + */ + function atan2(y, x) { + y = new this(y); + x = new this(x); + var r, + pr = this.precision, + rm = this.rounding, + wpr = pr + 4; + + // Either NaN + if (!y.s || !x.s) { + r = new this(NaN); + + // Both ±Infinity + } else if (!y.d && !x.d) { + r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75); + r.s = y.s; + + // x is ±Infinity or y is ±0 + } else if (!x.d || y.isZero()) { + r = x.s < 0 ? getPi(this, pr, rm) : new this(0); + r.s = y.s; + + // y is ±Infinity or x is ±0 + } else if (!y.d || x.isZero()) { + r = getPi(this, wpr, 1).times(0.5); + r.s = y.s; + + // Both non-zero and finite + } else if (x.s < 0) { + this.precision = wpr; + this.rounding = 1; + r = this.atan(divide(y, x, wpr, 1)); + x = getPi(this, wpr, 1); + this.precision = pr; + this.rounding = rm; + r = y.s < 0 ? r.minus(x) : r.plus(x); + } else { + r = this.atan(divide(y, x, wpr, 1)); + } + + return r; + } + + + /* + * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function cbrt(x) { + return new this(x).cbrt(); + } + + + /* + * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`. + * + * x {number|string|Decimal} + * + */ + function ceil(x) { + return finalise(x = new this(x), x.e + 1, 2); + } + + + /* + * Configure global settings for a Decimal constructor. + * + * `obj` is an object with one or more of the following properties, + * + * precision {number} + * rounding {number} + * toExpNeg {number} + * toExpPos {number} + * maxE {number} + * minE {number} + * modulo {number} + * crypto {boolean|number} + * defaults {true} + * + * E.g. Decimal.config({ precision: 20, rounding: 4 }) + * + */ + function config(obj) { + if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected'); + var i, p, v, + useDefaults = obj.defaults === true, + ps = [ + 'precision', 1, MAX_DIGITS, + 'rounding', 0, 8, + 'toExpNeg', -EXP_LIMIT, 0, + 'toExpPos', 0, EXP_LIMIT, + 'maxE', 0, EXP_LIMIT, + 'minE', -EXP_LIMIT, 0, + 'modulo', 0, 9 + ]; + + for (i = 0; i < ps.length; i += 3) { + if (p = ps[i], useDefaults) this[p] = DEFAULTS[p]; + if ((v = obj[p]) !== void 0) { + if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v; + else throw Error(invalidArgument + p + ': ' + v); + } + } + + if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p]; + if ((v = obj[p]) !== void 0) { + if (v === true || v === false || v === 0 || v === 1) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + this[p] = true; + } else { + throw Error(cryptoUnavailable); + } + } else { + this[p] = false; + } + } else { + throw Error(invalidArgument + p + ': ' + v); + } + } + + return this; + } + + + /* + * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function cos(x) { + return new this(x).cos(); + } + + + /* + * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function cosh(x) { + return new this(x).cosh(); + } + + + /* + * Create and return a Decimal constructor with the same configuration properties as this Decimal + * constructor. + * + */ + function clone(obj) { + var i, p, ps; + + /* + * The Decimal constructor and exported function. + * Return a new Decimal instance. + * + * v {number|string|Decimal} A numeric value. + * + */ + function Decimal(v) { + var e, i, t, + x = this; + + // Decimal called without new. + if (!(x instanceof Decimal)) return new Decimal(v); + + // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor + // which points to Object. + x.constructor = Decimal; + + // Duplicate. + if (v instanceof Decimal) { + x.s = v.s; + + if (external) { + if (!v.d || v.e > Decimal.maxE) { + + // Infinity. + x.e = NaN; + x.d = null; + } else if (v.e < Decimal.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + } else { + x.e = v.e; + x.d = v.d.slice(); + } + } else { + x.e = v.e; + x.d = v.d ? v.d.slice() : v.d; + } + + return; + } + + t = typeof v; + + if (t === 'number') { + if (v === 0) { + x.s = 1 / v < 0 ? -1 : 1; + x.e = 0; + x.d = [0]; + return; + } + + if (v < 0) { + v = -v; + x.s = -1; + } else { + x.s = 1; + } + + // Fast path for small integers. + if (v === ~~v && v < 1e7) { + for (e = 0, i = v; i >= 10; i /= 10) e++; + + if (external) { + if (e > Decimal.maxE) { + x.e = NaN; + x.d = null; + } else if (e < Decimal.minE) { + x.e = 0; + x.d = [0]; + } else { + x.e = e; + x.d = [v]; + } + } else { + x.e = e; + x.d = [v]; + } + + return; + + // Infinity, NaN. + } else if (v * 0 !== 0) { + if (!v) x.s = NaN; + x.e = NaN; + x.d = null; + return; + } + + return parseDecimal(x, v.toString()); + + } else if (t !== 'string') { + throw Error(invalidArgument + v); + } + + // Minus sign? + if ((i = v.charCodeAt(0)) === 45) { + v = v.slice(1); + x.s = -1; + } else { + // Plus sign? + if (i === 43) v = v.slice(1); + x.s = 1; + } + + return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); + } + + Decimal.prototype = P; + + Decimal.ROUND_UP = 0; + Decimal.ROUND_DOWN = 1; + Decimal.ROUND_CEIL = 2; + Decimal.ROUND_FLOOR = 3; + Decimal.ROUND_HALF_UP = 4; + Decimal.ROUND_HALF_DOWN = 5; + Decimal.ROUND_HALF_EVEN = 6; + Decimal.ROUND_HALF_CEIL = 7; + Decimal.ROUND_HALF_FLOOR = 8; + Decimal.EUCLID = 9; + + Decimal.config = Decimal.set = config; + Decimal.clone = clone; + Decimal.isDecimal = isDecimalInstance; + + Decimal.abs = abs; + Decimal.acos = acos; + Decimal.acosh = acosh; // ES6 + Decimal.add = add; + Decimal.asin = asin; + Decimal.asinh = asinh; // ES6 + Decimal.atan = atan; + Decimal.atanh = atanh; // ES6 + Decimal.atan2 = atan2; + Decimal.cbrt = cbrt; // ES6 + Decimal.ceil = ceil; + Decimal.cos = cos; + Decimal.cosh = cosh; // ES6 + Decimal.div = div; + Decimal.exp = exp; + Decimal.floor = floor; + Decimal.hypot = hypot; // ES6 + Decimal.ln = ln; + Decimal.log = log; + Decimal.log10 = log10; // ES6 + Decimal.log2 = log2; // ES6 + Decimal.max = max; + Decimal.min = min; + Decimal.mod = mod; + Decimal.mul = mul; + Decimal.pow = pow; + Decimal.random = random; + Decimal.round = round; + Decimal.sign = sign; // ES6 + Decimal.sin = sin; + Decimal.sinh = sinh; // ES6 + Decimal.sqrt = sqrt; + Decimal.sub = sub; + Decimal.tan = tan; + Decimal.tanh = tanh; // ES6 + Decimal.trunc = trunc; // ES6 + + if (obj === void 0) obj = {}; + if (obj) { + if (obj.defaults !== true) { + ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto']; + for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p]; + } + } + + Decimal.config(obj); + + return Decimal; + } + + + /* + * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function div(x, y) { + return new this(x).div(y); + } + + + /* + * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} The power to which to raise the base of the natural log. + * + */ + function exp(x) { + return new this(x).exp(); + } + + + /* + * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`. + * + * x {number|string|Decimal} + * + */ + function floor(x) { + return finalise(x = new this(x), x.e + 1, 3); + } + + + /* + * Return a new Decimal whose value is the square root of the sum of the squares of the arguments, + * rounded to `precision` significant digits using rounding mode `rounding`. + * + * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...) + * + * arguments {number|string|Decimal} + * + */ + function hypot() { + var i, n, + t = new this(0); + + external = false; + + for (i = 0; i < arguments.length;) { + n = new this(arguments[i++]); + if (!n.d) { + if (n.s) { + external = true; + return new this(1 / 0); + } + t = n; + } else if (t.d) { + t = t.plus(n.times(n)); + } + } + + external = true; + + return t.sqrt(); + } + + + /* + * Return true if object is a Decimal instance (where Decimal is any Decimal constructor), + * otherwise return false. + * + */ + function isDecimalInstance(obj) { + return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false; + } + + + /* + * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function ln(x) { + return new this(x).ln(); + } + + + /* + * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base + * is specified, rounded to `precision` significant digits using rounding mode `rounding`. + * + * log[y](x) + * + * x {number|string|Decimal} The argument of the logarithm. + * y {number|string|Decimal} The base of the logarithm. + * + */ + function log(x, y) { + return new this(x).log(y); + } + + + /* + * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function log2(x) { + return new this(x).log(2); + } + + + /* + * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function log10(x) { + return new this(x).log(10); + } + + + /* + * Return a new Decimal whose value is the maximum of the arguments. + * + * arguments {number|string|Decimal} + * + */ + function max() { + return maxOrMin(this, arguments, 'lt'); + } + + + /* + * Return a new Decimal whose value is the minimum of the arguments. + * + * arguments {number|string|Decimal} + * + */ + function min() { + return maxOrMin(this, arguments, 'gt'); + } + + + /* + * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function mod(x, y) { + return new this(x).mod(y); + } + + + /* + * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function mul(x, y) { + return new this(x).mul(y); + } + + + /* + * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} The base. + * y {number|string|Decimal} The exponent. + * + */ + function pow(x, y) { + return new this(x).pow(y); + } + + + /* + * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with + * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros + * are produced). + * + * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive. + * + */ + function random(sd) { + var d, e, k, n, + i = 0, + r = new this(1), + rd = []; + + if (sd === void 0) sd = this.precision; + else checkInt32(sd, 1, MAX_DIGITS); + + k = Math.ceil(sd / LOG_BASE); + + if (!this.crypto) { + for (; i < k;) rd[i++] = Math.random() * 1e7 | 0; + + // Browsers supporting crypto.getRandomValues. + } else if (crypto.getRandomValues) { + d = crypto.getRandomValues(new Uint32Array(k)); + + for (; i < k;) { + n = d[i]; + + // 0 <= n < 4294967296 + // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865). + if (n >= 4.29e9) { + d[i] = crypto.getRandomValues(new Uint32Array(1))[0]; + } else { + + // 0 <= n <= 4289999999 + // 0 <= (n % 1e7) <= 9999999 + rd[i++] = n % 1e7; + } + } + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + d = crypto.randomBytes(k *= 4); + + for (; i < k;) { + + // 0 <= n < 2147483648 + n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24); + + // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286). + if (n >= 2.14e9) { + crypto.randomBytes(4).copy(d, i); + } else { + + // 0 <= n <= 2139999999 + // 0 <= (n % 1e7) <= 9999999 + rd.push(n % 1e7); + i += 4; + } + } + + i = k / 4; + } else { + throw Error(cryptoUnavailable); + } + + k = rd[--i]; + sd %= LOG_BASE; + + // Convert trailing digits to zeros according to sd. + if (k && sd) { + n = mathpow(10, LOG_BASE - sd); + rd[i] = (k / n | 0) * n; + } + + // Remove trailing words which are zero. + for (; rd[i] === 0; i--) rd.pop(); + + // Zero? + if (i < 0) { + e = 0; + rd = [0]; + } else { + e = -1; + + // Remove leading words which are zero and adjust exponent accordingly. + for (; rd[0] === 0; e -= LOG_BASE) rd.shift(); + + // Count the digits of the first word of rd to determine leading zeros. + for (k = 1, n = rd[0]; n >= 10; n /= 10) k++; + + // Adjust the exponent for leading zeros of the first word of rd. + if (k < LOG_BASE) e -= LOG_BASE - k; + } + + r.e = e; + r.d = rd; + + return r; + } + + + /* + * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`. + * + * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL). + * + * x {number|string|Decimal} + * + */ + function round(x) { + return finalise(x = new this(x), x.e + 1, this.rounding); + } + + + /* + * Return + * 1 if x > 0, + * -1 if x < 0, + * 0 if x is 0, + * -0 if x is -0, + * NaN otherwise + * + * x {number|string|Decimal} + * + */ + function sign(x) { + x = new this(x); + return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN; + } + + + /* + * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function sin(x) { + return new this(x).sin(); + } + + + /* + * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function sinh(x) { + return new this(x).sinh(); + } + + + /* + * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function sqrt(x) { + return new this(x).sqrt(); + } + + + /* + * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function sub(x, y) { + return new this(x).sub(y); + } + + + /* + * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function tan(x) { + return new this(x).tan(); + } + + + /* + * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function tanh(x) { + return new this(x).tanh(); + } + + + /* + * Return a new Decimal whose value is `x` truncated to an integer. + * + * x {number|string|Decimal} + * + */ + function trunc(x) { + return finalise(x = new this(x), x.e + 1, 1); + } + + + // Create and configure initial Decimal constructor. + Decimal = clone(DEFAULTS); + + Decimal['default'] = Decimal.Decimal = Decimal; + + // Create the internal constants from their string values. + LN10 = new Decimal(LN10); + PI = new Decimal(PI); + + + // Export. + + + // AMD. + if (true) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { + return Decimal; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + // Node and other environments that support module.exports. + } else {} +})(this); + + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// Map the characters to escape to their escaped values. The list is derived +// from http://www.cespedes.org/blog/85/how-to-escape-latex-special-characters + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var defaultEscapes = { + "{": "\\{", + "}": "\\}", + "\\": "\\textbackslash{}", + "#": "\\#", + $: "\\$", + "%": "\\%", + "&": "\\&", + "^": "\\textasciicircum{}", + _: "\\_", + "~": "\\textasciitilde{}" +}; +var formatEscapes = { + "\u2013": "\\--", + "\u2014": "\\---", + " ": "~", + "\t": "\\qquad{}", + "\r\n": "\\newline{}", + "\n": "\\newline{}" +}; + +var defaultEscapeMapFn = function defaultEscapeMapFn(defaultEscapes, formatEscapes) { + return _extends({}, defaultEscapes, formatEscapes); +}; + +/** + * Escape a string to be used in LaTeX documents. + * @param {string} str the string to be escaped. + * @param {boolean} params.preserveFormatting whether formatting escapes should + * be performed (default: false). + * @param {function} params.escapeMapFn the function to modify the escape maps. + * @return {string} the escaped string, ready to be used in LaTeX. + */ +module.exports = function (str) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$preserveFormatti = _ref.preserveFormatting, + preserveFormatting = _ref$preserveFormatti === undefined ? false : _ref$preserveFormatti, + _ref$escapeMapFn = _ref.escapeMapFn, + escapeMapFn = _ref$escapeMapFn === undefined ? defaultEscapeMapFn : _ref$escapeMapFn; + + var runningStr = String(str); + var result = ""; + + var escapes = escapeMapFn(_extends({}, defaultEscapes), preserveFormatting ? _extends({}, formatEscapes) : {}); + var escapeKeys = Object.keys(escapes); // as it is reused later on + + // Algorithm: Go through the string character by character, if it matches + // with one of the special characters then we'll replace it with the escaped + // version. + + var _loop = function _loop() { + var specialCharFound = false; + escapeKeys.forEach(function (key, index) { + if (specialCharFound) { + return; + } + if (runningStr.length >= key.length && runningStr.slice(0, key.length) === key) { + result += escapes[escapeKeys[index]]; + runningStr = runningStr.slice(key.length, runningStr.length); + specialCharFound = true; + } + }); + if (!specialCharFound) { + result += runningStr.slice(0, 1); + runningStr = runningStr.slice(1, runningStr.length); + } + }; + + while (runningStr) { + _loop(); + } + return result; +}; + +/***/ }), +/* 18 */ +/***/ (function(module, exports) { + +function E () { + // Keep this empty so it's easier to inherit from + // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3) +} + +E.prototype = { + on: function (name, callback, ctx) { + var e = this.e || (this.e = {}); + + (e[name] || (e[name] = [])).push({ + fn: callback, + ctx: ctx + }); + + return this; + }, + + once: function (name, callback, ctx) { + var self = this; + function listener () { + self.off(name, listener); + callback.apply(ctx, arguments); + }; + + listener._ = callback + return this.on(name, listener, ctx); + }, + + emit: function (name) { + var data = [].slice.call(arguments, 1); + var evtArr = ((this.e || (this.e = {}))[name] || []).slice(); + var i = 0; + var len = evtArr.length; + + for (i; i < len; i++) { + evtArr[i].fn.apply(evtArr[i].ctx, data); + } + + return this; + }, + + off: function (name, callback) { + var e = this.e || (this.e = {}); + var evts = e[name]; + var liveEvents = []; + + if (evts && callback) { + for (var i = 0, len = evts.length; i < len; i++) { + if (evts[i].fn !== callback && evts[i].fn._ !== callback) + liveEvents.push(evts[i]); + } + } + + // Remove event from queue to prevent memory leak + // Suggested by https://github.com/lazd + // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910 + + (liveEvents.length) + ? e[name] = liveEvents + : delete e[name]; + + return this; + } +}; + +module.exports = E; +module.exports.TinyEmitter = E; + + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +var all = __webpack_require__(21); + +var _require = __webpack_require__(22), + create = _require.create; + +var defaultInstance = create(all); // TODO: not nice having to revert to CommonJS, find an ES6 solution + +module.exports = /* #__PURE__ */defaultInstance; + +/***/ }), +/* 20 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || new Function("return this")(); +} catch (e) { + // This works if the window reference is available + if (typeof window === "object") g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 21 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, "createTyped", function() { return /* reexport */ typed_createTyped; }); +__webpack_require__.d(__webpack_exports__, "createResultSet", function() { return /* reexport */ createResultSet; }); +__webpack_require__.d(__webpack_exports__, "createBigNumberClass", function() { return /* reexport */ createBigNumberClass; }); +__webpack_require__.d(__webpack_exports__, "createComplexClass", function() { return /* reexport */ createComplexClass; }); +__webpack_require__.d(__webpack_exports__, "createFractionClass", function() { return /* reexport */ createFractionClass; }); +__webpack_require__.d(__webpack_exports__, "createRangeClass", function() { return /* reexport */ createRangeClass; }); +__webpack_require__.d(__webpack_exports__, "createMatrixClass", function() { return /* reexport */ createMatrixClass; }); +__webpack_require__.d(__webpack_exports__, "createDenseMatrixClass", function() { return /* reexport */ createDenseMatrixClass; }); +__webpack_require__.d(__webpack_exports__, "createClone", function() { return /* reexport */ createClone; }); +__webpack_require__.d(__webpack_exports__, "createIsInteger", function() { return /* reexport */ createIsInteger; }); +__webpack_require__.d(__webpack_exports__, "createIsNegative", function() { return /* reexport */ createIsNegative; }); +__webpack_require__.d(__webpack_exports__, "createIsNumeric", function() { return /* reexport */ createIsNumeric; }); +__webpack_require__.d(__webpack_exports__, "createHasNumericValue", function() { return /* reexport */ createHasNumericValue; }); +__webpack_require__.d(__webpack_exports__, "createIsPositive", function() { return /* reexport */ createIsPositive; }); +__webpack_require__.d(__webpack_exports__, "createIsZero", function() { return /* reexport */ createIsZero; }); +__webpack_require__.d(__webpack_exports__, "createIsNaN", function() { return /* reexport */ createIsNaN; }); +__webpack_require__.d(__webpack_exports__, "createTypeOf", function() { return /* reexport */ createTypeOf; }); +__webpack_require__.d(__webpack_exports__, "createDeprecatedTypeof", function() { return /* reexport */ createDeprecatedTypeof; }); +__webpack_require__.d(__webpack_exports__, "createEqualScalar", function() { return /* reexport */ createEqualScalar; }); +__webpack_require__.d(__webpack_exports__, "createSparseMatrixClass", function() { return /* reexport */ createSparseMatrixClass; }); +__webpack_require__.d(__webpack_exports__, "createNumber", function() { return /* reexport */ createNumber; }); +__webpack_require__.d(__webpack_exports__, "createString", function() { return /* reexport */ createString; }); +__webpack_require__.d(__webpack_exports__, "createBoolean", function() { return /* reexport */ createBoolean; }); +__webpack_require__.d(__webpack_exports__, "createBignumber", function() { return /* reexport */ createBignumber; }); +__webpack_require__.d(__webpack_exports__, "createComplex", function() { return /* reexport */ createComplex; }); +__webpack_require__.d(__webpack_exports__, "createFraction", function() { return /* reexport */ createFraction; }); +__webpack_require__.d(__webpack_exports__, "createMatrix", function() { return /* reexport */ createMatrix; }); +__webpack_require__.d(__webpack_exports__, "createSplitUnit", function() { return /* reexport */ createSplitUnit; }); +__webpack_require__.d(__webpack_exports__, "createUnaryMinus", function() { return /* reexport */ createUnaryMinus; }); +__webpack_require__.d(__webpack_exports__, "createUnaryPlus", function() { return /* reexport */ createUnaryPlus; }); +__webpack_require__.d(__webpack_exports__, "createAbs", function() { return /* reexport */ createAbs; }); +__webpack_require__.d(__webpack_exports__, "createApply", function() { return /* reexport */ createApply; }); +__webpack_require__.d(__webpack_exports__, "createAddScalar", function() { return /* reexport */ createAddScalar; }); +__webpack_require__.d(__webpack_exports__, "createCbrt", function() { return /* reexport */ createCbrt; }); +__webpack_require__.d(__webpack_exports__, "createCeil", function() { return /* reexport */ createCeil; }); +__webpack_require__.d(__webpack_exports__, "createCube", function() { return /* reexport */ createCube; }); +__webpack_require__.d(__webpack_exports__, "createExp", function() { return /* reexport */ createExp; }); +__webpack_require__.d(__webpack_exports__, "createExpm1", function() { return /* reexport */ createExpm1; }); +__webpack_require__.d(__webpack_exports__, "createFix", function() { return /* reexport */ createFix; }); +__webpack_require__.d(__webpack_exports__, "createFloor", function() { return /* reexport */ createFloor; }); +__webpack_require__.d(__webpack_exports__, "createGcd", function() { return /* reexport */ createGcd; }); +__webpack_require__.d(__webpack_exports__, "createLcm", function() { return /* reexport */ createLcm; }); +__webpack_require__.d(__webpack_exports__, "createLog10", function() { return /* reexport */ createLog10; }); +__webpack_require__.d(__webpack_exports__, "createLog2", function() { return /* reexport */ createLog2; }); +__webpack_require__.d(__webpack_exports__, "createMod", function() { return /* reexport */ createMod; }); +__webpack_require__.d(__webpack_exports__, "createMultiplyScalar", function() { return /* reexport */ createMultiplyScalar; }); +__webpack_require__.d(__webpack_exports__, "createMultiply", function() { return /* reexport */ createMultiply; }); +__webpack_require__.d(__webpack_exports__, "createNthRoot", function() { return /* reexport */ createNthRoot; }); +__webpack_require__.d(__webpack_exports__, "createSign", function() { return /* reexport */ createSign; }); +__webpack_require__.d(__webpack_exports__, "createSqrt", function() { return /* reexport */ createSqrt; }); +__webpack_require__.d(__webpack_exports__, "createSquare", function() { return /* reexport */ createSquare; }); +__webpack_require__.d(__webpack_exports__, "createSubtract", function() { return /* reexport */ createSubtract; }); +__webpack_require__.d(__webpack_exports__, "createXgcd", function() { return /* reexport */ createXgcd; }); +__webpack_require__.d(__webpack_exports__, "createDotMultiply", function() { return /* reexport */ createDotMultiply; }); +__webpack_require__.d(__webpack_exports__, "createBitAnd", function() { return /* reexport */ createBitAnd; }); +__webpack_require__.d(__webpack_exports__, "createBitNot", function() { return /* reexport */ createBitNot; }); +__webpack_require__.d(__webpack_exports__, "createBitOr", function() { return /* reexport */ createBitOr; }); +__webpack_require__.d(__webpack_exports__, "createBitXor", function() { return /* reexport */ createBitXor; }); +__webpack_require__.d(__webpack_exports__, "createArg", function() { return /* reexport */ createArg; }); +__webpack_require__.d(__webpack_exports__, "createConj", function() { return /* reexport */ createConj; }); +__webpack_require__.d(__webpack_exports__, "createIm", function() { return /* reexport */ createIm; }); +__webpack_require__.d(__webpack_exports__, "createRe", function() { return /* reexport */ createRe; }); +__webpack_require__.d(__webpack_exports__, "createNot", function() { return /* reexport */ createNot; }); +__webpack_require__.d(__webpack_exports__, "createOr", function() { return /* reexport */ createOr; }); +__webpack_require__.d(__webpack_exports__, "createXor", function() { return /* reexport */ createXor; }); +__webpack_require__.d(__webpack_exports__, "createConcat", function() { return /* reexport */ createConcat; }); +__webpack_require__.d(__webpack_exports__, "createColumn", function() { return /* reexport */ createColumn; }); +__webpack_require__.d(__webpack_exports__, "createCross", function() { return /* reexport */ createCross; }); +__webpack_require__.d(__webpack_exports__, "createDiag", function() { return /* reexport */ createDiag; }); +__webpack_require__.d(__webpack_exports__, "createEye", function() { return /* reexport */ createEye; }); +__webpack_require__.d(__webpack_exports__, "createFilter", function() { return /* reexport */ createFilter; }); +__webpack_require__.d(__webpack_exports__, "createFlatten", function() { return /* reexport */ createFlatten; }); +__webpack_require__.d(__webpack_exports__, "createForEach", function() { return /* reexport */ createForEach; }); +__webpack_require__.d(__webpack_exports__, "createGetMatrixDataType", function() { return /* reexport */ createGetMatrixDataType; }); +__webpack_require__.d(__webpack_exports__, "createIdentity", function() { return /* reexport */ createIdentity; }); +__webpack_require__.d(__webpack_exports__, "createKron", function() { return /* reexport */ createKron; }); +__webpack_require__.d(__webpack_exports__, "createMap", function() { return /* reexport */ createMap; }); +__webpack_require__.d(__webpack_exports__, "createOnes", function() { return /* reexport */ createOnes; }); +__webpack_require__.d(__webpack_exports__, "createRange", function() { return /* reexport */ range_createRange; }); +__webpack_require__.d(__webpack_exports__, "createReshape", function() { return /* reexport */ createReshape; }); +__webpack_require__.d(__webpack_exports__, "createResize", function() { return /* reexport */ createResize; }); +__webpack_require__.d(__webpack_exports__, "createRow", function() { return /* reexport */ createRow; }); +__webpack_require__.d(__webpack_exports__, "createSize", function() { return /* reexport */ createSize; }); +__webpack_require__.d(__webpack_exports__, "createSqueeze", function() { return /* reexport */ createSqueeze; }); +__webpack_require__.d(__webpack_exports__, "createSubset", function() { return /* reexport */ createSubset; }); +__webpack_require__.d(__webpack_exports__, "createTranspose", function() { return /* reexport */ createTranspose; }); +__webpack_require__.d(__webpack_exports__, "createCtranspose", function() { return /* reexport */ createCtranspose; }); +__webpack_require__.d(__webpack_exports__, "createZeros", function() { return /* reexport */ createZeros; }); +__webpack_require__.d(__webpack_exports__, "createErf", function() { return /* reexport */ createErf; }); +__webpack_require__.d(__webpack_exports__, "createMode", function() { return /* reexport */ createMode; }); +__webpack_require__.d(__webpack_exports__, "createProd", function() { return /* reexport */ createProd; }); +__webpack_require__.d(__webpack_exports__, "createFormat", function() { return /* reexport */ createFormat; }); +__webpack_require__.d(__webpack_exports__, "createPrint", function() { return /* reexport */ createPrint; }); +__webpack_require__.d(__webpack_exports__, "createTo", function() { return /* reexport */ createTo; }); +__webpack_require__.d(__webpack_exports__, "createIsPrime", function() { return /* reexport */ createIsPrime; }); +__webpack_require__.d(__webpack_exports__, "createNumeric", function() { return /* reexport */ createNumeric; }); +__webpack_require__.d(__webpack_exports__, "createDivideScalar", function() { return /* reexport */ createDivideScalar; }); +__webpack_require__.d(__webpack_exports__, "createPow", function() { return /* reexport */ createPow; }); +__webpack_require__.d(__webpack_exports__, "createRound", function() { return /* reexport */ createRound; }); +__webpack_require__.d(__webpack_exports__, "createLog", function() { return /* reexport */ createLog; }); +__webpack_require__.d(__webpack_exports__, "createLog1p", function() { return /* reexport */ createLog1p; }); +__webpack_require__.d(__webpack_exports__, "createNthRoots", function() { return /* reexport */ createNthRoots; }); +__webpack_require__.d(__webpack_exports__, "createDotPow", function() { return /* reexport */ createDotPow; }); +__webpack_require__.d(__webpack_exports__, "createDotDivide", function() { return /* reexport */ createDotDivide; }); +__webpack_require__.d(__webpack_exports__, "createLsolve", function() { return /* reexport */ createLsolve; }); +__webpack_require__.d(__webpack_exports__, "createUsolve", function() { return /* reexport */ createUsolve; }); +__webpack_require__.d(__webpack_exports__, "createLeftShift", function() { return /* reexport */ createLeftShift; }); +__webpack_require__.d(__webpack_exports__, "createRightArithShift", function() { return /* reexport */ createRightArithShift; }); +__webpack_require__.d(__webpack_exports__, "createRightLogShift", function() { return /* reexport */ createRightLogShift; }); +__webpack_require__.d(__webpack_exports__, "createAnd", function() { return /* reexport */ createAnd; }); +__webpack_require__.d(__webpack_exports__, "createCompare", function() { return /* reexport */ createCompare; }); +__webpack_require__.d(__webpack_exports__, "createCompareNatural", function() { return /* reexport */ createCompareNatural; }); +__webpack_require__.d(__webpack_exports__, "createCompareText", function() { return /* reexport */ createCompareText; }); +__webpack_require__.d(__webpack_exports__, "createEqual", function() { return /* reexport */ createEqual; }); +__webpack_require__.d(__webpack_exports__, "createEqualText", function() { return /* reexport */ createEqualText; }); +__webpack_require__.d(__webpack_exports__, "createSmaller", function() { return /* reexport */ createSmaller; }); +__webpack_require__.d(__webpack_exports__, "createSmallerEq", function() { return /* reexport */ createSmallerEq; }); +__webpack_require__.d(__webpack_exports__, "createLarger", function() { return /* reexport */ createLarger; }); +__webpack_require__.d(__webpack_exports__, "createLargerEq", function() { return /* reexport */ createLargerEq; }); +__webpack_require__.d(__webpack_exports__, "createDeepEqual", function() { return /* reexport */ createDeepEqual; }); +__webpack_require__.d(__webpack_exports__, "createUnequal", function() { return /* reexport */ createUnequal; }); +__webpack_require__.d(__webpack_exports__, "createPartitionSelect", function() { return /* reexport */ createPartitionSelect; }); +__webpack_require__.d(__webpack_exports__, "createSort", function() { return /* reexport */ createSort; }); +__webpack_require__.d(__webpack_exports__, "createMax", function() { return /* reexport */ createMax; }); +__webpack_require__.d(__webpack_exports__, "createMin", function() { return /* reexport */ createMin; }); +__webpack_require__.d(__webpack_exports__, "createImmutableDenseMatrixClass", function() { return /* reexport */ createImmutableDenseMatrixClass; }); +__webpack_require__.d(__webpack_exports__, "createIndexClass", function() { return /* reexport */ createIndexClass; }); +__webpack_require__.d(__webpack_exports__, "createFibonacciHeapClass", function() { return /* reexport */ createFibonacciHeapClass; }); +__webpack_require__.d(__webpack_exports__, "createSpaClass", function() { return /* reexport */ createSpaClass; }); +__webpack_require__.d(__webpack_exports__, "createUnitClass", function() { return /* reexport */ createUnitClass; }); +__webpack_require__.d(__webpack_exports__, "createUnitFunction", function() { return /* reexport */ createUnitFunction; }); +__webpack_require__.d(__webpack_exports__, "createSparse", function() { return /* reexport */ createSparse; }); +__webpack_require__.d(__webpack_exports__, "createCreateUnit", function() { return /* reexport */ createCreateUnit; }); +__webpack_require__.d(__webpack_exports__, "createAcos", function() { return /* reexport */ createAcos; }); +__webpack_require__.d(__webpack_exports__, "createAcosh", function() { return /* reexport */ createAcosh; }); +__webpack_require__.d(__webpack_exports__, "createAcot", function() { return /* reexport */ createAcot; }); +__webpack_require__.d(__webpack_exports__, "createAcoth", function() { return /* reexport */ createAcoth; }); +__webpack_require__.d(__webpack_exports__, "createAcsc", function() { return /* reexport */ createAcsc; }); +__webpack_require__.d(__webpack_exports__, "createAcsch", function() { return /* reexport */ createAcsch; }); +__webpack_require__.d(__webpack_exports__, "createAsec", function() { return /* reexport */ createAsec; }); +__webpack_require__.d(__webpack_exports__, "createAsech", function() { return /* reexport */ createAsech; }); +__webpack_require__.d(__webpack_exports__, "createAsin", function() { return /* reexport */ createAsin; }); +__webpack_require__.d(__webpack_exports__, "createAsinh", function() { return /* reexport */ createAsinh; }); +__webpack_require__.d(__webpack_exports__, "createAtan", function() { return /* reexport */ createAtan; }); +__webpack_require__.d(__webpack_exports__, "createAtan2", function() { return /* reexport */ createAtan2; }); +__webpack_require__.d(__webpack_exports__, "createAtanh", function() { return /* reexport */ createAtanh; }); +__webpack_require__.d(__webpack_exports__, "createCos", function() { return /* reexport */ createCos; }); +__webpack_require__.d(__webpack_exports__, "createCosh", function() { return /* reexport */ createCosh; }); +__webpack_require__.d(__webpack_exports__, "createCot", function() { return /* reexport */ createCot; }); +__webpack_require__.d(__webpack_exports__, "createCoth", function() { return /* reexport */ createCoth; }); +__webpack_require__.d(__webpack_exports__, "createCsc", function() { return /* reexport */ createCsc; }); +__webpack_require__.d(__webpack_exports__, "createCsch", function() { return /* reexport */ createCsch; }); +__webpack_require__.d(__webpack_exports__, "createSec", function() { return /* reexport */ createSec; }); +__webpack_require__.d(__webpack_exports__, "createSech", function() { return /* reexport */ createSech; }); +__webpack_require__.d(__webpack_exports__, "createSin", function() { return /* reexport */ createSin; }); +__webpack_require__.d(__webpack_exports__, "createSinh", function() { return /* reexport */ createSinh; }); +__webpack_require__.d(__webpack_exports__, "createTan", function() { return /* reexport */ createTan; }); +__webpack_require__.d(__webpack_exports__, "createTanh", function() { return /* reexport */ createTanh; }); +__webpack_require__.d(__webpack_exports__, "createSetCartesian", function() { return /* reexport */ createSetCartesian; }); +__webpack_require__.d(__webpack_exports__, "createSetDifference", function() { return /* reexport */ createSetDifference; }); +__webpack_require__.d(__webpack_exports__, "createSetDistinct", function() { return /* reexport */ createSetDistinct; }); +__webpack_require__.d(__webpack_exports__, "createSetIntersect", function() { return /* reexport */ createSetIntersect; }); +__webpack_require__.d(__webpack_exports__, "createSetIsSubset", function() { return /* reexport */ createSetIsSubset; }); +__webpack_require__.d(__webpack_exports__, "createSetMultiplicity", function() { return /* reexport */ createSetMultiplicity; }); +__webpack_require__.d(__webpack_exports__, "createSetPowerset", function() { return /* reexport */ createSetPowerset; }); +__webpack_require__.d(__webpack_exports__, "createSetSize", function() { return /* reexport */ createSetSize; }); +__webpack_require__.d(__webpack_exports__, "createSetSymDifference", function() { return /* reexport */ createSetSymDifference; }); +__webpack_require__.d(__webpack_exports__, "createSetUnion", function() { return /* reexport */ createSetUnion; }); +__webpack_require__.d(__webpack_exports__, "createAdd", function() { return /* reexport */ createAdd; }); +__webpack_require__.d(__webpack_exports__, "createHypot", function() { return /* reexport */ createHypot; }); +__webpack_require__.d(__webpack_exports__, "createNorm", function() { return /* reexport */ createNorm; }); +__webpack_require__.d(__webpack_exports__, "createDot", function() { return /* reexport */ createDot; }); +__webpack_require__.d(__webpack_exports__, "createTrace", function() { return /* reexport */ createTrace; }); +__webpack_require__.d(__webpack_exports__, "createIndex", function() { return /* reexport */ createIndex; }); +__webpack_require__.d(__webpack_exports__, "createNode", function() { return /* reexport */ createNode; }); +__webpack_require__.d(__webpack_exports__, "createAccessorNode", function() { return /* reexport */ createAccessorNode; }); +__webpack_require__.d(__webpack_exports__, "createArrayNode", function() { return /* reexport */ createArrayNode; }); +__webpack_require__.d(__webpack_exports__, "createAssignmentNode", function() { return /* reexport */ createAssignmentNode; }); +__webpack_require__.d(__webpack_exports__, "createBlockNode", function() { return /* reexport */ createBlockNode; }); +__webpack_require__.d(__webpack_exports__, "createConditionalNode", function() { return /* reexport */ createConditionalNode; }); +__webpack_require__.d(__webpack_exports__, "createConstantNode", function() { return /* reexport */ ConstantNode_createConstantNode; }); +__webpack_require__.d(__webpack_exports__, "createFunctionAssignmentNode", function() { return /* reexport */ createFunctionAssignmentNode; }); +__webpack_require__.d(__webpack_exports__, "createIndexNode", function() { return /* reexport */ createIndexNode; }); +__webpack_require__.d(__webpack_exports__, "createObjectNode", function() { return /* reexport */ createObjectNode; }); +__webpack_require__.d(__webpack_exports__, "createOperatorNode", function() { return /* reexport */ createOperatorNode; }); +__webpack_require__.d(__webpack_exports__, "createParenthesisNode", function() { return /* reexport */ createParenthesisNode; }); +__webpack_require__.d(__webpack_exports__, "createRangeNode", function() { return /* reexport */ createRangeNode; }); +__webpack_require__.d(__webpack_exports__, "createRelationalNode", function() { return /* reexport */ createRelationalNode; }); +__webpack_require__.d(__webpack_exports__, "createSymbolNode", function() { return /* reexport */ createSymbolNode; }); +__webpack_require__.d(__webpack_exports__, "createFunctionNode", function() { return /* reexport */ createFunctionNode; }); +__webpack_require__.d(__webpack_exports__, "createParse", function() { return /* reexport */ createParse; }); +__webpack_require__.d(__webpack_exports__, "createCompile", function() { return /* reexport */ createCompile; }); +__webpack_require__.d(__webpack_exports__, "createEvaluate", function() { return /* reexport */ createEvaluate; }); +__webpack_require__.d(__webpack_exports__, "createDeprecatedEval", function() { return /* reexport */ createDeprecatedEval; }); +__webpack_require__.d(__webpack_exports__, "createParserClass", function() { return /* reexport */ createParserClass; }); +__webpack_require__.d(__webpack_exports__, "createParser", function() { return /* reexport */ createParser; }); +__webpack_require__.d(__webpack_exports__, "createLup", function() { return /* reexport */ createLup; }); +__webpack_require__.d(__webpack_exports__, "createQr", function() { return /* reexport */ createQr; }); +__webpack_require__.d(__webpack_exports__, "createSlu", function() { return /* reexport */ createSlu; }); +__webpack_require__.d(__webpack_exports__, "createLusolve", function() { return /* reexport */ createLusolve; }); +__webpack_require__.d(__webpack_exports__, "createHelpClass", function() { return /* reexport */ createHelpClass; }); +__webpack_require__.d(__webpack_exports__, "createChainClass", function() { return /* reexport */ createChainClass; }); +__webpack_require__.d(__webpack_exports__, "createHelp", function() { return /* reexport */ createHelp; }); +__webpack_require__.d(__webpack_exports__, "createChain", function() { return /* reexport */ createChain; }); +__webpack_require__.d(__webpack_exports__, "createDet", function() { return /* reexport */ createDet; }); +__webpack_require__.d(__webpack_exports__, "createInv", function() { return /* reexport */ createInv; }); +__webpack_require__.d(__webpack_exports__, "createEigs", function() { return /* reexport */ createEigs; }); +__webpack_require__.d(__webpack_exports__, "createExpm", function() { return /* reexport */ createExpm; }); +__webpack_require__.d(__webpack_exports__, "createSqrtm", function() { return /* reexport */ createSqrtm; }); +__webpack_require__.d(__webpack_exports__, "createDivide", function() { return /* reexport */ createDivide; }); +__webpack_require__.d(__webpack_exports__, "createDistance", function() { return /* reexport */ createDistance; }); +__webpack_require__.d(__webpack_exports__, "createIntersect", function() { return /* reexport */ createIntersect; }); +__webpack_require__.d(__webpack_exports__, "createSum", function() { return /* reexport */ createSum; }); +__webpack_require__.d(__webpack_exports__, "createMean", function() { return /* reexport */ createMean; }); +__webpack_require__.d(__webpack_exports__, "createMedian", function() { return /* reexport */ createMedian; }); +__webpack_require__.d(__webpack_exports__, "createMad", function() { return /* reexport */ createMad; }); +__webpack_require__.d(__webpack_exports__, "createVariance", function() { return /* reexport */ createVariance; }); +__webpack_require__.d(__webpack_exports__, "createDeprecatedVar", function() { return /* reexport */ createDeprecatedVar; }); +__webpack_require__.d(__webpack_exports__, "createQuantileSeq", function() { return /* reexport */ createQuantileSeq; }); +__webpack_require__.d(__webpack_exports__, "createStd", function() { return /* reexport */ createStd; }); +__webpack_require__.d(__webpack_exports__, "createCombinations", function() { return /* reexport */ createCombinations; }); +__webpack_require__.d(__webpack_exports__, "createCombinationsWithRep", function() { return /* reexport */ createCombinationsWithRep; }); +__webpack_require__.d(__webpack_exports__, "createGamma", function() { return /* reexport */ createGamma; }); +__webpack_require__.d(__webpack_exports__, "createFactorial", function() { return /* reexport */ createFactorial; }); +__webpack_require__.d(__webpack_exports__, "createKldivergence", function() { return /* reexport */ createKldivergence; }); +__webpack_require__.d(__webpack_exports__, "createMultinomial", function() { return /* reexport */ createMultinomial; }); +__webpack_require__.d(__webpack_exports__, "createPermutations", function() { return /* reexport */ createPermutations; }); +__webpack_require__.d(__webpack_exports__, "createPickRandom", function() { return /* reexport */ createPickRandom; }); +__webpack_require__.d(__webpack_exports__, "createRandom", function() { return /* reexport */ createRandom; }); +__webpack_require__.d(__webpack_exports__, "createRandomInt", function() { return /* reexport */ createRandomInt; }); +__webpack_require__.d(__webpack_exports__, "createStirlingS2", function() { return /* reexport */ createStirlingS2; }); +__webpack_require__.d(__webpack_exports__, "createBellNumbers", function() { return /* reexport */ createBellNumbers; }); +__webpack_require__.d(__webpack_exports__, "createCatalan", function() { return /* reexport */ createCatalan; }); +__webpack_require__.d(__webpack_exports__, "createComposition", function() { return /* reexport */ createComposition; }); +__webpack_require__.d(__webpack_exports__, "createSimplify", function() { return /* reexport */ createSimplify; }); +__webpack_require__.d(__webpack_exports__, "createDerivative", function() { return /* reexport */ createDerivative; }); +__webpack_require__.d(__webpack_exports__, "createRationalize", function() { return /* reexport */ createRationalize; }); +__webpack_require__.d(__webpack_exports__, "createReviver", function() { return /* reexport */ createReviver; }); +__webpack_require__.d(__webpack_exports__, "createReplacer", function() { return /* reexport */ createReplacer; }); +__webpack_require__.d(__webpack_exports__, "createE", function() { return /* reexport */ createE; }); +__webpack_require__.d(__webpack_exports__, "createUppercaseE", function() { return /* reexport */ createUppercaseE; }); +__webpack_require__.d(__webpack_exports__, "createFalse", function() { return /* reexport */ createFalse; }); +__webpack_require__.d(__webpack_exports__, "createI", function() { return /* reexport */ createI; }); +__webpack_require__.d(__webpack_exports__, "createInfinity", function() { return /* reexport */ createInfinity; }); +__webpack_require__.d(__webpack_exports__, "createLN10", function() { return /* reexport */ createLN10; }); +__webpack_require__.d(__webpack_exports__, "createLN2", function() { return /* reexport */ createLN2; }); +__webpack_require__.d(__webpack_exports__, "createLOG10E", function() { return /* reexport */ createLOG10E; }); +__webpack_require__.d(__webpack_exports__, "createLOG2E", function() { return /* reexport */ createLOG2E; }); +__webpack_require__.d(__webpack_exports__, "createNaN", function() { return /* reexport */ createNaN; }); +__webpack_require__.d(__webpack_exports__, "createNull", function() { return /* reexport */ createNull; }); +__webpack_require__.d(__webpack_exports__, "createPhi", function() { return /* reexport */ createPhi; }); +__webpack_require__.d(__webpack_exports__, "createPi", function() { return /* reexport */ createPi; }); +__webpack_require__.d(__webpack_exports__, "createUppercasePi", function() { return /* reexport */ createUppercasePi; }); +__webpack_require__.d(__webpack_exports__, "createSQRT1_2", function() { return /* reexport */ createSQRT1_2; }); +__webpack_require__.d(__webpack_exports__, "createSQRT2", function() { return /* reexport */ createSQRT2; }); +__webpack_require__.d(__webpack_exports__, "createTau", function() { return /* reexport */ createTau; }); +__webpack_require__.d(__webpack_exports__, "createTrue", function() { return /* reexport */ createTrue; }); +__webpack_require__.d(__webpack_exports__, "createVersion", function() { return /* reexport */ createVersion; }); +__webpack_require__.d(__webpack_exports__, "createAtomicMass", function() { return /* reexport */ createAtomicMass; }); +__webpack_require__.d(__webpack_exports__, "createAvogadro", function() { return /* reexport */ createAvogadro; }); +__webpack_require__.d(__webpack_exports__, "createBohrMagneton", function() { return /* reexport */ createBohrMagneton; }); +__webpack_require__.d(__webpack_exports__, "createBohrRadius", function() { return /* reexport */ createBohrRadius; }); +__webpack_require__.d(__webpack_exports__, "createBoltzmann", function() { return /* reexport */ createBoltzmann; }); +__webpack_require__.d(__webpack_exports__, "createClassicalElectronRadius", function() { return /* reexport */ createClassicalElectronRadius; }); +__webpack_require__.d(__webpack_exports__, "createConductanceQuantum", function() { return /* reexport */ createConductanceQuantum; }); +__webpack_require__.d(__webpack_exports__, "createCoulomb", function() { return /* reexport */ createCoulomb; }); +__webpack_require__.d(__webpack_exports__, "createDeuteronMass", function() { return /* reexport */ createDeuteronMass; }); +__webpack_require__.d(__webpack_exports__, "createEfimovFactor", function() { return /* reexport */ createEfimovFactor; }); +__webpack_require__.d(__webpack_exports__, "createElectricConstant", function() { return /* reexport */ createElectricConstant; }); +__webpack_require__.d(__webpack_exports__, "createElectronMass", function() { return /* reexport */ createElectronMass; }); +__webpack_require__.d(__webpack_exports__, "createElementaryCharge", function() { return /* reexport */ createElementaryCharge; }); +__webpack_require__.d(__webpack_exports__, "createFaraday", function() { return /* reexport */ createFaraday; }); +__webpack_require__.d(__webpack_exports__, "createFermiCoupling", function() { return /* reexport */ createFermiCoupling; }); +__webpack_require__.d(__webpack_exports__, "createFineStructure", function() { return /* reexport */ createFineStructure; }); +__webpack_require__.d(__webpack_exports__, "createFirstRadiation", function() { return /* reexport */ createFirstRadiation; }); +__webpack_require__.d(__webpack_exports__, "createGasConstant", function() { return /* reexport */ createGasConstant; }); +__webpack_require__.d(__webpack_exports__, "createGravitationConstant", function() { return /* reexport */ createGravitationConstant; }); +__webpack_require__.d(__webpack_exports__, "createGravity", function() { return /* reexport */ createGravity; }); +__webpack_require__.d(__webpack_exports__, "createHartreeEnergy", function() { return /* reexport */ createHartreeEnergy; }); +__webpack_require__.d(__webpack_exports__, "createInverseConductanceQuantum", function() { return /* reexport */ createInverseConductanceQuantum; }); +__webpack_require__.d(__webpack_exports__, "createKlitzing", function() { return /* reexport */ createKlitzing; }); +__webpack_require__.d(__webpack_exports__, "createLoschmidt", function() { return /* reexport */ createLoschmidt; }); +__webpack_require__.d(__webpack_exports__, "createMagneticConstant", function() { return /* reexport */ createMagneticConstant; }); +__webpack_require__.d(__webpack_exports__, "createMagneticFluxQuantum", function() { return /* reexport */ createMagneticFluxQuantum; }); +__webpack_require__.d(__webpack_exports__, "createMolarMass", function() { return /* reexport */ createMolarMass; }); +__webpack_require__.d(__webpack_exports__, "createMolarMassC12", function() { return /* reexport */ createMolarMassC12; }); +__webpack_require__.d(__webpack_exports__, "createMolarPlanckConstant", function() { return /* reexport */ createMolarPlanckConstant; }); +__webpack_require__.d(__webpack_exports__, "createMolarVolume", function() { return /* reexport */ createMolarVolume; }); +__webpack_require__.d(__webpack_exports__, "createNeutronMass", function() { return /* reexport */ createNeutronMass; }); +__webpack_require__.d(__webpack_exports__, "createNuclearMagneton", function() { return /* reexport */ createNuclearMagneton; }); +__webpack_require__.d(__webpack_exports__, "createPlanckCharge", function() { return /* reexport */ createPlanckCharge; }); +__webpack_require__.d(__webpack_exports__, "createPlanckConstant", function() { return /* reexport */ createPlanckConstant; }); +__webpack_require__.d(__webpack_exports__, "createPlanckLength", function() { return /* reexport */ createPlanckLength; }); +__webpack_require__.d(__webpack_exports__, "createPlanckMass", function() { return /* reexport */ createPlanckMass; }); +__webpack_require__.d(__webpack_exports__, "createPlanckTemperature", function() { return /* reexport */ createPlanckTemperature; }); +__webpack_require__.d(__webpack_exports__, "createPlanckTime", function() { return /* reexport */ createPlanckTime; }); +__webpack_require__.d(__webpack_exports__, "createProtonMass", function() { return /* reexport */ createProtonMass; }); +__webpack_require__.d(__webpack_exports__, "createQuantumOfCirculation", function() { return /* reexport */ createQuantumOfCirculation; }); +__webpack_require__.d(__webpack_exports__, "createReducedPlanckConstant", function() { return /* reexport */ createReducedPlanckConstant; }); +__webpack_require__.d(__webpack_exports__, "createRydberg", function() { return /* reexport */ createRydberg; }); +__webpack_require__.d(__webpack_exports__, "createSackurTetrode", function() { return /* reexport */ createSackurTetrode; }); +__webpack_require__.d(__webpack_exports__, "createSecondRadiation", function() { return /* reexport */ createSecondRadiation; }); +__webpack_require__.d(__webpack_exports__, "createSpeedOfLight", function() { return /* reexport */ createSpeedOfLight; }); +__webpack_require__.d(__webpack_exports__, "createStefanBoltzmann", function() { return /* reexport */ createStefanBoltzmann; }); +__webpack_require__.d(__webpack_exports__, "createThomsonCrossSection", function() { return /* reexport */ createThomsonCrossSection; }); +__webpack_require__.d(__webpack_exports__, "createVacuumImpedance", function() { return /* reexport */ createVacuumImpedance; }); +__webpack_require__.d(__webpack_exports__, "createWeakMixingAngle", function() { return /* reexport */ createWeakMixingAngle; }); +__webpack_require__.d(__webpack_exports__, "createWienDisplacement", function() { return /* reexport */ createWienDisplacement; }); +__webpack_require__.d(__webpack_exports__, "createApplyTransform", function() { return /* reexport */ createApplyTransform; }); +__webpack_require__.d(__webpack_exports__, "createColumnTransform", function() { return /* reexport */ createColumnTransform; }); +__webpack_require__.d(__webpack_exports__, "createFilterTransform", function() { return /* reexport */ createFilterTransform; }); +__webpack_require__.d(__webpack_exports__, "createForEachTransform", function() { return /* reexport */ createForEachTransform; }); +__webpack_require__.d(__webpack_exports__, "createIndexTransform", function() { return /* reexport */ createIndexTransform; }); +__webpack_require__.d(__webpack_exports__, "createMapTransform", function() { return /* reexport */ createMapTransform; }); +__webpack_require__.d(__webpack_exports__, "createMaxTransform", function() { return /* reexport */ createMaxTransform; }); +__webpack_require__.d(__webpack_exports__, "createMeanTransform", function() { return /* reexport */ createMeanTransform; }); +__webpack_require__.d(__webpack_exports__, "createMinTransform", function() { return /* reexport */ createMinTransform; }); +__webpack_require__.d(__webpack_exports__, "createRangeTransform", function() { return /* reexport */ createRangeTransform; }); +__webpack_require__.d(__webpack_exports__, "createRowTransform", function() { return /* reexport */ createRowTransform; }); +__webpack_require__.d(__webpack_exports__, "createSubsetTransform", function() { return /* reexport */ createSubsetTransform; }); +__webpack_require__.d(__webpack_exports__, "createConcatTransform", function() { return /* reexport */ createConcatTransform; }); +__webpack_require__.d(__webpack_exports__, "createStdTransform", function() { return /* reexport */ createStdTransform; }); +__webpack_require__.d(__webpack_exports__, "createSumTransform", function() { return /* reexport */ createSumTransform; }); +__webpack_require__.d(__webpack_exports__, "createVarianceTransform", function() { return /* reexport */ createVarianceTransform; }); + +// EXTERNAL MODULE: ./src/utils/is.js +var is = __webpack_require__(1); + +// EXTERNAL MODULE: ./node_modules/typed-function/typed-function.js +var typed_function = __webpack_require__(14); +var typed_function_default = /*#__PURE__*/__webpack_require__.n(typed_function); + +// EXTERNAL MODULE: ./src/utils/number.js +var utils_number = __webpack_require__(4); + +// EXTERNAL MODULE: ./src/utils/factory.js +var factory = __webpack_require__(0); + +// CONCATENATED MODULE: ./src/core/function/typed.js +/** + * Create a typed-function which checks the types of the arguments and + * can match them against multiple provided signatures. The typed-function + * automatically converts inputs in order to find a matching signature. + * Typed functions throw informative errors in case of wrong input arguments. + * + * See the library [typed-function](https://github.com/josdejong/typed-function) + * for detailed documentation. + * + * Syntax: + * + * math.typed(name, signatures) : function + * math.typed(signatures) : function + * + * Examples: + * + * // create a typed function with multiple types per argument (type union) + * const fn2 = typed({ + * 'number | boolean': function (b) { + * return 'b is a number or boolean' + * }, + * 'string, number | boolean': function (a, b) { + * return 'a is a string, b is a number or boolean' + * } + * }) + * + * // create a typed function with an any type argument + * const log = typed({ + * 'string, any': function (event, data) { + * console.log('event: ' + event + ', data: ' + JSON.stringify(data)) + * } + * }) + * + * @param {string} [name] Optional name for the typed-function + * @param {Object} signatures Object with one or multiple function signatures + * @returns {function} The created typed-function. + */ + + + + // returns a new instance of typed-function + +var _createTyped2 = function _createTyped() { + // initially, return the original instance of typed-function + // consecutively, return a new instance from typed.create. + _createTyped2 = typed_function_default.a.create; + return typed_function_default.a; +}; + +var typed_dependencies = ['?BigNumber', '?Complex', '?DenseMatrix', '?Fraction']; +/** + * Factory function for creating a new typed instance + * @param {Object} dependencies Object with data types like Complex and BigNumber + * @returns {Function} + */ + +var typed_createTyped = /* #__PURE__ */Object(factory["a" /* factory */])('typed', typed_dependencies, function createTyped(_ref) { + var BigNumber = _ref.BigNumber, + Complex = _ref.Complex, + DenseMatrix = _ref.DenseMatrix, + Fraction = _ref.Fraction; + + // TODO: typed-function must be able to silently ignore signatures with unknown data types + // get a new instance of typed-function + var typed = _createTyped2(); // define all types. The order of the types determines in which order function + // arguments are type-checked (so for performance it's important to put the + // most used types first). + + + typed.types = [{ + name: 'number', + test: is["y" /* isNumber */] + }, { + name: 'Complex', + test: is["j" /* isComplex */] + }, { + name: 'BigNumber', + test: is["e" /* isBigNumber */] + }, { + name: 'Fraction', + test: is["o" /* isFraction */] + }, { + name: 'Unit', + test: is["L" /* isUnit */] + }, { + name: 'string', + test: is["I" /* isString */] + }, { + name: 'Chain', + test: is["h" /* isChain */] + }, { + name: 'Array', + test: is["b" /* isArray */] + }, { + name: 'Matrix', + test: is["v" /* isMatrix */] + }, { + name: 'DenseMatrix', + test: is["n" /* isDenseMatrix */] + }, { + name: 'SparseMatrix', + test: is["H" /* isSparseMatrix */] + }, { + name: 'Range', + test: is["D" /* isRange */] + }, { + name: 'Index', + test: is["t" /* isIndex */] + }, { + name: 'boolean', + test: is["g" /* isBoolean */] + }, { + name: 'ResultSet', + test: is["G" /* isResultSet */] + }, { + name: 'Help', + test: is["s" /* isHelp */] + }, { + name: 'function', + test: is["p" /* isFunction */] + }, { + name: 'Date', + test: is["m" /* isDate */] + }, { + name: 'RegExp', + test: is["F" /* isRegExp */] + }, { + name: 'null', + test: is["x" /* isNull */] + }, { + name: 'undefined', + test: is["K" /* isUndefined */] + }, { + name: 'AccessorNode', + test: is["a" /* isAccessorNode */] + }, { + name: 'ArrayNode', + test: is["c" /* isArrayNode */] + }, { + name: 'AssignmentNode', + test: is["d" /* isAssignmentNode */] + }, { + name: 'BlockNode', + test: is["f" /* isBlockNode */] + }, { + name: 'ConditionalNode', + test: is["k" /* isConditionalNode */] + }, { + name: 'ConstantNode', + test: is["l" /* isConstantNode */] + }, { + name: 'FunctionNode', + test: is["r" /* isFunctionNode */] + }, { + name: 'FunctionAssignmentNode', + test: is["q" /* isFunctionAssignmentNode */] + }, { + name: 'IndexNode', + test: is["u" /* isIndexNode */] + }, { + name: 'Node', + test: is["w" /* isNode */] + }, { + name: 'ObjectNode', + test: is["A" /* isObjectNode */] + }, { + name: 'OperatorNode', + test: is["B" /* isOperatorNode */] + }, { + name: 'ParenthesisNode', + test: is["C" /* isParenthesisNode */] + }, { + name: 'RangeNode', + test: is["E" /* isRangeNode */] + }, { + name: 'SymbolNode', + test: is["J" /* isSymbolNode */] + }, { + name: 'Object', + test: is["z" /* isObject */] + } // order 'Object' last, it matches on other classes too + ]; + typed.conversions = [{ + from: 'number', + to: 'BigNumber', + convert: function convert(x) { + if (!BigNumber) { + throwNoBignumber(x); + } // note: conversion from number to BigNumber can fail if x has >15 digits + + + if (Object(utils_number["f" /* digits */])(x) > 15) { + throw new TypeError('Cannot implicitly convert a number with >15 significant digits to BigNumber ' + '(value: ' + x + '). ' + 'Use function bignumber(x) to convert to BigNumber.'); + } + + return new BigNumber(x); + } + }, { + from: 'number', + to: 'Complex', + convert: function convert(x) { + if (!Complex) { + throwNoComplex(x); + } + + return new Complex(x, 0); + } + }, { + from: 'number', + to: 'string', + convert: function convert(x) { + return x + ''; + } + }, { + from: 'BigNumber', + to: 'Complex', + convert: function convert(x) { + if (!Complex) { + throwNoComplex(x); + } + + return new Complex(x.toNumber(), 0); + } + }, { + from: 'Fraction', + to: 'BigNumber', + convert: function convert(x) { + throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' + 'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.'); + } + }, { + from: 'Fraction', + to: 'Complex', + convert: function convert(x) { + if (!Complex) { + throwNoComplex(x); + } + + return new Complex(x.valueOf(), 0); + } + }, { + from: 'number', + to: 'Fraction', + convert: function convert(x) { + if (!Fraction) { + throwNoFraction(x); + } + + var f = new Fraction(x); + + if (f.valueOf() !== x) { + throw new TypeError('Cannot implicitly convert a number to a Fraction when there will be a loss of precision ' + '(value: ' + x + '). ' + 'Use function fraction(x) to convert to Fraction.'); + } + + return f; + } + }, { + // FIXME: add conversion from Fraction to number, for example for `sqrt(fraction(1,3))` + // from: 'Fraction', + // to: 'number', + // convert: function (x) { + // return x.valueOf() + // } + // }, { + from: 'string', + to: 'number', + convert: function convert(x) { + var n = Number(x); + + if (isNaN(n)) { + throw new Error('Cannot convert "' + x + '" to a number'); + } + + return n; + } + }, { + from: 'string', + to: 'BigNumber', + convert: function convert(x) { + if (!BigNumber) { + throwNoBignumber(x); + } + + try { + return new BigNumber(x); + } catch (err) { + throw new Error('Cannot convert "' + x + '" to BigNumber'); + } + } + }, { + from: 'string', + to: 'Fraction', + convert: function convert(x) { + if (!Fraction) { + throwNoFraction(x); + } + + try { + return new Fraction(x); + } catch (err) { + throw new Error('Cannot convert "' + x + '" to Fraction'); + } + } + }, { + from: 'string', + to: 'Complex', + convert: function convert(x) { + if (!Complex) { + throwNoComplex(x); + } + + try { + return new Complex(x); + } catch (err) { + throw new Error('Cannot convert "' + x + '" to Complex'); + } + } + }, { + from: 'boolean', + to: 'number', + convert: function convert(x) { + return +x; + } + }, { + from: 'boolean', + to: 'BigNumber', + convert: function convert(x) { + if (!BigNumber) { + throwNoBignumber(x); + } + + return new BigNumber(+x); + } + }, { + from: 'boolean', + to: 'Fraction', + convert: function convert(x) { + if (!Fraction) { + throwNoFraction(x); + } + + return new Fraction(+x); + } + }, { + from: 'boolean', + to: 'string', + convert: function convert(x) { + return String(x); + } + }, { + from: 'Array', + to: 'Matrix', + convert: function convert(array) { + if (!DenseMatrix) { + throwNoMatrix(); + } + + return new DenseMatrix(array); + } + }, { + from: 'Matrix', + to: 'Array', + convert: function convert(matrix) { + return matrix.valueOf(); + } + }]; + return typed; +}); + +function throwNoBignumber(x) { + throw new Error("Cannot convert value ".concat(x, " into a BigNumber: no class 'BigNumber' provided")); +} + +function throwNoComplex(x) { + throw new Error("Cannot convert value ".concat(x, " into a Complex number: no class 'Complex' provided")); +} + +function throwNoMatrix() { + throw new Error('Cannot convert array into a Matrix: no class \'DenseMatrix\' provided'); +} + +function throwNoFraction(x) { + throw new Error("Cannot convert value ".concat(x, " into a Fraction, no class 'Fraction' provided.")); +} +// CONCATENATED MODULE: ./src/type/resultset/ResultSet.js + +var ResultSet_name = 'ResultSet'; +var ResultSet_dependencies = []; +var createResultSet = /* #__PURE__ */Object(factory["a" /* factory */])(ResultSet_name, ResultSet_dependencies, function () { + /** + * A ResultSet contains a list or results + * @class ResultSet + * @param {Array} entries + * @constructor ResultSet + */ + function ResultSet(entries) { + if (!(this instanceof ResultSet)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.entries = entries || []; + } + /** + * Attach type information + */ + + + ResultSet.prototype.type = 'ResultSet'; + ResultSet.prototype.isResultSet = true; + /** + * Returns the array with results hold by this ResultSet + * @memberof ResultSet + * @returns {Array} entries + */ + + ResultSet.prototype.valueOf = function () { + return this.entries; + }; + /** + * Returns the stringified results of the ResultSet + * @memberof ResultSet + * @returns {string} string + */ + + + ResultSet.prototype.toString = function () { + return '[' + this.entries.join(', ') + ']'; + }; + /** + * Get a JSON representation of the ResultSet + * @memberof ResultSet + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "ResultSet", "entries": [...]}` + */ + + + ResultSet.prototype.toJSON = function () { + return { + mathjs: 'ResultSet', + entries: this.entries + }; + }; + /** + * Instantiate a ResultSet from a JSON object + * @memberof ResultSet + * @param {Object} json A JSON object structured as: + * `{"mathjs": "ResultSet", "entries": [...]}` + * @return {ResultSet} + */ + + + ResultSet.fromJSON = function (json) { + return new ResultSet(json.entries); + }; + + return ResultSet; +}, { + isClass: true +}); +// EXTERNAL MODULE: ./node_modules/decimal.js/decimal.js +var decimal = __webpack_require__(16); +var decimal_default = /*#__PURE__*/__webpack_require__.n(decimal); + +// CONCATENATED MODULE: ./src/type/bignumber/BigNumber.js + + +var BigNumber_name = 'BigNumber'; +var BigNumber_dependencies = ['?on', 'config']; +var createBigNumberClass = /* #__PURE__ */Object(factory["a" /* factory */])(BigNumber_name, BigNumber_dependencies, function (_ref) { + var on = _ref.on, + config = _ref.config; + var BigNumber = decimal_default.a.clone({ + precision: config.precision + }); + /** + * Attach type information + */ + + BigNumber.prototype.type = 'BigNumber'; + BigNumber.prototype.isBigNumber = true; + /** + * Get a JSON representation of a BigNumber containing + * type information + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "BigNumber", "value": "0.2"}` + */ + + BigNumber.prototype.toJSON = function () { + return { + mathjs: 'BigNumber', + value: this.toString() + }; + }; + /** + * Instantiate a BigNumber from a JSON object + * @param {Object} json a JSON object structured as: + * `{"mathjs": "BigNumber", "value": "0.2"}` + * @return {BigNumber} + */ + + + BigNumber.fromJSON = function (json) { + return new BigNumber(json.value); + }; + + if (on) { + // listen for changed in the configuration, automatically apply changed precision + on('config', function (curr, prev) { + if (curr.precision !== prev.precision) { + BigNumber.config({ + precision: curr.precision + }); + } + }); + } + + return BigNumber; +}, { + isClass: true +}); +// EXTERNAL MODULE: ./node_modules/complex.js/complex.js +var complex_js_complex = __webpack_require__(9); +var complex_default = /*#__PURE__*/__webpack_require__.n(complex_js_complex); + +// CONCATENATED MODULE: ./src/type/complex/Complex.js +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + + + + + +var Complex_name = 'Complex'; +var Complex_dependencies = []; +var createComplexClass = /* #__PURE__ */Object(factory["a" /* factory */])(Complex_name, Complex_dependencies, function () { + /** + * Attach type information + */ + complex_default.a.prototype.type = 'Complex'; + complex_default.a.prototype.isComplex = true; + /** + * Get a JSON representation of the complex number + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "Complex", "re": 2, "im": 3}` + */ + + complex_default.a.prototype.toJSON = function () { + return { + mathjs: 'Complex', + re: this.re, + im: this.im + }; + }; + /* + * Return the value of the complex number in polar notation + * The angle phi will be set in the interval of [-pi, pi]. + * @return {{r: number, phi: number}} Returns and object with properties r and phi. + */ + + + complex_default.a.prototype.toPolar = function () { + return { + r: this.abs(), + phi: this.arg() + }; + }; + /** + * Get a string representation of the complex number, + * with optional formatting options. + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @return {string} str + */ + + + complex_default.a.prototype.format = function (options) { + var str = ''; + var im = this.im; + var re = this.re; + var strRe = Object(utils_number["h" /* format */])(this.re, options); + var strIm = Object(utils_number["h" /* format */])(this.im, options); // round either re or im when smaller than the configured precision + + var precision = Object(is["y" /* isNumber */])(options) ? options : options ? options.precision : null; + + if (precision !== null) { + var epsilon = Math.pow(10, -precision); + + if (Math.abs(re / im) < epsilon) { + re = 0; + } + + if (Math.abs(im / re) < epsilon) { + im = 0; + } + } + + if (im === 0) { + // real value + str = strRe; + } else if (re === 0) { + // purely complex value + if (im === 1) { + str = 'i'; + } else if (im === -1) { + str = '-i'; + } else { + str = strIm + 'i'; + } + } else { + // complex value + if (im < 0) { + if (im === -1) { + str = strRe + ' - i'; + } else { + str = strRe + ' - ' + strIm.substring(1) + 'i'; + } + } else { + if (im === 1) { + str = strRe + ' + i'; + } else { + str = strRe + ' + ' + strIm + 'i'; + } + } + } + + return str; + }; + /** + * Create a complex number from polar coordinates + * + * Usage: + * + * Complex.fromPolar(r: number, phi: number) : Complex + * Complex.fromPolar({r: number, phi: number}) : Complex + * + * @param {*} args... + * @return {Complex} + */ + + + complex_default.a.fromPolar = function (args) { + switch (arguments.length) { + case 1: + { + var arg = arguments[0]; + + if (_typeof(arg) === 'object') { + return complex_default()(arg); + } else { + throw new TypeError('Input has to be an object with r and phi keys.'); + } + } + + case 2: + { + var r = arguments[0]; + var phi = arguments[1]; + + if (Object(is["y" /* isNumber */])(r)) { + if (Object(is["L" /* isUnit */])(phi) && phi.hasBase('ANGLE')) { + // convert unit to a number in radians + phi = phi.toNumber('rad'); + } + + if (Object(is["y" /* isNumber */])(phi)) { + return new complex_default.a({ + r: r, + phi: phi + }); + } + + throw new TypeError('Phi is not a number nor an angle unit.'); + } else { + throw new TypeError('Radius r is not a number.'); + } + } + + default: + throw new SyntaxError('Wrong number of arguments in function fromPolar'); + } + }; + + complex_default.a.prototype.valueOf = complex_default.a.prototype.toString; + /** + * Create a Complex number from a JSON object + * @param {Object} json A JSON Object structured as + * {"mathjs": "Complex", "re": 2, "im": 3} + * All properties are optional, default values + * for `re` and `im` are 0. + * @return {Complex} Returns a new Complex number + */ + + complex_default.a.fromJSON = function (json) { + return new complex_default.a(json); + }; + /** + * Compare two complex numbers, `a` and `b`: + * + * - Returns 1 when the real part of `a` is larger than the real part of `b` + * - Returns -1 when the real part of `a` is smaller than the real part of `b` + * - Returns 1 when the real parts are equal + * and the imaginary part of `a` is larger than the imaginary part of `b` + * - Returns -1 when the real parts are equal + * and the imaginary part of `a` is smaller than the imaginary part of `b` + * - Returns 0 when both real and imaginary parts are equal. + * + * @params {Complex} a + * @params {Complex} b + * @returns {number} Returns the comparison result: -1, 0, or 1 + */ + + + complex_default.a.compare = function (a, b) { + if (a.re > b.re) { + return 1; + } + + if (a.re < b.re) { + return -1; + } + + if (a.im > b.im) { + return 1; + } + + if (a.im < b.im) { + return -1; + } + + return 0; + }; + + return complex_default.a; +}, { + isClass: true +}); +// EXTERNAL MODULE: ./node_modules/fraction.js/fraction.js +var fraction_js_fraction = __webpack_require__(11); +var fraction_default = /*#__PURE__*/__webpack_require__.n(fraction_js_fraction); + +// CONCATENATED MODULE: ./src/type/fraction/Fraction.js + + +var Fraction_name = 'Fraction'; +var Fraction_dependencies = []; +var createFractionClass = /* #__PURE__ */Object(factory["a" /* factory */])(Fraction_name, Fraction_dependencies, function () { + /** + * Attach type information + */ + fraction_default.a.prototype.type = 'Fraction'; + fraction_default.a.prototype.isFraction = true; + /** + * Get a JSON representation of a Fraction containing type information + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "Fraction", "n": 3, "d": 8}` + */ + + fraction_default.a.prototype.toJSON = function () { + return { + mathjs: 'Fraction', + n: this.s * this.n, + d: this.d + }; + }; + /** + * Instantiate a Fraction from a JSON object + * @param {Object} json a JSON object structured as: + * `{"mathjs": "Fraction", "n": 3, "d": 8}` + * @return {BigNumber} + */ + + + fraction_default.a.fromJSON = function (json) { + return new fraction_default.a(json); + }; + + return fraction_default.a; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/matrix/Range.js + + + +var Range_name = 'Range'; +var Range_dependencies = []; +var createRangeClass = /* #__PURE__ */Object(factory["a" /* factory */])(Range_name, Range_dependencies, function () { + /** + * Create a range. A range has a start, step, and end, and contains functions + * to iterate over the range. + * + * A range can be constructed as: + * + * const range = new Range(start, end) + * const range = new Range(start, end, step) + * + * To get the result of the range: + * range.forEach(function (x) { + * console.log(x) + * }) + * range.map(function (x) { + * return math.sin(x) + * }) + * range.toArray() + * + * Example usage: + * + * const c = new Range(2, 6) // 2:1:5 + * c.toArray() // [2, 3, 4, 5] + * const d = new Range(2, -3, -1) // 2:-1:-2 + * d.toArray() // [2, 1, 0, -1, -2] + * + * @class Range + * @constructor Range + * @param {number} start included lower bound + * @param {number} end excluded upper bound + * @param {number} [step] step size, default value is 1 + */ + function Range(start, end, step) { + if (!(this instanceof Range)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + var hasStart = start !== null && start !== undefined; + var hasEnd = end !== null && end !== undefined; + var hasStep = step !== null && step !== undefined; + + if (hasStart) { + if (Object(is["e" /* isBigNumber */])(start)) { + start = start.toNumber(); + } else if (typeof start !== 'number') { + throw new TypeError('Parameter start must be a number'); + } + } + + if (hasEnd) { + if (Object(is["e" /* isBigNumber */])(end)) { + end = end.toNumber(); + } else if (typeof end !== 'number') { + throw new TypeError('Parameter end must be a number'); + } + } + + if (hasStep) { + if (Object(is["e" /* isBigNumber */])(step)) { + step = step.toNumber(); + } else if (typeof step !== 'number') { + throw new TypeError('Parameter step must be a number'); + } + } + + this.start = hasStart ? parseFloat(start) : 0; + this.end = hasEnd ? parseFloat(end) : 0; + this.step = hasStep ? parseFloat(step) : 1; + } + /** + * Attach type information + */ + + + Range.prototype.type = 'Range'; + Range.prototype.isRange = true; + /** + * Parse a string into a range, + * The string contains the start, optional step, and end, separated by a colon. + * If the string does not contain a valid range, null is returned. + * For example str='0:2:11'. + * @memberof Range + * @param {string} str + * @return {Range | null} range + */ + + Range.parse = function (str) { + if (typeof str !== 'string') { + return null; + } + + var args = str.split(':'); + var nums = args.map(function (arg) { + return parseFloat(arg); + }); + var invalid = nums.some(function (num) { + return isNaN(num); + }); + + if (invalid) { + return null; + } + + switch (nums.length) { + case 2: + return new Range(nums[0], nums[1]); + + case 3: + return new Range(nums[0], nums[2], nums[1]); + + default: + return null; + } + }; + /** + * Create a clone of the range + * @return {Range} clone + */ + + + Range.prototype.clone = function () { + return new Range(this.start, this.end, this.step); + }; + /** + * Retrieve the size of the range. + * Returns an array containing one number, the number of elements in the range. + * @memberof Range + * @returns {number[]} size + */ + + + Range.prototype.size = function () { + var len = 0; + var start = this.start; + var step = this.step; + var end = this.end; + var diff = end - start; + + if (Object(utils_number["n" /* sign */])(step) === Object(utils_number["n" /* sign */])(diff)) { + len = Math.ceil(diff / step); + } else if (diff === 0) { + len = 0; + } + + if (isNaN(len)) { + len = 0; + } + + return [len]; + }; + /** + * Calculate the minimum value in the range + * @memberof Range + * @return {number | undefined} min + */ + + + Range.prototype.min = function () { + var size = this.size()[0]; + + if (size > 0) { + if (this.step > 0) { + // positive step + return this.start; + } else { + // negative step + return this.start + (size - 1) * this.step; + } + } else { + return undefined; + } + }; + /** + * Calculate the maximum value in the range + * @memberof Range + * @return {number | undefined} max + */ + + + Range.prototype.max = function () { + var size = this.size()[0]; + + if (size > 0) { + if (this.step > 0) { + // positive step + return this.start + (size - 1) * this.step; + } else { + // negative step + return this.start; + } + } else { + return undefined; + } + }; + /** + * Execute a callback function for each value in the range. + * @memberof Range + * @param {function} callback The callback method is invoked with three + * parameters: the value of the element, the index + * of the element, and the Range being traversed. + */ + + + Range.prototype.forEach = function (callback) { + var x = this.start; + var step = this.step; + var end = this.end; + var i = 0; + + if (step > 0) { + while (x < end) { + callback(x, [i], this); + x += step; + i++; + } + } else if (step < 0) { + while (x > end) { + callback(x, [i], this); + x += step; + i++; + } + } + }; + /** + * Execute a callback function for each value in the Range, and return the + * results as an array + * @memberof Range + * @param {function} callback The callback method is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + * @returns {Array} array + */ + + + Range.prototype.map = function (callback) { + var array = []; + this.forEach(function (value, index, obj) { + array[index[0]] = callback(value, index, obj); + }); + return array; + }; + /** + * Create an Array with a copy of the Ranges data + * @memberof Range + * @returns {Array} array + */ + + + Range.prototype.toArray = function () { + var array = []; + this.forEach(function (value, index) { + array[index[0]] = value; + }); + return array; + }; + /** + * Get the primitive value of the Range, a one dimensional array + * @memberof Range + * @returns {Array} array + */ + + + Range.prototype.valueOf = function () { + // TODO: implement a caching mechanism for range.valueOf() + return this.toArray(); + }; + /** + * Get a string representation of the range, with optional formatting options. + * Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11' + * @memberof Range + * @param {Object | number | function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @returns {string} str + */ + + + Range.prototype.format = function (options) { + var str = Object(utils_number["h" /* format */])(this.start, options); + + if (this.step !== 1) { + str += ':' + Object(utils_number["h" /* format */])(this.step, options); + } + + str += ':' + Object(utils_number["h" /* format */])(this.end, options); + return str; + }; + /** + * Get a string representation of the range. + * @memberof Range + * @returns {string} + */ + + + Range.prototype.toString = function () { + return this.format(); + }; + /** + * Get a JSON representation of the range + * @memberof Range + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` + */ + + + Range.prototype.toJSON = function () { + return { + mathjs: 'Range', + start: this.start, + end: this.end, + step: this.step + }; + }; + /** + * Instantiate a Range from a JSON object + * @memberof Range + * @param {Object} json A JSON object structured as: + * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` + * @return {Range} + */ + + + Range.fromJSON = function (json) { + return new Range(json.start, json.end, json.step); + }; + + return Range; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/matrix/Matrix.js + +var Matrix_name = 'Matrix'; +var Matrix_dependencies = []; +var createMatrixClass = /* #__PURE__ */Object(factory["a" /* factory */])(Matrix_name, Matrix_dependencies, function () { + /** + * @constructor Matrix + * + * A Matrix is a wrapper around an Array. A matrix can hold a multi dimensional + * array. A matrix can be constructed as: + * + * let matrix = math.matrix(data) + * + * Matrix contains the functions to resize, get and set values, get the size, + * clone the matrix and to convert the matrix to a vector, array, or scalar. + * Furthermore, one can iterate over the matrix using map and forEach. + * The internal Array of the Matrix can be accessed using the function valueOf. + * + * Example usage: + * + * let matrix = math.matrix([[1, 2], [3, 4]]) + * matix.size() // [2, 2] + * matrix.resize([3, 2], 5) + * matrix.valueOf() // [[1, 2], [3, 4], [5, 5]] + * matrix.subset([1,2]) // 3 (indexes are zero-based) + * + */ + function Matrix() { + if (!(this instanceof Matrix)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + } + /** + * Attach type information + */ + + + Matrix.prototype.type = 'Matrix'; + Matrix.prototype.isMatrix = true; + /** + * Get the Matrix storage constructor for the given format. + * + * @param {string} format The Matrix storage format. + * + * @return {Function} The Matrix storage constructor. + */ + + Matrix.storage = function (format) { + // TODO: deprecated since v6.0.0. Clean up some day + throw new Error('Matrix.storage is deprecated since v6.0.0. ' + 'Use the factory function math.matrix instead.'); + }; + /** + * Get the storage format used by the matrix. + * + * Usage: + * const format = matrix.storage() // retrieve storage format + * + * @return {string} The storage format. + */ + + + Matrix.prototype.storage = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke storage on a Matrix interface'); + }; + /** + * Get the datatype of the data stored in the matrix. + * + * Usage: + * const format = matrix.datatype() // retrieve matrix datatype + * + * @return {string} The datatype. + */ + + + Matrix.prototype.datatype = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke datatype on a Matrix interface'); + }; + /** + * Create a new Matrix With the type of the current matrix instance + * @param {Array | Object} data + * @param {string} [datatype] + */ + + + Matrix.prototype.create = function (data, datatype) { + throw new Error('Cannot invoke create on a Matrix interface'); + }; + /** + * Get a subset of the matrix, or replace a subset of the matrix. + * + * Usage: + * const subset = matrix.subset(index) // retrieve subset + * const value = matrix.subset(index, replacement) // replace subset + * + * @param {Index} index + * @param {Array | Matrix | *} [replacement] + * @param {*} [defaultValue=0] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be filled with zeros. + */ + + + Matrix.prototype.subset = function (index, replacement, defaultValue) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke subset on a Matrix interface'); + }; + /** + * Get a single element from the matrix. + * @param {number[]} index Zero-based index + * @return {*} value + */ + + + Matrix.prototype.get = function (index) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke get on a Matrix interface'); + }; + /** + * Replace a single element in the matrix. + * @param {number[]} index Zero-based index + * @param {*} value + * @param {*} [defaultValue] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be left undefined. + * @return {Matrix} self + */ + + + Matrix.prototype.set = function (index, value, defaultValue) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke set on a Matrix interface'); + }; + /** + * Resize the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (resize in place). + * + * @param {number[]} size The new size the matrix should have. + * @param {*} [defaultValue=0] Default value, filled in on new entries. + * If not provided, the matrix elements will + * be filled with zeros. + * @param {boolean} [copy] Return a resized copy of the matrix + * + * @return {Matrix} The resized matrix + */ + + + Matrix.prototype.resize = function (size, defaultValue) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke resize on a Matrix interface'); + }; + /** + * Reshape the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (reshape in place). + * + * @param {number[]} size The new size the matrix should have. + * @param {boolean} [copy] Return a reshaped copy of the matrix + * + * @return {Matrix} The reshaped matrix + */ + + + Matrix.prototype.reshape = function (size, defaultValue) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke reshape on a Matrix interface'); + }; + /** + * Create a clone of the matrix + * @return {Matrix} clone + */ + + + Matrix.prototype.clone = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke clone on a Matrix interface'); + }; + /** + * Retrieve the size of the matrix. + * @returns {number[]} size + */ + + + Matrix.prototype.size = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke size on a Matrix interface'); + }; + /** + * Create a new matrix with the results of the callback function executed on + * each entry of the matrix. + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + * @param {boolean} [skipZeros] Invoke callback function for non-zero values only. + * + * @return {Matrix} matrix + */ + + + Matrix.prototype.map = function (callback, skipZeros) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke map on a Matrix interface'); + }; + /** + * Execute a callback function on each entry of the matrix. + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + */ + + + Matrix.prototype.forEach = function (callback) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke forEach on a Matrix interface'); + }; + /** + * Create an Array with a copy of the data of the Matrix + * @returns {Array} array + */ + + + Matrix.prototype.toArray = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke toArray on a Matrix interface'); + }; + /** + * Get the primitive value of the Matrix: a multidimensional array + * @returns {Array} array + */ + + + Matrix.prototype.valueOf = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke valueOf on a Matrix interface'); + }; + /** + * Get a string representation of the matrix, with optional formatting options. + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @returns {string} str + */ + + + Matrix.prototype.format = function (options) { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke format on a Matrix interface'); + }; + /** + * Get a string representation of the matrix + * @returns {string} str + */ + + + Matrix.prototype.toString = function () { + // must be implemented by each of the Matrix implementations + throw new Error('Cannot invoke toString on a Matrix interface'); + }; + + return Matrix; +}, { + isClass: true +}); +// EXTERNAL MODULE: ./src/utils/array.js +var utils_array = __webpack_require__(2); + +// EXTERNAL MODULE: ./src/utils/string.js + 1 modules +var utils_string = __webpack_require__(5); + +// EXTERNAL MODULE: ./src/utils/object.js +var utils_object = __webpack_require__(3); + +// EXTERNAL MODULE: ./src/error/DimensionError.js +var DimensionError = __webpack_require__(6); + +// CONCATENATED MODULE: ./src/type/matrix/DenseMatrix.js + + + + + + + +var DenseMatrix_name = 'DenseMatrix'; +var DenseMatrix_dependencies = ['Matrix']; +var createDenseMatrixClass = /* #__PURE__ */Object(factory["a" /* factory */])(DenseMatrix_name, DenseMatrix_dependencies, function (_ref) { + var Matrix = _ref.Matrix; + + /** + * Dense Matrix implementation. A regular, dense matrix, supporting multi-dimensional matrices. This is the default matrix type. + * @class DenseMatrix + */ + function DenseMatrix(data, datatype) { + if (!(this instanceof DenseMatrix)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (datatype && !Object(is["I" /* isString */])(datatype)) { + throw new Error('Invalid datatype: ' + datatype); + } + + if (Object(is["v" /* isMatrix */])(data)) { + // check data is a DenseMatrix + if (data.type === 'DenseMatrix') { + // clone data & size + this._data = Object(utils_object["a" /* clone */])(data._data); + this._size = Object(utils_object["a" /* clone */])(data._size); + this._datatype = datatype || data._datatype; + } else { + // build data from existing matrix + this._data = data.toArray(); + this._size = data.size(); + this._datatype = datatype || data._datatype; + } + } else if (data && Object(is["b" /* isArray */])(data.data) && Object(is["b" /* isArray */])(data.size)) { + // initialize fields from JSON representation + this._data = data.data; + this._size = data.size; // verify the dimensions of the array + + Object(utils_array["r" /* validate */])(this._data, this._size); + this._datatype = datatype || data.datatype; + } else if (Object(is["b" /* isArray */])(data)) { + // replace nested Matrices with Arrays + this._data = preprocess(data); // get the dimensions of the array + + this._size = Object(utils_array["a" /* arraySize */])(this._data); // verify the dimensions of the array, TODO: compute size while processing array + + Object(utils_array["r" /* validate */])(this._data, this._size); // data type unknown + + this._datatype = datatype; + } else if (data) { + // unsupported type + throw new TypeError('Unsupported type of data (' + Object(is["M" /* typeOf */])(data) + ')'); + } else { + // nothing provided + this._data = []; + this._size = [0]; + this._datatype = datatype; + } + } + + DenseMatrix.prototype = new Matrix(); + /** + * Create a new DenseMatrix + */ + + DenseMatrix.prototype.createDenseMatrix = function (data, datatype) { + return new DenseMatrix(data, datatype); + }; + /** + * Attach type information + */ + + + DenseMatrix.prototype.type = 'DenseMatrix'; + DenseMatrix.prototype.isDenseMatrix = true; + /** + * Get the matrix type + * + * Usage: + * const matrixType = matrix.getDataType() // retrieves the matrix type + * + * @memberOf DenseMatrix + * @return {string} type information; if multiple types are found from the Matrix, it will return "mixed" + */ + + DenseMatrix.prototype.getDataType = function () { + return Object(utils_array["h" /* getArrayDataType */])(this._data, is["M" /* typeOf */]); + }; + /** + * Get the storage format used by the matrix. + * + * Usage: + * const format = matrix.storage() // retrieve storage format + * + * @memberof DenseMatrix + * @return {string} The storage format. + */ + + + DenseMatrix.prototype.storage = function () { + return 'dense'; + }; + /** + * Get the datatype of the data stored in the matrix. + * + * Usage: + * const format = matrix.datatype() // retrieve matrix datatype + * + * @memberof DenseMatrix + * @return {string} The datatype. + */ + + + DenseMatrix.prototype.datatype = function () { + return this._datatype; + }; + /** + * Create a new DenseMatrix + * @memberof DenseMatrix + * @param {Array} data + * @param {string} [datatype] + */ + + + DenseMatrix.prototype.create = function (data, datatype) { + return new DenseMatrix(data, datatype); + }; + /** + * Get a subset of the matrix, or replace a subset of the matrix. + * + * Usage: + * const subset = matrix.subset(index) // retrieve subset + * const value = matrix.subset(index, replacement) // replace subset + * + * @memberof DenseMatrix + * @param {Index} index + * @param {Array | Matrix | *} [replacement] + * @param {*} [defaultValue=0] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be filled with zeros. + */ + + + DenseMatrix.prototype.subset = function (index, replacement, defaultValue) { + switch (arguments.length) { + case 1: + return _get(this, index); + // intentional fall through + + case 2: + case 3: + return _set(this, index, replacement, defaultValue); + + default: + throw new SyntaxError('Wrong number of arguments'); + } + }; + /** + * Get a single element from the matrix. + * @memberof DenseMatrix + * @param {number[]} index Zero-based index + * @return {*} value + */ + + + DenseMatrix.prototype.get = function (index) { + if (!Object(is["b" /* isArray */])(index)) { + throw new TypeError('Array expected'); + } + + if (index.length !== this._size.length) { + throw new DimensionError["a" /* DimensionError */](index.length, this._size.length); + } // check index + + + for (var x = 0; x < index.length; x++) { + Object(utils_array["s" /* validateIndex */])(index[x], this._size[x]); + } + + var data = this._data; + + for (var i = 0, ii = index.length; i < ii; i++) { + var indexI = index[i]; + Object(utils_array["s" /* validateIndex */])(indexI, data.length); + data = data[indexI]; + } + + return data; + }; + /** + * Replace a single element in the matrix. + * @memberof DenseMatrix + * @param {number[]} index Zero-based index + * @param {*} value + * @param {*} [defaultValue] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be left undefined. + * @return {DenseMatrix} self + */ + + + DenseMatrix.prototype.set = function (index, value, defaultValue) { + if (!Object(is["b" /* isArray */])(index)) { + throw new TypeError('Array expected'); + } + + if (index.length < this._size.length) { + throw new DimensionError["a" /* DimensionError */](index.length, this._size.length, '<'); + } + + var i, ii, indexI; // enlarge matrix when needed + + var size = index.map(function (i) { + return i + 1; + }); + + _fit(this, size, defaultValue); // traverse over the dimensions + + + var data = this._data; + + for (i = 0, ii = index.length - 1; i < ii; i++) { + indexI = index[i]; + Object(utils_array["s" /* validateIndex */])(indexI, data.length); + data = data[indexI]; + } // set new value + + + indexI = index[index.length - 1]; + Object(utils_array["s" /* validateIndex */])(indexI, data.length); + data[indexI] = value; + return this; + }; + /** + * Get a submatrix of this matrix + * @memberof DenseMatrix + * @param {DenseMatrix} matrix + * @param {Index} index Zero-based index + * @private + */ + + + function _get(matrix, index) { + if (!Object(is["t" /* isIndex */])(index)) { + throw new TypeError('Invalid index'); + } + + var isScalar = index.isScalar(); + + if (isScalar) { + // return a scalar + return matrix.get(index.min()); + } else { + // validate dimensions + var size = index.size(); + + if (size.length !== matrix._size.length) { + throw new DimensionError["a" /* DimensionError */](size.length, matrix._size.length); + } // validate if any of the ranges in the index is out of range + + + var min = index.min(); + var max = index.max(); + + for (var i = 0, ii = matrix._size.length; i < ii; i++) { + Object(utils_array["s" /* validateIndex */])(min[i], matrix._size[i]); + Object(utils_array["s" /* validateIndex */])(max[i], matrix._size[i]); + } // retrieve submatrix + // TODO: more efficient when creating an empty matrix and setting _data and _size manually + + + return new DenseMatrix(_getSubmatrix(matrix._data, index, size.length, 0), matrix._datatype); + } + } + /** + * Recursively get a submatrix of a multi dimensional matrix. + * Index is not checked for correct number or length of dimensions. + * @memberof DenseMatrix + * @param {Array} data + * @param {Index} index + * @param {number} dims Total number of dimensions + * @param {number} dim Current dimension + * @return {Array} submatrix + * @private + */ + + + function _getSubmatrix(data, index, dims, dim) { + var last = dim === dims - 1; + var range = index.dimension(dim); + + if (last) { + return range.map(function (i) { + Object(utils_array["s" /* validateIndex */])(i, data.length); + return data[i]; + }).valueOf(); + } else { + return range.map(function (i) { + Object(utils_array["s" /* validateIndex */])(i, data.length); + var child = data[i]; + return _getSubmatrix(child, index, dims, dim + 1); + }).valueOf(); + } + } + /** + * Replace a submatrix in this matrix + * Indexes are zero-based. + * @memberof DenseMatrix + * @param {DenseMatrix} matrix + * @param {Index} index + * @param {DenseMatrix | Array | *} submatrix + * @param {*} defaultValue Default value, filled in on new entries when + * the matrix is resized. + * @return {DenseMatrix} matrix + * @private + */ + + + function _set(matrix, index, submatrix, defaultValue) { + if (!index || index.isIndex !== true) { + throw new TypeError('Invalid index'); + } // get index size and check whether the index contains a single value + + + var iSize = index.size(); + var isScalar = index.isScalar(); // calculate the size of the submatrix, and convert it into an Array if needed + + var sSize; + + if (Object(is["v" /* isMatrix */])(submatrix)) { + sSize = submatrix.size(); + submatrix = submatrix.valueOf(); + } else { + sSize = Object(utils_array["a" /* arraySize */])(submatrix); + } + + if (isScalar) { + // set a scalar + // check whether submatrix is a scalar + if (sSize.length !== 0) { + throw new TypeError('Scalar expected'); + } + + matrix.set(index.min(), submatrix, defaultValue); + } else { + // set a submatrix + // validate dimensions + if (iSize.length < matrix._size.length) { + throw new DimensionError["a" /* DimensionError */](iSize.length, matrix._size.length, '<'); + } + + if (sSize.length < iSize.length) { + // calculate number of missing outer dimensions + var i = 0; + var outer = 0; + + while (iSize[i] === 1 && sSize[i] === 1) { + i++; + } + + while (iSize[i] === 1) { + outer++; + i++; + } // unsqueeze both outer and inner dimensions + + + submatrix = Object(utils_array["q" /* unsqueeze */])(submatrix, iSize.length, outer, sSize); + } // check whether the size of the submatrix matches the index size + + + if (!Object(utils_object["d" /* deepStrictEqual */])(iSize, sSize)) { + throw new DimensionError["a" /* DimensionError */](iSize, sSize, '>'); + } // enlarge matrix when needed + + + var size = index.max().map(function (i) { + return i + 1; + }); + + _fit(matrix, size, defaultValue); // insert the sub matrix + + + var dims = iSize.length; + var dim = 0; + + _setSubmatrix(matrix._data, index, submatrix, dims, dim); + } + + return matrix; + } + /** + * Replace a submatrix of a multi dimensional matrix. + * @memberof DenseMatrix + * @param {Array} data + * @param {Index} index + * @param {Array} submatrix + * @param {number} dims Total number of dimensions + * @param {number} dim + * @private + */ + + + function _setSubmatrix(data, index, submatrix, dims, dim) { + var last = dim === dims - 1; + var range = index.dimension(dim); + + if (last) { + range.forEach(function (dataIndex, subIndex) { + Object(utils_array["s" /* validateIndex */])(dataIndex); + data[dataIndex] = submatrix[subIndex[0]]; + }); + } else { + range.forEach(function (dataIndex, subIndex) { + Object(utils_array["s" /* validateIndex */])(dataIndex); + + _setSubmatrix(data[dataIndex], index, submatrix[subIndex[0]], dims, dim + 1); + }); + } + } + /** + * Resize the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (resize in place). + * + * @memberof DenseMatrix + * @param {number[]} size The new size the matrix should have. + * @param {*} [defaultValue=0] Default value, filled in on new entries. + * If not provided, the matrix elements will + * be filled with zeros. + * @param {boolean} [copy] Return a resized copy of the matrix + * + * @return {Matrix} The resized matrix + */ + + + DenseMatrix.prototype.resize = function (size, defaultValue, copy) { + // validate arguments + if (!Object(is["b" /* isArray */])(size)) { + throw new TypeError('Array expected'); + } // matrix to resize + + + var m = copy ? this.clone() : this; // resize matrix + + return _resize(m, size, defaultValue); + }; + + function _resize(matrix, size, defaultValue) { + // check size + if (size.length === 0) { + // first value in matrix + var v = matrix._data; // go deep + + while (Object(is["b" /* isArray */])(v)) { + v = v[0]; + } + + return v; + } // resize matrix + + + matrix._size = size.slice(0); // copy the array + + matrix._data = Object(utils_array["o" /* resize */])(matrix._data, matrix._size, defaultValue); // return matrix + + return matrix; + } + /** + * Reshape the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (reshape in place). + * + * NOTE: This might be better suited to copy by default, instead of modifying + * in place. For now, it operates in place to remain consistent with + * resize(). + * + * @memberof DenseMatrix + * @param {number[]} size The new size the matrix should have. + * @param {boolean} [copy] Return a reshaped copy of the matrix + * + * @return {Matrix} The reshaped matrix + */ + + + DenseMatrix.prototype.reshape = function (size, copy) { + var m = copy ? this.clone() : this; + m._data = Object(utils_array["n" /* reshape */])(m._data, size); + m._size = size.slice(0); + return m; + }; + /** + * Enlarge the matrix when it is smaller than given size. + * If the matrix is larger or equal sized, nothing is done. + * @memberof DenseMatrix + * @param {DenseMatrix} matrix The matrix to be resized + * @param {number[]} size + * @param {*} defaultValue Default value, filled in on new entries. + * @private + */ + + + function _fit(matrix, size, defaultValue) { + var // copy the array + newSize = matrix._size.slice(0); + + var changed = false; // add dimensions when needed + + while (newSize.length < size.length) { + newSize.push(0); + changed = true; + } // enlarge size when needed + + + for (var i = 0, ii = size.length; i < ii; i++) { + if (size[i] > newSize[i]) { + newSize[i] = size[i]; + changed = true; + } + } + + if (changed) { + // resize only when size is changed + _resize(matrix, newSize, defaultValue); + } + } + /** + * Create a clone of the matrix + * @memberof DenseMatrix + * @return {DenseMatrix} clone + */ + + + DenseMatrix.prototype.clone = function () { + var m = new DenseMatrix({ + data: Object(utils_object["a" /* clone */])(this._data), + size: Object(utils_object["a" /* clone */])(this._size), + datatype: this._datatype + }); + return m; + }; + /** + * Retrieve the size of the matrix. + * @memberof DenseMatrix + * @returns {number[]} size + */ + + + DenseMatrix.prototype.size = function () { + return this._size.slice(0); // return a clone of _size + }; + /** + * Create a new matrix with the results of the callback function executed on + * each entry of the matrix. + * @memberof DenseMatrix + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + * + * @return {DenseMatrix} matrix + */ + + + DenseMatrix.prototype.map = function (callback) { + // matrix instance + var me = this; + + var recurse = function recurse(value, index) { + if (Object(is["b" /* isArray */])(value)) { + return value.map(function (child, i) { + return recurse(child, index.concat(i)); + }); + } else { + return callback(value, index, me); + } + }; // determine the new datatype when the original matrix has datatype defined + // TODO: should be done in matrix constructor instead + + + var data = recurse(this._data, []); + var datatype = this._datatype !== undefined ? Object(utils_array["h" /* getArrayDataType */])(data, is["M" /* typeOf */]) : undefined; + return new DenseMatrix(data, datatype); + }; + /** + * Execute a callback function on each entry of the matrix. + * @memberof DenseMatrix + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + */ + + + DenseMatrix.prototype.forEach = function (callback) { + // matrix instance + var me = this; + + var recurse = function recurse(value, index) { + if (Object(is["b" /* isArray */])(value)) { + value.forEach(function (child, i) { + recurse(child, index.concat(i)); + }); + } else { + callback(value, index, me); + } + }; + + recurse(this._data, []); + }; + /** + * Create an Array with a copy of the data of the DenseMatrix + * @memberof DenseMatrix + * @returns {Array} array + */ + + + DenseMatrix.prototype.toArray = function () { + return Object(utils_object["a" /* clone */])(this._data); + }; + /** + * Get the primitive value of the DenseMatrix: a multidimensional array + * @memberof DenseMatrix + * @returns {Array} array + */ + + + DenseMatrix.prototype.valueOf = function () { + return this._data; + }; + /** + * Get a string representation of the matrix, with optional formatting options. + * @memberof DenseMatrix + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @returns {string} str + */ + + + DenseMatrix.prototype.format = function (options) { + return Object(utils_string["d" /* format */])(this._data, options); + }; + /** + * Get a string representation of the matrix + * @memberof DenseMatrix + * @returns {string} str + */ + + + DenseMatrix.prototype.toString = function () { + return Object(utils_string["d" /* format */])(this._data); + }; + /** + * Get a JSON representation of the matrix + * @memberof DenseMatrix + * @returns {Object} + */ + + + DenseMatrix.prototype.toJSON = function () { + return { + mathjs: 'DenseMatrix', + data: this._data, + size: this._size, + datatype: this._datatype + }; + }; + /** + * Get the kth Matrix diagonal. + * + * @memberof DenseMatrix + * @param {number | BigNumber} [k=0] The kth diagonal where the vector will retrieved. + * + * @returns {Matrix} The matrix with the diagonal values. + */ + + + DenseMatrix.prototype.diagonal = function (k) { + // validate k if any + if (k) { + // convert BigNumber to a number + if (Object(is["e" /* isBigNumber */])(k)) { + k = k.toNumber(); + } // is must be an integer + + + if (!Object(is["y" /* isNumber */])(k) || !Object(utils_number["i" /* isInteger */])(k)) { + throw new TypeError('The parameter k must be an integer number'); + } + } else { + // default value + k = 0; + } + + var kSuper = k > 0 ? k : 0; + var kSub = k < 0 ? -k : 0; // rows & columns + + var rows = this._size[0]; + var columns = this._size[1]; // number diagonal values + + var n = Math.min(rows - kSub, columns - kSuper); // x is a matrix get diagonal from matrix + + var data = []; // loop rows + + for (var i = 0; i < n; i++) { + data[i] = this._data[i + kSub][i + kSuper]; + } // create DenseMatrix + + + return new DenseMatrix({ + data: data, + size: [n], + datatype: this._datatype + }); + }; + /** + * Create a diagonal matrix. + * + * @memberof DenseMatrix + * @param {Array} size The matrix size. + * @param {number | Matrix | Array } value The values for the diagonal. + * @param {number | BigNumber} [k=0] The kth diagonal where the vector will be filled in. + * @param {number} [defaultValue] The default value for non-diagonal + * @param {string} [datatype] The datatype for the diagonal + * + * @returns {DenseMatrix} + */ + + + DenseMatrix.diagonal = function (size, value, k, defaultValue) { + if (!Object(is["b" /* isArray */])(size)) { + throw new TypeError('Array expected, size parameter'); + } + + if (size.length !== 2) { + throw new Error('Only two dimensions matrix are supported'); + } // map size & validate + + + size = size.map(function (s) { + // check it is a big number + if (Object(is["e" /* isBigNumber */])(s)) { + // convert it + s = s.toNumber(); + } // validate arguments + + + if (!Object(is["y" /* isNumber */])(s) || !Object(utils_number["i" /* isInteger */])(s) || s < 1) { + throw new Error('Size values must be positive integers'); + } + + return s; + }); // validate k if any + + if (k) { + // convert BigNumber to a number + if (Object(is["e" /* isBigNumber */])(k)) { + k = k.toNumber(); + } // is must be an integer + + + if (!Object(is["y" /* isNumber */])(k) || !Object(utils_number["i" /* isInteger */])(k)) { + throw new TypeError('The parameter k must be an integer number'); + } + } else { + // default value + k = 0; + } + + var kSuper = k > 0 ? k : 0; + var kSub = k < 0 ? -k : 0; // rows and columns + + var rows = size[0]; + var columns = size[1]; // number of non-zero items + + var n = Math.min(rows - kSub, columns - kSuper); // value extraction function + + var _value; // check value + + + if (Object(is["b" /* isArray */])(value)) { + // validate array + if (value.length !== n) { + // number of values in array must be n + throw new Error('Invalid value array length'); + } // define function + + + _value = function _value(i) { + // return value @ i + return value[i]; + }; + } else if (Object(is["v" /* isMatrix */])(value)) { + // matrix size + var ms = value.size(); // validate matrix + + if (ms.length !== 1 || ms[0] !== n) { + // number of values in array must be n + throw new Error('Invalid matrix length'); + } // define function + + + _value = function _value(i) { + // return value @ i + return value.get([i]); + }; + } else { + // define function + _value = function _value() { + // return value + return value; + }; + } // discover default value if needed + + + if (!defaultValue) { + // check first value in array + defaultValue = Object(is["e" /* isBigNumber */])(_value(0)) ? _value(0).mul(0) // trick to create a BigNumber with value zero + : 0; + } // empty array + + + var data = []; // check we need to resize array + + if (size.length > 0) { + // resize array + data = Object(utils_array["o" /* resize */])(data, size, defaultValue); // fill diagonal + + for (var d = 0; d < n; d++) { + data[d + kSub][d + kSuper] = _value(d); + } + } // create DenseMatrix + + + return new DenseMatrix({ + data: data, + size: [rows, columns] + }); + }; + /** + * Generate a matrix from a JSON object + * @memberof DenseMatrix + * @param {Object} json An object structured like + * `{"mathjs": "DenseMatrix", data: [], size: []}`, + * where mathjs is optional + * @returns {DenseMatrix} + */ + + + DenseMatrix.fromJSON = function (json) { + return new DenseMatrix(json); + }; + /** + * Swap rows i and j in Matrix. + * + * @memberof DenseMatrix + * @param {number} i Matrix row index 1 + * @param {number} j Matrix row index 2 + * + * @return {Matrix} The matrix reference + */ + + + DenseMatrix.prototype.swapRows = function (i, j) { + // check index + if (!Object(is["y" /* isNumber */])(i) || !Object(utils_number["i" /* isInteger */])(i) || !Object(is["y" /* isNumber */])(j) || !Object(utils_number["i" /* isInteger */])(j)) { + throw new Error('Row index must be positive integers'); + } // check dimensions + + + if (this._size.length !== 2) { + throw new Error('Only two dimensional matrix is supported'); + } // validate index + + + Object(utils_array["s" /* validateIndex */])(i, this._size[0]); + Object(utils_array["s" /* validateIndex */])(j, this._size[0]); // swap rows + + DenseMatrix._swapRows(i, j, this._data); // return current instance + + + return this; + }; + /** + * Swap rows i and j in Dense Matrix data structure. + * + * @param {number} i Matrix row index 1 + * @param {number} j Matrix row index 2 + * @param {Array} data Matrix data + */ + + + DenseMatrix._swapRows = function (i, j, data) { + // swap values i <-> j + var vi = data[i]; + data[i] = data[j]; + data[j] = vi; + }; + /** + * Preprocess data, which can be an Array or DenseMatrix with nested Arrays and + * Matrices. Replaces all nested Matrices with Arrays + * @memberof DenseMatrix + * @param {Array} data + * @return {Array} data + */ + + + function preprocess(data) { + for (var i = 0, ii = data.length; i < ii; i++) { + var elem = data[i]; + + if (Object(is["b" /* isArray */])(elem)) { + data[i] = preprocess(elem); + } else if (elem && elem.isMatrix === true) { + data[i] = preprocess(elem.valueOf()); + } + } + + return data; + } + + return DenseMatrix; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/function/utils/clone.js + + +var clone_name = 'clone'; +var clone_dependencies = ['typed']; +var createClone = /* #__PURE__ */Object(factory["a" /* factory */])(clone_name, clone_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Clone an object. + * + * Syntax: + * + * math.clone(x) + * + * Examples: + * + * math.clone(3.5) // returns number 3.5 + * math.clone(math.complex('2-4i') // returns Complex 2 - 4i + * math.clone(math.unit(45, 'deg')) // returns Unit 45 deg + * math.clone([[1, 2], [3, 4]]) // returns Array [[1, 2], [3, 4]] + * math.clone("hello world") // returns string "hello world" + * + * @param {*} x Object to be cloned + * @return {*} A clone of object x + */ + return typed(clone_name, { + any: utils_object["a" /* clone */] + }); +}); +// EXTERNAL MODULE: ./src/error/IndexError.js +var IndexError = __webpack_require__(10); + +// CONCATENATED MODULE: ./src/utils/collection.js + + + +/** + * Test whether an array contains collections + * @param {Array} array + * @returns {boolean} Returns true when the array contains one or multiple + * collections (Arrays or Matrices). Returns false otherwise. + */ + +function containsCollections(array) { + for (var i = 0; i < array.length; i++) { + if (Object(is["i" /* isCollection */])(array[i])) { + return true; + } + } + + return false; +} +/** + * Recursively loop over all elements in a given multi dimensional array + * and invoke the callback on each of the elements. + * @param {Array | Matrix} array + * @param {Function} callback The callback method is invoked with one + * parameter: the current element in the array + */ + +function deepForEach(array, callback) { + if (Object(is["v" /* isMatrix */])(array)) { + array = array.valueOf(); + } + + for (var i = 0, ii = array.length; i < ii; i++) { + var value = array[i]; + + if (Array.isArray(value)) { + deepForEach(value, callback); + } else { + callback(value); + } + } +} +/** + * Execute the callback function element wise for each element in array and any + * nested array + * Returns an array with the results + * @param {Array | Matrix} array + * @param {Function} callback The callback is called with two parameters: + * value1 and value2, which contain the current + * element of both arrays. + * @param {boolean} [skipZeros] Invoke callback function for non-zero values only. + * + * @return {Array | Matrix} res + */ + +function deepMap(array, callback, skipZeros) { + if (array && typeof array.map === 'function') { + // TODO: replace array.map with a for loop to improve performance + return array.map(function (x) { + return deepMap(x, callback, skipZeros); + }); + } else { + return callback(array); + } +} +/** + * Reduce a given matrix or array to a new matrix or + * array with one less dimension, applying the given + * callback in the selected dimension. + * @param {Array | Matrix} mat + * @param {number} dim + * @param {Function} callback + * @return {Array | Matrix} res + */ + +function reduce(mat, dim, callback) { + var size = Array.isArray(mat) ? Object(utils_array["a" /* arraySize */])(mat) : mat.size(); + + if (dim < 0 || dim >= size.length) { + // TODO: would be more clear when throwing a DimensionError here + throw new IndexError["a" /* IndexError */](dim, size.length); + } + + if (Object(is["v" /* isMatrix */])(mat)) { + return mat.create(_reduce(mat.valueOf(), dim, callback)); + } else { + return _reduce(mat, dim, callback); + } +} +/** + * Recursively reduce a matrix + * @param {Array} mat + * @param {number} dim + * @param {Function} callback + * @returns {Array} ret + * @private + */ + +function _reduce(mat, dim, callback) { + var i, ret, val, tran; + + if (dim <= 0) { + if (!Array.isArray(mat[0])) { + val = mat[0]; + + for (i = 1; i < mat.length; i++) { + val = callback(val, mat[i]); + } + + return val; + } else { + tran = _switch(mat); + ret = []; + + for (i = 0; i < tran.length; i++) { + ret[i] = _reduce(tran[i], dim - 1, callback); + } + + return ret; + } + } else { + ret = []; + + for (i = 0; i < mat.length; i++) { + ret[i] = _reduce(mat[i], dim - 1, callback); + } + + return ret; + } +} +/** + * Transpose a matrix + * @param {Array} mat + * @returns {Array} ret + * @private + */ + + +function _switch(mat) { + var I = mat.length; + var J = mat[0].length; + var i, j; + var ret = []; + + for (j = 0; j < J; j++) { + var tmp = []; + + for (i = 0; i < I; i++) { + tmp.push(mat[i][j]); + } + + ret.push(tmp); + } + + return ret; +} // TODO: document function scatter + + +function scatter(a, j, w, x, u, mark, cindex, f, inverse, update, value) { + // a arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; // vars + + var k, k0, k1, i; // check we need to process values (pattern matrix) + + if (x) { + // values in j + for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + i = aindex[k]; // check value exists in current j + + if (w[i] !== mark) { + // i is new entry in j + w[i] = mark; // add i to pattern of C + + cindex.push(i); // x(i) = A, check we need to call function this time + + if (update) { + // copy value to workspace calling callback function + x[i] = inverse ? f(avalues[k], value) : f(value, avalues[k]); // function was called on current row + + u[i] = mark; + } else { + // copy value to workspace + x[i] = avalues[k]; + } + } else { + // i exists in C already + x[i] = inverse ? f(avalues[k], x[i]) : f(x[i], avalues[k]); // function was called on current row + + u[i] = mark; + } + } + } else { + // values in j + for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + i = aindex[k]; // check value exists in current j + + if (w[i] !== mark) { + // i is new entry in j + w[i] = mark; // add i to pattern of C + + cindex.push(i); + } else { + // indicate function was called on current row + u[i] = mark; + } + } + } +} +// CONCATENATED MODULE: ./src/function/utils/isInteger.js + + + +var isInteger_name = 'isInteger'; +var isInteger_dependencies = ['typed']; +var createIsInteger = /* #__PURE__ */Object(factory["a" /* factory */])(isInteger_name, isInteger_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is an integer number. + * The function supports `number`, `BigNumber`, and `Fraction`. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isInteger(x) + * + * Examples: + * + * math.isInteger(2) // returns true + * math.isInteger(0) // returns true + * math.isInteger(0.5) // returns false + * math.isInteger(math.bignumber(500)) // returns true + * math.isInteger(math.fraction(4)) // returns true + * math.isInteger('3') // returns true + * math.isInteger([3, 0.5, -2]) // returns [true, false, true] + * math.isInteger(math.complex('2-4i') // throws an error + * + * See also: + * + * isNumeric, isPositive, isNegative, isZero + * + * @param {number | BigNumber | Fraction | Array | Matrix} x Value to be tested + * @return {boolean} Returns true when `x` contains a numeric, integer value. + * Throws an error in case of an unknown data type. + */ + var isInteger = typed(isInteger_name, { + number: utils_number["i" /* isInteger */], + // TODO: what to do with isInteger(add(0.1, 0.2)) ? + BigNumber: function BigNumber(x) { + return x.isInt(); + }, + Fraction: function Fraction(x) { + return x.d === 1 && isFinite(x.n); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, isInteger); + } + }); + return isInteger; +}); +// CONCATENATED MODULE: ./src/plain/number/utils.js + +var utils_n1 = 'number'; +function isIntegerNumber(x) { + return Object(utils_number["i" /* isInteger */])(x); +} +isIntegerNumber.signature = utils_n1; +function isNegativeNumber(x) { + return x < 0; +} +isNegativeNumber.signature = utils_n1; +function isPositiveNumber(x) { + return x > 0; +} +isPositiveNumber.signature = utils_n1; +function isZeroNumber(x) { + return x === 0; +} +isZeroNumber.signature = utils_n1; +function isNaNNumber(x) { + return Number.isNaN(x); +} +isNaNNumber.signature = utils_n1; +// CONCATENATED MODULE: ./src/function/utils/isNegative.js + + + +var isNegative_name = 'isNegative'; +var isNegative_dependencies = ['typed']; +var createIsNegative = /* #__PURE__ */Object(factory["a" /* factory */])(isNegative_name, isNegative_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is negative: smaller than zero. + * The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isNegative(x) + * + * Examples: + * + * math.isNegative(3) // returns false + * math.isNegative(-2) // returns true + * math.isNegative(0) // returns false + * math.isNegative(-0) // returns false + * math.isNegative(math.bignumber(2)) // returns false + * math.isNegative(math.fraction(-2, 5)) // returns true + * math.isNegative('-2') // returns true + * math.isNegative([2, 0, -3]') // returns [false, false, true] + * + * See also: + * + * isNumeric, isPositive, isZero, isInteger + * + * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested + * @return {boolean} Returns true when `x` is larger than zero. + * Throws an error in case of an unknown data type. + */ + var isNegative = typed(isNegative_name, { + number: isNegativeNumber, + BigNumber: function BigNumber(x) { + return x.isNeg() && !x.isZero() && !x.isNaN(); + }, + Fraction: function Fraction(x) { + return x.s < 0; // It's enough to decide on the sign + }, + Unit: function Unit(x) { + return isNegative(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, isNegative); + } + }); + return isNegative; +}); +// CONCATENATED MODULE: ./src/function/utils/isNumeric.js + + +var isNumeric_name = 'isNumeric'; +var isNumeric_dependencies = ['typed']; +var createIsNumeric = /* #__PURE__ */Object(factory["a" /* factory */])(isNumeric_name, isNumeric_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is an numeric value. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isNumeric(x) + * + * Examples: + * + * math.isNumeric(2) // returns true + * math.isNumeric('2') // returns false + * math.hasNumericValue('2') // returns true + * math.isNumeric(0) // returns true + * math.isNumeric(math.bignumber(500)) // returns true + * math.isNumeric(math.fraction(4)) // returns true + * math.isNumeric(math.complex('2-4i') // returns false + * math.isNumeric([2.3, 'foo', false]) // returns [true, false, true] + * + * See also: + * + * isZero, isPositive, isNegative, isInteger, hasNumericValue + * + * @param {*} x Value to be tested + * @return {boolean} Returns true when `x` is a `number`, `BigNumber`, + * `Fraction`, or `boolean`. Returns false for other types. + * Throws an error in case of unknown types. + */ + var isNumeric = typed(isNumeric_name, { + 'number | BigNumber | Fraction | boolean': function numberBigNumberFractionBoolean() { + return true; + }, + 'Complex | Unit | string | null | undefined | Node': function ComplexUnitStringNullUndefinedNode() { + return false; + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, isNumeric); + } + }); + return isNumeric; +}); +// CONCATENATED MODULE: ./src/function/utils/hasNumericValue.js + +var hasNumericValue_name = 'hasNumericValue'; +var hasNumericValue_dependencies = ['typed', 'isNumeric']; +var createHasNumericValue = /* #__PURE__ */Object(factory["a" /* factory */])(hasNumericValue_name, hasNumericValue_dependencies, function (_ref) { + var typed = _ref.typed, + isNumeric = _ref.isNumeric; + + /** + * Test whether a value is an numeric value. + * + * In case of a string, true is returned if the string contains a numeric value. + * + * Syntax: + * + * math.hasNumericValue(x) + * + * Examples: + * + * math.hasNumericValue(2) // returns true + * math.hasNumericValue('2') // returns true + * math.isNumeric('2') // returns false + * math.hasNumericValue(0) // returns true + * math.hasNumericValue(math.bignumber(500)) // returns true + * math.hasNumericValue(math.fraction(4)) // returns true + * math.hasNumericValue(math.complex('2-4i') // returns false + * math.hasNumericValue([2.3, 'foo', false]) // returns [true, false, true] + * + * See also: + * + * isZero, isPositive, isNegative, isInteger, isNumeric + * + * @param {*} x Value to be tested + * @return {boolean} Returns true when `x` is a `number`, `BigNumber`, + * `Fraction`, `Boolean`, or a `String` containing number. Returns false for other types. + * Throws an error in case of unknown types. + */ + return typed(hasNumericValue_name, { + string: function string(x) { + return x.trim().length > 0 && !isNaN(Number(x)); + }, + any: function any(x) { + return isNumeric(x); + } + }); +}); +// CONCATENATED MODULE: ./src/function/utils/isPositive.js + + + +var isPositive_name = 'isPositive'; +var isPositive_dependencies = ['typed']; +var createIsPositive = /* #__PURE__ */Object(factory["a" /* factory */])(isPositive_name, isPositive_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is positive: larger than zero. + * The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isPositive(x) + * + * Examples: + * + * math.isPositive(3) // returns true + * math.isPositive(-2) // returns false + * math.isPositive(0) // returns false + * math.isPositive(-0) // returns false + * math.isPositive(0.5) // returns true + * math.isPositive(math.bignumber(2)) // returns true + * math.isPositive(math.fraction(-2, 5)) // returns false + * math.isPositive(math.fraction(1,3)) // returns false + * math.isPositive('2') // returns true + * math.isPositive([2, 0, -3]) // returns [true, false, false] + * + * See also: + * + * isNumeric, isZero, isNegative, isInteger + * + * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested + * @return {boolean} Returns true when `x` is larger than zero. + * Throws an error in case of an unknown data type. + */ + var isPositive = typed(isPositive_name, { + number: isPositiveNumber, + BigNumber: function BigNumber(x) { + return !x.isNeg() && !x.isZero() && !x.isNaN(); + }, + Fraction: function Fraction(x) { + return x.s > 0 && x.n > 0; + }, + Unit: function Unit(x) { + return isPositive(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, isPositive); + } + }); + return isPositive; +}); +// CONCATENATED MODULE: ./src/function/utils/isZero.js + + + +var isZero_name = 'isZero'; +var isZero_dependencies = ['typed']; +var createIsZero = /* #__PURE__ */Object(factory["a" /* factory */])(isZero_name, isZero_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is zero. + * The function can check for zero for types `number`, `BigNumber`, `Fraction`, + * `Complex`, and `Unit`. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isZero(x) + * + * Examples: + * + * math.isZero(0) // returns true + * math.isZero(2) // returns false + * math.isZero(0.5) // returns false + * math.isZero(math.bignumber(0)) // returns true + * math.isZero(math.fraction(0)) // returns true + * math.isZero(math.fraction(1,3)) // returns false + * math.isZero(math.complex('2 - 4i') // returns false + * math.isZero(math.complex('0i') // returns true + * math.isZero('0') // returns true + * math.isZero('2') // returns false + * math.isZero([2, 0, -3]') // returns [false, true, false] + * + * See also: + * + * isNumeric, isPositive, isNegative, isInteger + * + * @param {number | BigNumber | Complex | Fraction | Unit | Array | Matrix} x Value to be tested + * @return {boolean} Returns true when `x` is zero. + * Throws an error in case of an unknown data type. + */ + var isZero = typed(isZero_name, { + number: isZeroNumber, + BigNumber: function BigNumber(x) { + return x.isZero(); + }, + Complex: function Complex(x) { + return x.re === 0 && x.im === 0; + }, + Fraction: function Fraction(x) { + return x.d === 1 && x.n === 0; + }, + Unit: function Unit(x) { + return isZero(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, isZero); + } + }); + return isZero; +}); +// CONCATENATED MODULE: ./src/function/utils/isNaN.js + + + +var isNaN_name = 'isNaN'; +var isNaN_dependencies = ['typed']; +var createIsNaN = /* #__PURE__ */Object(factory["a" /* factory */])(isNaN_name, isNaN_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is NaN (not a number). + * The function supports types `number`, `BigNumber`, `Fraction`, `Unit` and `Complex`. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isNaN(x) + * + * Examples: + * + * math.isNaN(3) // returns false + * math.isNaN(NaN) // returns true + * math.isNaN(0) // returns false + * math.isNaN(math.bignumber(NaN)) // returns true + * math.isNaN(math.bignumber(0)) // returns false + * math.isNaN(math.fraction(-2, 5)) // returns false + * math.isNaN('-2') // returns false + * math.isNaN([2, 0, -3, NaN]') // returns [false, false, false, true] + * + * See also: + * + * isNumeric, isNegative, isPositive, isZero, isInteger + * + * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested + * @return {boolean} Returns true when `x` is NaN. + * Throws an error in case of an unknown data type. + */ + return typed(isNaN_name, { + number: isNaNNumber, + BigNumber: function BigNumber(x) { + return x.isNaN(); + }, + Fraction: function Fraction(x) { + return false; + }, + Complex: function Complex(x) { + return x.isNaN(); + }, + Unit: function Unit(x) { + return Number.isNaN(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, Number.isNaN); + } + }); +}); +// EXTERNAL MODULE: ./src/utils/log.js +var utils_log = __webpack_require__(8); + +// CONCATENATED MODULE: ./src/function/utils/typeOf.js + + + +var typeOf_name = 'typeOf'; +var typeOf_dependencies = ['typed']; +var createTypeOf = /* #__PURE__ */Object(factory["a" /* factory */])(typeOf_name, typeOf_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Determine the type of a variable. + * + * Function `typeOf` recognizes the following types of objects: + * + * Object | Returns | Example + * ---------------------- | ------------- | ------------------------------------------ + * null | `'null'` | `math.typeOf(null)` + * number | `'number'` | `math.typeOf(3.5)` + * boolean | `'boolean'` | `math.typeOf(true)` + * string | `'string'` | `math.typeOf('hello world')` + * Array | `'Array'` | `math.typeOf([1, 2, 3])` + * Date | `'Date'` | `math.typeOf(new Date())` + * Function | `'Function'` | `math.typeOf(function () {})` + * Object | `'Object'` | `math.typeOf({a: 2, b: 3})` + * RegExp | `'RegExp'` | `math.typeOf(/a regexp/)` + * undefined | `'undefined'` | `math.typeOf(undefined)` + * math.BigNumber | `'BigNumber'` | `math.typeOf(math.bignumber('2.3e500'))` + * math.Chain | `'Chain'` | `math.typeOf(math.chain(2))` + * math.Complex | `'Complex'` | `math.typeOf(math.complex(2, 3))` + * math.Fraction | `'Fraction'` | `math.typeOf(math.fraction(1, 3))` + * math.Help | `'Help'` | `math.typeOf(math.help('sqrt'))` + * math.Help | `'Help'` | `math.typeOf(math.help('sqrt'))` + * math.Index | `'Index'` | `math.typeOf(math.index(1, 3))` + * math.Matrix | `'Matrix'` | `math.typeOf(math.matrix([[1,2], [3, 4]]))` + * math.Range | `'Range'` | `math.typeOf(math.range(0, 10))` + * math.ResultSet | `'ResultSet'` | `math.typeOf(math.evaluate('a=2\nb=3'))` + * math.Unit | `'Unit'` | `math.typeOf(math.unit('45 deg'))` + * math.AccessorNode | `'AccessorNode'` | `math.typeOf(math.parse('A[2]'))` + * math.ArrayNode | `'ArrayNode'` | `math.typeOf(math.parse('[1,2,3]'))` + * math.AssignmentNode | `'AssignmentNode'` | `math.typeOf(math.parse('x=2'))` + * math.BlockNode | `'BlockNode'` | `math.typeOf(math.parse('a=2; b=3'))` + * math.ConditionalNode | `'ConditionalNode'` | `math.typeOf(math.parse('x<0 ? -x : x'))` + * math.ConstantNode | `'ConstantNode'` | `math.typeOf(math.parse('2.3'))` + * math.FunctionAssignmentNode | `'FunctionAssignmentNode'` | `math.typeOf(math.parse('f(x)=x^2'))` + * math.FunctionNode | `'FunctionNode'` | `math.typeOf(math.parse('sqrt(4)'))` + * math.IndexNode | `'IndexNode'` | `math.typeOf(math.parse('A[2]').index)` + * math.ObjectNode | `'ObjectNode'` | `math.typeOf(math.parse('{a:2}'))` + * math.ParenthesisNode | `'ParenthesisNode'` | `math.typeOf(math.parse('(2+3)'))` + * math.RangeNode | `'RangeNode'` | `math.typeOf(math.parse('1:10'))` + * math.SymbolNode | `'SymbolNode'` | `math.typeOf(math.parse('x'))` + * + * Syntax: + * + * math.typeOf(x) + * + * Examples: + * + * math.typeOf(3.5) // returns 'number' + * math.typeOf(math.complex('2-4i')) // returns 'Complex' + * math.typeOf(math.unit('45 deg')) // returns 'Unit' + * math.typeOf('hello world') // returns 'string' + * + * @param {*} x The variable for which to test the type. + * @return {string} Returns the name of the type. Primitive types are lower case, + * non-primitive types are upper-camel-case. + * For example 'number', 'string', 'Array', 'Date'. + */ + return typed(typeOf_name, { + any: is["M" /* typeOf */] + }); +}); // For backward compatibility, deprecated since version 6.0.0. Date: 2018-11-06 + +var createDeprecatedTypeof = /* #__PURE__ */Object(factory["a" /* factory */])('typeof', [], function () { + return function () { + Object(utils_log["a" /* warnOnce */])('Function "typeof" has been renamed to "typeOf" in v6.0.0, please use the new function instead.'); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return is["M" /* typeOf */].apply(is["M" /* typeOf */], args); + }; +}); +// CONCATENATED MODULE: ./src/utils/bignumber/nearlyEqual.js +/** + * Compares two BigNumbers. + * @param {BigNumber} x First value to compare + * @param {BigNumber} y Second value to compare + * @param {number} [epsilon] The maximum relative difference between x and y + * If epsilon is undefined or null, the function will + * test whether x and y are exactly equal. + * @return {boolean} whether the two numbers are nearly equal + */ +function nearlyEqual(x, y, epsilon) { + // if epsilon is null or undefined, test whether x and y are exactly equal + if (epsilon === null || epsilon === undefined) { + return x.eq(y); + } // use "==" operator, handles infinities + + + if (x.eq(y)) { + return true; + } // NaN + + + if (x.isNaN() || y.isNaN()) { + return false; + } // at this point x and y should be finite + + + if (x.isFinite() && y.isFinite()) { + // check numbers are very close, needed when comparing numbers near zero + var diff = x.minus(y).abs(); + + if (diff.isZero()) { + return true; + } else { + // use relative error + var max = x.constructor.max(x.abs(), y.abs()); + return diff.lte(max.times(epsilon)); + } + } // Infinite and Number or negative Infinite and positive Infinite cases + + + return false; +} +// CONCATENATED MODULE: ./src/utils/complex.js + +/** + * Test whether two complex values are equal provided a given epsilon. + * Does not use or change the global Complex.EPSILON setting + * @param {Complex} x + * @param {Complex} y + * @param {number} epsilon + * @returns {boolean} + */ + +function complexEquals(x, y, epsilon) { + return Object(utils_number["m" /* nearlyEqual */])(x.re, y.re, epsilon) && Object(utils_number["m" /* nearlyEqual */])(x.im, y.im, epsilon); +} +// CONCATENATED MODULE: ./src/function/relational/equalScalar.js + + + + +var equalScalar_name = 'equalScalar'; +var equalScalar_dependencies = ['typed', 'config']; +var createEqualScalar = /* #__PURE__ */Object(factory["a" /* factory */])(equalScalar_name, equalScalar_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config; + + /** + * Test whether two scalar values are nearly equal. + * + * @param {number | BigNumber | Fraction | boolean | Complex | Unit} x First value to compare + * @param {number | BigNumber | Fraction | boolean | Complex} y Second value to compare + * @return {boolean} Returns true when the compared values are equal, else returns false + * @private + */ + var equalScalar = typed(equalScalar_name, { + 'boolean, boolean': function booleanBoolean(x, y) { + return x === y; + }, + 'number, number': function numberNumber(x, y) { + return Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.eq(y) || nearlyEqual(x, y, config.epsilon); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.equals(y); + }, + 'Complex, Complex': function ComplexComplex(x, y) { + return complexEquals(x, y, config.epsilon); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (!x.equalBase(y)) { + throw new Error('Cannot compare units with different base'); + } + + return equalScalar(x.value, y.value); + } + }); + return equalScalar; +}); +var createEqualScalarNumber = Object(factory["a" /* factory */])(equalScalar_name, ['typed', 'config'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config; + return typed(equalScalar_name, { + 'number, number': function numberNumber(x, y) { + return Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + } + }); +}); +// CONCATENATED MODULE: ./src/type/matrix/SparseMatrix.js + + + + + + + +var SparseMatrix_name = 'SparseMatrix'; +var SparseMatrix_dependencies = ['typed', 'equalScalar', 'Matrix']; +var createSparseMatrixClass = /* #__PURE__ */Object(factory["a" /* factory */])(SparseMatrix_name, SparseMatrix_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar, + Matrix = _ref.Matrix; + + /** + * Sparse Matrix implementation. This type implements a Compressed Column Storage format + * for sparse matrices. + * @class SparseMatrix + */ + function SparseMatrix(data, datatype) { + if (!(this instanceof SparseMatrix)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (datatype && !Object(is["I" /* isString */])(datatype)) { + throw new Error('Invalid datatype: ' + datatype); + } + + if (Object(is["v" /* isMatrix */])(data)) { + // create from matrix + _createFromMatrix(this, data, datatype); + } else if (data && Object(is["b" /* isArray */])(data.index) && Object(is["b" /* isArray */])(data.ptr) && Object(is["b" /* isArray */])(data.size)) { + // initialize fields + this._values = data.values; + this._index = data.index; + this._ptr = data.ptr; + this._size = data.size; + this._datatype = datatype || data.datatype; + } else if (Object(is["b" /* isArray */])(data)) { + // create from array + _createFromArray(this, data, datatype); + } else if (data) { + // unsupported type + throw new TypeError('Unsupported type of data (' + Object(is["M" /* typeOf */])(data) + ')'); + } else { + // nothing provided + this._values = []; + this._index = []; + this._ptr = [0]; + this._size = [0, 0]; + this._datatype = datatype; + } + } + + function _createFromMatrix(matrix, source, datatype) { + // check matrix type + if (source.type === 'SparseMatrix') { + // clone arrays + matrix._values = source._values ? Object(utils_object["a" /* clone */])(source._values) : undefined; + matrix._index = Object(utils_object["a" /* clone */])(source._index); + matrix._ptr = Object(utils_object["a" /* clone */])(source._ptr); + matrix._size = Object(utils_object["a" /* clone */])(source._size); + matrix._datatype = datatype || source._datatype; + } else { + // build from matrix data + _createFromArray(matrix, source.valueOf(), datatype || source._datatype); + } + } + + function _createFromArray(matrix, data, datatype) { + // initialize fields + matrix._values = []; + matrix._index = []; + matrix._ptr = []; + matrix._datatype = datatype; // discover rows & columns, do not use math.size() to avoid looping array twice + + var rows = data.length; + var columns = 0; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; + + if (Object(is["I" /* isString */])(datatype)) { + // find signature that matches (datatype, datatype) + eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar; // convert 0 to the same datatype + + zero = typed.convert(0, datatype); + } // check we have rows (empty array) + + + if (rows > 0) { + // column index + var j = 0; + + do { + // store pointer to values index + matrix._ptr.push(matrix._index.length); // loop rows + + + for (var i = 0; i < rows; i++) { + // current row + var row = data[i]; // check row is an array + + if (Object(is["b" /* isArray */])(row)) { + // update columns if needed (only on first column) + if (j === 0 && columns < row.length) { + columns = row.length; + } // check row has column + + + if (j < row.length) { + // value + var v = row[j]; // check value != 0 + + if (!eq(v, zero)) { + // store value + matrix._values.push(v); // index + + + matrix._index.push(i); + } + } + } else { + // update columns if needed (only on first column) + if (j === 0 && columns < 1) { + columns = 1; + } // check value != 0 (row is a scalar) + + + if (!eq(row, zero)) { + // store value + matrix._values.push(row); // index + + + matrix._index.push(i); + } + } + } // increment index + + + j++; + } while (j < columns); + } // store number of values in ptr + + + matrix._ptr.push(matrix._index.length); // size + + + matrix._size = [rows, columns]; + } + + SparseMatrix.prototype = new Matrix(); + /** + * Create a new SparseMatrix + */ + + SparseMatrix.prototype.createSparseMatrix = function (data, datatype) { + return new SparseMatrix(data, datatype); + }; + /** + * Attach type information + */ + + + SparseMatrix.prototype.type = 'SparseMatrix'; + SparseMatrix.prototype.isSparseMatrix = true; + /** + * Get the matrix type + * + * Usage: + * const matrixType = matrix.getDataType() // retrieves the matrix type + * + * @memberOf SparseMatrix + * @return {string} type information; if multiple types are found from the Matrix, it will return "mixed" + */ + + SparseMatrix.prototype.getDataType = function () { + return Object(utils_array["h" /* getArrayDataType */])(this._values, is["M" /* typeOf */]); + }; + /** + * Get the storage format used by the matrix. + * + * Usage: + * const format = matrix.storage() // retrieve storage format + * + * @memberof SparseMatrix + * @return {string} The storage format. + */ + + + SparseMatrix.prototype.storage = function () { + return 'sparse'; + }; + /** + * Get the datatype of the data stored in the matrix. + * + * Usage: + * const format = matrix.datatype() // retrieve matrix datatype + * + * @memberof SparseMatrix + * @return {string} The datatype. + */ + + + SparseMatrix.prototype.datatype = function () { + return this._datatype; + }; + /** + * Create a new SparseMatrix + * @memberof SparseMatrix + * @param {Array} data + * @param {string} [datatype] + */ + + + SparseMatrix.prototype.create = function (data, datatype) { + return new SparseMatrix(data, datatype); + }; + /** + * Get the matrix density. + * + * Usage: + * const density = matrix.density() // retrieve matrix density + * + * @memberof SparseMatrix + * @return {number} The matrix density. + */ + + + SparseMatrix.prototype.density = function () { + // rows & columns + var rows = this._size[0]; + var columns = this._size[1]; // calculate density + + return rows !== 0 && columns !== 0 ? this._index.length / (rows * columns) : 0; + }; + /** + * Get a subset of the matrix, or replace a subset of the matrix. + * + * Usage: + * const subset = matrix.subset(index) // retrieve subset + * const value = matrix.subset(index, replacement) // replace subset + * + * @memberof SparseMatrix + * @param {Index} index + * @param {Array | Matrix | *} [replacement] + * @param {*} [defaultValue=0] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be filled with zeros. + */ + + + SparseMatrix.prototype.subset = function (index, replacement, defaultValue) { + // check it is a pattern matrix + if (!this._values) { + throw new Error('Cannot invoke subset on a Pattern only matrix'); + } // check arguments + + + switch (arguments.length) { + case 1: + return _getsubset(this, index); + // intentional fall through + + case 2: + case 3: + return _setsubset(this, index, replacement, defaultValue); + + default: + throw new SyntaxError('Wrong number of arguments'); + } + }; + + function _getsubset(matrix, idx) { + // check idx + if (!Object(is["t" /* isIndex */])(idx)) { + throw new TypeError('Invalid index'); + } + + var isScalar = idx.isScalar(); + + if (isScalar) { + // return a scalar + return matrix.get(idx.min()); + } // validate dimensions + + + var size = idx.size(); + + if (size.length !== matrix._size.length) { + throw new DimensionError["a" /* DimensionError */](size.length, matrix._size.length); + } // vars + + + var i, ii, k, kk; // validate if any of the ranges in the index is out of range + + var min = idx.min(); + var max = idx.max(); + + for (i = 0, ii = matrix._size.length; i < ii; i++) { + Object(utils_array["s" /* validateIndex */])(min[i], matrix._size[i]); + Object(utils_array["s" /* validateIndex */])(max[i], matrix._size[i]); + } // matrix arrays + + + var mvalues = matrix._values; + var mindex = matrix._index; + var mptr = matrix._ptr; // rows & columns dimensions for result matrix + + var rows = idx.dimension(0); + var columns = idx.dimension(1); // workspace & permutation vector + + var w = []; + var pv = []; // loop rows in resulting matrix + + rows.forEach(function (i, r) { + // update permutation vector + pv[i] = r[0]; // mark i in workspace + + w[i] = true; + }); // result matrix arrays + + var values = mvalues ? [] : undefined; + var index = []; + var ptr = []; // loop columns in result matrix + + columns.forEach(function (j) { + // update ptr + ptr.push(index.length); // loop values in column j + + for (k = mptr[j], kk = mptr[j + 1]; k < kk; k++) { + // row + i = mindex[k]; // check row is in result matrix + + if (w[i] === true) { + // push index + index.push(pv[i]); // check we need to process values + + if (values) { + values.push(mvalues[k]); + } + } + } + }); // update ptr + + ptr.push(index.length); // return matrix + + return new SparseMatrix({ + values: values, + index: index, + ptr: ptr, + size: size, + datatype: matrix._datatype + }); + } + + function _setsubset(matrix, index, submatrix, defaultValue) { + // check index + if (!index || index.isIndex !== true) { + throw new TypeError('Invalid index'); + } // get index size and check whether the index contains a single value + + + var iSize = index.size(); + var isScalar = index.isScalar(); // calculate the size of the submatrix, and convert it into an Array if needed + + var sSize; + + if (Object(is["v" /* isMatrix */])(submatrix)) { + // submatrix size + sSize = submatrix.size(); // use array representation + + submatrix = submatrix.toArray(); + } else { + // get submatrix size (array, scalar) + sSize = Object(utils_array["a" /* arraySize */])(submatrix); + } // check index is a scalar + + + if (isScalar) { + // verify submatrix is a scalar + if (sSize.length !== 0) { + throw new TypeError('Scalar expected'); + } // set value + + + matrix.set(index.min(), submatrix, defaultValue); + } else { + // validate dimensions, index size must be one or two dimensions + if (iSize.length !== 1 && iSize.length !== 2) { + throw new DimensionError["a" /* DimensionError */](iSize.length, matrix._size.length, '<'); + } // check submatrix and index have the same dimensions + + + if (sSize.length < iSize.length) { + // calculate number of missing outer dimensions + var i = 0; + var outer = 0; + + while (iSize[i] === 1 && sSize[i] === 1) { + i++; + } + + while (iSize[i] === 1) { + outer++; + i++; + } // unsqueeze both outer and inner dimensions + + + submatrix = Object(utils_array["q" /* unsqueeze */])(submatrix, iSize.length, outer, sSize); + } // check whether the size of the submatrix matches the index size + + + if (!Object(utils_object["d" /* deepStrictEqual */])(iSize, sSize)) { + throw new DimensionError["a" /* DimensionError */](iSize, sSize, '>'); + } // offsets + + + var x0 = index.min()[0]; + var y0 = index.min()[1]; // submatrix rows and columns + + var m = sSize[0]; + var n = sSize[1]; // loop submatrix + + for (var x = 0; x < m; x++) { + // loop columns + for (var y = 0; y < n; y++) { + // value at i, j + var v = submatrix[x][y]; // invoke set (zero value will remove entry from matrix) + + matrix.set([x + x0, y + y0], v, defaultValue); + } + } + } + + return matrix; + } + /** + * Get a single element from the matrix. + * @memberof SparseMatrix + * @param {number[]} index Zero-based index + * @return {*} value + */ + + + SparseMatrix.prototype.get = function (index) { + if (!Object(is["b" /* isArray */])(index)) { + throw new TypeError('Array expected'); + } + + if (index.length !== this._size.length) { + throw new DimensionError["a" /* DimensionError */](index.length, this._size.length); + } // check it is a pattern matrix + + + if (!this._values) { + throw new Error('Cannot invoke get on a Pattern only matrix'); + } // row and column + + + var i = index[0]; + var j = index[1]; // check i, j are valid + + Object(utils_array["s" /* validateIndex */])(i, this._size[0]); + Object(utils_array["s" /* validateIndex */])(j, this._size[1]); // find value index + + var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index); // check k is prior to next column k and it is in the correct row + + + if (k < this._ptr[j + 1] && this._index[k] === i) { + return this._values[k]; + } + + return 0; + }; + /** + * Replace a single element in the matrix. + * @memberof SparseMatrix + * @param {number[]} index Zero-based index + * @param {*} v + * @param {*} [defaultValue] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be set to zero. + * @return {SparseMatrix} self + */ + + + SparseMatrix.prototype.set = function (index, v, defaultValue) { + if (!Object(is["b" /* isArray */])(index)) { + throw new TypeError('Array expected'); + } + + if (index.length !== this._size.length) { + throw new DimensionError["a" /* DimensionError */](index.length, this._size.length); + } // check it is a pattern matrix + + + if (!this._values) { + throw new Error('Cannot invoke set on a Pattern only matrix'); + } // row and column + + + var i = index[0]; + var j = index[1]; // rows & columns + + var rows = this._size[0]; + var columns = this._size[1]; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; + + if (Object(is["I" /* isString */])(this._datatype)) { + // find signature that matches (datatype, datatype) + eq = typed.find(equalScalar, [this._datatype, this._datatype]) || equalScalar; // convert 0 to the same datatype + + zero = typed.convert(0, this._datatype); + } // check we need to resize matrix + + + if (i > rows - 1 || j > columns - 1) { + // resize matrix + _resize(this, Math.max(i + 1, rows), Math.max(j + 1, columns), defaultValue); // update rows & columns + + + rows = this._size[0]; + columns = this._size[1]; + } // check i, j are valid + + + Object(utils_array["s" /* validateIndex */])(i, rows); + Object(utils_array["s" /* validateIndex */])(j, columns); // find value index + + var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index); // check k is prior to next column k and it is in the correct row + + + if (k < this._ptr[j + 1] && this._index[k] === i) { + // check value != 0 + if (!eq(v, zero)) { + // update value + this._values[k] = v; + } else { + // remove value from matrix + _remove(k, j, this._values, this._index, this._ptr); + } + } else { + // insert value @ (i, j) + _insert(k, i, j, v, this._values, this._index, this._ptr); + } + + return this; + }; + + function _getValueIndex(i, top, bottom, index) { + // check row is on the bottom side + if (bottom - top === 0) { + return bottom; + } // loop rows [top, bottom[ + + + for (var r = top; r < bottom; r++) { + // check we found value index + if (index[r] === i) { + return r; + } + } // we did not find row + + + return top; + } + + function _remove(k, j, values, index, ptr) { + // remove value @ k + values.splice(k, 1); + index.splice(k, 1); // update pointers + + for (var x = j + 1; x < ptr.length; x++) { + ptr[x]--; + } + } + + function _insert(k, i, j, v, values, index, ptr) { + // insert value + values.splice(k, 0, v); // update row for k + + index.splice(k, 0, i); // update column pointers + + for (var x = j + 1; x < ptr.length; x++) { + ptr[x]++; + } + } + /** + * Resize the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (resize in place). + * + * @memberof SparseMatrix + * @param {number[]} size The new size the matrix should have. + * @param {*} [defaultValue=0] Default value, filled in on new entries. + * If not provided, the matrix elements will + * be filled with zeros. + * @param {boolean} [copy] Return a resized copy of the matrix + * + * @return {Matrix} The resized matrix + */ + + + SparseMatrix.prototype.resize = function (size, defaultValue, copy) { + // validate arguments + if (!Object(is["b" /* isArray */])(size)) { + throw new TypeError('Array expected'); + } + + if (size.length !== 2) { + throw new Error('Only two dimensions matrix are supported'); + } // check sizes + + + size.forEach(function (value) { + if (!Object(is["y" /* isNumber */])(value) || !Object(utils_number["i" /* isInteger */])(value) || value < 0) { + throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + }); // matrix to resize + + var m = copy ? this.clone() : this; // resize matrix + + return _resize(m, size[0], size[1], defaultValue); + }; + + function _resize(matrix, rows, columns, defaultValue) { + // value to insert at the time of growing matrix + var value = defaultValue || 0; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; + + if (Object(is["I" /* isString */])(matrix._datatype)) { + // find signature that matches (datatype, datatype) + eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar; // convert 0 to the same datatype + + zero = typed.convert(0, matrix._datatype); // convert value to the same datatype + + value = typed.convert(value, matrix._datatype); + } // should we insert the value? + + + var ins = !eq(value, zero); // old columns and rows + + var r = matrix._size[0]; + var c = matrix._size[1]; + var i, j, k; // check we need to increase columns + + if (columns > c) { + // loop new columns + for (j = c; j < columns; j++) { + // update matrix._ptr for current column + matrix._ptr[j] = matrix._values.length; // check we need to insert matrix._values + + if (ins) { + // loop rows + for (i = 0; i < r; i++) { + // add new matrix._values + matrix._values.push(value); // update matrix._index + + + matrix._index.push(i); + } + } + } // store number of matrix._values in matrix._ptr + + + matrix._ptr[columns] = matrix._values.length; + } else if (columns < c) { + // truncate matrix._ptr + matrix._ptr.splice(columns + 1, c - columns); // truncate matrix._values and matrix._index + + + matrix._values.splice(matrix._ptr[columns], matrix._values.length); + + matrix._index.splice(matrix._ptr[columns], matrix._index.length); + } // update columns + + + c = columns; // check we need to increase rows + + if (rows > r) { + // check we have to insert values + if (ins) { + // inserts + var n = 0; // loop columns + + for (j = 0; j < c; j++) { + // update matrix._ptr for current column + matrix._ptr[j] = matrix._ptr[j] + n; // where to insert matrix._values + + k = matrix._ptr[j + 1] + n; // pointer + + var p = 0; // loop new rows, initialize pointer + + for (i = r; i < rows; i++, p++) { + // add value + matrix._values.splice(k + p, 0, value); // update matrix._index + + + matrix._index.splice(k + p, 0, i); // increment inserts + + + n++; + } + } // store number of matrix._values in matrix._ptr + + + matrix._ptr[c] = matrix._values.length; + } + } else if (rows < r) { + // deletes + var d = 0; // loop columns + + for (j = 0; j < c; j++) { + // update matrix._ptr for current column + matrix._ptr[j] = matrix._ptr[j] - d; // where matrix._values start for next column + + var k0 = matrix._ptr[j]; + var k1 = matrix._ptr[j + 1] - d; // loop matrix._index + + for (k = k0; k < k1; k++) { + // row + i = matrix._index[k]; // check we need to delete value and matrix._index + + if (i > rows - 1) { + // remove value + matrix._values.splice(k, 1); // remove item from matrix._index + + + matrix._index.splice(k, 1); // increase deletes + + + d++; + } + } + } // update matrix._ptr for current column + + + matrix._ptr[j] = matrix._values.length; + } // update matrix._size + + + matrix._size[0] = rows; + matrix._size[1] = columns; // return matrix + + return matrix; + } + /** + * Reshape the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (reshape in place). + * + * NOTE: This might be better suited to copy by default, instead of modifying + * in place. For now, it operates in place to remain consistent with + * resize(). + * + * @memberof SparseMatrix + * @param {number[]} size The new size the matrix should have. + * @param {boolean} [copy] Return a reshaped copy of the matrix + * + * @return {Matrix} The reshaped matrix + */ + + + SparseMatrix.prototype.reshape = function (size, copy) { + // validate arguments + if (!Object(is["b" /* isArray */])(size)) { + throw new TypeError('Array expected'); + } + + if (size.length !== 2) { + throw new Error('Sparse matrices can only be reshaped in two dimensions'); + } // check sizes + + + size.forEach(function (value) { + if (!Object(is["y" /* isNumber */])(value) || !Object(utils_number["i" /* isInteger */])(value) || value < 0) { + throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + }); // m * n must not change + + if (this._size[0] * this._size[1] !== size[0] * size[1]) { + throw new Error('Reshaping sparse matrix will result in the wrong number of elements'); + } // matrix to reshape + + + var m = copy ? this.clone() : this; // return unchanged if the same shape + + if (this._size[0] === size[0] && this._size[1] === size[1]) { + return m; + } // Convert to COO format (generate a column index) + + + var colIndex = []; + + for (var i = 0; i < m._ptr.length; i++) { + for (var j = 0; j < m._ptr[i + 1] - m._ptr[i]; j++) { + colIndex.push(i); + } + } // Clone the values array + + + var values = m._values.slice(); // Clone the row index array + + + var rowIndex = m._index.slice(); // Transform the (row, column) indices + + + for (var _i = 0; _i < m._index.length; _i++) { + var r1 = rowIndex[_i]; + var c1 = colIndex[_i]; + var flat = r1 * m._size[1] + c1; + colIndex[_i] = flat % size[1]; + rowIndex[_i] = Math.floor(flat / size[1]); + } // Now reshaping is supposed to preserve the row-major order, BUT these sparse matrices are stored + // in column-major order, so we have to reorder the value array now. One option is to use a multisort, + // sorting several arrays based on some other array. + // OR, we could easily just: + // 1. Remove all values from the matrix + + + m._values.length = 0; + m._index.length = 0; + m._ptr.length = size[1] + 1; + m._size = size.slice(); + + for (var _i2 = 0; _i2 < m._ptr.length; _i2++) { + m._ptr[_i2] = 0; + } // 2. Re-insert all elements in the proper order (simplified code from SparseMatrix.prototype.set) + // This step is probably the most time-consuming + + + for (var h = 0; h < values.length; h++) { + var _i3 = rowIndex[h]; + var _j = colIndex[h]; + var v = values[h]; + + var k = _getValueIndex(_i3, m._ptr[_j], m._ptr[_j + 1], m._index); + + _insert(k, _i3, _j, v, m._values, m._index, m._ptr); + } // The value indices are inserted out of order, but apparently that's... still OK? + + + return m; + }; + /** + * Create a clone of the matrix + * @memberof SparseMatrix + * @return {SparseMatrix} clone + */ + + + SparseMatrix.prototype.clone = function () { + var m = new SparseMatrix({ + values: this._values ? Object(utils_object["a" /* clone */])(this._values) : undefined, + index: Object(utils_object["a" /* clone */])(this._index), + ptr: Object(utils_object["a" /* clone */])(this._ptr), + size: Object(utils_object["a" /* clone */])(this._size), + datatype: this._datatype + }); + return m; + }; + /** + * Retrieve the size of the matrix. + * @memberof SparseMatrix + * @returns {number[]} size + */ + + + SparseMatrix.prototype.size = function () { + return this._size.slice(0); // copy the Array + }; + /** + * Create a new matrix with the results of the callback function executed on + * each entry of the matrix. + * @memberof SparseMatrix + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + * @param {boolean} [skipZeros] Invoke callback function for non-zero values only. + * + * @return {SparseMatrix} matrix + */ + + + SparseMatrix.prototype.map = function (callback, skipZeros) { + // check it is a pattern matrix + if (!this._values) { + throw new Error('Cannot invoke map on a Pattern only matrix'); + } // matrix instance + + + var me = this; // rows and columns + + var rows = this._size[0]; + var columns = this._size[1]; // invoke callback + + var invoke = function invoke(v, i, j) { + // invoke callback + return callback(v, [i, j], me); + }; // invoke _map + + + return _map(this, 0, rows - 1, 0, columns - 1, invoke, skipZeros); + }; + /** + * Create a new matrix with the results of the callback function executed on the interval + * [minRow..maxRow, minColumn..maxColumn]. + */ + + + function _map(matrix, minRow, maxRow, minColumn, maxColumn, callback, skipZeros) { + // result arrays + var values = []; + var index = []; + var ptr = []; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; + + if (Object(is["I" /* isString */])(matrix._datatype)) { + // find signature that matches (datatype, datatype) + eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar; // convert 0 to the same datatype + + zero = typed.convert(0, matrix._datatype); + } // invoke callback + + + var invoke = function invoke(v, x, y) { + // invoke callback + v = callback(v, x, y); // check value != 0 + + if (!eq(v, zero)) { + // store value + values.push(v); // index + + index.push(x); + } + }; // loop columns + + + for (var j = minColumn; j <= maxColumn; j++) { + // store pointer to values index + ptr.push(values.length); // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + + var k0 = matrix._ptr[j]; + var k1 = matrix._ptr[j + 1]; + + if (skipZeros) { + // loop k within [k0, k1[ + for (var k = k0; k < k1; k++) { + // row index + var i = matrix._index[k]; // check i is in range + + if (i >= minRow && i <= maxRow) { + // value @ k + invoke(matrix._values[k], i - minRow, j - minColumn); + } + } + } else { + // create a cache holding all defined values + var _values = {}; + + for (var _k = k0; _k < k1; _k++) { + var _i4 = matrix._index[_k]; + _values[_i4] = matrix._values[_k]; + } // loop over all rows (indexes can be unordered so we can't use that), + // and either read the value or zero + + + for (var _i5 = minRow; _i5 <= maxRow; _i5++) { + var value = _i5 in _values ? _values[_i5] : 0; + invoke(value, _i5 - minRow, j - minColumn); + } + } + } // store number of values in ptr + + + ptr.push(values.length); // return sparse matrix + + return new SparseMatrix({ + values: values, + index: index, + ptr: ptr, + size: [maxRow - minRow + 1, maxColumn - minColumn + 1] + }); + } + /** + * Execute a callback function on each entry of the matrix. + * @memberof SparseMatrix + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix being traversed. + * @param {boolean} [skipZeros] Invoke callback function for non-zero values only. + */ + + + SparseMatrix.prototype.forEach = function (callback, skipZeros) { + // check it is a pattern matrix + if (!this._values) { + throw new Error('Cannot invoke forEach on a Pattern only matrix'); + } // matrix instance + + + var me = this; // rows and columns + + var rows = this._size[0]; + var columns = this._size[1]; // loop columns + + for (var j = 0; j < columns; j++) { + // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + var k0 = this._ptr[j]; + var k1 = this._ptr[j + 1]; + + if (skipZeros) { + // loop k within [k0, k1[ + for (var k = k0; k < k1; k++) { + // row index + var i = this._index[k]; // value @ k + + callback(this._values[k], [i, j], me); + } + } else { + // create a cache holding all defined values + var values = {}; + + for (var _k2 = k0; _k2 < k1; _k2++) { + var _i6 = this._index[_k2]; + values[_i6] = this._values[_k2]; + } // loop over all rows (indexes can be unordered so we can't use that), + // and either read the value or zero + + + for (var _i7 = 0; _i7 < rows; _i7++) { + var value = _i7 in values ? values[_i7] : 0; + callback(value, [_i7, j], me); + } + } + } + }; + /** + * Create an Array with a copy of the data of the SparseMatrix + * @memberof SparseMatrix + * @returns {Array} array + */ + + + SparseMatrix.prototype.toArray = function () { + return _toArray(this._values, this._index, this._ptr, this._size, true); + }; + /** + * Get the primitive value of the SparseMatrix: a two dimensions array + * @memberof SparseMatrix + * @returns {Array} array + */ + + + SparseMatrix.prototype.valueOf = function () { + return _toArray(this._values, this._index, this._ptr, this._size, false); + }; + + function _toArray(values, index, ptr, size, copy) { + // rows and columns + var rows = size[0]; + var columns = size[1]; // result + + var a = []; // vars + + var i, j; // initialize array + + for (i = 0; i < rows; i++) { + a[i] = []; + + for (j = 0; j < columns; j++) { + a[i][j] = 0; + } + } // loop columns + + + for (j = 0; j < columns; j++) { + // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + var k0 = ptr[j]; + var k1 = ptr[j + 1]; // loop k within [k0, k1[ + + for (var k = k0; k < k1; k++) { + // row index + i = index[k]; // set value (use one for pattern matrix) + + a[i][j] = values ? copy ? Object(utils_object["a" /* clone */])(values[k]) : values[k] : 1; + } + } + + return a; + } + /** + * Get a string representation of the matrix, with optional formatting options. + * @memberof SparseMatrix + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @returns {string} str + */ + + + SparseMatrix.prototype.format = function (options) { + // rows and columns + var rows = this._size[0]; + var columns = this._size[1]; // density + + var density = this.density(); // rows & columns + + var str = 'Sparse Matrix [' + Object(utils_string["d" /* format */])(rows, options) + ' x ' + Object(utils_string["d" /* format */])(columns, options) + '] density: ' + Object(utils_string["d" /* format */])(density, options) + '\n'; // loop columns + + for (var j = 0; j < columns; j++) { + // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + var k0 = this._ptr[j]; + var k1 = this._ptr[j + 1]; // loop k within [k0, k1[ + + for (var k = k0; k < k1; k++) { + // row index + var i = this._index[k]; // append value + + str += '\n (' + Object(utils_string["d" /* format */])(i, options) + ', ' + Object(utils_string["d" /* format */])(j, options) + ') ==> ' + (this._values ? Object(utils_string["d" /* format */])(this._values[k], options) : 'X'); + } + } + + return str; + }; + /** + * Get a string representation of the matrix + * @memberof SparseMatrix + * @returns {string} str + */ + + + SparseMatrix.prototype.toString = function () { + return Object(utils_string["d" /* format */])(this.toArray()); + }; + /** + * Get a JSON representation of the matrix + * @memberof SparseMatrix + * @returns {Object} + */ + + + SparseMatrix.prototype.toJSON = function () { + return { + mathjs: 'SparseMatrix', + values: this._values, + index: this._index, + ptr: this._ptr, + size: this._size, + datatype: this._datatype + }; + }; + /** + * Get the kth Matrix diagonal. + * + * @memberof SparseMatrix + * @param {number | BigNumber} [k=0] The kth diagonal where the vector will retrieved. + * + * @returns {Matrix} The matrix vector with the diagonal values. + */ + + + SparseMatrix.prototype.diagonal = function (k) { + // validate k if any + if (k) { + // convert BigNumber to a number + if (Object(is["e" /* isBigNumber */])(k)) { + k = k.toNumber(); + } // is must be an integer + + + if (!Object(is["y" /* isNumber */])(k) || !Object(utils_number["i" /* isInteger */])(k)) { + throw new TypeError('The parameter k must be an integer number'); + } + } else { + // default value + k = 0; + } + + var kSuper = k > 0 ? k : 0; + var kSub = k < 0 ? -k : 0; // rows & columns + + var rows = this._size[0]; + var columns = this._size[1]; // number diagonal values + + var n = Math.min(rows - kSub, columns - kSuper); // diagonal arrays + + var values = []; + var index = []; + var ptr = []; // initial ptr value + + ptr[0] = 0; // loop columns + + for (var j = kSuper; j < columns && values.length < n; j++) { + // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + var k0 = this._ptr[j]; + var k1 = this._ptr[j + 1]; // loop x within [k0, k1[ + + for (var x = k0; x < k1; x++) { + // row index + var i = this._index[x]; // check row + + if (i === j - kSuper + kSub) { + // value on this column + values.push(this._values[x]); // store row + + index[values.length - 1] = i - kSub; // exit loop + + break; + } + } + } // close ptr + + + ptr.push(values.length); // return matrix + + return new SparseMatrix({ + values: values, + index: index, + ptr: ptr, + size: [n, 1] + }); + }; + /** + * Generate a matrix from a JSON object + * @memberof SparseMatrix + * @param {Object} json An object structured like + * `{"mathjs": "SparseMatrix", "values": [], "index": [], "ptr": [], "size": []}`, + * where mathjs is optional + * @returns {SparseMatrix} + */ + + + SparseMatrix.fromJSON = function (json) { + return new SparseMatrix(json); + }; + /** + * Create a diagonal matrix. + * + * @memberof SparseMatrix + * @param {Array} size The matrix size. + * @param {number | Array | Matrix } value The values for the diagonal. + * @param {number | BigNumber} [k=0] The kth diagonal where the vector will be filled in. + * @param {number} [defaultValue] The default value for non-diagonal + * @param {string} [datatype] The Matrix datatype, values must be of this datatype. + * + * @returns {SparseMatrix} + */ + + + SparseMatrix.diagonal = function (size, value, k, defaultValue, datatype) { + if (!Object(is["b" /* isArray */])(size)) { + throw new TypeError('Array expected, size parameter'); + } + + if (size.length !== 2) { + throw new Error('Only two dimensions matrix are supported'); + } // map size & validate + + + size = size.map(function (s) { + // check it is a big number + if (Object(is["e" /* isBigNumber */])(s)) { + // convert it + s = s.toNumber(); + } // validate arguments + + + if (!Object(is["y" /* isNumber */])(s) || !Object(utils_number["i" /* isInteger */])(s) || s < 1) { + throw new Error('Size values must be positive integers'); + } + + return s; + }); // validate k if any + + if (k) { + // convert BigNumber to a number + if (Object(is["e" /* isBigNumber */])(k)) { + k = k.toNumber(); + } // is must be an integer + + + if (!Object(is["y" /* isNumber */])(k) || !Object(utils_number["i" /* isInteger */])(k)) { + throw new TypeError('The parameter k must be an integer number'); + } + } else { + // default value + k = 0; + } // equal signature to use + + + var eq = equalScalar; // zero value + + var zero = 0; + + if (Object(is["I" /* isString */])(datatype)) { + // find signature that matches (datatype, datatype) + eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar; // convert 0 to the same datatype + + zero = typed.convert(0, datatype); + } + + var kSuper = k > 0 ? k : 0; + var kSub = k < 0 ? -k : 0; // rows and columns + + var rows = size[0]; + var columns = size[1]; // number of non-zero items + + var n = Math.min(rows - kSub, columns - kSuper); // value extraction function + + var _value; // check value + + + if (Object(is["b" /* isArray */])(value)) { + // validate array + if (value.length !== n) { + // number of values in array must be n + throw new Error('Invalid value array length'); + } // define function + + + _value = function _value(i) { + // return value @ i + return value[i]; + }; + } else if (Object(is["v" /* isMatrix */])(value)) { + // matrix size + var ms = value.size(); // validate matrix + + if (ms.length !== 1 || ms[0] !== n) { + // number of values in array must be n + throw new Error('Invalid matrix length'); + } // define function + + + _value = function _value(i) { + // return value @ i + return value.get([i]); + }; + } else { + // define function + _value = function _value() { + // return value + return value; + }; + } // create arrays + + + var values = []; + var index = []; + var ptr = []; // loop items + + for (var j = 0; j < columns; j++) { + // number of rows with value + ptr.push(values.length); // diagonal index + + var i = j - kSuper; // check we need to set diagonal value + + if (i >= 0 && i < n) { + // get value @ i + var v = _value(i); // check for zero + + + if (!eq(v, zero)) { + // column + index.push(i + kSub); // add value + + values.push(v); + } + } + } // last value should be number of values + + + ptr.push(values.length); // create SparseMatrix + + return new SparseMatrix({ + values: values, + index: index, + ptr: ptr, + size: [rows, columns] + }); + }; + /** + * Swap rows i and j in Matrix. + * + * @memberof SparseMatrix + * @param {number} i Matrix row index 1 + * @param {number} j Matrix row index 2 + * + * @return {Matrix} The matrix reference + */ + + + SparseMatrix.prototype.swapRows = function (i, j) { + // check index + if (!Object(is["y" /* isNumber */])(i) || !Object(utils_number["i" /* isInteger */])(i) || !Object(is["y" /* isNumber */])(j) || !Object(utils_number["i" /* isInteger */])(j)) { + throw new Error('Row index must be positive integers'); + } // check dimensions + + + if (this._size.length !== 2) { + throw new Error('Only two dimensional matrix is supported'); + } // validate index + + + Object(utils_array["s" /* validateIndex */])(i, this._size[0]); + Object(utils_array["s" /* validateIndex */])(j, this._size[0]); // swap rows + + SparseMatrix._swapRows(i, j, this._size[1], this._values, this._index, this._ptr); // return current instance + + + return this; + }; + /** + * Loop rows with data in column j. + * + * @param {number} j Column + * @param {Array} values Matrix values + * @param {Array} index Matrix row indeces + * @param {Array} ptr Matrix column pointers + * @param {Function} callback Callback function invoked for every row in column j + */ + + + SparseMatrix._forEachRow = function (j, values, index, ptr, callback) { + // indeces for column j + var k0 = ptr[j]; + var k1 = ptr[j + 1]; // loop + + for (var k = k0; k < k1; k++) { + // invoke callback + callback(index[k], values[k]); + } + }; + /** + * Swap rows x and y in Sparse Matrix data structures. + * + * @param {number} x Matrix row index 1 + * @param {number} y Matrix row index 2 + * @param {number} columns Number of columns in matrix + * @param {Array} values Matrix values + * @param {Array} index Matrix row indeces + * @param {Array} ptr Matrix column pointers + */ + + + SparseMatrix._swapRows = function (x, y, columns, values, index, ptr) { + // loop columns + for (var j = 0; j < columns; j++) { + // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + var k0 = ptr[j]; + var k1 = ptr[j + 1]; // find value index @ x + + var kx = _getValueIndex(x, k0, k1, index); // find value index @ x + + + var ky = _getValueIndex(y, k0, k1, index); // check both rows exist in matrix + + + if (kx < k1 && ky < k1 && index[kx] === x && index[ky] === y) { + // swap values (check for pattern matrix) + if (values) { + var v = values[kx]; + values[kx] = values[ky]; + values[ky] = v; + } // next column + + + continue; + } // check x row exist & no y row + + + if (kx < k1 && index[kx] === x && (ky >= k1 || index[ky] !== y)) { + // value @ x (check for pattern matrix) + var vx = values ? values[kx] : undefined; // insert value @ y + + index.splice(ky, 0, y); + + if (values) { + values.splice(ky, 0, vx); + } // remove value @ x (adjust array index if needed) + + + index.splice(ky <= kx ? kx + 1 : kx, 1); + + if (values) { + values.splice(ky <= kx ? kx + 1 : kx, 1); + } // next column + + + continue; + } // check y row exist & no x row + + + if (ky < k1 && index[ky] === y && (kx >= k1 || index[kx] !== x)) { + // value @ y (check for pattern matrix) + var vy = values ? values[ky] : undefined; // insert value @ x + + index.splice(kx, 0, x); + + if (values) { + values.splice(kx, 0, vy); + } // remove value @ y (adjust array index if needed) + + + index.splice(kx <= ky ? ky + 1 : ky, 1); + + if (values) { + values.splice(kx <= ky ? ky + 1 : ky, 1); + } + } + } + }; + + return SparseMatrix; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/number.js + + +var number_name = 'number'; +var number_dependencies = ['typed']; +var createNumber = /* #__PURE__ */Object(factory["a" /* factory */])(number_name, number_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Create a number or convert a string, boolean, or unit to a number. + * When value is a matrix, all elements will be converted to number. + * + * Syntax: + * + * math.number(value) + * math.number(unit, valuelessUnit) + * + * Examples: + * + * math.number(2) // returns number 2 + * math.number('7.2') // returns number 7.2 + * math.number(true) // returns number 1 + * math.number([true, false, true, true]) // returns [1, 0, 1, 1] + * math.number(math.unit('52cm'), 'm') // returns 0.52 + * + * See also: + * + * bignumber, boolean, complex, index, matrix, string, unit + * + * @param {string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null} [value] Value to be converted + * @param {Unit | string} [valuelessUnit] A valueless unit, used to convert a unit to a number + * @return {number | Array | Matrix} The created number + */ + var number = typed('number', { + '': function _() { + return 0; + }, + number: function number(x) { + return x; + }, + string: function string(x) { + if (x === 'NaN') return NaN; + var num = Number(x); + + if (isNaN(num)) { + throw new SyntaxError('String "' + x + '" is no valid number'); + } + + return num; + }, + BigNumber: function BigNumber(x) { + return x.toNumber(); + }, + Fraction: function Fraction(x) { + return x.valueOf(); + }, + Unit: function Unit(x) { + throw new Error('Second argument with valueless unit expected'); + }, + "null": function _null(x) { + return 0; + }, + 'Unit, string | Unit': function UnitStringUnit(unit, valuelessUnit) { + return unit.toNumber(valuelessUnit); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, number); + } + }); // reviver function to parse a JSON object like: + // + // {"mathjs":"number","value":"2.3"} + // + // into a number 2.3 + + number.fromJSON = function (json) { + return parseFloat(json.value); + }; + + return number; +}); +// CONCATENATED MODULE: ./src/type/string.js + + + +var string_name = 'string'; +var string_dependencies = ['typed']; +var createString = /* #__PURE__ */Object(factory["a" /* factory */])(string_name, string_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Create a string or convert any object into a string. + * Elements of Arrays and Matrices are processed element wise. + * + * Syntax: + * + * math.string(value) + * + * Examples: + * + * math.string(4.2) // returns string '4.2' + * math.string(math.complex(3, 2) // returns string '3 + 2i' + * + * const u = math.unit(5, 'km') + * math.string(u.to('m')) // returns string '5000 m' + * + * math.string([true, false]) // returns ['true', 'false'] + * + * See also: + * + * bignumber, boolean, complex, index, matrix, number, unit + * + * @param {* | Array | Matrix | null} [value] A value to convert to a string + * @return {string | Array | Matrix} The created string + */ + var string = typed(string_name, { + '': function _() { + return ''; + }, + number: utils_number["h" /* format */], + "null": function _null(x) { + return 'null'; + }, + "boolean": function boolean(x) { + return x + ''; + }, + string: function string(x) { + return x; + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, string); + }, + any: function any(x) { + return String(x); + } + }); + return string; +}); +// CONCATENATED MODULE: ./src/type/boolean.js + + +var boolean_name = 'boolean'; +var boolean_dependencies = ['typed']; +var createBoolean = /* #__PURE__ */Object(factory["a" /* factory */])(boolean_name, boolean_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Create a boolean or convert a string or number to a boolean. + * In case of a number, `true` is returned for non-zero numbers, and `false` in + * case of zero. + * Strings can be `'true'` or `'false'`, or can contain a number. + * When value is a matrix, all elements will be converted to boolean. + * + * Syntax: + * + * math.boolean(x) + * + * Examples: + * + * math.boolean(0) // returns false + * math.boolean(1) // returns true + * math.boolean(-3) // returns true + * math.boolean('true') // returns true + * math.boolean('false') // returns false + * math.boolean([1, 0, 1, 1]) // returns [true, false, true, true] + * + * See also: + * + * bignumber, complex, index, matrix, string, unit + * + * @param {string | number | boolean | Array | Matrix | null} value A value of any type + * @return {boolean | Array | Matrix} The boolean value + */ + var bool = typed(boolean_name, { + '': function _() { + return false; + }, + "boolean": function boolean(x) { + return x; + }, + number: function number(x) { + return !!x; + }, + "null": function _null(x) { + return false; + }, + BigNumber: function BigNumber(x) { + return !x.isZero(); + }, + string: function string(x) { + // try case insensitive + var lcase = x.toLowerCase(); + + if (lcase === 'true') { + return true; + } else if (lcase === 'false') { + return false; + } // test whether value is a valid number + + + var num = Number(x); + + if (x !== '' && !isNaN(num)) { + return !!num; + } + + throw new Error('Cannot convert "' + x + '" to a boolean'); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, bool); + } + }); + return bool; +}); +// CONCATENATED MODULE: ./src/type/bignumber/function/bignumber.js + + +var bignumber_name = 'bignumber'; +var bignumber_dependencies = ['typed', 'BigNumber']; +var createBignumber = /* #__PURE__ */Object(factory["a" /* factory */])(bignumber_name, bignumber_dependencies, function (_ref) { + var typed = _ref.typed, + BigNumber = _ref.BigNumber; + + /** + * Create a BigNumber, which can store numbers with arbitrary precision. + * When a matrix is provided, all elements will be converted to BigNumber. + * + * Syntax: + * + * math.bignumber(x) + * + * Examples: + * + * 0.1 + 0.2 // returns number 0.30000000000000004 + * math.bignumber(0.1) + math.bignumber(0.2) // returns BigNumber 0.3 + * + * + * 7.2e500 // returns number Infinity + * math.bignumber('7.2e500') // returns BigNumber 7.2e500 + * + * See also: + * + * boolean, complex, index, matrix, string, unit + * + * @param {number | string | Fraction | BigNumber | Array | Matrix | boolean | null} [value] Value for the big number, + * 0 by default. + * @returns {BigNumber} The created bignumber + */ + var bignumber = typed('bignumber', { + '': function _() { + return new BigNumber(0); + }, + number: function number(x) { + // convert to string to prevent errors in case of >15 digits + return new BigNumber(x + ''); + }, + string: function string(x) { + return new BigNumber(x); + }, + BigNumber: function BigNumber(x) { + // we assume a BigNumber is immutable + return x; + }, + Fraction: function Fraction(x) { + return new BigNumber(x.n).div(x.d).times(x.s); + }, + "null": function _null(x) { + return new BigNumber(0); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, bignumber); + } + }); + return bignumber; +}); +// CONCATENATED MODULE: ./src/type/complex/function/complex.js + + +var complex_name = 'complex'; +var complex_dependencies = ['typed', 'Complex']; +var createComplex = /* #__PURE__ */Object(factory["a" /* factory */])(complex_name, complex_dependencies, function (_ref) { + var typed = _ref.typed, + Complex = _ref.Complex; + + /** + * Create a complex value or convert a value to a complex value. + * + * Syntax: + * + * math.complex() // creates a complex value with zero + * // as real and imaginary part. + * math.complex(re : number, im : string) // creates a complex value with provided + * // values for real and imaginary part. + * math.complex(re : number) // creates a complex value with provided + * // real value and zero imaginary part. + * math.complex(complex : Complex) // clones the provided complex value. + * math.complex(arg : string) // parses a string into a complex value. + * math.complex(array : Array) // converts the elements of the array + * // or matrix element wise into a + * // complex value. + * math.complex({re: number, im: number}) // creates a complex value with provided + * // values for real an imaginary part. + * math.complex({r: number, phi: number}) // creates a complex value with provided + * // polar coordinates + * + * Examples: + * + * const a = math.complex(3, -4) // a = Complex 3 - 4i + * a.re = 5 // a = Complex 5 - 4i + * const i = a.im // Number -4 + * const b = math.complex('2 + 6i') // Complex 2 + 6i + * const c = math.complex() // Complex 0 + 0i + * const d = math.add(a, b) // Complex 5 + 2i + * + * See also: + * + * bignumber, boolean, index, matrix, number, string, unit + * + * @param {* | Array | Matrix} [args] + * Arguments specifying the real and imaginary part of the complex number + * @return {Complex | Array | Matrix} Returns a complex value + */ + var complex = typed('complex', { + '': function _() { + return Complex.ZERO; + }, + number: function number(x) { + return new Complex(x, 0); + }, + 'number, number': function numberNumber(re, im) { + return new Complex(re, im); + }, + // TODO: this signature should be redundant + 'BigNumber, BigNumber': function BigNumberBigNumber(re, im) { + return new Complex(re.toNumber(), im.toNumber()); + }, + Fraction: function Fraction(x) { + return new Complex(x.valueOf(), 0); + }, + Complex: function Complex(x) { + return x.clone(); + }, + string: function string(x) { + return Complex(x); // for example '2 + 3i' + }, + "null": function _null(x) { + return Complex(0); + }, + Object: function Object(x) { + if ('re' in x && 'im' in x) { + return new Complex(x.re, x.im); + } + + if ('r' in x && 'phi' in x || 'abs' in x && 'arg' in x) { + return new Complex(x); + } + + throw new Error('Expected object with properties (re and im) or (r and phi) or (abs and arg)'); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, complex); + } + }); + return complex; +}); +// CONCATENATED MODULE: ./src/type/fraction/function/fraction.js + + +var fraction_name = 'fraction'; +var fraction_dependencies = ['typed', 'Fraction']; +var createFraction = /* #__PURE__ */Object(factory["a" /* factory */])(fraction_name, fraction_dependencies, function (_ref) { + var typed = _ref.typed, + Fraction = _ref.Fraction; + + /** + * Create a fraction convert a value to a fraction. + * + * Syntax: + * math.fraction(numerator, denominator) + * math.fraction({n: numerator, d: denominator}) + * math.fraction(matrix: Array | Matrix) Turn all matrix entries + * into fractions + * + * Examples: + * + * math.fraction(1, 3) + * math.fraction('2/3') + * math.fraction({n: 2, d: 3}) + * math.fraction([0.2, 0.25, 1.25]) + * + * See also: + * + * bignumber, number, string, unit + * + * @param {number | string | Fraction | BigNumber | Array | Matrix} [args] + * Arguments specifying the numerator and denominator of + * the fraction + * @return {Fraction | Array | Matrix} Returns a fraction + */ + var fraction = typed('fraction', { + number: function number(x) { + if (!isFinite(x) || isNaN(x)) { + throw new Error(x + ' cannot be represented as a fraction'); + } + + return new Fraction(x); + }, + string: function string(x) { + return new Fraction(x); + }, + 'number, number': function numberNumber(numerator, denominator) { + return new Fraction(numerator, denominator); + }, + "null": function _null(x) { + return new Fraction(0); + }, + BigNumber: function BigNumber(x) { + return new Fraction(x.toString()); + }, + Fraction: function Fraction(x) { + return x; // fractions are immutable + }, + Object: function Object(x) { + return new Fraction(x); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, fraction); + } + }); + return fraction; +}); +// CONCATENATED MODULE: ./src/type/matrix/function/matrix.js + +var matrix_name = 'matrix'; +var matrix_dependencies = ['typed', 'Matrix', 'DenseMatrix', 'SparseMatrix']; +var createMatrix = /* #__PURE__ */Object(factory["a" /* factory */])(matrix_name, matrix_dependencies, function (_ref) { + var typed = _ref.typed, + Matrix = _ref.Matrix, + DenseMatrix = _ref.DenseMatrix, + SparseMatrix = _ref.SparseMatrix; + + /** + * Create a Matrix. The function creates a new `math.Matrix` object from + * an `Array`. A Matrix has utility functions to manipulate the data in the + * matrix, like getting the size and getting or setting values in the matrix. + * Supported storage formats are 'dense' and 'sparse'. + * + * Syntax: + * + * math.matrix() // creates an empty matrix using default storage format (dense). + * math.matrix(data) // creates a matrix with initial data using default storage format (dense). + * math.matrix('dense') // creates an empty matrix using the given storage format. + * math.matrix(data, 'dense') // creates a matrix with initial data using the given storage format. + * math.matrix(data, 'sparse') // creates a sparse matrix with initial data. + * math.matrix(data, 'sparse', 'number') // creates a sparse matrix with initial data, number data type. + * + * Examples: + * + * let m = math.matrix([[1, 2], [3, 4]]) + * m.size() // Array [2, 2] + * m.resize([3, 2], 5) + * m.valueOf() // Array [[1, 2], [3, 4], [5, 5]] + * m.get([1, 0]) // number 3 + * + * See also: + * + * bignumber, boolean, complex, index, number, string, unit, sparse + * + * @param {Array | Matrix} [data] A multi dimensional array + * @param {string} [format] The Matrix storage format + * + * @return {Matrix} The created matrix + */ + return typed(matrix_name, { + '': function _() { + return _create([]); + }, + string: function string(format) { + return _create([], format); + }, + 'string, string': function stringString(format, datatype) { + return _create([], format, datatype); + }, + Array: function Array(data) { + return _create(data); + }, + Matrix: function Matrix(data) { + return _create(data, data.storage()); + }, + 'Array | Matrix, string': _create, + 'Array | Matrix, string, string': _create + }); + /** + * Create a new Matrix with given storage format + * @param {Array} data + * @param {string} [format] + * @param {string} [datatype] + * @returns {Matrix} Returns a new Matrix + * @private + */ + + function _create(data, format, datatype) { + // get storage format constructor + if (format === 'dense' || format === 'default' || format === undefined) { + return new DenseMatrix(data, datatype); + } + + if (format === 'sparse') { + return new SparseMatrix(data, datatype); + } + + throw new TypeError('Unknown matrix type ' + JSON.stringify(format) + '.'); + } +}); +// CONCATENATED MODULE: ./src/type/unit/function/splitUnit.js + +var splitUnit_name = 'splitUnit'; +var splitUnit_dependencies = ['typed']; +var createSplitUnit = /* #__PURE__ */Object(factory["a" /* factory */])(splitUnit_name, splitUnit_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Split a unit in an array of units whose sum is equal to the original unit. + * + * Syntax: + * + * splitUnit(unit: Unit, parts: Array.) + * + * Example: + * + * math.splitUnit(new Unit(1, 'm'), ['feet', 'inch']) + * // [ 3 feet, 3.3700787401575 inch ] + * + * See also: + * + * unit + * + * @param {Array} [parts] An array of strings or valueless units. + * @return {Array} An array of units. + */ + return typed(splitUnit_name, { + 'Unit, Array': function UnitArray(unit, parts) { + return unit.splitUnit(parts); + } + }); +}); +// CONCATENATED MODULE: ./src/plain/number/arithmetic.js + +var arithmetic_n1 = 'number'; +var arithmetic_n2 = 'number, number'; +function absNumber(a) { + return Math.abs(a); +} +absNumber.signature = arithmetic_n1; +function addNumber(a, b) { + return a + b; +} +addNumber.signature = arithmetic_n2; +function subtractNumber(a, b) { + return a - b; +} +subtractNumber.signature = arithmetic_n2; +function multiplyNumber(a, b) { + return a * b; +} +multiplyNumber.signature = arithmetic_n2; +function divideNumber(a, b) { + return a / b; +} +divideNumber.signature = arithmetic_n2; +function unaryMinusNumber(x) { + return -x; +} +unaryMinusNumber.signature = arithmetic_n1; +function unaryPlusNumber(x) { + return x; +} +unaryPlusNumber.signature = arithmetic_n1; +function cbrtNumber(x) { + return Object(utils_number["d" /* cbrt */])(x); +} +cbrtNumber.signature = arithmetic_n1; +function ceilNumber(x) { + return Math.ceil(x); +} +ceilNumber.signature = arithmetic_n1; +function cubeNumber(x) { + return x * x * x; +} +cubeNumber.signature = arithmetic_n1; +function expNumber(x) { + return Math.exp(x); +} +expNumber.signature = arithmetic_n1; +function expm1Number(x) { + return Object(utils_number["g" /* expm1 */])(x); +} +expm1Number.signature = arithmetic_n1; +function fixNumber(x) { + return x > 0 ? Math.floor(x) : Math.ceil(x); +} +fixNumber.signature = arithmetic_n1; +function floorNumber(x) { + return Math.floor(x); +} +floorNumber.signature = arithmetic_n1; +/** + * Calculate gcd for numbers + * @param {number} a + * @param {number} b + * @returns {number} Returns the greatest common denominator of a and b + */ + +function gcdNumber(a, b) { + if (!Object(utils_number["i" /* isInteger */])(a) || !Object(utils_number["i" /* isInteger */])(b)) { + throw new Error('Parameters in function gcd must be integer numbers'); + } // https://en.wikipedia.org/wiki/Euclidean_algorithm + + + var r; + + while (b !== 0) { + r = a % b; + a = b; + b = r; + } + + return a < 0 ? -a : a; +} +gcdNumber.signature = arithmetic_n2; +/** + * Calculate lcm for two numbers + * @param {number} a + * @param {number} b + * @returns {number} Returns the least common multiple of a and b + */ + +function lcmNumber(a, b) { + if (!Object(utils_number["i" /* isInteger */])(a) || !Object(utils_number["i" /* isInteger */])(b)) { + throw new Error('Parameters in function lcm must be integer numbers'); + } + + if (a === 0 || b === 0) { + return 0; + } // https://en.wikipedia.org/wiki/Euclidean_algorithm + // evaluate lcm here inline to reduce overhead + + + var t; + var prod = a * b; + + while (b !== 0) { + t = b; + b = a % t; + a = t; + } + + return Math.abs(prod / a); +} +lcmNumber.signature = arithmetic_n2; +/** + * Calculate the logarithm of a value. + * @param {number} x + * @return {number} + */ + +function logNumber(x) { + return Math.log(x); +} +logNumber.signature = arithmetic_n1; +/** + * Calculate the 10-base logarithm of a number + * @param {number} x + * @return {number} + */ + +function log10Number(x) { + return Object(utils_number["j" /* log10 */])(x); +} +log10Number.signature = arithmetic_n1; +/** + * Calculate the 2-base logarithm of a number + * @param {number} x + * @return {number} + */ + +function log2Number(x) { + return Object(utils_number["l" /* log2 */])(x); +} +log2Number.signature = arithmetic_n1; +/** + * Calculate the natural logarithm of a `number+1` + * @param {number} x + * @returns {number} + */ + +function log1pNumber(x) { + return Object(utils_number["k" /* log1p */])(x); +} +log1pNumber.signature = arithmetic_n1; +/** + * Calculate the modulus of two numbers + * @param {number} x + * @param {number} y + * @returns {number} res + * @private + */ + +function modNumber(x, y) { + if (y > 0) { + // We don't use JavaScript's % operator here as this doesn't work + // correctly for x < 0 and x === 0 + // see https://en.wikipedia.org/wiki/Modulo_operation + return x - y * Math.floor(x / y); + } else if (y === 0) { + return x; + } else { + // y < 0 + // TODO: implement mod for a negative divisor + throw new Error('Cannot calculate mod for a negative divisor'); + } +} +modNumber.signature = arithmetic_n2; +/** + * Calculate the nth root of a, solve x^root == a + * http://rosettacode.org/wiki/Nth_root#JavaScript + * @param {number} a + * @param {number} root + * @private + */ + +function nthRootNumber(a, root) { + var inv = root < 0; + + if (inv) { + root = -root; + } + + if (root === 0) { + throw new Error('Root must be non-zero'); + } + + if (a < 0 && Math.abs(root) % 2 !== 1) { + throw new Error('Root must be odd when a is negative.'); + } // edge cases zero and infinity + + + if (a === 0) { + return inv ? Infinity : 0; + } + + if (!isFinite(a)) { + return inv ? 0 : a; + } + + var x = Math.pow(Math.abs(a), 1 / root); // If a < 0, we require that root is an odd integer, + // so (-1) ^ (1/root) = -1 + + x = a < 0 ? -x : x; + return inv ? 1 / x : x; // Very nice algorithm, but fails with nthRoot(-2, 3). + // Newton's method has some well-known problems at times: + // https://en.wikipedia.org/wiki/Newton%27s_method#Failure_analysis + + /* + let x = 1 // Initial guess + let xPrev = 1 + let i = 0 + const iMax = 10000 + do { + const delta = (a / Math.pow(x, root - 1) - x) / root + xPrev = x + x = x + delta + i++ + } + while (xPrev !== x && i < iMax) + if (xPrev !== x) { + throw new Error('Function nthRoot failed to converge') + } + return inv ? 1 / x : x + */ +} +nthRootNumber.signature = arithmetic_n2; +function signNumber(x) { + return Object(utils_number["n" /* sign */])(x); +} +signNumber.signature = arithmetic_n1; +function sqrtNumber(x) { + return Math.sqrt(x); +} +sqrtNumber.signature = arithmetic_n1; +function squareNumber(x) { + return x * x; +} +squareNumber.signature = arithmetic_n1; +/** + * Calculate xgcd for two numbers + * @param {number} a + * @param {number} b + * @return {number} result + * @private + */ + +function xgcdNumber(a, b) { + // source: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm + var t; // used to swap two variables + + var q; // quotient + + var r; // remainder + + var x = 0; + var lastx = 1; + var y = 1; + var lasty = 0; + + if (!Object(utils_number["i" /* isInteger */])(a) || !Object(utils_number["i" /* isInteger */])(b)) { + throw new Error('Parameters in function xgcd must be integer numbers'); + } + + while (b) { + q = Math.floor(a / b); + r = a - q * b; + t = x; + x = lastx - q * x; + lastx = t; + t = y; + y = lasty - q * y; + lasty = t; + a = b; + b = r; + } + + var res; + + if (a < 0) { + res = [-a, -lastx, -lasty]; + } else { + res = [a, a ? lastx : 0, lasty]; + } + + return res; +} +xgcdNumber.signature = arithmetic_n2; +/** + * Calculates the power of x to y, x^y, for two numbers. + * @param {number} x + * @param {number} y + * @return {number} res + */ + +function powNumber(x, y) { + // x^Infinity === 0 if -1 < x < 1 + // A real number 0 is returned instead of complex(0) + if (x * x < 1 && y === Infinity || x * x > 1 && y === -Infinity) { + return 0; + } + + return Math.pow(x, y); +} +powNumber.signature = arithmetic_n2; +/** + * round a number to the given number of decimals, or to zero if decimals is + * not provided + * @param {number} value + * @param {number} decimals number of decimals, between 0 and 15 (0 by default) + * @return {number} roundedValue + */ + +function roundNumber(value) { + var decimals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + return parseFloat(Object(utils_number["q" /* toFixed */])(value, decimals)); +} +roundNumber.signature = arithmetic_n2; +/** + * Calculate the norm of a number, the absolute value. + * @param {number} x + * @return {number} + */ + +function normNumber(x) { + return Math.abs(x); +} +normNumber.signature = arithmetic_n1; +// CONCATENATED MODULE: ./src/function/arithmetic/unaryMinus.js + + + +var unaryMinus_name = 'unaryMinus'; +var unaryMinus_dependencies = ['typed']; +var createUnaryMinus = /* #__PURE__ */Object(factory["a" /* factory */])(unaryMinus_name, unaryMinus_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Inverse the sign of a value, apply a unary minus operation. + * + * For matrices, the function is evaluated element wise. Boolean values and + * strings will be converted to a number. For complex numbers, both real and + * complex value are inverted. + * + * Syntax: + * + * math.unaryMinus(x) + * + * Examples: + * + * math.unaryMinus(3.5) // returns -3.5 + * math.unaryMinus(-4.2) // returns 4.2 + * + * See also: + * + * add, subtract, unaryPlus + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Number to be inverted. + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Returns the value with inverted sign. + */ + var unaryMinus = typed(unaryMinus_name, { + number: unaryMinusNumber, + Complex: function Complex(x) { + return x.neg(); + }, + BigNumber: function BigNumber(x) { + return x.neg(); + }, + Fraction: function Fraction(x) { + return x.neg(); + }, + Unit: function Unit(x) { + var res = x.clone(); + res.value = unaryMinus(x.value); + return res; + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since unaryMinus(0) = 0 + return deepMap(x, unaryMinus, true); + } // TODO: add support for string + + }); + return unaryMinus; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/unaryPlus.js + + + +var unaryPlus_name = 'unaryPlus'; +var unaryPlus_dependencies = ['typed', 'config', 'BigNumber']; +var createUnaryPlus = /* #__PURE__ */Object(factory["a" /* factory */])(unaryPlus_name, unaryPlus_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + BigNumber = _ref.BigNumber; + + /** + * Unary plus operation. + * Boolean values and strings will be converted to a number, numeric values will be returned as is. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.unaryPlus(x) + * + * Examples: + * + * math.unaryPlus(3.5) // returns 3.5 + * math.unaryPlus(1) // returns 1 + * + * See also: + * + * unaryMinus, add, subtract + * + * @param {number | BigNumber | Fraction | string | Complex | Unit | Array | Matrix} x + * Input value + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} + * Returns the input value when numeric, converts to a number when input is non-numeric. + */ + var unaryPlus = typed(unaryPlus_name, { + number: unaryPlusNumber, + Complex: function Complex(x) { + return x; // complex numbers are immutable + }, + BigNumber: function BigNumber(x) { + return x; // bignumbers are immutable + }, + Fraction: function Fraction(x) { + return x; // fractions are immutable + }, + Unit: function Unit(x) { + return x.clone(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since unaryPlus(0) = 0 + return deepMap(x, unaryPlus, true); + }, + 'boolean | string': function booleanString(x) { + // convert to a number or bignumber + return config.number === 'BigNumber' ? new BigNumber(+x) : +x; + } + }); + return unaryPlus; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/abs.js + + + +var abs_name = 'abs'; +var abs_dependencies = ['typed']; +var createAbs = /* #__PURE__ */Object(factory["a" /* factory */])(abs_name, abs_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the absolute value of a number. For matrices, the function is + * evaluated element wise. + * + * Syntax: + * + * math.abs(x) + * + * Examples: + * + * math.abs(3.5) // returns number 3.5 + * math.abs(-4.2) // returns number 4.2 + * + * math.abs([3, -5, -1, 0, 2]) // returns Array [3, 5, 1, 0, 2] + * + * See also: + * + * sign + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x + * A number or matrix for which to get the absolute value + * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} + * Absolute value of `x` + */ + var abs = typed(abs_name, { + number: absNumber, + Complex: function Complex(x) { + return x.abs(); + }, + BigNumber: function BigNumber(x) { + return x.abs(); + }, + Fraction: function Fraction(x) { + return x.abs(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since abs(0) = 0 + return deepMap(x, abs, true); + }, + Unit: function Unit(x) { + return x.abs(); + } + }); + return abs; +}); +// CONCATENATED MODULE: ./src/function/matrix/apply.js + + + + +var apply_name = 'apply'; +var apply_dependencies = ['typed', 'isInteger']; +var createApply = /* #__PURE__ */Object(factory["a" /* factory */])(apply_name, apply_dependencies, function (_ref) { + var typed = _ref.typed, + isInteger = _ref.isInteger; + + /** + * Apply a function that maps an array to a scalar + * along a given axis of a matrix or array. + * Returns a new matrix or array with one less dimension than the input. + * + * Syntax: + * + * math.apply(A, dim, callback) + * + * Where: + * + * - `dim: number` is a zero-based dimension over which to concatenate the matrices. + * + * Examples: + * + * const A = [[1, 2], [3, 4]] + * const sum = math.sum + * + * math.apply(A, 0, sum) // returns [4, 6] + * math.apply(A, 1, sum) // returns [3, 7] + * + * See also: + * + * map, filter, forEach + * + * @param {Array | Matrix} array The input Matrix + * @param {number} dim The dimension along which the callback is applied + * @param {Function} callback The callback function that is applied. This Function + * should take an array or 1-d matrix as an input and + * return a number. + * @return {Array | Matrix} res The residual matrix with the function applied over some dimension. + */ + var apply = typed(apply_name, { + 'Array | Matrix, number | BigNumber, function': function ArrayMatrixNumberBigNumberFunction(mat, dim, callback) { + if (!isInteger(dim)) { + throw new TypeError('Integer number expected for dimension'); + } + + var size = Array.isArray(mat) ? Object(utils_array["a" /* arraySize */])(mat) : mat.size(); + + if (dim < 0 || dim >= size.length) { + throw new IndexError["a" /* IndexError */](dim, size.length); + } + + if (Object(is["v" /* isMatrix */])(mat)) { + return mat.create(_apply(mat.valueOf(), dim, callback)); + } else { + return _apply(mat, dim, callback); + } + } + }); + return apply; +}); +/** + * Recursively reduce a matrix + * @param {Array} mat + * @param {number} dim + * @param {Function} callback + * @returns {Array} ret + * @private + */ + +function _apply(mat, dim, callback) { + var i, ret, tran; + + if (dim <= 0) { + if (!Array.isArray(mat[0])) { + return callback(mat); + } else { + tran = apply_switch(mat); + ret = []; + + for (i = 0; i < tran.length; i++) { + ret[i] = _apply(tran[i], dim - 1, callback); + } + + return ret; + } + } else { + ret = []; + + for (i = 0; i < mat.length; i++) { + ret[i] = _apply(mat[i], dim - 1, callback); + } + + return ret; + } +} +/** + * Transpose a matrix + * @param {Array} mat + * @returns {Array} ret + * @private + */ + + +function apply_switch(mat) { + var I = mat.length; + var J = mat[0].length; + var i, j; + var ret = []; + + for (j = 0; j < J; j++) { + var tmp = []; + + for (i = 0; i < I; i++) { + tmp.push(mat[i][j]); + } + + ret.push(tmp); + } + + return ret; +} +// CONCATENATED MODULE: ./src/function/arithmetic/addScalar.js + + +var addScalar_name = 'addScalar'; +var addScalar_dependencies = ['typed']; +var createAddScalar = /* #__PURE__ */Object(factory["a" /* factory */])(addScalar_name, addScalar_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Add two scalar values, `x + y`. + * This function is meant for internal use: it is used by the public function + * `add` + * + * This function does not support collections (Array or Matrix). + * + * @param {number | BigNumber | Fraction | Complex | Unit} x First value to add + * @param {number | BigNumber | Fraction | Complex} y Second value to add + * @return {number | BigNumber | Fraction | Complex | Unit} Sum of `x` and `y` + * @private + */ + var addScalar = typed(addScalar_name, { + 'number, number': addNumber, + 'Complex, Complex': function ComplexComplex(x, y) { + return x.add(y); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.plus(y); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.add(y); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (x.value === null || x.value === undefined) throw new Error('Parameter x contains a unit with undefined value'); + if (y.value === null || y.value === undefined) throw new Error('Parameter y contains a unit with undefined value'); + if (!x.equalBase(y)) throw new Error('Units do not match'); + var res = x.clone(); + res.value = addScalar(res.value, y.value); + res.fixPrefix = false; + return res; + } + }); + return addScalar; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/cbrt.js + + + + +var cbrt_name = 'cbrt'; +var cbrt_dependencies = ['config', 'typed', 'isNegative', 'unaryMinus', 'matrix', 'Complex', 'BigNumber', 'Fraction']; +var createCbrt = /* #__PURE__ */Object(factory["a" /* factory */])(cbrt_name, cbrt_dependencies, function (_ref) { + var config = _ref.config, + typed = _ref.typed, + isNegative = _ref.isNegative, + unaryMinus = _ref.unaryMinus, + matrix = _ref.matrix, + Complex = _ref.Complex, + BigNumber = _ref.BigNumber, + Fraction = _ref.Fraction; + + /** + * Calculate the cubic root of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.cbrt(x) + * math.cbrt(x, allRoots) + * + * Examples: + * + * math.cbrt(27) // returns 3 + * math.cube(3) // returns 27 + * math.cbrt(-64) // returns -4 + * math.cbrt(math.unit('27 m^3')) // returns Unit 3 m + * math.cbrt([27, 64, 125]) // returns [3, 4, 5] + * + * const x = math.complex('8i') + * math.cbrt(x) // returns Complex 1.7320508075689 + i + * math.cbrt(x, true) // returns Matrix [ + * // 1.7320508075689 + i + * // -1.7320508075689 + i + * // -2i + * // ] + * + * See also: + * + * square, sqrt, cube + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x + * Value for which to calculate the cubic root. + * @param {boolean} [allRoots] Optional, false by default. Only applicable + * when `x` is a number or complex number. If true, all complex + * roots are returned, if false (default) the principal root is + * returned. + * @return {number | BigNumber | Complex | Unit | Array | Matrix} + * Returns the cubic root of `x` + */ + var cbrt = typed(cbrt_name, { + number: cbrtNumber, + // note: signature 'number, boolean' is also supported, + // created by typed as it knows how to convert number to Complex + Complex: _cbrtComplex, + 'Complex, boolean': _cbrtComplex, + BigNumber: function BigNumber(x) { + return x.cbrt(); + }, + Unit: _cbrtUnit, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since cbrt(0) = 0 + return deepMap(x, cbrt, true); + } + }); + /** + * Calculate the cubic root for a complex number + * @param {Complex} x + * @param {boolean} [allRoots] If true, the function will return an array + * with all three roots. If false or undefined, + * the principal root is returned. + * @returns {Complex | Array. | Matrix.} Returns the cubic root(s) of x + * @private + */ + + function _cbrtComplex(x, allRoots) { + // https://www.wikiwand.com/en/Cube_root#/Complex_numbers + var arg3 = x.arg() / 3; + var abs = x.abs(); // principal root: + + var principal = new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3).exp()); + + if (allRoots) { + var all = [principal, new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3 + Math.PI * 2 / 3).exp()), new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3 - Math.PI * 2 / 3).exp())]; + return config.matrix === 'Array' ? all : matrix(all); + } else { + return principal; + } + } + /** + * Calculate the cubic root for a Unit + * @param {Unit} x + * @return {Unit} Returns the cubic root of x + * @private + */ + + + function _cbrtUnit(x) { + if (x.value && Object(is["j" /* isComplex */])(x.value)) { + var result = x.clone(); + result.value = 1.0; + result = result.pow(1.0 / 3); // Compute the units + + result.value = _cbrtComplex(x.value); // Compute the value + + return result; + } else { + var negate = isNegative(x.value); + + if (negate) { + x.value = unaryMinus(x.value); + } // TODO: create a helper function for this + + + var third; + + if (Object(is["e" /* isBigNumber */])(x.value)) { + third = new BigNumber(1).div(3); + } else if (Object(is["o" /* isFraction */])(x.value)) { + third = new Fraction(1, 3); + } else { + third = 1 / 3; + } + + var _result = x.pow(third); + + if (negate) { + _result.value = unaryMinus(_result.value); + } + + return _result; + } + } + + return cbrt; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/ceil.js + + + + + +var ceil_name = 'ceil'; +var ceil_dependencies = ['typed', 'config', 'round']; +var createCeil = /* #__PURE__ */Object(factory["a" /* factory */])(ceil_name, ceil_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + round = _ref.round; + + /** + * Round a value towards plus infinity + * If `x` is complex, both real and imaginary part are rounded towards plus infinity. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.ceil(x) + * + * Examples: + * + * math.ceil(3.2) // returns number 4 + * math.ceil(3.8) // returns number 4 + * math.ceil(-4.2) // returns number -4 + * math.ceil(-4.7) // returns number -4 + * + * const c = math.complex(3.2, -2.7) + * math.ceil(c) // returns Complex 4 - 2i + * + * math.ceil([3.2, 3.8, -4.7]) // returns Array [4, 4, -4] + * + * See also: + * + * floor, fix, round + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded + * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value + */ + var ceil = typed('ceil', { + number: function number(x) { + if (Object(utils_number["m" /* nearlyEqual */])(x, round(x), config.epsilon)) { + return round(x); + } else { + return ceilNumber(x); + } + }, + Complex: function Complex(x) { + return x.ceil(); + }, + BigNumber: function BigNumber(x) { + if (nearlyEqual(x, round(x), config.epsilon)) { + return round(x); + } else { + return x.ceil(); + } + }, + Fraction: function Fraction(x) { + return x.ceil(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since ceil(0) = 0 + return deepMap(x, ceil, true); + } + }); + return ceil; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/cube.js + + + +var cube_name = 'cube'; +var cube_dependencies = ['typed']; +var createCube = /* #__PURE__ */Object(factory["a" /* factory */])(cube_name, cube_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the cube of a value, `x * x * x`. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.cube(x) + * + * Examples: + * + * math.cube(2) // returns number 8 + * math.pow(2, 3) // returns number 8 + * math.cube(4) // returns number 64 + * 4 * 4 * 4 // returns number 64 + * + * math.cube([1, 2, 3, 4]) // returns Array [1, 8, 27, 64] + * + * See also: + * + * multiply, square, pow, cbrt + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x Number for which to calculate the cube + * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} Cube of x + */ + var cube = typed(cube_name, { + number: cubeNumber, + Complex: function Complex(x) { + return x.mul(x).mul(x); // Is faster than pow(x, 3) + }, + BigNumber: function BigNumber(x) { + return x.times(x).times(x); + }, + Fraction: function Fraction(x) { + return x.pow(3); // Is faster than mul()mul()mul() + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since cube(0) = 0 + return deepMap(x, cube, true); + }, + Unit: function Unit(x) { + return x.pow(3); + } + }); + return cube; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/exp.js + + + +var exp_name = 'exp'; +var exp_dependencies = ['typed']; +var createExp = /* #__PURE__ */Object(factory["a" /* factory */])(exp_name, exp_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the exponent of a value. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.exp(x) + * + * Examples: + * + * math.exp(2) // returns number 7.3890560989306495 + * math.pow(math.e, 2) // returns number 7.3890560989306495 + * math.log(math.exp(2)) // returns number 2 + * + * math.exp([1, 2, 3]) + * // returns Array [ + * // 2.718281828459045, + * // 7.3890560989306495, + * // 20.085536923187668 + * // ] + * + * See also: + * + * expm1, log, pow + * + * @param {number | BigNumber | Complex | Array | Matrix} x A number or matrix to exponentiate + * @return {number | BigNumber | Complex | Array | Matrix} Exponent of `x` + */ + var exp = typed(exp_name, { + number: expNumber, + Complex: function Complex(x) { + return x.exp(); + }, + BigNumber: function BigNumber(x) { + return x.exp(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // TODO: exp(sparse) should return a dense matrix since exp(0)==1 + return deepMap(x, exp); + } + }); + return exp; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/expm1.js + + + +var expm1_name = 'expm1'; +var expm1_dependencies = ['typed', 'Complex']; +var createExpm1 = /* #__PURE__ */Object(factory["a" /* factory */])(expm1_name, expm1_dependencies, function (_ref) { + var typed = _ref.typed, + _Complex = _ref.Complex; + + /** + * Calculate the value of subtracting 1 from the exponential value. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.expm1(x) + * + * Examples: + * + * math.expm1(2) // returns number 6.38905609893065 + * math.pow(math.e, 2) - 1 // returns number 6.3890560989306495 + * math.log(math.expm1(2) + 1) // returns number 2 + * + * math.expm1([1, 2, 3]) + * // returns Array [ + * // 1.718281828459045, + * // 6.3890560989306495, + * // 19.085536923187668 + * // ] + * + * See also: + * + * exp, log, pow + * + * @param {number | BigNumber | Complex | Array | Matrix} x A number or matrix to apply expm1 + * @return {number | BigNumber | Complex | Array | Matrix} Exponent of `x` + */ + var expm1 = typed(expm1_name, { + number: expm1Number, + Complex: function Complex(x) { + var r = Math.exp(x.re); + return new _Complex(r * Math.cos(x.im) - 1, r * Math.sin(x.im)); + }, + BigNumber: function BigNumber(x) { + return x.exp().minus(1); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, expm1); + } + }); + return expm1; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/fix.js + + +var fix_name = 'fix'; +var fix_dependencies = ['typed', 'Complex', 'ceil', 'floor']; +var createFix = /* #__PURE__ */Object(factory["a" /* factory */])(fix_name, fix_dependencies, function (_ref) { + var typed = _ref.typed, + _Complex = _ref.Complex, + ceil = _ref.ceil, + floor = _ref.floor; + + /** + * Round a value towards zero. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.fix(x) + * + * Examples: + * + * math.fix(3.2) // returns number 3 + * math.fix(3.8) // returns number 3 + * math.fix(-4.2) // returns number -4 + * math.fix(-4.7) // returns number -4 + * + * const c = math.complex(3.2, -2.7) + * math.fix(c) // returns Complex 3 - 2i + * + * math.fix([3.2, 3.8, -4.7]) // returns Array [3, 3, -4] + * + * See also: + * + * ceil, floor, round + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded + * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value + */ + var fix = typed('fix', { + number: function number(x) { + return x > 0 ? floor(x) : ceil(x); + }, + Complex: function Complex(x) { + return new _Complex(x.re > 0 ? Math.floor(x.re) : Math.ceil(x.re), x.im > 0 ? Math.floor(x.im) : Math.ceil(x.im)); + }, + BigNumber: function BigNumber(x) { + return x.isNegative() ? ceil(x) : floor(x); + }, + Fraction: function Fraction(x) { + return x.s < 0 ? x.ceil() : x.floor(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since fix(0) = 0 + return deepMap(x, fix, true); + } + }); + return fix; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/floor.js + + + + +var floor_name = 'floor'; +var floor_dependencies = ['typed', 'config', 'round']; +var createFloor = /* #__PURE__ */Object(factory["a" /* factory */])(floor_name, floor_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + round = _ref.round; + + /** + * Round a value towards minus infinity. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.floor(x) + * + * Examples: + * + * math.floor(3.2) // returns number 3 + * math.floor(3.8) // returns number 3 + * math.floor(-4.2) // returns number -5 + * math.floor(-4.7) // returns number -5 + * + * const c = math.complex(3.2, -2.7) + * math.floor(c) // returns Complex 3 - 3i + * + * math.floor([3.2, 3.8, -4.7]) // returns Array [3, 3, -5] + * + * See also: + * + * ceil, fix, round + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded + * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value + */ + var floor = typed('floor', { + number: function number(x) { + if (Object(utils_number["m" /* nearlyEqual */])(x, round(x), config.epsilon)) { + return round(x); + } else { + return Math.floor(x); + } + }, + Complex: function Complex(x) { + return x.floor(); + }, + BigNumber: function BigNumber(x) { + if (nearlyEqual(x, round(x), config.epsilon)) { + return round(x); + } else { + return x.floor(); + } + }, + Fraction: function Fraction(x) { + return x.floor(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since floor(0) = 0 + return deepMap(x, floor, true); + } + }); + return floor; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm01.js + + +var algorithm01_name = 'algorithm01'; +var algorithm01_dependencies = ['typed']; +var createAlgorithm01 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm01_name, algorithm01_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Iterates over SparseMatrix nonzero items and invokes the callback function f(Dij, Sij). + * Callback function invoked NNZ times (number of nonzero items in SparseMatrix). + * + * + * ┌ f(Dij, Sij) ; S(i,j) !== 0 + * C(i,j) = ┤ + * └ Dij ; otherwise + * + * + * @param {Matrix} denseMatrix The DenseMatrix instance (D) + * @param {Matrix} sparseMatrix The SparseMatrix instance (S) + * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j) + * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij) + * + * @return {Matrix} DenseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571 + */ + return function algorithm1(denseMatrix, sparseMatrix, callback, inverse) { + // dense matrix arrays + var adata = denseMatrix._data; + var asize = denseMatrix._size; + var adt = denseMatrix._datatype; // sparse matrix arrays + + var bvalues = sparseMatrix._values; + var bindex = sparseMatrix._index; + var bptr = sparseMatrix._ptr; + var bsize = sparseMatrix._size; + var bdt = sparseMatrix._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // sparse matrix cannot be a Pattern matrix + + + if (!bvalues) { + throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // process data types + + var dt = typeof adt === 'string' && adt === bdt ? adt : undefined; // callback function + + var cf = dt ? typed.find(callback, [dt, dt]) : callback; // vars + + var i, j; // result (DenseMatrix) + + var cdata = []; // initialize c + + for (i = 0; i < rows; i++) { + cdata[i] = []; + } // workspace + + + var x = []; // marks indicating we have a value in x for a given column + + var w = []; // loop columns in b + + for (j = 0; j < columns; j++) { + // column mark + var mark = j + 1; // values in column j + + for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) { + // row + i = bindex[k]; // update workspace + + x[i] = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]); // mark i as updated + + w[i] = mark; + } // loop rows + + + for (i = 0; i < rows; i++) { + // check row is in workspace + if (w[i] === mark) { + // c[i][j] was already calculated + cdata[i][j] = x[i]; + } else { + // item does not exist in S + cdata[i][j] = adata[i][j]; + } + } + } // return dense matrix + + + return denseMatrix.createDenseMatrix({ + data: cdata, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm04.js + + +var algorithm04_name = 'algorithm04'; +var algorithm04_dependencies = ['typed', 'equalScalar']; +var createAlgorithm04 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm04_name, algorithm04_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij). + * Callback function invoked MAX(NNZA, NNZB) times + * + * + * ┌ f(Aij, Bij) ; A(i,j) !== 0 && B(i,j) !== 0 + * C(i,j) = ┤ A(i,j) ; A(i,j) !== 0 + * └ B(i,j) ; B(i,j) !== 0 + * + * + * @param {Matrix} a The SparseMatrix instance (A) + * @param {Matrix} b The SparseMatrix instance (B) + * @param {Function} callback The f(Aij,Bij) operation to invoke + * + * @return {Matrix} SparseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294 + */ + return function algorithm04(a, b, callback) { + // sparse matrix arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; + var adt = a._datatype; // sparse matrix arrays + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; + var bsize = b._size; + var bdt = b._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cvalues = avalues && bvalues ? [] : undefined; + var cindex = []; + var cptr = []; // workspace + + var xa = avalues && bvalues ? [] : undefined; + var xb = avalues && bvalues ? [] : undefined; // marks indicating we have a value in x for a given column + + var wa = []; + var wb = []; // vars + + var i, j, k, k0, k1; // loop columns + + for (j = 0; j < columns; j++) { + // update cptr + cptr[j] = cindex.length; // columns mark + + var mark = j + 1; // loop A(:,j) + + for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + i = aindex[k]; // update c + + cindex.push(i); // update workspace + + wa[i] = mark; // check we need to process values + + if (xa) { + xa[i] = avalues[k]; + } + } // loop B(:,j) + + + for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) { + // row + i = bindex[k]; // check row exists in A + + if (wa[i] === mark) { + // update record in xa @ i + if (xa) { + // invoke callback + var v = cf(xa[i], bvalues[k]); // check for zero + + if (!eq(v, zero)) { + // update workspace + xa[i] = v; + } else { + // remove mark (index will be removed later) + wa[i] = null; + } + } + } else { + // update c + cindex.push(i); // update workspace + + wb[i] = mark; // check we need to process values + + if (xb) { + xb[i] = bvalues[k]; + } + } + } // check we need to process values (non pattern matrix) + + + if (xa && xb) { + // initialize first index in j + k = cptr[j]; // loop index in j + + while (k < cindex.length) { + // row + i = cindex[k]; // check workspace has value @ i + + if (wa[i] === mark) { + // push value (Aij != 0 || (Aij != 0 && Bij != 0)) + cvalues[k] = xa[i]; // increment pointer + + k++; + } else if (wb[i] === mark) { + // push value (bij != 0) + cvalues[k] = xb[i]; // increment pointer + + k++; + } else { + // remove index @ k + cindex.splice(k, 1); + } + } + } + } // update cptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm10.js + +var algorithm10_name = 'algorithm10'; +var algorithm10_dependencies = ['typed', 'DenseMatrix']; +var createAlgorithm10 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm10_name, algorithm10_dependencies, function (_ref) { + var typed = _ref.typed, + DenseMatrix = _ref.DenseMatrix; + + /** + * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b). + * Callback function invoked NZ times (number of nonzero items in S). + * + * + * ┌ f(Sij, b) ; S(i,j) !== 0 + * C(i,j) = ┤ + * └ b ; otherwise + * + * + * @param {Matrix} s The SparseMatrix instance (S) + * @param {Scalar} b The Scalar value + * @param {Function} callback The f(Aij,b) operation to invoke + * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij) + * + * @return {Matrix} DenseMatrix (C) + * + * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813 + */ + return function algorithm10(s, b, callback, inverse) { + // sparse matrix arrays + var avalues = s._values; + var aindex = s._index; + var aptr = s._ptr; + var asize = s._size; + var adt = s._datatype; // sparse matrix cannot be a Pattern matrix + + if (!avalues) { + throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string') { + // datatype + dt = adt; // convert b to the same datatype + + b = typed.convert(b, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cdata = []; // workspaces + + var x = []; // marks indicating we have a value in x for a given column + + var w = []; // loop columns + + for (var j = 0; j < columns; j++) { + // columns mark + var mark = j + 1; // values in j + + for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + var r = aindex[k]; // update workspace + + x[r] = avalues[k]; + w[r] = mark; + } // loop rows + + + for (var i = 0; i < rows; i++) { + // initialize C on first column + if (j === 0) { + // create row array + cdata[i] = []; + } // check sparse matrix has a value @ i,j + + + if (w[i] === mark) { + // invoke callback, update C + cdata[i][j] = inverse ? cf(b, x[i]) : cf(x[i], b); + } else { + // dense matrix value @ i, j + cdata[i][j] = b; + } + } + } // return dense matrix + + + return new DenseMatrix({ + data: cdata, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm13.js + + +var algorithm13_name = 'algorithm13'; +var algorithm13_dependencies = ['typed']; +var createAlgorithm13 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm13_name, algorithm13_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, Bij..z). + * Callback function invoked MxN times. + * + * C(i,j,...z) = f(Aij..z, Bij..z) + * + * @param {Matrix} a The DenseMatrix instance (A) + * @param {Matrix} b The DenseMatrix instance (B) + * @param {Function} callback The f(Aij..z,Bij..z) operation to invoke + * + * @return {Matrix} DenseMatrix (C) + * + * https://github.com/josdejong/mathjs/pull/346#issuecomment-97658658 + */ + return function algorithm13(a, b, callback) { + // a arrays + var adata = a._data; + var asize = a._size; + var adt = a._datatype; // b arrays + + var bdata = b._data; + var bsize = b._size; + var bdt = b._datatype; // c arrays + + var csize = []; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // validate each one of the dimension sizes + + + for (var s = 0; s < asize.length; s++) { + // must match + if (asize[s] !== bsize[s]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // update dimension in c + + + csize[s] = asize[s]; + } // datatype + + + var dt; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // callback + + cf = typed.find(callback, [dt, dt]); + } // populate cdata, iterate through dimensions + + + var cdata = csize.length > 0 ? _iterate(cf, 0, csize, csize[0], adata, bdata) : []; // c matrix + + return a.createDenseMatrix({ + data: cdata, + size: csize, + datatype: dt + }); + }; // recursive function + + function _iterate(f, level, s, n, av, bv) { + // initialize array for this level + var cv = []; // check we reach the last level + + if (level === s.length - 1) { + // loop arrays in last level + for (var i = 0; i < n; i++) { + // invoke callback and store value + cv[i] = f(av[i], bv[i]); + } + } else { + // iterate current level + for (var j = 0; j < n; j++) { + // iterate next level + cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv[j]); + } + } + + return cv; + } +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm14.js + + +var algorithm14_name = 'algorithm14'; +var algorithm14_dependencies = ['typed']; +var createAlgorithm14 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm14_name, algorithm14_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, b). + * Callback function invoked MxN times. + * + * C(i,j,...z) = f(Aij..z, b) + * + * @param {Matrix} a The DenseMatrix instance (A) + * @param {Scalar} b The Scalar value + * @param {Function} callback The f(Aij..z,b) operation to invoke + * @param {boolean} inverse A true value indicates callback should be invoked f(b,Aij..z) + * + * @return {Matrix} DenseMatrix (C) + * + * https://github.com/josdejong/mathjs/pull/346#issuecomment-97659042 + */ + return function algorithm14(a, b, callback, inverse) { + // a arrays + var adata = a._data; + var asize = a._size; + var adt = a._datatype; // datatype + + var dt; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string') { + // datatype + dt = adt; // convert b to the same datatype + + b = typed.convert(b, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // populate cdata, iterate through dimensions + + + var cdata = asize.length > 0 ? _iterate(cf, 0, asize, asize[0], adata, b, inverse) : []; // c matrix + + return a.createDenseMatrix({ + data: cdata, + size: Object(utils_object["a" /* clone */])(asize), + datatype: dt + }); + }; // recursive function + + function _iterate(f, level, s, n, av, bv, inverse) { + // initialize array for this level + var cv = []; // check we reach the last level + + if (level === s.length - 1) { + // loop arrays in last level + for (var i = 0; i < n; i++) { + // invoke callback and store value + cv[i] = inverse ? f(bv, av[i]) : f(av[i], bv); + } + } else { + // iterate current level + for (var j = 0; j < n; j++) { + // iterate next level + cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv, inverse); + } + } + + return cv; + } +}); +// CONCATENATED MODULE: ./src/function/arithmetic/gcd.js + + + + + + + +var gcd_name = 'gcd'; +var gcd_dependencies = ['typed', 'matrix', 'equalScalar', 'BigNumber', 'DenseMatrix']; +var createGcd = /* #__PURE__ */Object(factory["a" /* factory */])(gcd_name, gcd_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + BigNumber = _ref.BigNumber, + DenseMatrix = _ref.DenseMatrix; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm04 = createAlgorithm04({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Calculate the greatest common divisor for two or more values or arrays. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.gcd(a, b) + * math.gcd(a, b, c, ...) + * + * Examples: + * + * math.gcd(8, 12) // returns 4 + * math.gcd(-4, 6) // returns 2 + * math.gcd(25, 15, -10) // returns 5 + * + * math.gcd([8, -4], [12, 6]) // returns [4, 2] + * + * See also: + * + * lcm, xgcd + * + * @param {... number | BigNumber | Fraction | Array | Matrix} args Two or more integer numbers + * @return {number | BigNumber | Fraction | Array | Matrix} The greatest common divisor + */ + + var gcd = typed(gcd_name, { + 'number, number': gcdNumber, + 'BigNumber, BigNumber': _gcdBigNumber, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.gcd(y); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm04(x, y, gcd); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm01(y, x, gcd, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm01(x, y, gcd, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, gcd); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return gcd(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return gcd(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return gcd(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + return algorithm10(x, y, gcd, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + return algorithm14(x, y, gcd, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + return algorithm10(y, x, gcd, true); + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + return algorithm14(y, x, gcd, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, gcd, false).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, gcd, true).valueOf(); + }, + // TODO: need a smarter notation here + 'Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber': function ArrayMatrixNumberBigNumberArrayMatrixNumberBigNumberArrayMatrixNumberBigNumber(a, b, args) { + var res = gcd(a, b); + + for (var i = 0; i < args.length; i++) { + res = gcd(res, args[i]); + } + + return res; + } + }); + return gcd; + /** + * Calculate gcd for BigNumbers + * @param {BigNumber} a + * @param {BigNumber} b + * @returns {BigNumber} Returns greatest common denominator of a and b + * @private + */ + + function _gcdBigNumber(a, b) { + if (!a.isInt() || !b.isInt()) { + throw new Error('Parameters in function gcd must be integer numbers'); + } // https://en.wikipedia.org/wiki/Euclidean_algorithm + + + var zero = new BigNumber(0); + + while (!b.isZero()) { + var r = a.mod(b); + a = b; + b = r; + } + + return a.lt(zero) ? a.neg() : a; + } +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm02.js + + +var algorithm02_name = 'algorithm02'; +var algorithm02_dependencies = ['typed', 'equalScalar']; +var createAlgorithm02 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm02_name, algorithm02_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix nonzero items and invokes the callback function f(Dij, Sij). + * Callback function invoked NNZ times (number of nonzero items in SparseMatrix). + * + * + * ┌ f(Dij, Sij) ; S(i,j) !== 0 + * C(i,j) = ┤ + * └ 0 ; otherwise + * + * + * @param {Matrix} denseMatrix The DenseMatrix instance (D) + * @param {Matrix} sparseMatrix The SparseMatrix instance (S) + * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j) + * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij) + * + * @return {Matrix} SparseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571 + */ + return function algorithm02(denseMatrix, sparseMatrix, callback, inverse) { + // dense matrix arrays + var adata = denseMatrix._data; + var asize = denseMatrix._size; + var adt = denseMatrix._datatype; // sparse matrix arrays + + var bvalues = sparseMatrix._values; + var bindex = sparseMatrix._index; + var bptr = sparseMatrix._ptr; + var bsize = sparseMatrix._size; + var bdt = sparseMatrix._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // sparse matrix cannot be a Pattern matrix + + + if (!bvalues) { + throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result (SparseMatrix) + + + var cvalues = []; + var cindex = []; + var cptr = []; // loop columns in b + + for (var j = 0; j < columns; j++) { + // update cptr + cptr[j] = cindex.length; // values in column j + + for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) { + // row + var i = bindex[k]; // update C(i,j) + + var cij = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]); // check for nonzero + + if (!eq(cij, zero)) { + // push i & v + cindex.push(i); + cvalues.push(cij); + } + } + } // update cptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return sparseMatrix.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm06.js + + + +var algorithm06_name = 'algorithm06'; +var algorithm06_dependencies = ['typed', 'equalScalar']; +var createAlgorithm06 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm06_name, algorithm06_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij). + * Callback function invoked (Anz U Bnz) times, where Anz and Bnz are the nonzero elements in both matrices. + * + * + * ┌ f(Aij, Bij) ; A(i,j) !== 0 && B(i,j) !== 0 + * C(i,j) = ┤ + * └ 0 ; otherwise + * + * + * @param {Matrix} a The SparseMatrix instance (A) + * @param {Matrix} b The SparseMatrix instance (B) + * @param {Function} callback The f(Aij,Bij) operation to invoke + * + * @return {Matrix} SparseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294 + */ + return function algorithm06(a, b, callback) { + // sparse matrix arrays + var avalues = a._values; + var asize = a._size; + var adt = a._datatype; // sparse matrix arrays + + var bvalues = b._values; + var bsize = b._size; + var bdt = b._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cvalues = avalues && bvalues ? [] : undefined; + var cindex = []; + var cptr = []; // workspaces + + var x = cvalues ? [] : undefined; // marks indicating we have a value in x for a given column + + var w = []; // marks indicating value in a given row has been updated + + var u = []; // loop columns + + for (var j = 0; j < columns; j++) { + // update cptr + cptr[j] = cindex.length; // columns mark + + var mark = j + 1; // scatter the values of A(:,j) into workspace + + scatter(a, j, w, x, u, mark, cindex, cf); // scatter the values of B(:,j) into workspace + + scatter(b, j, w, x, u, mark, cindex, cf); // check we need to process values (non pattern matrix) + + if (x) { + // initialize first index in j + var k = cptr[j]; // loop index in j + + while (k < cindex.length) { + // row + var i = cindex[k]; // check function was invoked on current row (Aij !=0 && Bij != 0) + + if (u[i] === mark) { + // value @ i + var v = x[i]; // check for zero value + + if (!eq(v, zero)) { + // push value + cvalues.push(v); // increment pointer + + k++; + } else { + // remove value @ i, do not increment pointer + cindex.splice(k, 1); + } + } else { + // remove value @ i, do not increment pointer + cindex.splice(k, 1); + } + } + } else { + // initialize first index in j + var p = cptr[j]; // loop index in j + + while (p < cindex.length) { + // row + var r = cindex[p]; // check function was invoked on current row (Aij !=0 && Bij != 0) + + if (u[r] !== mark) { + // remove value @ i, do not increment pointer + cindex.splice(p, 1); + } else { + // increment pointer + p++; + } + } + } + } // update cptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm11.js + +var algorithm11_name = 'algorithm11'; +var algorithm11_dependencies = ['typed', 'equalScalar']; +var createAlgorithm11 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm11_name, algorithm11_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b). + * Callback function invoked NZ times (number of nonzero items in S). + * + * + * ┌ f(Sij, b) ; S(i,j) !== 0 + * C(i,j) = ┤ + * └ 0 ; otherwise + * + * + * @param {Matrix} s The SparseMatrix instance (S) + * @param {Scalar} b The Scalar value + * @param {Function} callback The f(Aij,b) operation to invoke + * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij) + * + * @return {Matrix} SparseMatrix (C) + * + * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813 + */ + return function algorithm11(s, b, callback, inverse) { + // sparse matrix arrays + var avalues = s._values; + var aindex = s._index; + var aptr = s._ptr; + var asize = s._size; + var adt = s._datatype; // sparse matrix cannot be a Pattern matrix + + if (!avalues) { + throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string') { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // convert b to the same datatype + + b = typed.convert(b, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cvalues = []; + var cindex = []; + var cptr = []; // loop columns + + for (var j = 0; j < columns; j++) { + // initialize ptr + cptr[j] = cindex.length; // values in j + + for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + var i = aindex[k]; // invoke callback + + var v = inverse ? cf(b, avalues[k]) : cf(avalues[k], b); // check value is zero + + if (!eq(v, zero)) { + // push index & value + cindex.push(i); + cvalues.push(v); + } + } + } // update ptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return s.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/lcm.js + + + + + + + +var lcm_name = 'lcm'; +var lcm_dependencies = ['typed', 'matrix', 'equalScalar']; +var createLcm = /* #__PURE__ */Object(factory["a" /* factory */])(lcm_name, lcm_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm06 = createAlgorithm06({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Calculate the least common multiple for two or more values or arrays. + * + * lcm is defined as: + * + * lcm(a, b) = abs(a * b) / gcd(a, b) + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.lcm(a, b) + * math.lcm(a, b, c, ...) + * + * Examples: + * + * math.lcm(4, 6) // returns 12 + * math.lcm(6, 21) // returns 42 + * math.lcm(6, 21, 5) // returns 210 + * + * math.lcm([4, 6], [6, 21]) // returns [12, 42] + * + * See also: + * + * gcd, xgcd + * + * @param {... number | BigNumber | Array | Matrix} args Two or more integer numbers + * @return {number | BigNumber | Array | Matrix} The least common multiple + */ + + var lcm = typed(lcm_name, { + 'number, number': lcmNumber, + 'BigNumber, BigNumber': _lcmBigNumber, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.lcm(y); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm06(x, y, lcm); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, lcm, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm02(x, y, lcm, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, lcm); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return lcm(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return lcm(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return lcm(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + return algorithm11(x, y, lcm, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + return algorithm14(x, y, lcm, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + return algorithm11(y, x, lcm, true); + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + return algorithm14(y, x, lcm, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, lcm, false).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, lcm, true).valueOf(); + }, + // TODO: need a smarter notation here + 'Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber': function ArrayMatrixNumberBigNumberArrayMatrixNumberBigNumberArrayMatrixNumberBigNumber(a, b, args) { + var res = lcm(a, b); + + for (var i = 0; i < args.length; i++) { + res = lcm(res, args[i]); + } + + return res; + } + }); + return lcm; + /** + * Calculate lcm for two BigNumbers + * @param {BigNumber} a + * @param {BigNumber} b + * @returns {BigNumber} Returns the least common multiple of a and b + * @private + */ + + function _lcmBigNumber(a, b) { + if (!a.isInt() || !b.isInt()) { + throw new Error('Parameters in function lcm must be integer numbers'); + } + + if (a.isZero()) { + return a; + } + + if (b.isZero()) { + return b; + } // https://en.wikipedia.org/wiki/Euclidean_algorithm + // evaluate lcm here inline to reduce overhead + + + var prod = a.times(b); + + while (!b.isZero()) { + var t = b; + b = a.mod(t); + a = t; + } + + return prod.div(a).abs(); + } +}); +// CONCATENATED MODULE: ./src/function/arithmetic/log10.js + + + +var log10_name = 'log10'; +var log10_dependencies = ['typed', 'config', 'Complex']; +var createLog10 = /* #__PURE__ */Object(factory["a" /* factory */])(log10_name, log10_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + _Complex = _ref.Complex; + + /** + * Calculate the 10-base logarithm of a value. This is the same as calculating `log(x, 10)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.log10(x) + * + * Examples: + * + * math.log10(0.00001) // returns -5 + * math.log10(10000) // returns 4 + * math.log(10000) / math.log(10) // returns 4 + * math.pow(10, 4) // returns 10000 + * + * See also: + * + * exp, log, log1p, log2 + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * Value for which to calculate the logarithm. + * @return {number | BigNumber | Complex | Array | Matrix} + * Returns the 10-base logarithm of `x` + */ + var log10 = typed(log10_name, { + number: function number(x) { + if (x >= 0 || config.predictable) { + return log10Number(x); + } else { + // negative value -> complex value computation + return new _Complex(x, 0).log().div(Math.LN10); + } + }, + Complex: function Complex(x) { + return new _Complex(x).log().div(Math.LN10); + }, + BigNumber: function BigNumber(x) { + if (!x.isNegative() || config.predictable) { + return x.log(); + } else { + // downgrade to number, return Complex valued result + return new _Complex(x.toNumber(), 0).log().div(Math.LN10); + } + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, log10); + } + }); + return log10; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/log2.js + + + +var log2_name = 'log2'; +var log2_dependencies = ['typed', 'config', 'Complex']; +var createLog2 = /* #__PURE__ */Object(factory["a" /* factory */])(log2_name, log2_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex; + + /** + * Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.log2(x) + * + * Examples: + * + * math.log2(0.03125) // returns -5 + * math.log2(16) // returns 4 + * math.log2(16) / math.log2(2) // returns 4 + * math.pow(2, 4) // returns 16 + * + * See also: + * + * exp, log, log1p, log10 + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * Value for which to calculate the logarithm. + * @return {number | BigNumber | Complex | Array | Matrix} + * Returns the 2-base logarithm of `x` + */ + var log2 = typed(log2_name, { + number: function number(x) { + if (x >= 0 || config.predictable) { + return log2Number(x); + } else { + // negative value -> complex value computation + return _log2Complex(new Complex(x, 0)); + } + }, + Complex: _log2Complex, + BigNumber: function BigNumber(x) { + if (!x.isNegative() || config.predictable) { + return x.log(2); + } else { + // downgrade to number, return Complex valued result + return _log2Complex(new Complex(x.toNumber(), 0)); + } + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, log2); + } + }); + /** + * Calculate log2 for a complex value + * @param {Complex} x + * @returns {Complex} + * @private + */ + + function _log2Complex(x) { + var newX = Math.sqrt(x.re * x.re + x.im * x.im); + return new Complex(Math.log2 ? Math.log2(newX) : Math.log(newX) / Math.LN2, Math.atan2(x.im, x.re) / Math.LN2); + } + + return log2; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm03.js + + +var algorithm03_name = 'algorithm03'; +var algorithm03_dependencies = ['typed']; +var createAlgorithm03 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm03_name, algorithm03_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Iterates over SparseMatrix items and invokes the callback function f(Dij, Sij). + * Callback function invoked M*N times. + * + * + * ┌ f(Dij, Sij) ; S(i,j) !== 0 + * C(i,j) = ┤ + * └ f(Dij, 0) ; otherwise + * + * + * @param {Matrix} denseMatrix The DenseMatrix instance (D) + * @param {Matrix} sparseMatrix The SparseMatrix instance (C) + * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j) + * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij) + * + * @return {Matrix} DenseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571 + */ + return function algorithm03(denseMatrix, sparseMatrix, callback, inverse) { + // dense matrix arrays + var adata = denseMatrix._data; + var asize = denseMatrix._size; + var adt = denseMatrix._datatype; // sparse matrix arrays + + var bvalues = sparseMatrix._values; + var bindex = sparseMatrix._index; + var bptr = sparseMatrix._ptr; + var bsize = sparseMatrix._size; + var bdt = sparseMatrix._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // sparse matrix cannot be a Pattern matrix + + + if (!bvalues) { + throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result (DenseMatrix) + + + var cdata = []; // initialize dense matrix + + for (var z = 0; z < rows; z++) { + // initialize row + cdata[z] = []; + } // workspace + + + var x = []; // marks indicating we have a value in x for a given column + + var w = []; // loop columns in b + + for (var j = 0; j < columns; j++) { + // column mark + var mark = j + 1; // values in column j + + for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) { + // row + var i = bindex[k]; // update workspace + + x[i] = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]); + w[i] = mark; + } // process workspace + + + for (var y = 0; y < rows; y++) { + // check we have a calculated value for current row + if (w[y] === mark) { + // use calculated value + cdata[y][j] = x[y]; + } else { + // calculate value + cdata[y][j] = inverse ? cf(zero, adata[y][j]) : cf(adata[y][j], zero); + } + } + } // return dense matrix + + + return denseMatrix.createDenseMatrix({ + data: cdata, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm05.js + + +var algorithm05_name = 'algorithm05'; +var algorithm05_dependencies = ['typed', 'equalScalar']; +var createAlgorithm05 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm05_name, algorithm05_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij). + * Callback function invoked MAX(NNZA, NNZB) times + * + * + * ┌ f(Aij, Bij) ; A(i,j) !== 0 || B(i,j) !== 0 + * C(i,j) = ┤ + * └ 0 ; otherwise + * + * + * @param {Matrix} a The SparseMatrix instance (A) + * @param {Matrix} b The SparseMatrix instance (B) + * @param {Function} callback The f(Aij,Bij) operation to invoke + * + * @return {Matrix} SparseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294 + */ + return function algorithm05(a, b, callback) { + // sparse matrix arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; + var adt = a._datatype; // sparse matrix arrays + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; + var bsize = b._size; + var bdt = b._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cvalues = avalues && bvalues ? [] : undefined; + var cindex = []; + var cptr = []; // workspaces + + var xa = cvalues ? [] : undefined; + var xb = cvalues ? [] : undefined; // marks indicating we have a value in x for a given column + + var wa = []; + var wb = []; // vars + + var i, j, k, k1; // loop columns + + for (j = 0; j < columns; j++) { + // update cptr + cptr[j] = cindex.length; // columns mark + + var mark = j + 1; // loop values A(:,j) + + for (k = aptr[j], k1 = aptr[j + 1]; k < k1; k++) { + // row + i = aindex[k]; // push index + + cindex.push(i); // update workspace + + wa[i] = mark; // check we need to process values + + if (xa) { + xa[i] = avalues[k]; + } + } // loop values B(:,j) + + + for (k = bptr[j], k1 = bptr[j + 1]; k < k1; k++) { + // row + i = bindex[k]; // check row existed in A + + if (wa[i] !== mark) { + // push index + cindex.push(i); + } // update workspace + + + wb[i] = mark; // check we need to process values + + if (xb) { + xb[i] = bvalues[k]; + } + } // check we need to process values (non pattern matrix) + + + if (cvalues) { + // initialize first index in j + k = cptr[j]; // loop index in j + + while (k < cindex.length) { + // row + i = cindex[k]; // marks + + var wai = wa[i]; + var wbi = wb[i]; // check Aij or Bij are nonzero + + if (wai === mark || wbi === mark) { + // matrix values @ i,j + var va = wai === mark ? xa[i] : zero; + var vb = wbi === mark ? xb[i] : zero; // Cij + + var vc = cf(va, vb); // check for zero + + if (!eq(vc, zero)) { + // push value + cvalues.push(vc); // increment pointer + + k++; + } else { + // remove value @ i, do not increment pointer + cindex.splice(k, 1); + } + } + } + } + } // update cptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm12.js + +var algorithm12_name = 'algorithm12'; +var algorithm12_dependencies = ['typed', 'DenseMatrix']; +var createAlgorithm12 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm12_name, algorithm12_dependencies, function (_ref) { + var typed = _ref.typed, + DenseMatrix = _ref.DenseMatrix; + + /** + * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b). + * Callback function invoked MxN times. + * + * + * ┌ f(Sij, b) ; S(i,j) !== 0 + * C(i,j) = ┤ + * └ f(0, b) ; otherwise + * + * + * @param {Matrix} s The SparseMatrix instance (S) + * @param {Scalar} b The Scalar value + * @param {Function} callback The f(Aij,b) operation to invoke + * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij) + * + * @return {Matrix} DenseMatrix (C) + * + * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813 + */ + return function algorithm12(s, b, callback, inverse) { + // sparse matrix arrays + var avalues = s._values; + var aindex = s._index; + var aptr = s._ptr; + var asize = s._size; + var adt = s._datatype; // sparse matrix cannot be a Pattern matrix + + if (!avalues) { + throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string') { + // datatype + dt = adt; // convert b to the same datatype + + b = typed.convert(b, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cdata = []; // workspaces + + var x = []; // marks indicating we have a value in x for a given column + + var w = []; // loop columns + + for (var j = 0; j < columns; j++) { + // columns mark + var mark = j + 1; // values in j + + for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + var r = aindex[k]; // update workspace + + x[r] = avalues[k]; + w[r] = mark; + } // loop rows + + + for (var i = 0; i < rows; i++) { + // initialize C on first column + if (j === 0) { + // create row array + cdata[i] = []; + } // check sparse matrix has a value @ i,j + + + if (w[i] === mark) { + // invoke callback, update C + cdata[i][j] = inverse ? cf(b, x[i]) : cf(x[i], b); + } else { + // dense matrix value @ i, j + cdata[i][j] = inverse ? cf(b, 0) : cf(0, b); + } + } + } // return dense matrix + + + return new DenseMatrix({ + data: cdata, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/mod.js + + + + + + + + + +var mod_name = 'mod'; +var mod_dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix']; +var createMod = /* #__PURE__ */Object(factory["a" /* factory */])(mod_name, mod_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm05 = createAlgorithm05({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Calculates the modulus, the remainder of an integer division. + * + * For matrices, the function is evaluated element wise. + * + * The modulus is defined as: + * + * x - y * floor(x / y) + * + * See https://en.wikipedia.org/wiki/Modulo_operation. + * + * Syntax: + * + * math.mod(x, y) + * + * Examples: + * + * math.mod(8, 3) // returns 2 + * math.mod(11, 2) // returns 1 + * + * function isOdd(x) { + * return math.mod(x, 2) != 0 + * } + * + * isOdd(2) // returns false + * isOdd(3) // returns true + * + * See also: + * + * divide + * + * @param {number | BigNumber | Fraction | Array | Matrix} x Dividend + * @param {number | BigNumber | Fraction | Array | Matrix} y Divisor + * @return {number | BigNumber | Fraction | Array | Matrix} Returns the remainder of `x` divided by `y`. + */ + + var mod = typed(mod_name, { + 'number, number': modNumber, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return y.isZero() ? x : x.mod(y); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.mod(y); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm05(x, y, mod, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, mod, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, mod, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, mod); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return mod(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return mod(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return mod(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, mod, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, mod, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, mod, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, mod, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, mod, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, mod, true).valueOf(); + } + }); + return mod; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/multiplyScalar.js + + +var multiplyScalar_name = 'multiplyScalar'; +var multiplyScalar_dependencies = ['typed']; +var createMultiplyScalar = /* #__PURE__ */Object(factory["a" /* factory */])(multiplyScalar_name, multiplyScalar_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Multiply two scalar values, `x * y`. + * This function is meant for internal use: it is used by the public function + * `multiply` + * + * This function does not support collections (Array or Matrix). + * + * @param {number | BigNumber | Fraction | Complex | Unit} x First value to multiply + * @param {number | BigNumber | Fraction | Complex} y Second value to multiply + * @return {number | BigNumber | Fraction | Complex | Unit} Multiplication of `x` and `y` + * @private + */ + var multiplyScalar = typed('multiplyScalar', { + 'number, number': multiplyNumber, + 'Complex, Complex': function ComplexComplex(x, y) { + return x.mul(y); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.times(y); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.mul(y); + }, + 'number | Fraction | BigNumber | Complex, Unit': function numberFractionBigNumberComplexUnit(x, y) { + var res = y.clone(); + res.value = res.value === null ? res._normalize(x) : multiplyScalar(res.value, x); + return res; + }, + 'Unit, number | Fraction | BigNumber | Complex': function UnitNumberFractionBigNumberComplex(x, y) { + var res = x.clone(); + res.value = res.value === null ? res._normalize(y) : multiplyScalar(res.value, y); + return res; + }, + 'Unit, Unit': function UnitUnit(x, y) { + return x.multiply(y); + } + }); + return multiplyScalar; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/multiply.js + + + + + + +var multiply_name = 'multiply'; +var multiply_dependencies = ['typed', 'matrix', 'addScalar', 'multiplyScalar', 'equalScalar']; +var createMultiply = /* #__PURE__ */Object(factory["a" /* factory */])(multiply_name, multiply_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + addScalar = _ref.addScalar, + multiplyScalar = _ref.multiplyScalar, + equalScalar = _ref.equalScalar; + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Multiply two or more values, `x * y`. + * For matrices, the matrix product is calculated. + * + * Syntax: + * + * math.multiply(x, y) + * math.multiply(x, y, z, ...) + * + * Examples: + * + * math.multiply(4, 5.2) // returns number 20.8 + * math.multiply(2, 3, 4) // returns number 24 + * + * const a = math.complex(2, 3) + * const b = math.complex(4, 1) + * math.multiply(a, b) // returns Complex 5 + 14i + * + * const c = [[1, 2], [4, 3]] + * const d = [[1, 2, 3], [3, -4, 7]] + * math.multiply(c, d) // returns Array [[7, -6, 17], [13, -4, 33]] + * + * const e = math.unit('2.1 km') + * math.multiply(3, e) // returns Unit 6.3 km + * + * See also: + * + * divide, prod, cross, dot + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First value to multiply + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second value to multiply + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y` + */ + + var multiply = typed(multiply_name, Object(utils_object["e" /* extend */])({ + // we extend the signatures of multiplyScalar with signatures dealing with matrices + 'Array, Array': function ArrayArray(x, y) { + // check dimensions + _validateMatrixDimensions(Object(utils_array["a" /* arraySize */])(x), Object(utils_array["a" /* arraySize */])(y)); // use dense matrix implementation + + + var m = multiply(matrix(x), matrix(y)); // return array or scalar + + return Object(is["v" /* isMatrix */])(m) ? m.valueOf() : m; + }, + 'Matrix, Matrix': function MatrixMatrix(x, y) { + // dimensions + var xsize = x.size(); + var ysize = y.size(); // check dimensions + + _validateMatrixDimensions(xsize, ysize); // process dimensions + + + if (xsize.length === 1) { + // process y dimensions + if (ysize.length === 1) { + // Vector * Vector + return _multiplyVectorVector(x, y, xsize[0]); + } // Vector * Matrix + + + return _multiplyVectorMatrix(x, y); + } // process y dimensions + + + if (ysize.length === 1) { + // Matrix * Vector + return _multiplyMatrixVector(x, y); + } // Matrix * Matrix + + + return _multiplyMatrixMatrix(x, y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use Matrix * Matrix implementation + return multiply(x, matrix(y)); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use Matrix * Matrix implementation + return multiply(matrix(x, y.storage()), y); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, multiplyScalar, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, multiplyScalar, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm11(y, x, multiplyScalar, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, multiplyScalar, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, multiplyScalar, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, multiplyScalar, true).valueOf(); + }, + 'any, any': multiplyScalar, + 'any, any, ...any': function anyAnyAny(x, y, rest) { + var result = multiply(x, y); + + for (var i = 0; i < rest.length; i++) { + result = multiply(result, rest[i]); + } + + return result; + } + }, multiplyScalar.signatures)); + + function _validateMatrixDimensions(size1, size2) { + // check left operand dimensions + switch (size1.length) { + case 1: + // check size2 + switch (size2.length) { + case 1: + // Vector x Vector + if (size1[0] !== size2[0]) { + // throw error + throw new RangeError('Dimension mismatch in multiplication. Vectors must have the same length'); + } + + break; + + case 2: + // Vector x Matrix + if (size1[0] !== size2[0]) { + // throw error + throw new RangeError('Dimension mismatch in multiplication. Vector length (' + size1[0] + ') must match Matrix rows (' + size2[0] + ')'); + } + + break; + + default: + throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)'); + } + + break; + + case 2: + // check size2 + switch (size2.length) { + case 1: + // Matrix x Vector + if (size1[1] !== size2[0]) { + // throw error + throw new RangeError('Dimension mismatch in multiplication. Matrix columns (' + size1[1] + ') must match Vector length (' + size2[0] + ')'); + } + + break; + + case 2: + // Matrix x Matrix + if (size1[1] !== size2[0]) { + // throw error + throw new RangeError('Dimension mismatch in multiplication. Matrix A columns (' + size1[1] + ') must match Matrix B rows (' + size2[0] + ')'); + } + + break; + + default: + throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)'); + } + + break; + + default: + throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix A has ' + size1.length + ' dimensions)'); + } + } + /** + * C = A * B + * + * @param {Matrix} a Dense Vector (N) + * @param {Matrix} b Dense Vector (N) + * + * @return {number} Scalar value + */ + + + function _multiplyVectorVector(a, b, n) { + // check empty vector + if (n === 0) { + throw new Error('Cannot multiply two empty vectors'); + } // a dense + + + var adata = a._data; + var adt = a._datatype; // b dense + + var bdata = b._data; + var bdt = b._datatype; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + } // result (do not initialize it with zero) + + + var c = mf(adata[0], bdata[0]); // loop data + + for (var i = 1; i < n; i++) { + // multiply and accumulate + c = af(c, mf(adata[i], bdata[i])); + } + + return c; + } + /** + * C = A * B + * + * @param {Matrix} a Dense Vector (M) + * @param {Matrix} b Matrix (MxN) + * + * @return {Matrix} Dense Vector (N) + */ + + + function _multiplyVectorMatrix(a, b) { + // process storage + if (b.storage() !== 'dense') { + throw new Error('Support for SparseMatrix not implemented'); + } + + return _multiplyVectorDenseMatrix(a, b); + } + /** + * C = A * B + * + * @param {Matrix} a Dense Vector (M) + * @param {Matrix} b Dense Matrix (MxN) + * + * @return {Matrix} Dense Vector (N) + */ + + + function _multiplyVectorDenseMatrix(a, b) { + // a dense + var adata = a._data; + var asize = a._size; + var adt = a._datatype; // b dense + + var bdata = b._data; + var bsize = b._size; + var bdt = b._datatype; // rows & columns + + var alength = asize[0]; + var bcolumns = bsize[1]; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + } // result + + + var c = []; // loop matrix columns + + for (var j = 0; j < bcolumns; j++) { + // sum (do not initialize it with zero) + var sum = mf(adata[0], bdata[0][j]); // loop vector + + for (var i = 1; i < alength; i++) { + // multiply & accumulate + sum = af(sum, mf(adata[i], bdata[i][j])); + } + + c[j] = sum; + } // return matrix + + + return a.createDenseMatrix({ + data: c, + size: [bcolumns], + datatype: dt + }); + } + /** + * C = A * B + * + * @param {Matrix} a Matrix (MxN) + * @param {Matrix} b Dense Vector (N) + * + * @return {Matrix} Dense Vector (M) + */ + + + var _multiplyMatrixVector = typed('_multiplyMatrixVector', { + 'DenseMatrix, any': _multiplyDenseMatrixVector, + 'SparseMatrix, any': _multiplySparseMatrixVector + }); + /** + * C = A * B + * + * @param {Matrix} a Matrix (MxN) + * @param {Matrix} b Matrix (NxC) + * + * @return {Matrix} Matrix (MxC) + */ + + + var _multiplyMatrixMatrix = typed('_multiplyMatrixMatrix', { + 'DenseMatrix, DenseMatrix': _multiplyDenseMatrixDenseMatrix, + 'DenseMatrix, SparseMatrix': _multiplyDenseMatrixSparseMatrix, + 'SparseMatrix, DenseMatrix': _multiplySparseMatrixDenseMatrix, + 'SparseMatrix, SparseMatrix': _multiplySparseMatrixSparseMatrix + }); + /** + * C = A * B + * + * @param {Matrix} a DenseMatrix (MxN) + * @param {Matrix} b Dense Vector (N) + * + * @return {Matrix} Dense Vector (M) + */ + + + function _multiplyDenseMatrixVector(a, b) { + // a dense + var adata = a._data; + var asize = a._size; + var adt = a._datatype; // b dense + + var bdata = b._data; + var bdt = b._datatype; // rows & columns + + var arows = asize[0]; + var acolumns = asize[1]; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + } // result + + + var c = []; // loop matrix a rows + + for (var i = 0; i < arows; i++) { + // current row + var row = adata[i]; // sum (do not initialize it with zero) + + var sum = mf(row[0], bdata[0]); // loop matrix a columns + + for (var j = 1; j < acolumns; j++) { + // multiply & accumulate + sum = af(sum, mf(row[j], bdata[j])); + } + + c[i] = sum; + } // return matrix + + + return a.createDenseMatrix({ + data: c, + size: [arows], + datatype: dt + }); + } + /** + * C = A * B + * + * @param {Matrix} a DenseMatrix (MxN) + * @param {Matrix} b DenseMatrix (NxC) + * + * @return {Matrix} DenseMatrix (MxC) + */ + + + function _multiplyDenseMatrixDenseMatrix(a, b) { + // a dense + var adata = a._data; + var asize = a._size; + var adt = a._datatype; // b dense + + var bdata = b._data; + var bsize = b._size; + var bdt = b._datatype; // rows & columns + + var arows = asize[0]; + var acolumns = asize[1]; + var bcolumns = bsize[1]; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + } // result + + + var c = []; // loop matrix a rows + + for (var i = 0; i < arows; i++) { + // current row + var row = adata[i]; // initialize row array + + c[i] = []; // loop matrix b columns + + for (var j = 0; j < bcolumns; j++) { + // sum (avoid initializing sum to zero) + var sum = mf(row[0], bdata[0][j]); // loop matrix a columns + + for (var x = 1; x < acolumns; x++) { + // multiply & accumulate + sum = af(sum, mf(row[x], bdata[x][j])); + } + + c[i][j] = sum; + } + } // return matrix + + + return a.createDenseMatrix({ + data: c, + size: [arows, bcolumns], + datatype: dt + }); + } + /** + * C = A * B + * + * @param {Matrix} a DenseMatrix (MxN) + * @param {Matrix} b SparseMatrix (NxC) + * + * @return {Matrix} SparseMatrix (MxC) + */ + + + function _multiplyDenseMatrixSparseMatrix(a, b) { + // a dense + var adata = a._data; + var asize = a._size; + var adt = a._datatype; // b sparse + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; + var bsize = b._size; + var bdt = b._datatype; // validate b matrix + + if (!bvalues) { + throw new Error('Cannot multiply Dense Matrix times Pattern only Matrix'); + } // rows & columns + + + var arows = asize[0]; + var bcolumns = bsize[1]; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // equalScalar signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); + } // result + + + var cvalues = []; + var cindex = []; + var cptr = []; // c matrix + + var c = b.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [arows, bcolumns], + datatype: dt + }); // loop b columns + + for (var jb = 0; jb < bcolumns; jb++) { + // update ptr + cptr[jb] = cindex.length; // indeces in column jb + + var kb0 = bptr[jb]; + var kb1 = bptr[jb + 1]; // do not process column jb if no data exists + + if (kb1 > kb0) { + // last row mark processed + var last = 0; // loop a rows + + for (var i = 0; i < arows; i++) { + // column mark + var mark = i + 1; // C[i, jb] + + var cij = void 0; // values in b column j + + for (var kb = kb0; kb < kb1; kb++) { + // row + var ib = bindex[kb]; // check value has been initialized + + if (last !== mark) { + // first value in column jb + cij = mf(adata[i][ib], bvalues[kb]); // update mark + + last = mark; + } else { + // accumulate value + cij = af(cij, mf(adata[i][ib], bvalues[kb])); + } + } // check column has been processed and value != 0 + + + if (last === mark && !eq(cij, zero)) { + // push row & value + cindex.push(i); + cvalues.push(cij); + } + } + } + } // update ptr + + + cptr[bcolumns] = cindex.length; // return sparse matrix + + return c; + } + /** + * C = A * B + * + * @param {Matrix} a SparseMatrix (MxN) + * @param {Matrix} b Dense Vector (N) + * + * @return {Matrix} SparseMatrix (M, 1) + */ + + + function _multiplySparseMatrixVector(a, b) { + // a sparse + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var adt = a._datatype; // validate a matrix + + if (!avalues) { + throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix'); + } // b dense + + + var bdata = b._data; + var bdt = b._datatype; // rows & columns + + var arows = a._size[0]; + var brows = b._size[0]; // result + + var cvalues = []; + var cindex = []; + var cptr = []; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // equalScalar signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); + } // workspace + + + var x = []; // vector with marks indicating a value x[i] exists in a given column + + var w = []; // update ptr + + cptr[0] = 0; // rows in b + + for (var ib = 0; ib < brows; ib++) { + // b[ib] + var vbi = bdata[ib]; // check b[ib] != 0, avoid loops + + if (!eq(vbi, zero)) { + // A values & index in ib column + for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) { + // a row + var ia = aindex[ka]; // check value exists in current j + + if (!w[ia]) { + // ia is new entry in j + w[ia] = true; // add i to pattern of C + + cindex.push(ia); // x(ia) = A + + x[ia] = mf(vbi, avalues[ka]); + } else { + // i exists in C already + x[ia] = af(x[ia], mf(vbi, avalues[ka])); + } + } + } + } // copy values from x to column jb of c + + + for (var p1 = cindex.length, p = 0; p < p1; p++) { + // row + var ic = cindex[p]; // copy value + + cvalues[p] = x[ic]; + } // update ptr + + + cptr[1] = cindex.length; // return sparse matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [arows, 1], + datatype: dt + }); + } + /** + * C = A * B + * + * @param {Matrix} a SparseMatrix (MxN) + * @param {Matrix} b DenseMatrix (NxC) + * + * @return {Matrix} SparseMatrix (MxC) + */ + + + function _multiplySparseMatrixDenseMatrix(a, b) { + // a sparse + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var adt = a._datatype; // validate a matrix + + if (!avalues) { + throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix'); + } // b dense + + + var bdata = b._data; + var bdt = b._datatype; // rows & columns + + var arows = a._size[0]; + var brows = b._size[0]; + var bcolumns = b._size[1]; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // equalScalar signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); + } // result + + + var cvalues = []; + var cindex = []; + var cptr = []; // c matrix + + var c = a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [arows, bcolumns], + datatype: dt + }); // workspace + + var x = []; // vector with marks indicating a value x[i] exists in a given column + + var w = []; // loop b columns + + for (var jb = 0; jb < bcolumns; jb++) { + // update ptr + cptr[jb] = cindex.length; // mark in workspace for current column + + var mark = jb + 1; // rows in jb + + for (var ib = 0; ib < brows; ib++) { + // b[ib, jb] + var vbij = bdata[ib][jb]; // check b[ib, jb] != 0, avoid loops + + if (!eq(vbij, zero)) { + // A values & index in ib column + for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) { + // a row + var ia = aindex[ka]; // check value exists in current j + + if (w[ia] !== mark) { + // ia is new entry in j + w[ia] = mark; // add i to pattern of C + + cindex.push(ia); // x(ia) = A + + x[ia] = mf(vbij, avalues[ka]); + } else { + // i exists in C already + x[ia] = af(x[ia], mf(vbij, avalues[ka])); + } + } + } + } // copy values from x to column jb of c + + + for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) { + // row + var ic = cindex[p]; // copy value + + cvalues[p] = x[ic]; + } + } // update ptr + + + cptr[bcolumns] = cindex.length; // return sparse matrix + + return c; + } + /** + * C = A * B + * + * @param {Matrix} a SparseMatrix (MxN) + * @param {Matrix} b SparseMatrix (NxC) + * + * @return {Matrix} SparseMatrix (MxC) + */ + + + function _multiplySparseMatrixSparseMatrix(a, b) { + // a sparse + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var adt = a._datatype; // b sparse + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; + var bdt = b._datatype; // rows & columns + + var arows = a._size[0]; + var bcolumns = b._size[1]; // flag indicating both matrices (a & b) contain data + + var values = avalues && bvalues; // datatype + + var dt; // addScalar signature to use + + var af = addScalar; // multiplyScalar signature to use + + var mf = multiplyScalar; // process data types + + if (adt && bdt && adt === bdt && typeof adt === 'string') { + // datatype + dt = adt; // find signatures that matches (dt, dt) + + af = typed.find(addScalar, [dt, dt]); + mf = typed.find(multiplyScalar, [dt, dt]); + } // result + + + var cvalues = values ? [] : undefined; + var cindex = []; + var cptr = []; // c matrix + + var c = a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [arows, bcolumns], + datatype: dt + }); // workspace + + var x = values ? [] : undefined; // vector with marks indicating a value x[i] exists in a given column + + var w = []; // variables + + var ka, ka0, ka1, kb, kb0, kb1, ia, ib; // loop b columns + + for (var jb = 0; jb < bcolumns; jb++) { + // update ptr + cptr[jb] = cindex.length; // mark in workspace for current column + + var mark = jb + 1; // B values & index in j + + for (kb0 = bptr[jb], kb1 = bptr[jb + 1], kb = kb0; kb < kb1; kb++) { + // b row + ib = bindex[kb]; // check we need to process values + + if (values) { + // loop values in a[:,ib] + for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) { + // row + ia = aindex[ka]; // check value exists in current j + + if (w[ia] !== mark) { + // ia is new entry in j + w[ia] = mark; // add i to pattern of C + + cindex.push(ia); // x(ia) = A + + x[ia] = mf(bvalues[kb], avalues[ka]); + } else { + // i exists in C already + x[ia] = af(x[ia], mf(bvalues[kb], avalues[ka])); + } + } + } else { + // loop values in a[:,ib] + for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) { + // row + ia = aindex[ka]; // check value exists in current j + + if (w[ia] !== mark) { + // ia is new entry in j + w[ia] = mark; // add i to pattern of C + + cindex.push(ia); + } + } + } + } // check we need to process matrix values (pattern matrix) + + + if (values) { + // copy values from x to column jb of c + for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) { + // row + var ic = cindex[p]; // copy value + + cvalues[p] = x[ic]; + } + } + } // update ptr + + + cptr[bcolumns] = cindex.length; // return sparse matrix + + return c; + } + + return multiply; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/nthRoot.js + + + + + + + + +var nthRoot_name = 'nthRoot'; +var nthRoot_dependencies = ['typed', 'matrix', 'equalScalar', 'BigNumber']; +var createNthRoot = /* #__PURE__ */Object(factory["a" /* factory */])(nthRoot_name, nthRoot_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + _BigNumber = _ref.BigNumber; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm06 = createAlgorithm06({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Calculate the nth root of a value. + * The principal nth root of a positive real number A, is the positive real + * solution of the equation + * + * x^root = A + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.nthRoot(a) + * math.nthRoot(a, root) + * + * Examples: + * + * math.nthRoot(9, 2) // returns 3, as 3^2 == 9 + * math.sqrt(9) // returns 3, as 3^2 == 9 + * math.nthRoot(64, 3) // returns 4, as 4^3 == 64 + * + * See also: + * + * sqrt, pow + * + * @param {number | BigNumber | Array | Matrix | Complex} a + * Value for which to calculate the nth root + * @param {number | BigNumber} [root=2] The root. + * @return {number | Complex | Array | Matrix} Returns the nth root of `a` + */ + + var complexErr = '' + 'Complex number not supported in function nthRoot. ' + 'Use nthRoots instead.'; + var nthRoot = typed(nthRoot_name, { + number: function number(x) { + return nthRootNumber(x, 2); + }, + 'number, number': nthRootNumber, + BigNumber: function BigNumber(x) { + return _bigNthRoot(x, new _BigNumber(2)); + }, + Complex: function Complex(x) { + throw new Error(complexErr); + }, + 'Complex, number': function ComplexNumber(x, y) { + throw new Error(complexErr); + }, + 'BigNumber, BigNumber': _bigNthRoot, + 'Array | Matrix': function ArrayMatrix(x) { + return nthRoot(x, 2); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + // density must be one (no zeros in matrix) + if (y.density() === 1) { + // sparse + sparse + return algorithm06(x, y, nthRoot); + } else { + // throw exception + throw new Error('Root must be non-zero'); + } + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, nthRoot, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + // density must be one (no zeros in matrix) + if (y.density() === 1) { + // dense + sparse + return algorithm01(x, y, nthRoot, false); + } else { + // throw exception + throw new Error('Root must be non-zero'); + } + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, nthRoot); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return nthRoot(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return nthRoot(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return nthRoot(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + return algorithm11(x, y, nthRoot, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + return algorithm14(x, y, nthRoot, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + // density must be one (no zeros in matrix) + if (y.density() === 1) { + // sparse - scalar + return algorithm11(y, x, nthRoot, true); + } else { + // throw exception + throw new Error('Root must be non-zero'); + } + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + return algorithm14(y, x, nthRoot, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return nthRoot(matrix(x), y).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + // use matrix implementation + return nthRoot(x, matrix(y)).valueOf(); + } + }); + return nthRoot; + /** + * Calculate the nth root of a for BigNumbers, solve x^root == a + * https://rosettacode.org/wiki/Nth_root#JavaScript + * @param {BigNumber} a + * @param {BigNumber} root + * @private + */ + + function _bigNthRoot(a, root) { + var precision = _BigNumber.precision; + + var Big = _BigNumber.clone({ + precision: precision + 2 + }); + + var zero = new _BigNumber(0); + var one = new Big(1); + var inv = root.isNegative(); + + if (inv) { + root = root.neg(); + } + + if (root.isZero()) { + throw new Error('Root must be non-zero'); + } + + if (a.isNegative() && !root.abs().mod(2).equals(1)) { + throw new Error('Root must be odd when a is negative.'); + } // edge cases zero and infinity + + + if (a.isZero()) { + return inv ? new Big(Infinity) : 0; + } + + if (!a.isFinite()) { + return inv ? zero : a; + } + + var x = a.abs().pow(one.div(root)); // If a < 0, we require that root is an odd integer, + // so (-1) ^ (1/root) = -1 + + x = a.isNeg() ? x.neg() : x; + return new _BigNumber((inv ? one.div(x) : x).toPrecision(precision)); + } +}); +var createNthRootNumber = /* #__PURE__ */Object(factory["a" /* factory */])(nthRoot_name, ['typed'], function (_ref2) { + var typed = _ref2.typed; + return typed(nthRoot_name, { + number: nthRootNumber, + 'number, number': nthRootNumber + }); +}); +// CONCATENATED MODULE: ./src/function/arithmetic/sign.js + + + +var sign_name = 'sign'; +var sign_dependencies = ['typed', 'BigNumber', 'Fraction', 'complex']; +var createSign = /* #__PURE__ */Object(factory["a" /* factory */])(sign_name, sign_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber, + complex = _ref.complex, + _Fraction = _ref.Fraction; + + /** + * Compute the sign of a value. The sign of a value x is: + * + * - 1 when x > 0 + * - -1 when x < 0 + * - 0 when x == 0 + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.sign(x) + * + * Examples: + * + * math.sign(3.5) // returns 1 + * math.sign(-4.2) // returns -1 + * math.sign(0) // returns 0 + * + * math.sign([3, 5, -2, 0, 2]) // returns [1, 1, -1, 0, 1] + * + * See also: + * + * abs + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x + * The number for which to determine the sign + * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit}e + * The sign of `x` + */ + var sign = typed(sign_name, { + number: signNumber, + Complex: function Complex(x) { + return x.im === 0 ? complex(signNumber(x.re)) : x.sign(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(x.cmp(0)); + }, + Fraction: function Fraction(x) { + return new _Fraction(x.s, 1); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since sign(0) = 0 + return deepMap(x, sign, true); + }, + Unit: function Unit(x) { + return sign(x.value); + } + }); + return sign; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/sqrt.js + + +var sqrt_name = 'sqrt'; +var sqrt_dependencies = ['config', 'typed', 'Complex']; +var createSqrt = /* #__PURE__ */Object(factory["a" /* factory */])(sqrt_name, sqrt_dependencies, function (_ref) { + var config = _ref.config, + typed = _ref.typed, + Complex = _ref.Complex; + + /** + * Calculate the square root of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.sqrt(x) + * + * Examples: + * + * math.sqrt(25) // returns 5 + * math.square(5) // returns 25 + * math.sqrt(-4) // returns Complex 2i + * + * See also: + * + * square, multiply, cube, cbrt, sqrtm + * + * @param {number | BigNumber | Complex | Array | Matrix | Unit} x + * Value for which to calculate the square root. + * @return {number | BigNumber | Complex | Array | Matrix | Unit} + * Returns the square root of `x` + */ + var sqrt = typed('sqrt', { + number: _sqrtNumber, + Complex: function Complex(x) { + return x.sqrt(); + }, + BigNumber: function BigNumber(x) { + if (!x.isNegative() || config.predictable) { + return x.sqrt(); + } else { + // negative value -> downgrade to number to do complex value computation + return _sqrtNumber(x.toNumber()); + } + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since sqrt(0) = 0 + return deepMap(x, sqrt, true); + }, + Unit: function Unit(x) { + // Someday will work for complex units when they are implemented + return x.pow(0.5); + } + }); + /** + * Calculate sqrt for a number + * @param {number} x + * @returns {number | Complex} Returns the square root of x + * @private + */ + + function _sqrtNumber(x) { + if (isNaN(x)) { + return NaN; + } else if (x >= 0 || config.predictable) { + return Math.sqrt(x); + } else { + return new Complex(x, 0).sqrt(); + } + } + + return sqrt; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/square.js + + + +var square_name = 'square'; +var square_dependencies = ['typed']; +var createSquare = /* #__PURE__ */Object(factory["a" /* factory */])(square_name, square_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the square of a value, `x * x`. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.square(x) + * + * Examples: + * + * math.square(2) // returns number 4 + * math.square(3) // returns number 9 + * math.pow(3, 2) // returns number 9 + * math.multiply(3, 3) // returns number 9 + * + * math.square([1, 2, 3, 4]) // returns Array [1, 4, 9, 16] + * + * See also: + * + * multiply, cube, sqrt, pow + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x + * Number for which to calculate the square + * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} + * Squared value + */ + var square = typed(square_name, { + number: squareNumber, + Complex: function Complex(x) { + return x.mul(x); + }, + BigNumber: function BigNumber(x) { + return x.times(x); + }, + Fraction: function Fraction(x) { + return x.mul(x); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since square(0) = 0 + return deepMap(x, square, true); + }, + Unit: function Unit(x) { + return x.pow(2); + } + }); + return square; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/subtract.js + + + + + + + + +var subtract_name = 'subtract'; +var subtract_dependencies = ['typed', 'matrix', 'equalScalar', 'addScalar', 'unaryMinus', 'DenseMatrix']; +var createSubtract = /* #__PURE__ */Object(factory["a" /* factory */])(subtract_name, subtract_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + addScalar = _ref.addScalar, + unaryMinus = _ref.unaryMinus, + DenseMatrix = _ref.DenseMatrix; + // TODO: split function subtract in two: subtract and subtractScalar + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm05 = createAlgorithm05({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Subtract two values, `x - y`. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.subtract(x, y) + * + * Examples: + * + * math.subtract(5.3, 2) // returns number 3.3 + * + * const a = math.complex(2, 3) + * const b = math.complex(4, 1) + * math.subtract(a, b) // returns Complex -2 + 2i + * + * math.subtract([5, 7, 4], 4) // returns Array [1, 3, 0] + * + * const c = math.unit('2.1 km') + * const d = math.unit('500m') + * math.subtract(c, d) // returns Unit 1.6 km + * + * See also: + * + * add + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x + * Initial value + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y + * Value to subtract from `x` + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} + * Subtraction of `x` and `y` + */ + + var subtract = typed(subtract_name, { + 'number, number': function numberNumber(x, y) { + return x - y; + }, + 'Complex, Complex': function ComplexComplex(x, y) { + return x.sub(y); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.minus(y); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.sub(y); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (x.value === null) { + throw new Error('Parameter x contains a unit with undefined value'); + } + + if (y.value === null) { + throw new Error('Parameter y contains a unit with undefined value'); + } + + if (!x.equalBase(y)) { + throw new Error('Units do not match'); + } + + var res = x.clone(); + res.value = subtract(res.value, y.value); + res.fixPrefix = false; + return res; + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + checkEqualDimensions(x, y); + return algorithm05(x, y, subtract); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + checkEqualDimensions(x, y); + return algorithm03(y, x, subtract, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + checkEqualDimensions(x, y); + return algorithm01(x, y, subtract, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + checkEqualDimensions(x, y); + return algorithm13(x, y, subtract); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return subtract(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return subtract(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return subtract(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm10(x, unaryMinus(y), addScalar); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, subtract); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm10(y, x, subtract, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, subtract, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, subtract, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, subtract, true).valueOf(); + } + }); + return subtract; +}); +/** + * Check whether matrix x and y have the same number of dimensions. + * Throws a DimensionError when dimensions are not equal + * @param {Matrix} x + * @param {Matrix} y + */ + +function checkEqualDimensions(x, y) { + var xsize = x.size(); + var ysize = y.size(); + + if (xsize.length !== ysize.length) { + throw new DimensionError["a" /* DimensionError */](xsize.length, ysize.length); + } +} +// CONCATENATED MODULE: ./src/function/arithmetic/xgcd.js + + +var xgcd_name = 'xgcd'; +var xgcd_dependencies = ['typed', 'config', 'matrix', 'BigNumber']; +var createXgcd = /* #__PURE__ */Object(factory["a" /* factory */])(xgcd_name, xgcd_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + BigNumber = _ref.BigNumber; + + /** + * Calculate the extended greatest common divisor for two values. + * See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm. + * + * Syntax: + * + * math.xgcd(a, b) + * + * Examples: + * + * math.xgcd(8, 12) // returns [4, -1, 1] + * math.gcd(8, 12) // returns 4 + * math.xgcd(36163, 21199) // returns [1247, -7, 12] + * + * See also: + * + * gcd, lcm + * + * @param {number | BigNumber} a An integer number + * @param {number | BigNumber} b An integer number + * @return {Array} Returns an array containing 3 integers `[div, m, n]` + * where `div = gcd(a, b)` and `a*m + b*n = div` + */ + return typed(xgcd_name, { + 'number, number': function numberNumber(a, b) { + var res = xgcdNumber(a, b); + return config.matrix === 'Array' ? res : matrix(res); + }, + 'BigNumber, BigNumber': _xgcdBigNumber // TODO: implement support for Fraction + + }); + /** + * Calculate xgcd for two BigNumbers + * @param {BigNumber} a + * @param {BigNumber} b + * @return {BigNumber[]} result + * @private + */ + + function _xgcdBigNumber(a, b) { + // source: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm + var // used to swap two variables + t; + var // quotient + q; + var // remainder + r; + var zero = new BigNumber(0); + var one = new BigNumber(1); + var x = zero; + var lastx = one; + var y = one; + var lasty = zero; + + if (!a.isInt() || !b.isInt()) { + throw new Error('Parameters in function xgcd must be integer numbers'); + } + + while (!b.isZero()) { + q = a.div(b).floor(); + r = a.mod(b); + t = x; + x = lastx.minus(q.times(x)); + lastx = t; + t = y; + y = lasty.minus(q.times(y)); + lasty = t; + a = b; + b = r; + } + + var res; + + if (a.lt(zero)) { + res = [a.neg(), lastx.neg(), lasty.neg()]; + } else { + res = [a, !a.isZero() ? lastx : 0, lasty]; + } + + return config.matrix === 'Array' ? res : matrix(res); + } +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm09.js + + +var algorithm09_name = 'algorithm09'; +var algorithm09_dependencies = ['typed', 'equalScalar']; +var createAlgorithm09 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm09_name, algorithm09_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix A and invokes the callback function f(Aij, Bij). + * Callback function invoked NZA times, number of nonzero elements in A. + * + * + * ┌ f(Aij, Bij) ; A(i,j) !== 0 + * C(i,j) = ┤ + * └ 0 ; otherwise + * + * + * @param {Matrix} a The SparseMatrix instance (A) + * @param {Matrix} b The SparseMatrix instance (B) + * @param {Function} callback The f(Aij,Bij) operation to invoke + * + * @return {Matrix} SparseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294 + */ + return function algorithm09(a, b, callback) { + // sparse matrix arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; + var adt = a._datatype; // sparse matrix arrays + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; + var bsize = b._size; + var bdt = b._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cvalues = avalues && bvalues ? [] : undefined; + var cindex = []; + var cptr = []; // workspaces + + var x = cvalues ? [] : undefined; // marks indicating we have a value in x for a given column + + var w = []; // vars + + var i, j, k, k0, k1; // loop columns + + for (j = 0; j < columns; j++) { + // update cptr + cptr[j] = cindex.length; // column mark + + var mark = j + 1; // check we need to process values + + if (x) { + // loop B(:,j) + for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) { + // row + i = bindex[k]; // update workspace + + w[i] = mark; + x[i] = bvalues[k]; + } + } // loop A(:,j) + + + for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + i = aindex[k]; // check we need to process values + + if (x) { + // b value @ i,j + var vb = w[i] === mark ? x[i] : zero; // invoke f + + var vc = cf(avalues[k], vb); // check zero value + + if (!eq(vc, zero)) { + // push index + cindex.push(i); // push value + + cvalues.push(vc); + } + } else { + // push index + cindex.push(i); + } + } + } // update cptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/dotMultiply.js + + + + + + +var dotMultiply_name = 'dotMultiply'; +var dotMultiply_dependencies = ['typed', 'matrix', 'equalScalar', 'multiplyScalar']; +var createDotMultiply = /* #__PURE__ */Object(factory["a" /* factory */])(dotMultiply_name, dotMultiply_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + multiplyScalar = _ref.multiplyScalar; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm09 = createAlgorithm09({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Multiply two matrices element wise. The function accepts both matrices and + * scalar values. + * + * Syntax: + * + * math.dotMultiply(x, y) + * + * Examples: + * + * math.dotMultiply(2, 4) // returns 8 + * + * a = [[9, 5], [6, 1]] + * b = [[3, 2], [5, 2]] + * + * math.dotMultiply(a, b) // returns [[27, 10], [30, 2]] + * math.multiply(a, b) // returns [[52, 28], [23, 14]] + * + * See also: + * + * multiply, divide, dotDivide + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Left hand value + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Right hand value + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y` + */ + + var dotMultiply = typed(dotMultiply_name, { + 'any, any': multiplyScalar, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm09(x, y, multiplyScalar, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, multiplyScalar, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm02(x, y, multiplyScalar, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, multiplyScalar); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return dotMultiply(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return dotMultiply(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return dotMultiply(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, multiplyScalar, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, multiplyScalar, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm11(y, x, multiplyScalar, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, multiplyScalar, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, multiplyScalar, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, multiplyScalar, true).valueOf(); + } + }); + return dotMultiply; +}); +// CONCATENATED MODULE: ./src/utils/bignumber/bitwise.js +/** + * Bitwise and for Bignumbers + * + * Special Cases: + * N & n = N + * n & 0 = 0 + * n & -1 = n + * n & n = n + * I & I = I + * -I & -I = -I + * I & -I = 0 + * I & n = n + * I & -n = I + * -I & n = 0 + * -I & -n = -I + * + * @param {BigNumber} x + * @param {BigNumber} y + * @return {BigNumber} Result of `x` & `y`, is fully precise + * @private + */ +function bitAndBigNumber(x, y) { + if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) { + throw new Error('Integers expected in function bitAnd'); + } + + var BigNumber = x.constructor; + + if (x.isNaN() || y.isNaN()) { + return new BigNumber(NaN); + } + + if (x.isZero() || y.eq(-1) || x.eq(y)) { + return x; + } + + if (y.isZero() || x.eq(-1)) { + return y; + } + + if (!x.isFinite() || !y.isFinite()) { + if (!x.isFinite() && !y.isFinite()) { + if (x.isNegative() === y.isNegative()) { + return x; + } + + return new BigNumber(0); + } + + if (!x.isFinite()) { + if (y.isNegative()) { + return x; + } + + if (x.isNegative()) { + return new BigNumber(0); + } + + return y; + } + + if (!y.isFinite()) { + if (x.isNegative()) { + return y; + } + + if (y.isNegative()) { + return new BigNumber(0); + } + + return x; + } + } + + return bitwise(x, y, function (a, b) { + return a & b; + }); +} +/** + * Bitwise not + * @param {BigNumber} x + * @return {BigNumber} Result of ~`x`, fully precise + * + */ + +function bitNotBigNumber(x) { + if (x.isFinite() && !x.isInteger()) { + throw new Error('Integer expected in function bitNot'); + } + + var BigNumber = x.constructor; + var prevPrec = BigNumber.precision; + BigNumber.config({ + precision: 1E9 + }); + var result = x.plus(new BigNumber(1)); + result.s = -result.s || null; + BigNumber.config({ + precision: prevPrec + }); + return result; +} +/** + * Bitwise OR for BigNumbers + * + * Special Cases: + * N | n = N + * n | 0 = n + * n | -1 = -1 + * n | n = n + * I | I = I + * -I | -I = -I + * I | -n = -1 + * I | -I = -1 + * I | n = I + * -I | n = -I + * -I | -n = -n + * + * @param {BigNumber} x + * @param {BigNumber} y + * @return {BigNumber} Result of `x` | `y`, fully precise + */ + +function bitOrBigNumber(x, y) { + if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) { + throw new Error('Integers expected in function bitOr'); + } + + var BigNumber = x.constructor; + + if (x.isNaN() || y.isNaN()) { + return new BigNumber(NaN); + } + + var negOne = new BigNumber(-1); + + if (x.isZero() || y.eq(negOne) || x.eq(y)) { + return y; + } + + if (y.isZero() || x.eq(negOne)) { + return x; + } + + if (!x.isFinite() || !y.isFinite()) { + if (!x.isFinite() && !x.isNegative() && y.isNegative() || x.isNegative() && !y.isNegative() && !y.isFinite()) { + return negOne; + } + + if (x.isNegative() && y.isNegative()) { + return x.isFinite() ? x : y; + } + + return x.isFinite() ? y : x; + } + + return bitwise(x, y, function (a, b) { + return a | b; + }); +} +/** + * Applies bitwise function to numbers + * @param {BigNumber} x + * @param {BigNumber} y + * @param {function (a, b)} func + * @return {BigNumber} + */ + +function bitwise(x, y, func) { + var BigNumber = x.constructor; + var xBits, yBits; + var xSign = +(x.s < 0); + var ySign = +(y.s < 0); + + if (xSign) { + xBits = decCoefficientToBinaryString(bitNotBigNumber(x)); + + for (var i = 0; i < xBits.length; ++i) { + xBits[i] ^= 1; + } + } else { + xBits = decCoefficientToBinaryString(x); + } + + if (ySign) { + yBits = decCoefficientToBinaryString(bitNotBigNumber(y)); + + for (var _i = 0; _i < yBits.length; ++_i) { + yBits[_i] ^= 1; + } + } else { + yBits = decCoefficientToBinaryString(y); + } + + var minBits, maxBits, minSign; + + if (xBits.length <= yBits.length) { + minBits = xBits; + maxBits = yBits; + minSign = xSign; + } else { + minBits = yBits; + maxBits = xBits; + minSign = ySign; + } + + var shortLen = minBits.length; + var longLen = maxBits.length; + var expFuncVal = func(xSign, ySign) ^ 1; + var outVal = new BigNumber(expFuncVal ^ 1); + var twoPower = new BigNumber(1); + var two = new BigNumber(2); + var prevPrec = BigNumber.precision; + BigNumber.config({ + precision: 1E9 + }); + + while (shortLen > 0) { + if (func(minBits[--shortLen], maxBits[--longLen]) === expFuncVal) { + outVal = outVal.plus(twoPower); + } + + twoPower = twoPower.times(two); + } + + while (longLen > 0) { + if (func(minSign, maxBits[--longLen]) === expFuncVal) { + outVal = outVal.plus(twoPower); + } + + twoPower = twoPower.times(two); + } + + BigNumber.config({ + precision: prevPrec + }); + + if (expFuncVal === 0) { + outVal.s = -outVal.s; + } + + return outVal; +} +/* Extracted from decimal.js, and edited to specialize. */ + +function decCoefficientToBinaryString(x) { + // Convert to string + var a = x.d; // array with digits + + var r = a[0] + ''; + + for (var i = 1; i < a.length; ++i) { + var s = a[i] + ''; + + for (var z = 7 - s.length; z--;) { + s = '0' + s; + } + + r += s; + } + + var j = r.length; + + while (r.charAt(j) === '0') { + j--; + } + + var xe = x.e; + var str = r.slice(0, j + 1 || 1); + var strL = str.length; + + if (xe > 0) { + if (++xe > strL) { + // Append zeros. + xe -= strL; + + while (xe--) { + str += '0'; + } + } else if (xe < strL) { + str = str.slice(0, xe) + '.' + str.slice(xe); + } + } // Convert from base 10 (decimal) to base 2 + + + var arr = [0]; + + for (var _i2 = 0; _i2 < str.length;) { + var arrL = arr.length; + + while (arrL--) { + arr[arrL] *= 10; + } + + arr[0] += parseInt(str.charAt(_i2++)); // convert to int + + for (var _j = 0; _j < arr.length; ++_j) { + if (arr[_j] > 1) { + if (arr[_j + 1] === null || arr[_j + 1] === undefined) { + arr[_j + 1] = 0; + } + + arr[_j + 1] += arr[_j] >> 1; + arr[_j] &= 1; + } + } + } + + return arr.reverse(); +} +/** + * Bitwise XOR for BigNumbers + * + * Special Cases: + * N ^ n = N + * n ^ 0 = n + * n ^ n = 0 + * n ^ -1 = ~n + * I ^ n = I + * I ^ -n = -I + * I ^ -I = -1 + * -I ^ n = -I + * -I ^ -n = I + * + * @param {BigNumber} x + * @param {BigNumber} y + * @return {BigNumber} Result of `x` ^ `y`, fully precise + * + */ + + +function bitwise_bitXor(x, y) { + if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) { + throw new Error('Integers expected in function bitXor'); + } + + var BigNumber = x.constructor; + + if (x.isNaN() || y.isNaN()) { + return new BigNumber(NaN); + } + + if (x.isZero()) { + return y; + } + + if (y.isZero()) { + return x; + } + + if (x.eq(y)) { + return new BigNumber(0); + } + + var negOne = new BigNumber(-1); + + if (x.eq(negOne)) { + return bitNotBigNumber(y); + } + + if (y.eq(negOne)) { + return bitNotBigNumber(x); + } + + if (!x.isFinite() || !y.isFinite()) { + if (!x.isFinite() && !y.isFinite()) { + return negOne; + } + + return new BigNumber(x.isNegative() === y.isNegative() ? Infinity : -Infinity); + } + + return bitwise(x, y, function (a, b) { + return a ^ b; + }); +} +/** + * Bitwise left shift + * + * Special Cases: + * n << -n = N + * n << N = N + * N << n = N + * n << 0 = n + * 0 << n = 0 + * I << I = N + * I << n = I + * n << I = I + * + * @param {BigNumber} x + * @param {BigNumber} y + * @return {BigNumber} Result of `x` << `y` + * + */ + +function leftShiftBigNumber(x, y) { + if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) { + throw new Error('Integers expected in function leftShift'); + } + + var BigNumber = x.constructor; + + if (x.isNaN() || y.isNaN() || y.isNegative() && !y.isZero()) { + return new BigNumber(NaN); + } + + if (x.isZero() || y.isZero()) { + return x; + } + + if (!x.isFinite() && !y.isFinite()) { + return new BigNumber(NaN); + } // Math.pow(2, y) is fully precise for y < 55, and fast + + + if (y.lt(55)) { + return x.times(Math.pow(2, y.toNumber()) + ''); + } + + return x.times(new BigNumber(2).pow(y)); +} +/* + * Special Cases: + * n >> -n = N + * n >> N = N + * N >> n = N + * I >> I = N + * n >> 0 = n + * I >> n = I + * -I >> n = -I + * -I >> I = -I + * n >> I = I + * -n >> I = -1 + * 0 >> n = 0 + * + * @param {BigNumber} value + * @param {BigNumber} value + * @return {BigNumber} Result of `x` >> `y` + * + */ + +function rightArithShiftBigNumber(x, y) { + if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) { + throw new Error('Integers expected in function rightArithShift'); + } + + var BigNumber = x.constructor; + + if (x.isNaN() || y.isNaN() || y.isNegative() && !y.isZero()) { + return new BigNumber(NaN); + } + + if (x.isZero() || y.isZero()) { + return x; + } + + if (!y.isFinite()) { + if (x.isNegative()) { + return new BigNumber(-1); + } + + if (!x.isFinite()) { + return new BigNumber(NaN); + } + + return new BigNumber(0); + } // Math.pow(2, y) is fully precise for y < 55, and fast + + + if (y.lt(55)) { + return x.div(Math.pow(2, y.toNumber()) + '').floor(); + } + + return x.div(new BigNumber(2).pow(y)).floor(); +} +// CONCATENATED MODULE: ./src/plain/number/bitwise.js + +var bitwise_n1 = 'number'; +var bitwise_n2 = 'number, number'; +function bitAndNumber(x, y) { + if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) { + throw new Error('Integers expected in function bitAnd'); + } + + return x & y; +} +bitAndNumber.signature = bitwise_n2; +function bitNotNumber(x) { + if (!Object(utils_number["i" /* isInteger */])(x)) { + throw new Error('Integer expected in function bitNot'); + } + + return ~x; +} +bitNotNumber.signature = bitwise_n1; +function bitOrNumber(x, y) { + if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) { + throw new Error('Integers expected in function bitOr'); + } + + return x | y; +} +bitOrNumber.signature = bitwise_n2; +function bitXorNumber(x, y) { + if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) { + throw new Error('Integers expected in function bitXor'); + } + + return x ^ y; +} +bitXorNumber.signature = bitwise_n2; +function leftShiftNumber(x, y) { + if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) { + throw new Error('Integers expected in function leftShift'); + } + + return x << y; +} +leftShiftNumber.signature = bitwise_n2; +function rightArithShiftNumber(x, y) { + if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) { + throw new Error('Integers expected in function rightArithShift'); + } + + return x >> y; +} +rightArithShiftNumber.signature = bitwise_n2; +function rightLogShiftNumber(x, y) { + if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) { + throw new Error('Integers expected in function rightLogShift'); + } + + return x >>> y; +} +rightLogShiftNumber.signature = bitwise_n2; +// CONCATENATED MODULE: ./src/function/bitwise/bitAnd.js + + + + + + + + +var bitAnd_name = 'bitAnd'; +var bitAnd_dependencies = ['typed', 'matrix', 'equalScalar']; +var createBitAnd = /* #__PURE__ */Object(factory["a" /* factory */])(bitAnd_name, bitAnd_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm06 = createAlgorithm06({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Bitwise AND two values, `x & y`. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.bitAnd(x, y) + * + * Examples: + * + * math.bitAnd(53, 131) // returns number 1 + * + * math.bitAnd([1, 12, 31], 42) // returns Array [0, 8, 10] + * + * See also: + * + * bitNot, bitOr, bitXor, leftShift, rightArithShift, rightLogShift + * + * @param {number | BigNumber | Array | Matrix} x First value to and + * @param {number | BigNumber | Array | Matrix} y Second value to and + * @return {number | BigNumber | Array | Matrix} AND of `x` and `y` + */ + + var bitAnd = typed(bitAnd_name, { + 'number, number': bitAndNumber, + 'BigNumber, BigNumber': bitAndBigNumber, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm06(x, y, bitAnd, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, bitAnd, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm02(x, y, bitAnd, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, bitAnd); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return bitAnd(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return bitAnd(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return bitAnd(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, bitAnd, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, bitAnd, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm11(y, x, bitAnd, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, bitAnd, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, bitAnd, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, bitAnd, true).valueOf(); + } + }); + return bitAnd; +}); +// CONCATENATED MODULE: ./src/function/bitwise/bitNot.js + + + + +var bitNot_name = 'bitNot'; +var bitNot_dependencies = ['typed']; +var createBitNot = /* #__PURE__ */Object(factory["a" /* factory */])(bitNot_name, bitNot_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Bitwise NOT value, `~x`. + * For matrices, the function is evaluated element wise. + * For units, the function is evaluated on the best prefix base. + * + * Syntax: + * + * math.bitNot(x) + * + * Examples: + * + * math.bitNot(1) // returns number -2 + * + * math.bitNot([2, -3, 4]) // returns Array [-3, 2, 5] + * + * See also: + * + * bitAnd, bitOr, bitXor, leftShift, rightArithShift, rightLogShift + * + * @param {number | BigNumber | Array | Matrix} x Value to not + * @return {number | BigNumber | Array | Matrix} NOT of `x` + */ + var bitNot = typed(bitNot_name, { + number: bitNotNumber, + BigNumber: bitNotBigNumber, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, bitNot); + } + }); + return bitNot; +}); +// CONCATENATED MODULE: ./src/function/bitwise/bitOr.js + + + + + + + + +var bitOr_name = 'bitOr'; +var bitOr_dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix']; +var createBitOr = /* #__PURE__ */Object(factory["a" /* factory */])(bitOr_name, bitOr_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm04 = createAlgorithm04({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Bitwise OR two values, `x | y`. + * For matrices, the function is evaluated element wise. + * For units, the function is evaluated on the lowest print base. + * + * Syntax: + * + * math.bitOr(x, y) + * + * Examples: + * + * math.bitOr(1, 2) // returns number 3 + * + * math.bitOr([1, 2, 3], 4) // returns Array [5, 6, 7] + * + * See also: + * + * bitAnd, bitNot, bitXor, leftShift, rightArithShift, rightLogShift + * + * @param {number | BigNumber | Array | Matrix} x First value to or + * @param {number | BigNumber | Array | Matrix} y Second value to or + * @return {number | BigNumber | Array | Matrix} OR of `x` and `y` + */ + + var bitOr = typed(bitOr_name, { + 'number, number': bitOrNumber, + 'BigNumber, BigNumber': bitOrBigNumber, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm04(x, y, bitOr); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm01(y, x, bitOr, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm01(x, y, bitOr, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, bitOr); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return bitOr(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return bitOr(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return bitOr(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm10(x, y, bitOr, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, bitOr, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm10(y, x, bitOr, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, bitOr, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, bitOr, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, bitOr, true).valueOf(); + } + }); + return bitOr; +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm07.js + + +var algorithm07_name = 'algorithm07'; +var algorithm07_dependencies = ['typed', 'DenseMatrix']; +var createAlgorithm07 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm07_name, algorithm07_dependencies, function (_ref) { + var typed = _ref.typed, + DenseMatrix = _ref.DenseMatrix; + + /** + * Iterates over SparseMatrix A and SparseMatrix B items (zero and nonzero) and invokes the callback function f(Aij, Bij). + * Callback function invoked MxN times. + * + * C(i,j) = f(Aij, Bij) + * + * @param {Matrix} a The SparseMatrix instance (A) + * @param {Matrix} b The SparseMatrix instance (B) + * @param {Function} callback The f(Aij,Bij) operation to invoke + * + * @return {Matrix} DenseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294 + */ + return function algorithm07(a, b, callback) { + // sparse matrix arrays + var asize = a._size; + var adt = a._datatype; // sparse matrix arrays + + var bsize = b._size; + var bdt = b._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // vars + + + var i, j; // result arrays + + var cdata = []; // initialize c + + for (i = 0; i < rows; i++) { + cdata[i] = []; + } // workspaces + + + var xa = []; + var xb = []; // marks indicating we have a value in x for a given column + + var wa = []; + var wb = []; // loop columns + + for (j = 0; j < columns; j++) { + // columns mark + var mark = j + 1; // scatter the values of A(:,j) into workspace + + _scatter(a, j, wa, xa, mark); // scatter the values of B(:,j) into workspace + + + _scatter(b, j, wb, xb, mark); // loop rows + + + for (i = 0; i < rows; i++) { + // matrix values @ i,j + var va = wa[i] === mark ? xa[i] : zero; + var vb = wb[i] === mark ? xb[i] : zero; // invoke callback + + cdata[i][j] = cf(va, vb); + } + } // return dense matrix + + + return new DenseMatrix({ + data: cdata, + size: [rows, columns], + datatype: dt + }); + }; + + function _scatter(m, j, w, x, mark) { + // a arrays + var values = m._values; + var index = m._index; + var ptr = m._ptr; // loop values in column j + + for (var k = ptr[j], k1 = ptr[j + 1]; k < k1; k++) { + // row + var i = index[k]; // update workspace + + w[i] = mark; + x[i] = values[k]; + } + } +}); +// CONCATENATED MODULE: ./src/function/bitwise/bitXor.js + + + + + + + + +var bitXor_name = 'bitXor'; +var bitXor_dependencies = ['typed', 'matrix', 'DenseMatrix']; +var createBitXor = /* #__PURE__ */Object(factory["a" /* factory */])(bitXor_name, bitXor_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Bitwise XOR two values, `x ^ y`. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.bitXor(x, y) + * + * Examples: + * + * math.bitXor(1, 2) // returns number 3 + * + * math.bitXor([2, 3, 4], 4) // returns Array [6, 7, 0] + * + * See also: + * + * bitAnd, bitNot, bitOr, leftShift, rightArithShift, rightLogShift + * + * @param {number | BigNumber | Array | Matrix} x First value to xor + * @param {number | BigNumber | Array | Matrix} y Second value to xor + * @return {number | BigNumber | Array | Matrix} XOR of `x` and `y` + */ + + var bitXor = typed(bitXor_name, { + 'number, number': bitXorNumber, + 'BigNumber, BigNumber': bitwise_bitXor, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, bitXor); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, bitXor, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, bitXor, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, bitXor); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return bitXor(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return bitXor(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return bitXor(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, bitXor, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, bitXor, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, bitXor, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, bitXor, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, bitXor, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, bitXor, true).valueOf(); + } + }); + return bitXor; +}); +// CONCATENATED MODULE: ./src/function/complex/arg.js + + +var arg_name = 'arg'; +var arg_dependencies = ['typed']; +var createArg = /* #__PURE__ */Object(factory["a" /* factory */])(arg_name, arg_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the argument of a complex value. + * For a complex number `a + bi`, the argument is computed as `atan2(b, a)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.arg(x) + * + * Examples: + * + * const a = math.complex(2, 2) + * math.arg(a) / math.pi // returns number 0.25 + * + * const b = math.complex('2 + 3i') + * math.arg(b) // returns number 0.982793723247329 + * math.atan2(3, 2) // returns number 0.982793723247329 + * + * See also: + * + * re, im, conj, abs + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * A complex number or array with complex numbers + * @return {number | BigNumber | Array | Matrix} The argument of x + */ + var arg = typed(arg_name, { + number: function number(x) { + return Math.atan2(0, x); + }, + BigNumber: function BigNumber(x) { + return x.constructor.atan2(0, x); + }, + Complex: function Complex(x) { + return x.arg(); + }, + // TODO: implement BigNumber support for function arg + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, arg); + } + }); + return arg; +}); +// CONCATENATED MODULE: ./src/function/complex/conj.js + + +var conj_name = 'conj'; +var conj_dependencies = ['typed']; +var createConj = /* #__PURE__ */Object(factory["a" /* factory */])(conj_name, conj_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the complex conjugate of a complex value. + * If `x = a+bi`, the complex conjugate of `x` is `a - bi`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.conj(x) + * + * Examples: + * + * math.conj(math.complex('2 + 3i')) // returns Complex 2 - 3i + * math.conj(math.complex('2 - 3i')) // returns Complex 2 + 3i + * math.conj(math.complex('-5.2i')) // returns Complex 5.2i + * + * See also: + * + * re, im, arg, abs + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * A complex number or array with complex numbers + * @return {number | BigNumber | Complex | Array | Matrix} + * The complex conjugate of x + */ + var conj = typed(conj_name, { + number: function number(x) { + return x; + }, + BigNumber: function BigNumber(x) { + return x; + }, + Complex: function Complex(x) { + return x.conjugate(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, conj); + } + }); + return conj; +}); +// CONCATENATED MODULE: ./src/function/complex/im.js + + +var im_name = 'im'; +var im_dependencies = ['typed']; +var createIm = /* #__PURE__ */Object(factory["a" /* factory */])(im_name, im_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Get the imaginary part of a complex number. + * For a complex number `a + bi`, the function returns `b`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.im(x) + * + * Examples: + * + * const a = math.complex(2, 3) + * math.re(a) // returns number 2 + * math.im(a) // returns number 3 + * + * math.re(math.complex('-5.2i')) // returns number -5.2 + * math.re(math.complex(2.4)) // returns number 0 + * + * See also: + * + * re, conj, abs, arg + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * A complex number or array with complex numbers + * @return {number | BigNumber | Array | Matrix} The imaginary part of x + */ + var im = typed(im_name, { + number: function number(x) { + return 0; + }, + BigNumber: function BigNumber(x) { + return x.mul(0); + }, + Complex: function Complex(x) { + return x.im; + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, im); + } + }); + return im; +}); +// CONCATENATED MODULE: ./src/function/complex/re.js + + +var re_name = 're'; +var re_dependencies = ['typed']; +var createRe = /* #__PURE__ */Object(factory["a" /* factory */])(re_name, re_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Get the real part of a complex number. + * For a complex number `a + bi`, the function returns `a`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.re(x) + * + * Examples: + * + * const a = math.complex(2, 3) + * math.re(a) // returns number 2 + * math.im(a) // returns number 3 + * + * math.re(math.complex('-5.2i')) // returns number 0 + * math.re(math.complex(2.4)) // returns number 2.4 + * + * See also: + * + * im, conj, abs, arg + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * A complex number or array with complex numbers + * @return {number | BigNumber | Array | Matrix} The real part of x + */ + var re = typed(re_name, { + number: function number(x) { + return x; + }, + BigNumber: function BigNumber(x) { + return x; + }, + Complex: function Complex(x) { + return x.re; + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, re); + } + }); + return re; +}); +// CONCATENATED MODULE: ./src/plain/number/logical.js +var logical_n1 = 'number'; +var logical_n2 = 'number, number'; +function notNumber(x) { + return !x; +} +notNumber.signature = logical_n1; +function orNumber(x, y) { + return !!(x || y); +} +orNumber.signature = logical_n2; +function xorNumber(x, y) { + return !!x !== !!y; +} +xorNumber.signature = logical_n2; +function andNumber(x, y) { + return !!(x && y); +} +andNumber.signature = logical_n2; +// CONCATENATED MODULE: ./src/function/logical/not.js + + + +var not_name = 'not'; +var not_dependencies = ['typed']; +var createNot = /* #__PURE__ */Object(factory["a" /* factory */])(not_name, not_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Logical `not`. Flips boolean value of a given parameter. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.not(x) + * + * Examples: + * + * math.not(2) // returns false + * math.not(0) // returns true + * math.not(true) // returns false + * + * a = [2, -7, 0] + * math.not(a) // returns [false, false, true] + * + * See also: + * + * and, or, xor + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check + * @return {boolean | Array | Matrix} + * Returns true when input is a zero or empty value. + */ + var not = typed(not_name, { + number: notNumber, + Complex: function Complex(x) { + return x.re === 0 && x.im === 0; + }, + BigNumber: function BigNumber(x) { + return x.isZero() || x.isNaN(); + }, + Unit: function Unit(x) { + return x.value !== null ? not(x.value) : true; + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, not); + } + }); + return not; +}); +// CONCATENATED MODULE: ./src/function/logical/or.js + + + + + + + +var or_name = 'or'; +var or_dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix']; +var createOr = /* #__PURE__ */Object(factory["a" /* factory */])(or_name, or_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm05 = createAlgorithm05({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Logical `or`. Test if at least one value is defined with a nonzero/nonempty value. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.or(x, y) + * + * Examples: + * + * math.or(2, 4) // returns true + * + * a = [2, 5, 0] + * b = [0, 22, 0] + * c = 0 + * + * math.or(a, b) // returns [true, true, false] + * math.or(b, c) // returns [false, true, false] + * + * See also: + * + * and, not, xor + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check + * @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check + * @return {boolean | Array | Matrix} + * Returns true when one of the inputs is defined with a nonzero/nonempty value. + */ + + var or = typed(or_name, { + 'number, number': orNumber, + 'Complex, Complex': function ComplexComplex(x, y) { + return x.re !== 0 || x.im !== 0 || y.re !== 0 || y.im !== 0; + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return !x.isZero() && !x.isNaN() || !y.isZero() && !y.isNaN(); + }, + 'Unit, Unit': function UnitUnit(x, y) { + return or(x.value || 0, y.value || 0); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm05(x, y, or); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, or, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, or, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, or); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return or(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return or(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return or(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, or, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, or, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, or, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, or, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, or, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, or, true).valueOf(); + } + }); + return or; +}); +// CONCATENATED MODULE: ./src/function/logical/xor.js + + + + + + + +var xor_name = 'xor'; +var xor_dependencies = ['typed', 'matrix', 'DenseMatrix']; +var createXor = /* #__PURE__ */Object(factory["a" /* factory */])(xor_name, xor_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Logical `xor`. Test whether one and only one value is defined with a nonzero/nonempty value. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.xor(x, y) + * + * Examples: + * + * math.xor(2, 4) // returns false + * + * a = [2, 0, 0] + * b = [2, 7, 0] + * c = 0 + * + * math.xor(a, b) // returns [false, true, false] + * math.xor(a, c) // returns [true, false, false] + * + * See also: + * + * and, not, or + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check + * @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check + * @return {boolean | Array | Matrix} + * Returns true when one and only one input is defined with a nonzero/nonempty value. + */ + + var xor = typed(xor_name, { + 'number, number': xorNumber, + 'Complex, Complex': function ComplexComplex(x, y) { + return (x.re !== 0 || x.im !== 0) !== (y.re !== 0 || y.im !== 0); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return (!x.isZero() && !x.isNaN()) !== (!y.isZero() && !y.isNaN()); + }, + 'Unit, Unit': function UnitUnit(x, y) { + return xor(x.value || 0, y.value || 0); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, xor); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, xor, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, xor, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, xor); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return xor(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return xor(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return xor(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, xor, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, xor, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, xor, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, xor, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, xor, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, xor, true).valueOf(); + } + }); + return xor; +}); +// CONCATENATED MODULE: ./src/function/matrix/concat.js + + + + + + +var concat_name = 'concat'; +var concat_dependencies = ['typed', 'matrix', 'isInteger']; +var createConcat = /* #__PURE__ */Object(factory["a" /* factory */])(concat_name, concat_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + isInteger = _ref.isInteger; + + /** + * Concatenate two or more matrices. + * + * Syntax: + * + * math.concat(A, B, C, ...) + * math.concat(A, B, C, ..., dim) + * + * Where: + * + * - `dim: number` is a zero-based dimension over which to concatenate the matrices. + * By default the last dimension of the matrices. + * + * Examples: + * + * const A = [[1, 2], [5, 6]] + * const B = [[3, 4], [7, 8]] + * + * math.concat(A, B) // returns [[1, 2, 3, 4], [5, 6, 7, 8]] + * math.concat(A, B, 0) // returns [[1, 2], [5, 6], [3, 4], [7, 8]] + * math.concat('hello', ' ', 'world') // returns 'hello world' + * + * See also: + * + * size, squeeze, subset, transpose + * + * @param {... Array | Matrix} args Two or more matrices + * @return {Array | Matrix} Concatenated matrix + */ + return typed(concat_name, { + // TODO: change signature to '...Array | Matrix, dim?' when supported + '...Array | Matrix | number | BigNumber': function ArrayMatrixNumberBigNumber(args) { + var i; + var len = args.length; + var dim = -1; // zero-based dimension + + var prevDim; + var asMatrix = false; + var matrices = []; // contains multi dimensional arrays + + for (i = 0; i < len; i++) { + var arg = args[i]; // test whether we need to return a Matrix (if not we return an Array) + + if (Object(is["v" /* isMatrix */])(arg)) { + asMatrix = true; + } + + if (Object(is["y" /* isNumber */])(arg) || Object(is["e" /* isBigNumber */])(arg)) { + if (i !== len - 1) { + throw new Error('Dimension must be specified as last argument'); + } // last argument contains the dimension on which to concatenate + + + prevDim = dim; + dim = arg.valueOf(); // change BigNumber to number + + if (!isInteger(dim)) { + throw new TypeError('Integer number expected for dimension'); + } + + if (dim < 0 || i > 0 && dim > prevDim) { + // TODO: would be more clear when throwing a DimensionError here + throw new IndexError["a" /* IndexError */](dim, prevDim + 1); + } + } else { + // this is a matrix or array + var m = Object(utils_object["a" /* clone */])(arg).valueOf(); + var size = Object(utils_array["a" /* arraySize */])(m); + matrices[i] = m; + prevDim = dim; + dim = size.length - 1; // verify whether each of the matrices has the same number of dimensions + + if (i > 0 && dim !== prevDim) { + throw new DimensionError["a" /* DimensionError */](prevDim + 1, dim + 1); + } + } + } + + if (matrices.length === 0) { + throw new SyntaxError('At least one matrix expected'); + } + + var res = matrices.shift(); + + while (matrices.length) { + res = _concat(res, matrices.shift(), dim, 0); + } + + return asMatrix ? matrix(res) : res; + }, + '...string': function string(args) { + return args.join(''); + } + }); +}); +/** + * Recursively concatenate two matrices. + * The contents of the matrices is not cloned. + * @param {Array} a Multi dimensional array + * @param {Array} b Multi dimensional array + * @param {number} concatDim The dimension on which to concatenate (zero-based) + * @param {number} dim The current dim (zero-based) + * @return {Array} c The concatenated matrix + * @private + */ + +function _concat(a, b, concatDim, dim) { + if (dim < concatDim) { + // recurse into next dimension + if (a.length !== b.length) { + throw new DimensionError["a" /* DimensionError */](a.length, b.length); + } + + var c = []; + + for (var i = 0; i < a.length; i++) { + c[i] = _concat(a[i], b[i], concatDim, dim + 1); + } + + return c; + } else { + // concatenate this dimension + return a.concat(b); + } +} +// CONCATENATED MODULE: ./src/function/matrix/column.js + + + +var column_name = 'column'; +var column_dependencies = ['typed', 'Index', 'matrix', 'range']; +var createColumn = /* #__PURE__ */Object(factory["a" /* factory */])(column_name, column_dependencies, function (_ref) { + var typed = _ref.typed, + Index = _ref.Index, + matrix = _ref.matrix, + range = _ref.range; + + /** + * Return a column from a Matrix. + * + * Syntax: + * + * math.column(value, index) + * + * Example: + * + * // get a column + * const d = [[1, 2], [3, 4]] + * math.column(d, 1) // returns [[2], [4]] + * + * See also: + * + * row + * + * @param {Array | Matrix } value An array or matrix + * @param {number} column The index of the column + * @return {Array | Matrix} The retrieved column + */ + var column = typed(column_name, { + 'Matrix, number': _column, + 'Array, number': function ArrayNumber(value, column) { + return _column(matrix(Object(utils_object["a" /* clone */])(value)), column).valueOf(); + } + }); + return column; + /** + * Retrieve a column of a matrix + * @param {Matrix } value A matrix + * @param {number} column The index of the column + * @return {Matrix} The retrieved column + */ + + function _column(value, column) { + // check dimensions + if (value.size().length !== 2) { + throw new Error('Only two dimensional matrix is supported'); + } + + Object(utils_array["s" /* validateIndex */])(column, value.size()[1]); + var rowRange = range(0, value.size()[0]); + var index = new Index(rowRange, column); + return value.subset(index); + } +}); +// CONCATENATED MODULE: ./src/function/matrix/cross.js + + +var cross_name = 'cross'; +var cross_dependencies = ['typed', 'matrix', 'subtract', 'multiply']; +var createCross = /* #__PURE__ */Object(factory["a" /* factory */])(cross_name, cross_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + subtract = _ref.subtract, + multiply = _ref.multiply; + + /** + * Calculate the cross product for two vectors in three dimensional space. + * The cross product of `A = [a1, a2, a3]` and `B = [b1, b2, b3]` is defined + * as: + * + * cross(A, B) = [ + * a2 * b3 - a3 * b2, + * a3 * b1 - a1 * b3, + * a1 * b2 - a2 * b1 + * ] + * + * If one of the input vectors has a dimension greater than 1, the output + * vector will be a 1x3 (2-dimensional) matrix. + * + * Syntax: + * + * math.cross(x, y) + * + * Examples: + * + * math.cross([1, 1, 0], [0, 1, 1]) // Returns [1, -1, 1] + * math.cross([3, -3, 1], [4, 9, 2]) // Returns [-15, -2, 39] + * math.cross([2, 3, 4], [5, 6, 7]) // Returns [-3, 6, -3] + * math.cross([[1, 2, 3]], [[4], [5], [6]]) // Returns [[-3, 6, -3]] + * + * See also: + * + * dot, multiply + * + * @param {Array | Matrix} x First vector + * @param {Array | Matrix} y Second vector + * @return {Array | Matrix} Returns the cross product of `x` and `y` + */ + return typed(cross_name, { + 'Matrix, Matrix': function MatrixMatrix(x, y) { + return matrix(_cross(x.toArray(), y.toArray())); + }, + 'Matrix, Array': function MatrixArray(x, y) { + return matrix(_cross(x.toArray(), y)); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + return matrix(_cross(x, y.toArray())); + }, + 'Array, Array': _cross + }); + /** + * Calculate the cross product for two arrays + * @param {Array} x First vector + * @param {Array} y Second vector + * @returns {Array} Returns the cross product of x and y + * @private + */ + + function _cross(x, y) { + var highestDimension = Math.max(Object(utils_array["a" /* arraySize */])(x).length, Object(utils_array["a" /* arraySize */])(y).length); + x = Object(utils_array["p" /* squeeze */])(x); + y = Object(utils_array["p" /* squeeze */])(y); + var xSize = Object(utils_array["a" /* arraySize */])(x); + var ySize = Object(utils_array["a" /* arraySize */])(y); + + if (xSize.length !== 1 || ySize.length !== 1 || xSize[0] !== 3 || ySize[0] !== 3) { + throw new RangeError('Vectors with length 3 expected ' + '(Size A = [' + xSize.join(', ') + '], B = [' + ySize.join(', ') + '])'); + } + + var product = [subtract(multiply(x[1], y[2]), multiply(x[2], y[1])), subtract(multiply(x[2], y[0]), multiply(x[0], y[2])), subtract(multiply(x[0], y[1]), multiply(x[1], y[0]))]; + + if (highestDimension > 1) { + return [product]; + } else { + return product; + } + } +}); +// CONCATENATED MODULE: ./src/function/matrix/diag.js + + + + +var diag_name = 'diag'; +var diag_dependencies = ['typed', 'matrix', 'DenseMatrix', 'SparseMatrix']; +var createDiag = /* #__PURE__ */Object(factory["a" /* factory */])(diag_name, diag_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix, + SparseMatrix = _ref.SparseMatrix; + + /** + * Create a diagonal matrix or retrieve the diagonal of a matrix + * + * When `x` is a vector, a matrix with vector `x` on the diagonal will be returned. + * When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector. + * When k is positive, the values are placed on the super diagonal. + * When k is negative, the values are placed on the sub diagonal. + * + * Syntax: + * + * math.diag(X) + * math.diag(X, format) + * math.diag(X, k) + * math.diag(X, k, format) + * + * Examples: + * + * // create a diagonal matrix + * math.diag([1, 2, 3]) // returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]] + * math.diag([1, 2, 3], 1) // returns [[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]] + * math.diag([1, 2, 3], -1) // returns [[0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3]] + * + * // retrieve the diagonal from a matrix + * const a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + * math.diag(a) // returns [1, 5, 9] + * + * See also: + * + * ones, zeros, identity + * + * @param {Matrix | Array} x A two dimensional matrix or a vector + * @param {number | BigNumber} [k=0] The diagonal where the vector will be filled + * in or retrieved. + * @param {string} [format='dense'] The matrix storage format. + * + * @returns {Matrix | Array} Diagonal matrix from input vector, or diagonal from input matrix. + */ + return typed(diag_name, { + // FIXME: simplify this huge amount of signatures as soon as typed-function supports optional arguments + Array: function Array(x) { + return _diag(x, 0, Object(utils_array["a" /* arraySize */])(x), null); + }, + 'Array, number': function ArrayNumber(x, k) { + return _diag(x, k, Object(utils_array["a" /* arraySize */])(x), null); + }, + 'Array, BigNumber': function ArrayBigNumber(x, k) { + return _diag(x, k.toNumber(), Object(utils_array["a" /* arraySize */])(x), null); + }, + 'Array, string': function ArrayString(x, format) { + return _diag(x, 0, Object(utils_array["a" /* arraySize */])(x), format); + }, + 'Array, number, string': function ArrayNumberString(x, k, format) { + return _diag(x, k, Object(utils_array["a" /* arraySize */])(x), format); + }, + 'Array, BigNumber, string': function ArrayBigNumberString(x, k, format) { + return _diag(x, k.toNumber(), Object(utils_array["a" /* arraySize */])(x), format); + }, + Matrix: function Matrix(x) { + return _diag(x, 0, x.size(), x.storage()); + }, + 'Matrix, number': function MatrixNumber(x, k) { + return _diag(x, k, x.size(), x.storage()); + }, + 'Matrix, BigNumber': function MatrixBigNumber(x, k) { + return _diag(x, k.toNumber(), x.size(), x.storage()); + }, + 'Matrix, string': function MatrixString(x, format) { + return _diag(x, 0, x.size(), format); + }, + 'Matrix, number, string': function MatrixNumberString(x, k, format) { + return _diag(x, k, x.size(), format); + }, + 'Matrix, BigNumber, string': function MatrixBigNumberString(x, k, format) { + return _diag(x, k.toNumber(), x.size(), format); + } + }); + /** + * Creeate diagonal matrix from a vector or vice versa + * @param {Array | Matrix} x + * @param {number} k + * @param {string} format Storage format for matrix. If null, + * an Array is returned + * @returns {Array | Matrix} + * @private + */ + + function _diag(x, k, size, format) { + if (!Object(utils_number["i" /* isInteger */])(k)) { + throw new TypeError('Second parameter in function diag must be an integer'); + } + + var kSuper = k > 0 ? k : 0; + var kSub = k < 0 ? -k : 0; // check dimensions + + switch (size.length) { + case 1: + return _createDiagonalMatrix(x, k, format, size[0], kSub, kSuper); + + case 2: + return _getDiagonal(x, k, format, size, kSub, kSuper); + } + + throw new RangeError('Matrix for function diag must be 2 dimensional'); + } + + function _createDiagonalMatrix(x, k, format, l, kSub, kSuper) { + // matrix size + var ms = [l + kSub, l + kSuper]; + + if (format && format !== 'sparse' && format !== 'dense') { + throw new TypeError("Unknown matrix type ".concat(format, "\"")); + } // create diagonal matrix + + + var m = format === 'sparse' ? SparseMatrix.diagonal(ms, x, k) : DenseMatrix.diagonal(ms, x, k); // check we need to return a matrix + + return format !== null ? m : m.valueOf(); + } + + function _getDiagonal(x, k, format, s, kSub, kSuper) { + // check x is a Matrix + if (Object(is["v" /* isMatrix */])(x)) { + // get diagonal matrix + var dm = x.diagonal(k); // check we need to return a matrix + + if (format !== null) { + // check we need to change matrix format + if (format !== dm.storage()) { + return matrix(dm, format); + } + + return dm; + } + + return dm.valueOf(); + } // vector size + + + var n = Math.min(s[0] - kSub, s[1] - kSuper); // diagonal values + + var vector = []; // loop diagonal + + for (var i = 0; i < n; i++) { + vector[i] = x[i + kSub][i + kSuper]; + } // check we need to return a matrix + + + return format !== null ? matrix(vector) : vector; + } +}); +// CONCATENATED MODULE: ./src/function/matrix/eye.js +// TODO: function eye is removed since v5.0.0 (June 2018). Remove it some day. + +var createEye = /* #__PURE__ */Object(factory["a" /* factory */])('eye', [], function () { + return function eye() { + throw new Error('Function "eye" is renamed to "identity" since mathjs version 5.0.0. ' + 'To keep eye working, create an alias for it using "math.import({eye: math.identity}, {override: true})"'); + }; +}); +// CONCATENATED MODULE: ./src/utils/function.js +function function_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { function_typeof = function _typeof(obj) { return typeof obj; }; } else { function_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return function_typeof(obj); } + +// function utils + +/** + * Memoize a given function by caching the computed result. + * The cache of a memoized function can be cleared by deleting the `cache` + * property of the function. + * + * @param {function} fn The function to be memoized. + * Must be a pure function. + * @param {function(args: Array)} [hasher] A custom hash builder. + * Is JSON.stringify by default. + * @return {function} Returns the memoized function + */ +function memoize(fn, hasher) { + return function memoize() { + if (function_typeof(memoize.cache) !== 'object') { + memoize.cache = {}; + } + + var args = []; + + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + var hash = hasher ? hasher(args) : JSON.stringify(args); + + if (!(hash in memoize.cache)) { + memoize.cache[hash] = fn.apply(fn, args); + } + + return memoize.cache[hash]; + }; +} +/** + * Memoize a given function by caching all results and the arguments, + * and comparing against the arguments of previous results before + * executing again. + * This is less performant than `memoize` which calculates a hash, + * which is very fast to compare. Use `memoizeCompare` only when it is + * not possible to create a unique serializable hash from the function + * arguments. + * The isEqual function must compare two sets of arguments + * and return true when equal (can be a deep equality check for example). + * @param {function} fn + * @param {function(a: *, b: *) : boolean} isEqual + * @returns {function} + */ + +function memoizeCompare(fn, isEqual) { + var memoize = function memoize() { + var args = []; + + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + for (var c = 0; c < memoize.cache.length; c++) { + var cached = memoize.cache[c]; + + if (isEqual(args, cached.args)) { + // TODO: move this cache entry to the top so recently used entries move up? + return cached.res; + } + } + + var res = fn.apply(fn, args); + memoize.cache.unshift({ + args: args, + res: res + }); + return res; + }; + + memoize.cache = []; + return memoize; +} +/** + * Find the maximum number of arguments expected by a typed function. + * @param {function} fn A typed function + * @return {number} Returns the maximum number of expected arguments. + * Returns -1 when no signatures where found on the function. + */ + +function maxArgumentCount(fn) { + return Object.keys(fn.signatures || {}).reduce(function (args, signature) { + var count = (signature.match(/,/g) || []).length + 1; + return Math.max(args, count); + }, -1); +} +// CONCATENATED MODULE: ./src/function/matrix/filter.js + + + +var filter_name = 'filter'; +var filter_dependencies = ['typed']; +var createFilter = /* #__PURE__ */Object(factory["a" /* factory */])(filter_name, filter_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Filter the items in an array or one dimensional matrix. + * + * Syntax: + * + * math.filter(x, test) + * + * Examples: + * + * function isPositive (x) { + * return x > 0 + * } + * math.filter([6, -2, -1, 4, 3], isPositive) // returns [6, 4, 3] + * + * math.filter(["23", "foo", "100", "55", "bar"], /[0-9]+/) // returns ["23", "100", "55"] + * + * See also: + * + * forEach, map, sort + * + * @param {Matrix | Array} x A one dimensional matrix or array to filter + * @param {Function | RegExp} test + * A function or regular expression to test items. + * All entries for which `test` returns true are returned. + * When `test` is a function, it is invoked with three parameters: + * the value of the element, the index of the element, and the + * matrix/array being traversed. The function must return a boolean. + * @return {Matrix | Array} Returns the filtered matrix. + */ + return typed('filter', { + 'Array, function': _filterCallback, + 'Matrix, function': function MatrixFunction(x, test) { + return x.create(_filterCallback(x.toArray(), test)); + }, + 'Array, RegExp': utils_array["d" /* filterRegExp */], + 'Matrix, RegExp': function MatrixRegExp(x, test) { + return x.create(Object(utils_array["d" /* filterRegExp */])(x.toArray(), test)); + } + }); +}); +/** + * Filter values in a callback given a callback function + * @param {Array} x + * @param {Function} callback + * @return {Array} Returns the filtered array + * @private + */ + +function _filterCallback(x, callback) { + // figure out what number of arguments the callback function expects + var args = maxArgumentCount(callback); + return Object(utils_array["c" /* filter */])(x, function (value, index, array) { + // invoke the callback function with the right number of arguments + if (args === 1) { + return callback(value); + } else if (args === 2) { + return callback(value, [index]); + } else { + // 3 or -1 + return callback(value, [index], array); + } + }); +} +// CONCATENATED MODULE: ./src/function/matrix/flatten.js + + + +var flatten_name = 'flatten'; +var flatten_dependencies = ['typed', 'matrix']; +var createFlatten = /* #__PURE__ */Object(factory["a" /* factory */])(flatten_name, flatten_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + + /** + * Flatten a multi dimensional matrix into a single dimensional matrix. + * + * Syntax: + * + * math.flatten(x) + * + * Examples: + * + * math.flatten([[1,2], [3,4]]) // returns [1, 2, 3, 4] + * + * See also: + * + * concat, resize, size, squeeze + * + * @param {Matrix | Array} x Matrix to be flattened + * @return {Matrix | Array} Returns the flattened matrix + */ + return typed(flatten_name, { + Array: function Array(x) { + return Object(utils_array["e" /* flatten */])(Object(utils_object["a" /* clone */])(x)); + }, + Matrix: function Matrix(x) { + var flat = Object(utils_array["e" /* flatten */])(Object(utils_object["a" /* clone */])(x.toArray())); // TODO: return the same matrix type as x + + return matrix(flat); + } + }); +}); +// CONCATENATED MODULE: ./src/function/matrix/forEach.js + + + +var forEach_name = 'forEach'; +var forEach_dependencies = ['typed']; +var createForEach = /* #__PURE__ */Object(factory["a" /* factory */])(forEach_name, forEach_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Iterate over all elements of a matrix/array, and executes the given callback function. + * + * Syntax: + * + * math.forEach(x, callback) + * + * Examples: + * + * math.forEach([1, 2, 3], function(value) { + * console.log(value) + * }) + * // outputs 1, 2, 3 + * + * See also: + * + * filter, map, sort + * + * @param {Matrix | Array} x The matrix to iterate on. + * @param {Function} callback The callback function is invoked with three + * parameters: the value of the element, the index + * of the element, and the Matrix/array being traversed. + */ + return typed(forEach_name, { + 'Array, function': forEach_forEach, + 'Matrix, function': function MatrixFunction(x, callback) { + return x.forEach(callback); + } + }); +}); +/** + * forEach for a multi dimensional array + * @param {Array} array + * @param {Function} callback + * @private + */ + +function forEach_forEach(array, callback) { + // figure out what number of arguments the callback function expects + var args = maxArgumentCount(callback); + + var recurse = function recurse(value, index) { + if (Array.isArray(value)) { + Object(utils_array["f" /* forEach */])(value, function (child, i) { + // we create a copy of the index array and append the new index value + recurse(child, index.concat(i)); + }); + } else { + // invoke the callback function with the right number of arguments + if (args === 1) { + callback(value); + } else if (args === 2) { + callback(value, index); + } else { + // 3 or -1 + callback(value, index, array); + } + } + }; + + recurse(array, []); +} +// CONCATENATED MODULE: ./src/function/matrix/getMatrixDataType.js + + + +var getMatrixDataType_name = 'getMatrixDataType'; +var getMatrixDataType_dependencies = ['typed']; +var createGetMatrixDataType = /* #__PURE__ */Object(factory["a" /* factory */])(getMatrixDataType_name, getMatrixDataType_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Find the data type of all elements in a matrix or array, + * for example 'number' if all items are a number and 'Complex' if all values + * are complex numbers. + * If a matrix contains more than one data type, it will return 'mixed'. + * + * Syntax: + * + * math.getMatrixDataType(x) + * + * Examples: + * + * const x = [ [1, 2, 3], [4, 5, 6] ] + * const mixedX = [ [1, true], [2, 3] ] + * const fractionX = [ [math.fraction(1, 3)], [math.fraction(1, 3] ] + * const unitX = [ [math.unit('5cm')], [math.unit('5cm')] ] + * const bigNumberX = [ [math.bignumber(1)], [math.bignumber(0)] ] + * const sparse = math.sparse(x) + * const dense = math.matrix(x) + * math.getMatrixDataType(x) // returns 'number' + * math.getMatrixDataType(sparse) // returns 'number' + * math.getMatrixDataType(dense) // returns 'number' + * math.getMatrixDataType(mixedX) // returns 'mixed' + * math.getMatrixDataType(fractionX) // returns 'Fraction' + * math.getMatrixDataType(unitX) // returns 'Unit' + * math.getMatrixDataType(bigNumberX) // return 'BigNumber' + * + * See also: + * SparseMatrix, DenseMatrix + * + * @param {...Matrix | Array} x The Matrix with values. + * + * @return {string} A string representation of the matrix type + */ + return typed(getMatrixDataType_name, { + Array: function Array(x) { + return Object(utils_array["h" /* getArrayDataType */])(x, is["M" /* typeOf */]); + }, + Matrix: function Matrix(x) { + return x.getDataType(); + } + }); +}); +// CONCATENATED MODULE: ./src/function/matrix/identity.js + + + + +var identity_name = 'identity'; +var identity_dependencies = ['typed', 'config', 'matrix', 'BigNumber', 'DenseMatrix', 'SparseMatrix']; +var createIdentity = /* #__PURE__ */Object(factory["a" /* factory */])(identity_name, identity_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + BigNumber = _ref.BigNumber, + DenseMatrix = _ref.DenseMatrix, + SparseMatrix = _ref.SparseMatrix; + + /** + * Create a 2-dimensional identity matrix with size m x n or n x n. + * The matrix has ones on the diagonal and zeros elsewhere. + * + * Syntax: + * + * math.identity(n) + * math.identity(n, format) + * math.identity(m, n) + * math.identity(m, n, format) + * math.identity([m, n]) + * math.identity([m, n], format) + * + * Examples: + * + * math.identity(3) // returns [[1, 0, 0], [0, 1, 0], [0, 0, 1]] + * math.identity(3, 2) // returns [[1, 0], [0, 1], [0, 0]] + * + * const A = [[1, 2, 3], [4, 5, 6]] + * math.identity(math.size(A)) // returns [[1, 0, 0], [0, 1, 0]] + * + * See also: + * + * diag, ones, zeros, size, range + * + * @param {...number | Matrix | Array} size The size for the matrix + * @param {string} [format] The Matrix storage format + * + * @return {Matrix | Array | number} A matrix with ones on the diagonal. + */ + return typed(identity_name, { + '': function _() { + return config.matrix === 'Matrix' ? matrix([]) : []; + }, + string: function string(format) { + return matrix(format); + }, + 'number | BigNumber': function numberBigNumber(rows) { + return _identity(rows, rows, config.matrix === 'Matrix' ? 'dense' : undefined); + }, + 'number | BigNumber, string': function numberBigNumberString(rows, format) { + return _identity(rows, rows, format); + }, + 'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(rows, cols) { + return _identity(rows, cols, config.matrix === 'Matrix' ? 'dense' : undefined); + }, + 'number | BigNumber, number | BigNumber, string': function numberBigNumberNumberBigNumberString(rows, cols, format) { + return _identity(rows, cols, format); + }, + Array: function Array(size) { + return _identityVector(size); + }, + 'Array, string': function ArrayString(size, format) { + return _identityVector(size, format); + }, + Matrix: function Matrix(size) { + return _identityVector(size.valueOf(), size.storage()); + }, + 'Matrix, string': function MatrixString(size, format) { + return _identityVector(size.valueOf(), format); + } + }); + + function _identityVector(size, format) { + switch (size.length) { + case 0: + return format ? matrix(format) : []; + + case 1: + return _identity(size[0], size[0], format); + + case 2: + return _identity(size[0], size[1], format); + + default: + throw new Error('Vector containing two values expected'); + } + } + /** + * Create an identity matrix + * @param {number | BigNumber} rows + * @param {number | BigNumber} cols + * @param {string} [format] + * @returns {Matrix} + * @private + */ + + + function _identity(rows, cols, format) { + // BigNumber constructor with the right precision + var Big = Object(is["e" /* isBigNumber */])(rows) || Object(is["e" /* isBigNumber */])(cols) ? BigNumber : null; + if (Object(is["e" /* isBigNumber */])(rows)) rows = rows.toNumber(); + if (Object(is["e" /* isBigNumber */])(cols)) cols = cols.toNumber(); + + if (!Object(utils_number["i" /* isInteger */])(rows) || rows < 1) { + throw new Error('Parameters in function identity must be positive integers'); + } + + if (!Object(utils_number["i" /* isInteger */])(cols) || cols < 1) { + throw new Error('Parameters in function identity must be positive integers'); + } + + var one = Big ? new BigNumber(1) : 1; + var defaultValue = Big ? new Big(0) : 0; + var size = [rows, cols]; // check we need to return a matrix + + if (format) { + // create diagonal matrix (use optimized implementation for storage format) + if (format === 'sparse') { + return SparseMatrix.diagonal(size, one, 0, defaultValue); + } + + if (format === 'dense') { + return DenseMatrix.diagonal(size, one, 0, defaultValue); + } + + throw new TypeError("Unknown matrix type \"".concat(format, "\"")); + } // create and resize array + + + var res = Object(utils_array["o" /* resize */])([], size, defaultValue); // fill in ones on the diagonal + + var minimum = rows < cols ? rows : cols; // fill diagonal + + for (var d = 0; d < minimum; d++) { + res[d][d] = one; + } + + return res; + } +}); +// CONCATENATED MODULE: ./src/function/matrix/kron.js + + +var kron_name = 'kron'; +var kron_dependencies = ['typed', 'matrix', 'multiplyScalar']; +var createKron = /* #__PURE__ */Object(factory["a" /* factory */])(kron_name, kron_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + multiplyScalar = _ref.multiplyScalar; + + /** + * Calculates the kronecker product of 2 matrices or vectors. + * + * NOTE: If a one dimensional vector / matrix is given, it will be + * wrapped so its two dimensions. + * See the examples. + * + * Syntax: + * + * math.kron(x, y) + * + * Examples: + * + * math.kron([[1, 0], [0, 1]], [[1, 2], [3, 4]]) + * // returns [ [ 1, 2, 0, 0 ], [ 3, 4, 0, 0 ], [ 0, 0, 1, 2 ], [ 0, 0, 3, 4 ] ] + * + * math.kron([1,1], [2,3,4]) + * // returns [ [ 2, 3, 4, 2, 3, 4 ] ] + * + * See also: + * + * multiply, dot, cross + * + * @param {Array | Matrix} x First vector + * @param {Array | Matrix} y Second vector + * @return {Array | Matrix} Returns the kronecker product of `x` and `y` + */ + return typed(kron_name, { + 'Matrix, Matrix': function MatrixMatrix(x, y) { + return matrix(_kron(x.toArray(), y.toArray())); + }, + 'Matrix, Array': function MatrixArray(x, y) { + return matrix(_kron(x.toArray(), y)); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + return matrix(_kron(x, y.toArray())); + }, + 'Array, Array': _kron + }); + /** + * Calculate the kronecker product of two matrices / vectors + * @param {Array} a First vector + * @param {Array} b Second vector + * @returns {Array} Returns the kronecker product of x and y + * @private + */ + + function _kron(a, b) { + // Deal with the dimensions of the matricies. + if (Object(utils_array["a" /* arraySize */])(a).length === 1) { + // Wrap it in a 2D Matrix + a = [a]; + } + + if (Object(utils_array["a" /* arraySize */])(b).length === 1) { + // Wrap it in a 2D Matrix + b = [b]; + } + + if (Object(utils_array["a" /* arraySize */])(a).length > 2 || Object(utils_array["a" /* arraySize */])(b).length > 2) { + throw new RangeError('Vectors with dimensions greater then 2 are not supported expected ' + '(Size x = ' + JSON.stringify(a.length) + ', y = ' + JSON.stringify(b.length) + ')'); + } + + var t = []; + var r = []; + return a.map(function (a) { + return b.map(function (b) { + r = []; + t.push(r); + return a.map(function (y) { + return b.map(function (x) { + return r.push(multiplyScalar(y, x)); + }); + }); + }); + }) && t; + } +}); +// CONCATENATED MODULE: ./src/function/matrix/map.js + + +var map_name = 'map'; +var map_dependencies = ['typed']; +var createMap = /* #__PURE__ */Object(factory["a" /* factory */])(map_name, map_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Create a new matrix or array with the results of the callback function executed on + * each entry of the matrix/array. + * + * Syntax: + * + * math.map(x, callback) + * + * Examples: + * + * math.map([1, 2, 3], function(value) { + * return value * value + * }) // returns [1, 4, 9] + * + * See also: + * + * filter, forEach, sort + * + * @param {Matrix | Array} x The matrix to iterate on. + * @param {Function} callback The callback method is invoked with three + * parameters: the value of the element, the index + * of the element, and the matrix being traversed. + * @return {Matrix | array} Transformed map of x + */ + return typed(map_name, { + 'Array, function': map_map, + 'Matrix, function': function MatrixFunction(x, callback) { + return x.map(callback); + } + }); +}); +/** + * Map for a multi dimensional array + * @param {Array} array + * @param {Function} callback + * @return {Array} + * @private + */ + +function map_map(array, callback) { + // figure out what number of arguments the callback function expects + var args = maxArgumentCount(callback); + + var recurse = function recurse(value, index) { + if (Array.isArray(value)) { + return value.map(function (child, i) { + // we create a copy of the index array and append the new index value + return recurse(child, index.concat(i)); + }); + } else { + // invoke the callback function with the right number of arguments + if (args === 1) { + return callback(value); + } else if (args === 2) { + return callback(value, index); + } else { + // 3 or -1 + return callback(value, index, array); + } + } + }; + + return recurse(array, []); +} +// CONCATENATED MODULE: ./src/function/matrix/ones.js + + + + +var ones_name = 'ones'; +var ones_dependencies = ['typed', 'config', 'matrix', 'BigNumber']; +var createOnes = /* #__PURE__ */Object(factory["a" /* factory */])(ones_name, ones_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + BigNumber = _ref.BigNumber; + + /** + * Create a matrix filled with ones. The created matrix can have one or + * multiple dimensions. + * + * Syntax: + * + * math.ones(m) + * math.ones(m, format) + * math.ones(m, n) + * math.ones(m, n, format) + * math.ones([m, n]) + * math.ones([m, n], format) + * math.ones([m, n, p, ...]) + * math.ones([m, n, p, ...], format) + * + * Examples: + * + * math.ones(3) // returns [1, 1, 1] + * math.ones(3, 2) // returns [[1, 1], [1, 1], [1, 1]] + * math.ones(3, 2, 'dense') // returns Dense Matrix [[1, 1], [1, 1], [1, 1]] + * + * const A = [[1, 2, 3], [4, 5, 6]] + * math.ones(math.size(A)) // returns [[1, 1, 1], [1, 1, 1]] + * + * See also: + * + * zeros, identity, size, range + * + * @param {...number | Array} size The size of each dimension of the matrix + * @param {string} [format] The Matrix storage format + * + * @return {Array | Matrix | number} A matrix filled with ones + */ + return typed('ones', { + '': function _() { + return config.matrix === 'Array' ? _ones([]) : _ones([], 'default'); + }, + // math.ones(m, n, p, ..., format) + // TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this + '...number | BigNumber | string': function numberBigNumberString(size) { + var last = size[size.length - 1]; + + if (typeof last === 'string') { + var format = size.pop(); + return _ones(size, format); + } else if (config.matrix === 'Array') { + return _ones(size); + } else { + return _ones(size, 'default'); + } + }, + Array: _ones, + Matrix: function Matrix(size) { + var format = size.storage(); + return _ones(size.valueOf(), format); + }, + 'Array | Matrix, string': function ArrayMatrixString(size, format) { + return _ones(size.valueOf(), format); + } + }); + /** + * Create an Array or Matrix with ones + * @param {Array} size + * @param {string} [format='default'] + * @return {Array | Matrix} + * @private + */ + + function _ones(size, format) { + var hasBigNumbers = _normalize(size); + + var defaultValue = hasBigNumbers ? new BigNumber(1) : 1; + + _validate(size); + + if (format) { + // return a matrix + var m = matrix(format); + + if (size.length > 0) { + return m.resize(size, defaultValue); + } + + return m; + } else { + // return an Array + var arr = []; + + if (size.length > 0) { + return Object(utils_array["o" /* resize */])(arr, size, defaultValue); + } + + return arr; + } + } // replace BigNumbers with numbers, returns true if size contained BigNumbers + + + function _normalize(size) { + var hasBigNumbers = false; + size.forEach(function (value, index, arr) { + if (Object(is["e" /* isBigNumber */])(value)) { + hasBigNumbers = true; + arr[index] = value.toNumber(); + } + }); + return hasBigNumbers; + } // validate arguments + + + function _validate(size) { + size.forEach(function (value) { + if (typeof value !== 'number' || !Object(utils_number["i" /* isInteger */])(value) || value < 0) { + throw new Error('Parameters in function ones must be positive integers'); + } + }); + } +}); +// CONCATENATED MODULE: ./src/utils/noop.js +function noBignumber() { + throw new Error('No "bignumber" implementation available'); +} +function noFraction() { + throw new Error('No "fraction" implementation available'); +} +function noMatrix() { + throw new Error('No "matrix" implementation available'); +} +function noIndex() { + throw new Error('No "index" implementation available'); +} +function noSubset() { + throw new Error('No "matrix" implementation available'); +} +// CONCATENATED MODULE: ./src/function/matrix/range.js + + +var range_name = 'range'; +var range_dependencies = ['typed', 'config', '?matrix', '?bignumber', 'smaller', 'smallerEq', 'larger', 'largerEq']; +var range_createRange = /* #__PURE__ */Object(factory["a" /* factory */])(range_name, range_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + bignumber = _ref.bignumber, + smaller = _ref.smaller, + smallerEq = _ref.smallerEq, + larger = _ref.larger, + largerEq = _ref.largerEq; + + /** + * Create an array from a range. + * By default, the range end is excluded. This can be customized by providing + * an extra parameter `includeEnd`. + * + * Syntax: + * + * math.range(str [, includeEnd]) // Create a range from a string, + * // where the string contains the + * // start, optional step, and end, + * // separated by a colon. + * math.range(start, end [, includeEnd]) // Create a range with start and + * // end and a step size of 1. + * math.range(start, end, step [, includeEnd]) // Create a range with start, step, + * // and end. + * + * Where: + * + * - `str: string` + * A string 'start:end' or 'start:step:end' + * - `start: {number | BigNumber}` + * Start of the range + * - `end: number | BigNumber` + * End of the range, excluded by default, included when parameter includeEnd=true + * - `step: number | BigNumber` + * Step size. Default value is 1. + * - `includeEnd: boolean` + * Option to specify whether to include the end or not. False by default. + * + * Examples: + * + * math.range(2, 6) // [2, 3, 4, 5] + * math.range(2, -3, -1) // [2, 1, 0, -1, -2] + * math.range('2:1:6') // [2, 3, 4, 5] + * math.range(2, 6, true) // [2, 3, 4, 5, 6] + * + * See also: + * + * ones, zeros, size, subset + * + * @param {*} args Parameters describing the ranges `start`, `end`, and optional `step`. + * @return {Array | Matrix} range + */ + return typed(range_name, { + // TODO: simplify signatures when typed-function supports default values and optional arguments + // TODO: a number or boolean should not be converted to string here + string: _strRange, + 'string, boolean': _strRange, + 'number, number': function numberNumber(start, end) { + return _out(_rangeEx(start, end, 1)); + }, + 'number, number, number': function numberNumberNumber(start, end, step) { + return _out(_rangeEx(start, end, step)); + }, + 'number, number, boolean': function numberNumberBoolean(start, end, includeEnd) { + return includeEnd ? _out(_rangeInc(start, end, 1)) : _out(_rangeEx(start, end, 1)); + }, + 'number, number, number, boolean': function numberNumberNumberBoolean(start, end, step, includeEnd) { + return includeEnd ? _out(_rangeInc(start, end, step)) : _out(_rangeEx(start, end, step)); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(start, end) { + var BigNumber = start.constructor; + return _out(_bigRangeEx(start, end, new BigNumber(1))); + }, + 'BigNumber, BigNumber, BigNumber': function BigNumberBigNumberBigNumber(start, end, step) { + return _out(_bigRangeEx(start, end, step)); + }, + 'BigNumber, BigNumber, boolean': function BigNumberBigNumberBoolean(start, end, includeEnd) { + var BigNumber = start.constructor; + return includeEnd ? _out(_bigRangeInc(start, end, new BigNumber(1))) : _out(_bigRangeEx(start, end, new BigNumber(1))); + }, + 'BigNumber, BigNumber, BigNumber, boolean': function BigNumberBigNumberBigNumberBoolean(start, end, step, includeEnd) { + return includeEnd ? _out(_bigRangeInc(start, end, step)) : _out(_bigRangeEx(start, end, step)); + } + }); + + function _out(arr) { + if (config.matrix === 'Matrix') { + return matrix ? matrix(arr) : noMatrix(); + } + + return arr; + } + + function _strRange(str, includeEnd) { + var r = _parse(str); + + if (!r) { + throw new SyntaxError('String "' + str + '" is no valid range'); + } + + var fn; + + if (config.number === 'BigNumber') { + if (bignumber === undefined) { + noBignumber(); + } + + fn = includeEnd ? _bigRangeInc : _bigRangeEx; + return _out(fn(bignumber(r.start), bignumber(r.end), bignumber(r.step))); + } else { + fn = includeEnd ? _rangeInc : _rangeEx; + return _out(fn(r.start, r.end, r.step)); + } + } + /** + * Create a range with numbers. End is excluded + * @param {number} start + * @param {number} end + * @param {number} step + * @returns {Array} range + * @private + */ + + + function _rangeEx(start, end, step) { + var array = []; + var x = start; + + if (step > 0) { + while (smaller(x, end)) { + array.push(x); + x += step; + } + } else if (step < 0) { + while (larger(x, end)) { + array.push(x); + x += step; + } + } + + return array; + } + /** + * Create a range with numbers. End is included + * @param {number} start + * @param {number} end + * @param {number} step + * @returns {Array} range + * @private + */ + + + function _rangeInc(start, end, step) { + var array = []; + var x = start; + + if (step > 0) { + while (smallerEq(x, end)) { + array.push(x); + x += step; + } + } else if (step < 0) { + while (largerEq(x, end)) { + array.push(x); + x += step; + } + } + + return array; + } + /** + * Create a range with big numbers. End is excluded + * @param {BigNumber} start + * @param {BigNumber} end + * @param {BigNumber} step + * @returns {Array} range + * @private + */ + + + function _bigRangeEx(start, end, step) { + var zero = bignumber(0); + var array = []; + var x = start; + + if (step.gt(zero)) { + while (smaller(x, end)) { + array.push(x); + x = x.plus(step); + } + } else if (step.lt(zero)) { + while (larger(x, end)) { + array.push(x); + x = x.plus(step); + } + } + + return array; + } + /** + * Create a range with big numbers. End is included + * @param {BigNumber} start + * @param {BigNumber} end + * @param {BigNumber} step + * @returns {Array} range + * @private + */ + + + function _bigRangeInc(start, end, step) { + var zero = bignumber(0); + var array = []; + var x = start; + + if (step.gt(zero)) { + while (smallerEq(x, end)) { + array.push(x); + x = x.plus(step); + } + } else if (step.lt(zero)) { + while (largerEq(x, end)) { + array.push(x); + x = x.plus(step); + } + } + + return array; + } + /** + * Parse a string into a range, + * The string contains the start, optional step, and end, separated by a colon. + * If the string does not contain a valid range, null is returned. + * For example str='0:2:11'. + * @param {string} str + * @return {{start: number, end: number, step: number} | null} range Object containing properties start, end, step + * @private + */ + + + function _parse(str) { + var args = str.split(':'); // number + + var nums = args.map(function (arg) { + // use Number and not parseFloat as Number returns NaN on invalid garbage in the string + return Number(arg); + }); + var invalid = nums.some(function (num) { + return isNaN(num); + }); + + if (invalid) { + return null; + } + + switch (nums.length) { + case 2: + return { + start: nums[0], + end: nums[1], + step: 1 + }; + + case 3: + return { + start: nums[0], + end: nums[2], + step: nums[1] + }; + + default: + return null; + } + } +}); +// CONCATENATED MODULE: ./src/function/matrix/reshape.js + + +var reshape_name = 'reshape'; +var reshape_dependencies = ['typed', 'isInteger', 'matrix']; +var createReshape = /* #__PURE__ */Object(factory["a" /* factory */])(reshape_name, reshape_dependencies, function (_ref) { + var typed = _ref.typed, + isInteger = _ref.isInteger, + matrix = _ref.matrix; + + /** + * Reshape a multi dimensional array to fit the specified dimensions + * + * Syntax: + * + * math.reshape(x, sizes) + * + * Examples: + * + * math.reshape([1, 2, 3, 4, 5, 6], [2, 3]) + * // returns Array [[1, 2, 3], [4, 5, 6]] + * + * math.reshape([[1, 2], [3, 4]], [1, 4]) + * // returns Array [[1, 2, 3, 4]] + * + * math.reshape([[1, 2], [3, 4]], [4]) + * // returns Array [1, 2, 3, 4] + * + * const x = math.matrix([1, 2, 3, 4, 5, 6, 7, 8]) + * math.reshape(x, [2, 2, 2]) + * // returns Matrix [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + * + * See also: + * + * size, squeeze, resize + * + * @param {Array | Matrix | *} x Matrix to be reshaped + * @param {number[]} sizes One dimensional array with integral sizes for + * each dimension + * + * @return {* | Array | Matrix} A reshaped clone of matrix `x` + * + * @throws {TypeError} If `sizes` does not contain solely integers + * @throws {DimensionError} If the product of the new dimension sizes does + * not equal that of the old ones + */ + return typed(reshape_name, { + 'Matrix, Array': function MatrixArray(x, sizes) { + if (x.reshape) { + return x.reshape(sizes); + } else { + return matrix(Object(utils_array["n" /* reshape */])(x.valueOf(), sizes)); + } + }, + 'Array, Array': function ArrayArray(x, sizes) { + sizes.forEach(function (size) { + if (!isInteger(size)) { + throw new TypeError('Invalid size for dimension: ' + size); + } + }); + return Object(utils_array["n" /* reshape */])(x, sizes); + } + }); +}); +// EXTERNAL MODULE: ./src/error/ArgumentsError.js +var ArgumentsError = __webpack_require__(13); + +// CONCATENATED MODULE: ./src/function/matrix/resize.js + + + + + + + + +var resize_name = 'resize'; +var resize_dependencies = ['config', 'matrix']; +var createResize = /* #__PURE__ */Object(factory["a" /* factory */])(resize_name, resize_dependencies, function (_ref) { + var config = _ref.config, + matrix = _ref.matrix; + + /** + * Resize a matrix + * + * Syntax: + * + * math.resize(x, size) + * math.resize(x, size, defaultValue) + * + * Examples: + * + * math.resize([1, 2, 3, 4, 5], [3]) // returns Array [1, 2, 3] + * math.resize([1, 2, 3], [5], 0) // returns Array [1, 2, 3, 0, 0] + * math.resize(2, [2, 3], 0) // returns Matrix [[2, 0, 0], [0, 0, 0]] + * math.resize("hello", [8], "!") // returns string 'hello!!!' + * + * See also: + * + * size, squeeze, subset, reshape + * + * @param {Array | Matrix | *} x Matrix to be resized + * @param {Array | Matrix} size One dimensional array with numbers + * @param {number | string} [defaultValue=0] Zero by default, except in + * case of a string, in that case + * defaultValue = ' ' + * @return {* | Array | Matrix} A resized clone of matrix `x` + */ + // TODO: rework resize to a typed-function + return function resize(x, size, defaultValue) { + if (arguments.length !== 2 && arguments.length !== 3) { + throw new ArgumentsError["a" /* ArgumentsError */]('resize', arguments.length, 2, 3); + } + + if (Object(is["v" /* isMatrix */])(size)) { + size = size.valueOf(); // get Array + } + + if (Object(is["e" /* isBigNumber */])(size[0])) { + // convert bignumbers to numbers + size = size.map(function (value) { + return !Object(is["e" /* isBigNumber */])(value) ? value : value.toNumber(); + }); + } // check x is a Matrix + + + if (Object(is["v" /* isMatrix */])(x)) { + // use optimized matrix implementation, return copy + return x.resize(size, defaultValue, true); + } + + if (typeof x === 'string') { + // resize string + return _resizeString(x, size, defaultValue); + } // check result should be a matrix + + + var asMatrix = Array.isArray(x) ? false : config.matrix !== 'Array'; + + if (size.length === 0) { + // output a scalar + while (Array.isArray(x)) { + x = x[0]; + } + + return Object(utils_object["a" /* clone */])(x); + } else { + // output an array/matrix + if (!Array.isArray(x)) { + x = [x]; + } + + x = Object(utils_object["a" /* clone */])(x); + var res = Object(utils_array["o" /* resize */])(x, size, defaultValue); + return asMatrix ? matrix(res) : res; + } + }; + /** + * Resize a string + * @param {string} str + * @param {number[]} size + * @param {string} [defaultChar=' '] + * @private + */ + + function _resizeString(str, size, defaultChar) { + if (defaultChar !== undefined) { + if (typeof defaultChar !== 'string' || defaultChar.length !== 1) { + throw new TypeError('Single character expected as defaultValue'); + } + } else { + defaultChar = ' '; + } + + if (size.length !== 1) { + throw new DimensionError["a" /* DimensionError */](size.length, 1); + } + + var len = size[0]; + + if (typeof len !== 'number' || !Object(utils_number["i" /* isInteger */])(len)) { + throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + + if (str.length > len) { + return str.substring(0, len); + } else if (str.length < len) { + var res = str; + + for (var i = 0, ii = len - str.length; i < ii; i++) { + res += defaultChar; + } + + return res; + } else { + return str; + } + } +}); +// CONCATENATED MODULE: ./src/function/matrix/row.js + + + +var row_name = 'row'; +var row_dependencies = ['typed', 'Index', 'matrix', 'range']; +var createRow = /* #__PURE__ */Object(factory["a" /* factory */])(row_name, row_dependencies, function (_ref) { + var typed = _ref.typed, + Index = _ref.Index, + matrix = _ref.matrix, + range = _ref.range; + + /** + * Return a row from a Matrix. + * + * Syntax: + * + * math.row(value, index) + * + * Example: + * + * // get a row + * const d = [[1, 2], [3, 4]] + * math.row(d, 1) // returns [[3, 4]] + * + * See also: + * + * column + * + * @param {Array | Matrix } value An array or matrix + * @param {number} row The index of the row + * @return {Array | Matrix} The retrieved row + */ + var row = typed(row_name, { + 'Matrix, number': _row, + 'Array, number': function ArrayNumber(value, row) { + return _row(matrix(Object(utils_object["a" /* clone */])(value)), row).valueOf(); + } + }); + return row; + /** + * Retrieve a row of a matrix + * @param {Matrix } value A matrix + * @param {number} row The index of the row + * @return {Matrix} The retrieved row + */ + + function _row(value, row) { + // check dimensions + if (value.size().length !== 2) { + throw new Error('Only two dimensional matrix is supported'); + } + + Object(utils_array["s" /* validateIndex */])(row, value.size()[0]); + var columnRange = range(0, value.size()[1]); + var index = new Index(row, columnRange); + return value.subset(index); + } +}); +// CONCATENATED MODULE: ./src/function/matrix/size.js + + + +var size_name = 'size'; +var size_dependencies = ['typed', 'config', '?matrix']; +var createSize = /* #__PURE__ */Object(factory["a" /* factory */])(size_name, size_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix; + + /** + * Calculate the size of a matrix or scalar. + * + * Syntax: + * + * math.size(x) + * + * Examples: + * + * math.size(2.3) // returns [] + * math.size('hello world') // returns [11] + * + * const A = [[1, 2, 3], [4, 5, 6]] + * math.size(A) // returns [2, 3] + * math.size(math.range(1,6)) // returns [5] + * + * See also: + * + * resize, squeeze, subset + * + * @param {boolean | number | Complex | Unit | string | Array | Matrix} x A matrix + * @return {Array | Matrix} A vector with size of `x`. + */ + return typed(size_name, { + Matrix: function Matrix(x) { + return x.create(x.size()); + }, + Array: utils_array["a" /* arraySize */], + string: function string(x) { + return config.matrix === 'Array' ? [x.length] : matrix([x.length]); + }, + 'number | Complex | BigNumber | Unit | boolean | null': function numberComplexBigNumberUnitBooleanNull(x) { + // scalar + return config.matrix === 'Array' ? [] : matrix ? matrix([]) : noMatrix(); + } + }); +}); +// CONCATENATED MODULE: ./src/function/matrix/squeeze.js + + + +var squeeze_name = 'squeeze'; +var squeeze_dependencies = ['typed', 'matrix']; +var createSqueeze = /* #__PURE__ */Object(factory["a" /* factory */])(squeeze_name, squeeze_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + + /** + * Squeeze a matrix, remove inner and outer singleton dimensions from a matrix. + * + * Syntax: + * + * math.squeeze(x) + * + * Examples: + * + * math.squeeze([3]) // returns 3 + * math.squeeze([[3]]) // returns 3 + * + * const A = math.zeros(3, 1) // returns [[0], [0], [0]] (size 3x1) + * math.squeeze(A) // returns [0, 0, 0] (size 3) + * + * const B = math.zeros(1, 3) // returns [[0, 0, 0]] (size 1x3) + * math.squeeze(B) // returns [0, 0, 0] (size 3) + * + * // only inner and outer dimensions are removed + * const C = math.zeros(2, 1, 3) // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3) + * math.squeeze(C) // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3) + * + * See also: + * + * subset + * + * @param {Matrix | Array} x Matrix to be squeezed + * @return {Matrix | Array} Squeezed matrix + */ + return typed(squeeze_name, { + Array: function Array(x) { + return Object(utils_array["p" /* squeeze */])(Object(utils_object["a" /* clone */])(x)); + }, + Matrix: function Matrix(x) { + var res = Object(utils_array["p" /* squeeze */])(x.toArray()); // FIXME: return the same type of matrix as the input + + return Array.isArray(res) ? matrix(res) : res; + }, + any: function any(x) { + // scalar + return Object(utils_object["a" /* clone */])(x); + } + }); +}); +// CONCATENATED MODULE: ./src/utils/customs.js +function customs_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { customs_typeof = function _typeof(obj) { return typeof obj; }; } else { customs_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return customs_typeof(obj); } + + +/** + * Get a property of a plain object + * Throws an error in case the object is not a plain object or the + * property is not defined on the object itself + * @param {Object} object + * @param {string} prop + * @return {*} Returns the property value when safe + */ + +function getSafeProperty(object, prop) { + // only allow getting safe properties of a plain object + if (isPlainObject(object) && isSafeProperty(object, prop)) { + return object[prop]; + } + + if (typeof object[prop] === 'function' && isSafeMethod(object, prop)) { + throw new Error('Cannot access method "' + prop + '" as a property'); + } + + throw new Error('No access to property "' + prop + '"'); +} +/** + * Set a property on a plain object. + * Throws an error in case the object is not a plain object or the + * property would override an inherited property like .constructor or .toString + * @param {Object} object + * @param {string} prop + * @param {*} value + * @return {*} Returns the value + */ +// TODO: merge this function into access.js? + + +function setSafeProperty(object, prop, value) { + // only allow setting safe properties of a plain object + if (isPlainObject(object) && isSafeProperty(object, prop)) { + object[prop] = value; + return value; + } + + throw new Error('No access to property "' + prop + '"'); +} +/** + * Test whether a property is safe to use for an object. + * For example .toString and .constructor are not safe + * @param {string} prop + * @return {boolean} Returns true when safe + */ + + +function isSafeProperty(object, prop) { + if (!object || customs_typeof(object) !== 'object') { + return false; + } // SAFE: whitelisted + // e.g length + + + if (Object(utils_object["f" /* hasOwnProperty */])(safeNativeProperties, prop)) { + return true; + } // UNSAFE: inherited from Object prototype + // e.g constructor + + + if (prop in Object.prototype) { + // 'in' is used instead of hasOwnProperty for nodejs v0.10 + // which is inconsistent on root prototypes. It is safe + // here because Object.prototype is a root object + return false; + } // UNSAFE: inherited from Function prototype + // e.g call, apply + + + if (prop in Function.prototype) { + // 'in' is used instead of hasOwnProperty for nodejs v0.10 + // which is inconsistent on root prototypes. It is safe + // here because Function.prototype is a root object + return false; + } + + return true; +} +/** + * Validate whether a method is safe. + * Throws an error when that's not the case. + * @param {Object} object + * @param {string} method + */ +// TODO: merge this function into assign.js? + + +function validateSafeMethod(object, method) { + if (!isSafeMethod(object, method)) { + throw new Error('No access to method "' + method + '"'); + } +} +/** + * Check whether a method is safe. + * Throws an error when that's not the case (for example for `constructor`). + * @param {Object} object + * @param {string} method + * @return {boolean} Returns true when safe, false otherwise + */ + + +function isSafeMethod(object, method) { + if (object === null || object === undefined || typeof object[method] !== 'function') { + return false; + } // UNSAFE: ghosted + // e.g overridden toString + // Note that IE10 doesn't support __proto__ and we can't do this check there. + + + if (Object(utils_object["f" /* hasOwnProperty */])(object, method) && Object.getPrototypeOf && method in Object.getPrototypeOf(object)) { + return false; + } // SAFE: whitelisted + // e.g toString + + + if (Object(utils_object["f" /* hasOwnProperty */])(safeNativeMethods, method)) { + return true; + } // UNSAFE: inherited from Object prototype + // e.g constructor + + + if (method in Object.prototype) { + // 'in' is used instead of hasOwnProperty for nodejs v0.10 + // which is inconsistent on root prototypes. It is safe + // here because Object.prototype is a root object + return false; + } // UNSAFE: inherited from Function prototype + // e.g call, apply + + + if (method in Function.prototype) { + // 'in' is used instead of hasOwnProperty for nodejs v0.10 + // which is inconsistent on root prototypes. It is safe + // here because Function.prototype is a root object + return false; + } + + return true; +} + +function isPlainObject(object) { + return customs_typeof(object) === 'object' && object && object.constructor === Object; +} + +var safeNativeProperties = { + length: true, + name: true +}; +var safeNativeMethods = { + toString: true, + valueOf: true, + toLocaleString: true +}; + + + + + + +// CONCATENATED MODULE: ./src/function/matrix/subset.js + + + + + + +var subset_name = 'subset'; +var subset_dependencies = ['typed', 'matrix']; +var createSubset = /* #__PURE__ */Object(factory["a" /* factory */])(subset_name, subset_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + + /** + * Get or set a subset of a matrix or string. + * + * Syntax: + * math.subset(value, index) // retrieve a subset + * math.subset(value, index, replacement [, defaultValue]) // replace a subset + * + * Examples: + * + * // get a subset + * const d = [[1, 2], [3, 4]] + * math.subset(d, math.index(1, 0)) // returns 3 + * math.subset(d, math.index([0, 1], 1)) // returns [[2], [4]] + * + * // replace a subset + * const e = [] + * const f = math.subset(e, math.index(0, [0, 2]), [5, 6]) // f = [[5, 6]] + * const g = math.subset(f, math.index(1, 1), 7, 0) // g = [[5, 6], [0, 7]] + * + * See also: + * + * size, resize, squeeze, index + * + * @param {Array | Matrix | string} matrix An array, matrix, or string + * @param {Index} index An index containing ranges for each + * dimension + * @param {*} [replacement] An array, matrix, or scalar. + * If provided, the subset is replaced with replacement. + * If not provided, the subset is returned + * @param {*} [defaultValue=undefined] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * math.matrix elements will be left undefined. + * @return {Array | Matrix | string} Either the retrieved subset or the updated matrix. + */ + return typed(subset_name, { + // get subset + 'Array, Index': function ArrayIndex(value, index) { + var m = matrix(value); + var subset = m.subset(index); // returns a Matrix + + return index.isScalar() ? subset : subset.valueOf(); // return an Array (like the input) + }, + 'Matrix, Index': function MatrixIndex(value, index) { + return value.subset(index); + }, + 'Object, Index': _getObjectProperty, + 'string, Index': _getSubstring, + // set subset + 'Array, Index, any': function ArrayIndexAny(value, index, replacement) { + return matrix(Object(utils_object["a" /* clone */])(value)).subset(index, replacement, undefined).valueOf(); + }, + 'Array, Index, any, any': function ArrayIndexAnyAny(value, index, replacement, defaultValue) { + return matrix(Object(utils_object["a" /* clone */])(value)).subset(index, replacement, defaultValue).valueOf(); + }, + 'Matrix, Index, any': function MatrixIndexAny(value, index, replacement) { + return value.clone().subset(index, replacement); + }, + 'Matrix, Index, any, any': function MatrixIndexAnyAny(value, index, replacement, defaultValue) { + return value.clone().subset(index, replacement, defaultValue); + }, + 'string, Index, string': _setSubstring, + 'string, Index, string, string': _setSubstring, + 'Object, Index, any': _setObjectProperty + }); +}); +/** + * Retrieve a subset of a string + * @param {string} str string from which to get a substring + * @param {Index} index An index containing ranges for each dimension + * @returns {string} substring + * @private + */ + +function _getSubstring(str, index) { + if (!Object(is["t" /* isIndex */])(index)) { + // TODO: better error message + throw new TypeError('Index expected'); + } + + if (index.size().length !== 1) { + throw new DimensionError["a" /* DimensionError */](index.size().length, 1); + } // validate whether the range is out of range + + + var strLen = str.length; + Object(utils_array["s" /* validateIndex */])(index.min()[0], strLen); + Object(utils_array["s" /* validateIndex */])(index.max()[0], strLen); + var range = index.dimension(0); + var substr = ''; + range.forEach(function (v) { + substr += str.charAt(v); + }); + return substr; +} +/** + * Replace a substring in a string + * @param {string} str string to be replaced + * @param {Index} index An index containing ranges for each dimension + * @param {string} replacement Replacement string + * @param {string} [defaultValue] Default value to be uses when resizing + * the string. is ' ' by default + * @returns {string} result + * @private + */ + + +function _setSubstring(str, index, replacement, defaultValue) { + if (!index || index.isIndex !== true) { + // TODO: better error message + throw new TypeError('Index expected'); + } + + if (index.size().length !== 1) { + throw new DimensionError["a" /* DimensionError */](index.size().length, 1); + } + + if (defaultValue !== undefined) { + if (typeof defaultValue !== 'string' || defaultValue.length !== 1) { + throw new TypeError('Single character expected as defaultValue'); + } + } else { + defaultValue = ' '; + } + + var range = index.dimension(0); + var len = range.size()[0]; + + if (len !== replacement.length) { + throw new DimensionError["a" /* DimensionError */](range.size()[0], replacement.length); + } // validate whether the range is out of range + + + var strLen = str.length; + Object(utils_array["s" /* validateIndex */])(index.min()[0]); + Object(utils_array["s" /* validateIndex */])(index.max()[0]); // copy the string into an array with characters + + var chars = []; + + for (var i = 0; i < strLen; i++) { + chars[i] = str.charAt(i); + } + + range.forEach(function (v, i) { + chars[v] = replacement.charAt(i[0]); + }); // initialize undefined characters with a space + + if (chars.length > strLen) { + for (var _i = strLen - 1, _len = chars.length; _i < _len; _i++) { + if (!chars[_i]) { + chars[_i] = defaultValue; + } + } + } + + return chars.join(''); +} +/** + * Retrieve a property from an object + * @param {Object} object + * @param {Index} index + * @return {*} Returns the value of the property + * @private + */ + + +function _getObjectProperty(object, index) { + if (index.size().length !== 1) { + throw new DimensionError["a" /* DimensionError */](index.size(), 1); + } + + var key = index.dimension(0); + + if (typeof key !== 'string') { + throw new TypeError('String expected as index to retrieve an object property'); + } + + return getSafeProperty(object, key); +} +/** + * Set a property on an object + * @param {Object} object + * @param {Index} index + * @param {*} replacement + * @return {*} Returns the updated object + * @private + */ + + +function _setObjectProperty(object, index, replacement) { + if (index.size().length !== 1) { + throw new DimensionError["a" /* DimensionError */](index.size(), 1); + } + + var key = index.dimension(0); + + if (typeof key !== 'string') { + throw new TypeError('String expected as index to retrieve an object property'); + } // clone the object, and apply the property to the clone + + + var updated = Object(utils_object["a" /* clone */])(object); + setSafeProperty(updated, key, replacement); + return updated; +} +// CONCATENATED MODULE: ./src/function/matrix/transpose.js + + + +var transpose_name = 'transpose'; +var transpose_dependencies = ['typed', 'matrix']; +var createTranspose = /* #__PURE__ */Object(factory["a" /* factory */])(transpose_name, transpose_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + + /** + * Transpose a matrix. All values of the matrix are reflected over its + * main diagonal. Only applicable to two dimensional matrices containing + * a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional + * vectors and scalars return the input unchanged. + * + * Syntax: + * + * math.transpose(x) + * + * Examples: + * + * const A = [[1, 2, 3], [4, 5, 6]] + * math.transpose(A) // returns [[1, 4], [2, 5], [3, 6]] + * + * See also: + * + * diag, inv, subset, squeeze + * + * @param {Array | Matrix} x Matrix to be transposed + * @return {Array | Matrix} The transposed matrix + */ + var transpose = typed('transpose', { + Array: function Array(x) { + // use dense matrix implementation + return transpose(matrix(x)).valueOf(); + }, + Matrix: function Matrix(x) { + // matrix size + var size = x.size(); // result + + var c; // process dimensions + + switch (size.length) { + case 1: + // vector + c = x.clone(); + break; + + case 2: + { + // rows and columns + var rows = size[0]; + var columns = size[1]; // check columns + + if (columns === 0) { + // throw exception + throw new RangeError('Cannot transpose a 2D matrix with no columns (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } // process storage format + + + switch (x.storage()) { + case 'dense': + c = _denseTranspose(x, rows, columns); + break; + + case 'sparse': + c = _sparseTranspose(x, rows, columns); + break; + } + } + break; + + default: + // multi dimensional + throw new RangeError('Matrix must be a vector or two dimensional (size: ' + Object(utils_string["d" /* format */])(this._size) + ')'); + } + + return c; + }, + // scalars + any: function any(x) { + return Object(utils_object["a" /* clone */])(x); + } + }); + + function _denseTranspose(m, rows, columns) { + // matrix array + var data = m._data; // transposed matrix data + + var transposed = []; + var transposedRow; // loop columns + + for (var j = 0; j < columns; j++) { + // initialize row + transposedRow = transposed[j] = []; // loop rows + + for (var i = 0; i < rows; i++) { + // set data + transposedRow[i] = Object(utils_object["a" /* clone */])(data[i][j]); + } + } // return matrix + + + return m.createDenseMatrix({ + data: transposed, + size: [columns, rows], + datatype: m._datatype + }); + } + + function _sparseTranspose(m, rows, columns) { + // matrix arrays + var values = m._values; + var index = m._index; + var ptr = m._ptr; // result matrices + + var cvalues = values ? [] : undefined; + var cindex = []; + var cptr = []; // row counts + + var w = []; + + for (var x = 0; x < rows; x++) { + w[x] = 0; + } // vars + + + var p, l, j; // loop values in matrix + + for (p = 0, l = index.length; p < l; p++) { + // number of values in row + w[index[p]]++; + } // cumulative sum + + + var sum = 0; // initialize cptr with the cummulative sum of row counts + + for (var i = 0; i < rows; i++) { + // update cptr + cptr.push(sum); // update sum + + sum += w[i]; // update w + + w[i] = cptr[i]; + } // update cptr + + + cptr.push(sum); // loop columns + + for (j = 0; j < columns; j++) { + // values & index in column + for (var k0 = ptr[j], k1 = ptr[j + 1], k = k0; k < k1; k++) { + // C values & index + var q = w[index[k]]++; // C[j, i] = A[i, j] + + cindex[q] = j; // check we need to process values (pattern matrix) + + if (values) { + cvalues[q] = Object(utils_object["a" /* clone */])(values[k]); + } + } + } // return matrix + + + return m.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [columns, rows], + datatype: m._datatype + }); + } + + return transpose; +}); +// CONCATENATED MODULE: ./src/function/matrix/ctranspose.js + +var ctranspose_name = 'ctranspose'; +var ctranspose_dependencies = ['typed', 'transpose', 'conj']; +var createCtranspose = /* #__PURE__ */Object(factory["a" /* factory */])(ctranspose_name, ctranspose_dependencies, function (_ref) { + var typed = _ref.typed, + transpose = _ref.transpose, + conj = _ref.conj; + + /** + * Transpose and complex conjugate a matrix. All values of the matrix are + * reflected over its main diagonal and then the complex conjugate is + * taken. This is equivalent to complex conjugation for scalars and + * vectors. + * + * Syntax: + * + * math.ctranspose(x) + * + * Examples: + * + * const A = [[1, 2, 3], [4, 5, math.complex(6,7)]] + * math.ctranspose(A) // returns [[1, 4], [2, 5], [3, {re:6,im:7}]] + * + * See also: + * + * transpose, diag, inv, subset, squeeze + * + * @param {Array | Matrix} x Matrix to be ctransposed + * @return {Array | Matrix} The ctransposed matrix + */ + return typed(ctranspose_name, { + any: function any(x) { + return conj(transpose(x)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/matrix/zeros.js + + + + +var zeros_name = 'zeros'; +var zeros_dependencies = ['typed', 'config', 'matrix', 'BigNumber']; +var createZeros = /* #__PURE__ */Object(factory["a" /* factory */])(zeros_name, zeros_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + BigNumber = _ref.BigNumber; + + /** + * Create a matrix filled with zeros. The created matrix can have one or + * multiple dimensions. + * + * Syntax: + * + * math.zeros(m) + * math.zeros(m, format) + * math.zeros(m, n) + * math.zeros(m, n, format) + * math.zeros([m, n]) + * math.zeros([m, n], format) + * + * Examples: + * + * math.zeros(3) // returns [0, 0, 0] + * math.zeros(3, 2) // returns [[0, 0], [0, 0], [0, 0]] + * math.zeros(3, 'dense') // returns [0, 0, 0] + * + * const A = [[1, 2, 3], [4, 5, 6]] + * math.zeros(math.size(A)) // returns [[0, 0, 0], [0, 0, 0]] + * + * See also: + * + * ones, identity, size, range + * + * @param {...number | Array} size The size of each dimension of the matrix + * @param {string} [format] The Matrix storage format + * + * @return {Array | Matrix} A matrix filled with zeros + */ + return typed(zeros_name, { + '': function _() { + return config.matrix === 'Array' ? _zeros([]) : _zeros([], 'default'); + }, + // math.zeros(m, n, p, ..., format) + // TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this + '...number | BigNumber | string': function numberBigNumberString(size) { + var last = size[size.length - 1]; + + if (typeof last === 'string') { + var format = size.pop(); + return _zeros(size, format); + } else if (config.matrix === 'Array') { + return _zeros(size); + } else { + return _zeros(size, 'default'); + } + }, + Array: _zeros, + Matrix: function Matrix(size) { + var format = size.storage(); + return _zeros(size.valueOf(), format); + }, + 'Array | Matrix, string': function ArrayMatrixString(size, format) { + return _zeros(size.valueOf(), format); + } + }); + /** + * Create an Array or Matrix with zeros + * @param {Array} size + * @param {string} [format='default'] + * @return {Array | Matrix} + * @private + */ + + function _zeros(size, format) { + var hasBigNumbers = _normalize(size); + + var defaultValue = hasBigNumbers ? new BigNumber(0) : 0; + + _validate(size); + + if (format) { + // return a matrix + var m = matrix(format); + + if (size.length > 0) { + return m.resize(size, defaultValue); + } + + return m; + } else { + // return an Array + var arr = []; + + if (size.length > 0) { + return Object(utils_array["o" /* resize */])(arr, size, defaultValue); + } + + return arr; + } + } // replace BigNumbers with numbers, returns true if size contained BigNumbers + + + function _normalize(size) { + var hasBigNumbers = false; + size.forEach(function (value, index, arr) { + if (Object(is["e" /* isBigNumber */])(value)) { + hasBigNumbers = true; + arr[index] = value.toNumber(); + } + }); + return hasBigNumbers; + } // validate arguments + + + function _validate(size) { + size.forEach(function (value) { + if (typeof value !== 'number' || !Object(utils_number["i" /* isInteger */])(value) || value < 0) { + throw new Error('Parameters in function zeros must be positive integers'); + } + }); + } +}); // TODO: zeros contains almost the same code as ones. Reuse this? +// CONCATENATED MODULE: ./src/function/special/erf.js + + + +var erf_name = 'erf'; +var erf_dependencies = ['typed']; +var createErf = /* #__PURE__ */Object(factory["a" /* factory */])(erf_name, erf_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the erf function of a value using a rational Chebyshev + * approximations for different intervals of x. + * + * This is a translation of W. J. Cody's Fortran implementation from 1987 + * ( https://www.netlib.org/specfun/erf ). See the AMS publication + * "Rational Chebyshev Approximations for the Error Function" by W. J. Cody + * for an explanation of this process. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.erf(x) + * + * Examples: + * + * math.erf(0.2) // returns 0.22270258921047847 + * math.erf(-0.5) // returns -0.5204998778130465 + * math.erf(4) // returns 0.9999999845827421 + * + * @param {number | Array | Matrix} x A real number + * @return {number | Array | Matrix} The erf of `x` + */ + var erf = typed('name', { + number: function number(x) { + var y = Math.abs(x); + + if (y >= MAX_NUM) { + return Object(utils_number["n" /* sign */])(x); + } + + if (y <= THRESH) { + return Object(utils_number["n" /* sign */])(x) * erf1(y); + } + + if (y <= 4.0) { + return Object(utils_number["n" /* sign */])(x) * (1 - erfc2(y)); + } + + return Object(utils_number["n" /* sign */])(x) * (1 - erfc3(y)); + }, + 'Array | Matrix': function ArrayMatrix(n) { + return deepMap(n, erf); + } // TODO: For complex numbers, use the approximation for the Faddeeva function + // from "More Efficient Computation of the Complex Error Function" (AMS) + + }); + /** + * Approximates the error function erf() for x <= 0.46875 using this function: + * n + * erf(x) = x * sum (p_j * x^(2j)) / (q_j * x^(2j)) + * j=0 + */ + + function erf1(y) { + var ysq = y * y; + var xnum = erf_P[0][4] * ysq; + var xden = ysq; + var i; + + for (i = 0; i < 3; i += 1) { + xnum = (xnum + erf_P[0][i]) * ysq; + xden = (xden + Q[0][i]) * ysq; + } + + return y * (xnum + erf_P[0][3]) / (xden + Q[0][3]); + } + /** + * Approximates the complement of the error function erfc() for + * 0.46875 <= x <= 4.0 using this function: + * n + * erfc(x) = e^(-x^2) * sum (p_j * x^j) / (q_j * x^j) + * j=0 + */ + + + function erfc2(y) { + var xnum = erf_P[1][8] * y; + var xden = y; + var i; + + for (i = 0; i < 7; i += 1) { + xnum = (xnum + erf_P[1][i]) * y; + xden = (xden + Q[1][i]) * y; + } + + var result = (xnum + erf_P[1][7]) / (xden + Q[1][7]); + var ysq = parseInt(y * 16) / 16; + var del = (y - ysq) * (y + ysq); + return Math.exp(-ysq * ysq) * Math.exp(-del) * result; + } + /** + * Approximates the complement of the error function erfc() for x > 4.0 using + * this function: + * + * erfc(x) = (e^(-x^2) / x) * [ 1/sqrt(pi) + + * n + * 1/(x^2) * sum (p_j * x^(-2j)) / (q_j * x^(-2j)) ] + * j=0 + */ + + + function erfc3(y) { + var ysq = 1 / (y * y); + var xnum = erf_P[2][5] * ysq; + var xden = ysq; + var i; + + for (i = 0; i < 4; i += 1) { + xnum = (xnum + erf_P[2][i]) * ysq; + xden = (xden + Q[2][i]) * ysq; + } + + var result = ysq * (xnum + erf_P[2][4]) / (xden + Q[2][4]); + result = (SQRPI - result) / y; + ysq = parseInt(y * 16) / 16; + var del = (y - ysq) * (y + ysq); + return Math.exp(-ysq * ysq) * Math.exp(-del) * result; + } + + return erf; +}); +/** + * Upper bound for the first approximation interval, 0 <= x <= THRESH + * @constant + */ + +var THRESH = 0.46875; +/** + * Constant used by W. J. Cody's Fortran77 implementation to denote sqrt(pi) + * @constant + */ + +var SQRPI = 5.6418958354775628695e-1; +/** + * Coefficients for each term of the numerator sum (p_j) for each approximation + * interval (see W. J. Cody's paper for more details) + * @constant + */ + +var erf_P = [[3.16112374387056560e00, 1.13864154151050156e02, 3.77485237685302021e02, 3.20937758913846947e03, 1.85777706184603153e-1], [5.64188496988670089e-1, 8.88314979438837594e00, 6.61191906371416295e01, 2.98635138197400131e02, 8.81952221241769090e02, 1.71204761263407058e03, 2.05107837782607147e03, 1.23033935479799725e03, 2.15311535474403846e-8], [3.05326634961232344e-1, 3.60344899949804439e-1, 1.25781726111229246e-1, 1.60837851487422766e-2, 6.58749161529837803e-4, 1.63153871373020978e-2]]; +/** + * Coefficients for each term of the denominator sum (q_j) for each approximation + * interval (see W. J. Cody's paper for more details) + * @constant + */ + +var Q = [[2.36012909523441209e01, 2.44024637934444173e02, 1.28261652607737228e03, 2.84423683343917062e03], [1.57449261107098347e01, 1.17693950891312499e02, 5.37181101862009858e02, 1.62138957456669019e03, 3.29079923573345963e03, 4.36261909014324716e03, 3.43936767414372164e03, 1.23033935480374942e03], [2.56852019228982242e00, 1.87295284992346047e00, 5.27905102951428412e-1, 6.05183413124413191e-2, 2.33520497626869185e-3]]; +/** + * Maximum/minimum safe numbers to input to erf() (in ES6+, this number is + * Number.[MAX|MIN]_SAFE_INTEGER). erf() for all numbers beyond this limit will + * return 1 + */ + +var MAX_NUM = Math.pow(2, 53); +// CONCATENATED MODULE: ./src/function/statistics/mode.js + + +var mode_name = 'mode'; +var mode_dependencies = ['typed', 'isNaN', 'isNumeric']; +var createMode = /* #__PURE__ */Object(factory["a" /* factory */])(mode_name, mode_dependencies, function (_ref) { + var typed = _ref.typed, + isNaN = _ref.isNaN, + isNumeric = _ref.isNumeric; + + /** + * Computes the mode of a set of numbers or a list with values(numbers or characters). + * If there are more than one modes, it returns a list of those values. + * + * Syntax: + * + * math.mode(a, b, c, ...) + * math.mode(A) + * + * Examples: + * + * math.mode(2, 1, 4, 3, 1) // returns [1] + * math.mode([1, 2.7, 3.2, 4, 2.7]) // returns [2.7] + * math.mode(1, 4, 6, 1, 6) // returns [1, 6] + * math.mode('a','a','b','c') // returns ["a"] + * math.mode(1, 1.5, 'abc') // returns [1, 1.5, "abc"] + * + * See also: + * + * median, + * mean + * + * @param {... *} args A single matrix + * @return {*} The mode of all values + */ + return typed(mode_name, { + 'Array | Matrix': _mode, + '...': function _(args) { + return _mode(args); + } + }); + /** + * Calculates the mode in an 1-dimensional array + * @param {Array} values + * @return {Array} mode + * @private + */ + + function _mode(values) { + values = Object(utils_array["e" /* flatten */])(values.valueOf()); + var num = values.length; + + if (num === 0) { + throw new Error('Cannot calculate mode of an empty array'); + } + + var count = {}; + var mode = []; + var max = 0; + + for (var i = 0; i < values.length; i++) { + var value = values[i]; + + if (isNumeric(value) && isNaN(value)) { + throw new Error('Cannot calculate mode of an array containing NaN values'); + } + + if (!(value in count)) { + count[value] = 0; + } + + count[value]++; + + if (count[value] === max) { + mode.push(value); + } else if (count[value] > max) { + max = count[value]; + mode = [value]; + } + } + + return mode; + } +}); +// CONCATENATED MODULE: ./src/function/statistics/utils/improveErrorMessage.js + +/** + * Improve error messages for statistics functions. Errors are typically + * thrown in an internally used function like larger, causing the error + * not to mention the function (like max) which is actually used by the user. + * + * @param {Error} err + * @param {String} fnName + * @param {*} [value] + * @return {Error} + */ + +function improveErrorMessage(err, fnName, value) { + // TODO: add information with the index (also needs transform in expression parser) + var details; + + if (String(err).indexOf('Unexpected type') !== -1) { + details = arguments.length > 2 ? ' (type: ' + Object(is["M" /* typeOf */])(value) + ', value: ' + JSON.stringify(value) + ')' : ' (type: ' + err.data.actual + ')'; + return new TypeError('Cannot calculate ' + fnName + ', unexpected type of argument' + details); + } + + if (String(err).indexOf('complex numbers') !== -1) { + details = arguments.length > 2 ? ' (type: ' + Object(is["M" /* typeOf */])(value) + ', value: ' + JSON.stringify(value) + ')' : ''; + return new TypeError('Cannot calculate ' + fnName + ', no ordering relation is defined for complex numbers' + details); + } + + return err; +} +// CONCATENATED MODULE: ./src/function/statistics/prod.js + + + +var prod_name = 'prod'; +var prod_dependencies = ['typed', 'multiply']; +var createProd = /* #__PURE__ */Object(factory["a" /* factory */])(prod_name, prod_dependencies, function (_ref) { + var typed = _ref.typed, + multiply = _ref.multiply; + + /** + * Compute the product of a matrix or a list with values. + * In case of a (multi dimensional) array or matrix, the sum of all + * elements will be calculated. + * + * Syntax: + * + * math.prod(a, b, c, ...) + * math.prod(A) + * + * Examples: + * + * math.multiply(2, 3) // returns 6 + * math.prod(2, 3) // returns 6 + * math.prod(2, 3, 4) // returns 24 + * math.prod([2, 3, 4]) // returns 24 + * math.prod([[2, 5], [4, 3]]) // returns 120 + * + * See also: + * + * mean, median, min, max, sum, std, variance + * + * @param {... *} args A single matrix or or multiple scalar values + * @return {*} The product of all values + */ + return typed(prod_name, { + // prod([a, b, c, d, ...]) + 'Array | Matrix': _prod, + // prod([a, b, c, d, ...], dim) + 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) { + // TODO: implement prod(A, dim) + throw new Error('prod(A, dim) is not yet supported'); // return reduce(arguments[0], arguments[1], math.prod) + }, + // prod(a, b, c, d, ...) + '...': function _(args) { + return _prod(args); + } + }); + /** + * Recursively calculate the product of an n-dimensional array + * @param {Array} array + * @return {number} prod + * @private + */ + + function _prod(array) { + var prod; + deepForEach(array, function (value) { + try { + prod = prod === undefined ? value : multiply(prod, value); + } catch (err) { + throw improveErrorMessage(err, 'prod', value); + } + }); + + if (prod === undefined) { + throw new Error('Cannot calculate prod of an empty array'); + } + + return prod; + } +}); +// CONCATENATED MODULE: ./src/function/string/format.js + + +var format_name = 'format'; +var format_dependencies = ['typed']; +var createFormat = /* #__PURE__ */Object(factory["a" /* factory */])(format_name, format_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Format a value of any type into a string. + * + * Syntax: + * + * math.format(value) + * math.format(value, options) + * math.format(value, precision) + * math.format(value, callback) + * + * Where: + * + * - `value: *` + * The value to be formatted + * - `options: Object` + * An object with formatting options. Available options: + * - `notation: string` + * Number notation. Choose from: + * - 'fixed' + * Always use regular number notation. + * For example '123.40' and '14000000' + * - 'exponential' + * Always use exponential notation. + * For example '1.234e+2' and '1.4e+7' + * - 'engineering' + * Always use engineering notation: always have exponential notation, + * and select the exponent to be a multiple of 3. + * For example '123.4e+0' and '14.0e+6' + * - 'auto' (default) + * Regular number notation for numbers having an absolute value between + * `lower` and `upper` bounds, and uses exponential notation elsewhere. + * Lower bound is included, upper bound is excluded. + * For example '123.4' and '1.4e7'. + * - `precision: number` + * A number between 0 and 16 to round the digits of the number. In case + * of notations 'exponential', 'engineering', and 'auto', `precision` + * defines the total number of significant digits returned. + * In case of notation 'fixed', `precision` defines the number of + * significant digits after the decimal point. + * `precision` is undefined by default. + * - `lowerExp: number` + * Exponent determining the lower boundary for formatting a value with + * an exponent when `notation='auto`. Default value is `-3`. + * - `upperExp: number` + * Exponent determining the upper boundary for formatting a value with + * an exponent when `notation='auto`. Default value is `5`. + * - `fraction: string`. Available values: 'ratio' (default) or 'decimal'. + * For example `format(fraction(1, 3))` will output '1/3' when 'ratio' is + * configured, and will output `0.(3)` when 'decimal' is configured. + * - `callback: function` + * A custom formatting function, invoked for all numeric elements in `value`, + * for example all elements of a matrix, or the real and imaginary + * parts of a complex number. This callback can be used to override the + * built-in numeric notation with any type of formatting. Function `callback` + * is called with `value` as parameter and must return a string. + * + * When `value` is an Object: + * + * - When the object contains a property `format` being a function, this function + * is invoked as `value.format(options)` and the result is returned. + * - When the object has its own `toString` method, this method is invoked + * and the result is returned. + * - In other cases the function will loop over all object properties and + * return JSON object notation like '{"a": 2, "b": 3}'. + * + * When value is a function: + * + * - When the function has a property `syntax`, it returns this + * syntax description. + * - In other cases, a string `'function'` is returned. + * + * Examples: + * + * math.format(6.4) // returns '6.4' + * math.format(1240000) // returns '1.24e6' + * math.format(1/3) // returns '0.3333333333333333' + * math.format(1/3, 3) // returns '0.333' + * math.format(21385, 2) // returns '21000' + * math.format(12e8, {notation: 'fixed'}) // returns '1200000000' + * math.format(2.3, {notation: 'fixed', precision: 4}) // returns '2.3000' + * math.format(52.8, {notation: 'exponential'}) // returns '5.28e+1' + * math.format(12400,{notation: 'engineering'}) // returns '12.400e+3' + * math.format(2000, {lowerExp: -2, upperExp: 2}) // returns '2e+3' + * + * function formatCurrency(value) { + * // return currency notation with two digits: + * return '$' + value.toFixed(2) + * + * // you could also use math.format inside the callback: + * // return '$' + math.format(value, {notation: 'fixed', precision: 2}) + * } + * math.format([2.1, 3, 0.016], formatCurrency} // returns '[$2.10, $3.00, $0.02]' + * + * See also: + * + * print + * + * @param {*} value Value to be stringified + * @param {Object | Function | number} [options] Formatting options + * @return {string} The formatted value + */ + return typed(format_name, { + any: utils_string["d" /* format */], + 'any, Object | function | number': utils_string["d" /* format */] + }); +}); +// CONCATENATED MODULE: ./src/function/string/print.js + + + +var print_name = 'print'; +var print_dependencies = ['typed']; +var createPrint = /* #__PURE__ */Object(factory["a" /* factory */])(print_name, print_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Interpolate values into a string template. + * + * Syntax: + * + * math.print(template, values) + * math.print(template, values, precision) + * math.print(template, values, options) + * + * Example usage: + * + * // the following outputs: 'Lucy is 5 years old' + * math.print('Lucy is $age years old', {age: 5}) + * + * // the following outputs: 'The value of pi is 3.141592654' + * math.print('The value of pi is $pi', {pi: math.pi}, 10) + * + * // the following outputs: 'hello Mary! The date is 2013-03-23' + * math.print('Hello $user.name! The date is $date', { + * user: { + * name: 'Mary', + * }, + * date: new Date(2013, 2, 23).toISOString().substring(0, 10) + * }) + * + * // the following outputs: 'My favorite fruits are apples and bananas !' + * math.print('My favorite fruits are $0 and $1 !', [ + * 'apples', + * 'bananas' + * ]) + * + * See also: + * + * format + * + * @param {string} template A string containing variable placeholders. + * @param {Object | Array | Matrix} values An object or array containing variables + * which will be filled in in the template. + * @param {number | Object} [options] Formatting options, + * or the number of digits to format numbers. + * See function math.format for a description + * of all options. + * @return {string} Interpolated string + */ + return typed(print_name, { + // note: Matrix will be converted automatically to an Array + 'string, Object | Array': _print, + 'string, Object | Array, number | Object': _print + }); +}); +/** + * Interpolate values into a string template. + * @param {string} template + * @param {Object} values + * @param {number | Object} [options] + * @returns {string} Interpolated string + * @private + */ + +function _print(template, values, options) { + return template.replace(/\$([\w.]+)/g, function (original, key) { + var keys = key.split('.'); + var value = values[keys.shift()]; + + while (keys.length && value !== undefined) { + var k = keys.shift(); + value = k ? value[k] : value + '.'; + } + + if (value !== undefined) { + if (!Object(is["I" /* isString */])(value)) { + return Object(utils_string["d" /* format */])(value, options); + } else { + return value; + } + } + + return original; + }); +} +// CONCATENATED MODULE: ./src/function/unit/to.js + + + +var to_name = 'to'; +var to_dependencies = ['typed', 'matrix']; +var createTo = /* #__PURE__ */Object(factory["a" /* factory */])(to_name, to_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Change the unit of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.to(x, unit) + * + * Examples: + * + * math.to(math.unit('2 inch'), 'cm') // returns Unit 5.08 cm + * math.to(math.unit('2 inch'), math.unit(null, 'cm')) // returns Unit 5.08 cm + * math.to(math.unit(16, 'bytes'), 'bits') // returns Unit 128 bits + * + * See also: + * + * unit + * + * @param {Unit | Array | Matrix} x The unit to be converted. + * @param {Unit | Array | Matrix} unit New unit. Can be a string like "cm" + * or a unit without value. + * @return {Unit | Array | Matrix} value with changed, fixed unit. + */ + + var to = typed(to_name, { + 'Unit, Unit | string': function UnitUnitString(x, unit) { + return x.to(unit); + }, + 'Matrix, Matrix': function MatrixMatrix(x, y) { + // SparseMatrix does not support Units + return algorithm13(x, y, to); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return to(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return to(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return to(x, matrix(y)); + }, + 'Matrix, any': function MatrixAny(x, y) { + // SparseMatrix does not support Units + return algorithm14(x, y, to, false); + }, + 'any, Matrix': function anyMatrix(x, y) { + // SparseMatrix does not support Units + return algorithm14(y, x, to, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, to, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, to, true).valueOf(); + } + }); + return to; +}); +// CONCATENATED MODULE: ./src/function/utils/isPrime.js + + +var isPrime_name = 'isPrime'; +var isPrime_dependencies = ['typed']; +var createIsPrime = /* #__PURE__ */Object(factory["a" /* factory */])(isPrime_name, isPrime_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Test whether a value is prime: has no divisors other than itself and one. + * The function supports type `number`, `bignumber`. + * + * The function is evaluated element-wise in case of Array or Matrix input. + * + * Syntax: + * + * math.isPrime(x) + * + * Examples: + * + * math.isPrime(3) // returns true + * math.isPrime(-2) // returns false + * math.isPrime(0) // returns false + * math.isPrime(-0) // returns false + * math.isPrime(0.5) // returns false + * math.isPrime('2') // returns true + * math.isPrime([2, 17, 100]) // returns [true, true, false] + * + * See also: + * + * isNumeric, isZero, isNegative, isInteger + * + * @param {number | BigNumber | Array | Matrix} x Value to be tested + * @return {boolean} Returns true when `x` is larger than zero. + * Throws an error in case of an unknown data type. + */ + var isPrime = typed(isPrime_name, { + number: function number(x) { + if (x * 0 !== 0) { + return false; + } + + if (x <= 3) { + return x > 1; + } + + if (x % 2 === 0 || x % 3 === 0) { + return false; + } + + for (var i = 5; i * i <= x; i += 6) { + if (x % i === 0 || x % (i + 2) === 0) { + return false; + } + } + + return true; + }, + BigNumber: function BigNumber(n) { + if (n.toNumber() * 0 !== 0) { + return false; + } + + if (n.lte(3)) return n.gt(1); + if (n.mod(2).eq(0) || n.mod(3).eq(0)) return false; + + for (var i = 5; n.gte(i * i); i += 6) { + if (n.mod(i).eq(0) || n.mod(i + 2).eq(0)) { + return false; + } + } + + return true; + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, isPrime); + } + }); + return isPrime; +}); +// CONCATENATED MODULE: ./src/function/utils/numeric.js + + + +var numeric_name = 'numeric'; +var numeric_dependencies = ['number', '?bignumber', '?fraction']; +var createNumeric = /* #__PURE__ */Object(factory["a" /* factory */])(numeric_name, numeric_dependencies, function (_ref) { + var _number = _ref.number, + bignumber = _ref.bignumber, + fraction = _ref.fraction; + var validInputTypes = { + string: true, + number: true, + BigNumber: true, + Fraction: true + }; // Load the conversion functions for each output type + + var validOutputTypes = { + number: function number(x) { + return _number(x); + }, + BigNumber: bignumber ? function (x) { + return bignumber(x); + } : noBignumber, + Fraction: fraction ? function (x) { + return fraction(x); + } : noFraction + }; + /** + * Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction. + * + * Syntax: + * + * math.numeric(x) + * + * Examples: + * + * math.numeric('4') // returns number 4 + * math.numeric('4', 'number') // returns number 4 + * math.numeric('4', 'BigNumber') // returns BigNumber 4 + * math.numeric('4', 'Fraction') // returns Fraction 4 + * math.numeric(4, 'Fraction') // returns Fraction 4 + * math.numeric(math.fraction(2, 5), 'number') // returns number 0.4 + * + * See also: + * + * number, fraction, bignumber, string, format + * + * @param {string | number | BigNumber | Fraction } value + * A numeric value or a string containing a numeric value + * @param {string} outputType + * Desired numeric output type. + * Available values: 'number', 'BigNumber', or 'Fraction' + * @return {number | BigNumber | Fraction} + * Returns an instance of the numeric in the requested type + */ + + return function numeric(value, outputType) { + var inputType = Object(is["M" /* typeOf */])(value); + + if (!(inputType in validInputTypes)) { + throw new TypeError('Cannot convert ' + value + ' of type "' + inputType + '"; valid input types are ' + Object.keys(validInputTypes).join(', ')); + } + + if (!(outputType in validOutputTypes)) { + throw new TypeError('Cannot convert ' + value + ' to type "' + outputType + '"; valid output types are ' + Object.keys(validOutputTypes).join(', ')); + } + + if (outputType === inputType) { + return value; + } else { + return validOutputTypes[outputType](value); + } + }; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/divideScalar.js + + +var divideScalar_name = 'divideScalar'; +var divideScalar_dependencies = ['typed', 'numeric']; +var createDivideScalar = /* #__PURE__ */Object(factory["a" /* factory */])(divideScalar_name, divideScalar_dependencies, function (_ref) { + var typed = _ref.typed, + numeric = _ref.numeric; + + /** + * Divide two scalar values, `x / y`. + * This function is meant for internal use: it is used by the public functions + * `divide` and `inv`. + * + * This function does not support collections (Array or Matrix). + * + * @param {number | BigNumber | Fraction | Complex | Unit} x Numerator + * @param {number | BigNumber | Fraction | Complex} y Denominator + * @return {number | BigNumber | Fraction | Complex | Unit} Quotient, `x / y` + * @private + */ + var divideScalar = typed(divideScalar_name, { + 'number, number': function numberNumber(x, y) { + return x / y; + }, + 'Complex, Complex': function ComplexComplex(x, y) { + return x.div(y); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.div(y); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.div(y); + }, + 'Unit, number | Fraction | BigNumber': function UnitNumberFractionBigNumber(x, y) { + var res = x.clone(); // TODO: move the divide function to Unit.js, it uses internals of Unit + + var one = numeric(1, Object(is["M" /* typeOf */])(y)); + res.value = divideScalar(res.value === null ? res._normalize(one) : res.value, y); + return res; + }, + 'number | Fraction | BigNumber, Unit': function numberFractionBigNumberUnit(x, y) { + var res = y.clone(); + res = res.pow(-1); // TODO: move the divide function to Unit.js, it uses internals of Unit + + var one = numeric(1, Object(is["M" /* typeOf */])(x)); + res.value = divideScalar(x, y.value === null ? y._normalize(one) : y.value); + return res; + }, + 'Unit, Unit': function UnitUnit(x, y) { + return x.divide(y); + } + }); + return divideScalar; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/pow.js + + + + +var pow_name = 'pow'; +var pow_dependencies = ['typed', 'config', 'identity', 'multiply', 'matrix', 'fraction', 'number', 'Complex']; +var createPow = /* #__PURE__ */Object(factory["a" /* factory */])(pow_name, pow_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + identity = _ref.identity, + multiply = _ref.multiply, + matrix = _ref.matrix, + number = _ref.number, + fraction = _ref.fraction, + Complex = _ref.Complex; + + /** + * Calculates the power of x to y, `x ^ y`. + * Matrix exponentiation is supported for square matrices `x`, and positive + * integer exponents `y`. + * + * For cubic roots of negative numbers, the function returns the principal + * root by default. In order to let the function return the real root, + * math.js can be configured with `math.config({predictable: true})`. + * To retrieve all cubic roots of a value, use `math.cbrt(x, true)`. + * + * Syntax: + * + * math.pow(x, y) + * + * Examples: + * + * math.pow(2, 3) // returns number 8 + * + * const a = math.complex(2, 3) + * math.pow(a, 2) // returns Complex -5 + 12i + * + * const b = [[1, 2], [4, 3]] + * math.pow(b, 2) // returns Array [[9, 8], [16, 17]] + * + * See also: + * + * multiply, sqrt, cbrt, nthRoot + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x The base + * @param {number | BigNumber | Complex} y The exponent + * @return {number | BigNumber | Complex | Array | Matrix} The value of `x` to the power `y` + */ + return typed(pow_name, { + 'number, number': _pow, + 'Complex, Complex': function ComplexComplex(x, y) { + return x.pow(y); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + if (y.isInteger() || x >= 0 || config.predictable) { + return x.pow(y); + } else { + return new Complex(x.toNumber(), 0).pow(y.toNumber(), 0); + } + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + if (y.d !== 1) { + if (config.predictable) { + throw new Error('Function pow does not support non-integer exponents for fractions.'); + } else { + return _pow(x.valueOf(), y.valueOf()); + } + } else { + return x.pow(y); + } + }, + 'Array, number': _powArray, + 'Array, BigNumber': function ArrayBigNumber(x, y) { + return _powArray(x, y.toNumber()); + }, + 'Matrix, number': _powMatrix, + 'Matrix, BigNumber': function MatrixBigNumber(x, y) { + return _powMatrix(x, y.toNumber()); + }, + 'Unit, number | BigNumber': function UnitNumberBigNumber(x, y) { + return x.pow(y); + } + }); + /** + * Calculates the power of x to y, x^y, for two numbers. + * @param {number} x + * @param {number} y + * @return {number | Complex} res + * @private + */ + + function _pow(x, y) { + // Alternatively could define a 'realmode' config option or something, but + // 'predictable' will work for now + if (config.predictable && !Object(utils_number["i" /* isInteger */])(y) && x < 0) { + // Check to see if y can be represented as a fraction + try { + var yFrac = fraction(y); + var yNum = number(yFrac); + + if (y === yNum || Math.abs((y - yNum) / y) < 1e-14) { + if (yFrac.d % 2 === 1) { + return (yFrac.n % 2 === 0 ? 1 : -1) * Math.pow(-x, y); + } + } + } catch (ex) {} // fraction() throws an error if y is Infinity, etc. + // Unable to express y as a fraction, so continue on + + } // **for predictable mode** x^Infinity === NaN if x < -1 + // N.B. this behavour is different from `Math.pow` which gives + // (-2)^Infinity === Infinity + + + if (config.predictable && (x < -1 && y === Infinity || x > -1 && x < 0 && y === -Infinity)) { + return NaN; + } + + if (Object(utils_number["i" /* isInteger */])(y) || x >= 0 || config.predictable) { + return powNumber(x, y); + } else { + // TODO: the following infinity checks are duplicated from powNumber. Deduplicate this somehow + // x^Infinity === 0 if -1 < x < 1 + // A real number 0 is returned instead of complex(0) + if (x * x < 1 && y === Infinity || x * x > 1 && y === -Infinity) { + return 0; + } + + return new Complex(x, 0).pow(y, 0); + } + } + /** + * Calculate the power of a 2d array + * @param {Array} x must be a 2 dimensional, square matrix + * @param {number} y a positive, integer value + * @returns {Array} + * @private + */ + + + function _powArray(x, y) { + if (!Object(utils_number["i" /* isInteger */])(y) || y < 0) { + throw new TypeError('For A^b, b must be a positive integer (value is ' + y + ')'); + } // verify that A is a 2 dimensional square matrix + + + var s = Object(utils_array["a" /* arraySize */])(x); + + if (s.length !== 2) { + throw new Error('For A^b, A must be 2 dimensional (A has ' + s.length + ' dimensions)'); + } + + if (s[0] !== s[1]) { + throw new Error('For A^b, A must be square (size is ' + s[0] + 'x' + s[1] + ')'); + } + + var res = identity(s[0]).valueOf(); + var px = x; + + while (y >= 1) { + if ((y & 1) === 1) { + res = multiply(px, res); + } + + y >>= 1; + px = multiply(px, px); + } + + return res; + } + /** + * Calculate the power of a 2d matrix + * @param {Matrix} x must be a 2 dimensional, square matrix + * @param {number} y a positive, integer value + * @returns {Matrix} + * @private + */ + + + function _powMatrix(x, y) { + return matrix(_powArray(x.valueOf(), y)); + } +}); +// CONCATENATED MODULE: ./src/function/arithmetic/round.js +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + + + + + + + +var NO_INT = 'Number of decimals in function round must be an integer'; +var round_name = 'round'; +var round_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'BigNumber', 'DenseMatrix']; +var createRound = /* #__PURE__ */Object(factory["a" /* factory */])(round_name, round_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + zeros = _ref.zeros, + BigNumber = _ref.BigNumber, + DenseMatrix = _ref.DenseMatrix; + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Round a value towards the nearest integer. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.round(x) + * math.round(x, n) + * + * Examples: + * + * math.round(3.2) // returns number 3 + * math.round(3.8) // returns number 4 + * math.round(-4.2) // returns number -4 + * math.round(-4.7) // returns number -5 + * math.round(math.pi, 3) // returns number 3.142 + * math.round(123.45678, 2) // returns number 123.46 + * + * const c = math.complex(3.2, -2.7) + * math.round(c) // returns Complex 3 - 3i + * + * math.round([3.2, 3.8, -4.7]) // returns Array [3, 4, -5] + * + * See also: + * + * ceil, fix, floor + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded + * @param {number | BigNumber | Array} [n=0] Number of decimals + * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value + */ + + var round = typed(round_name, _objectSpread(_objectSpread({}, roundNumberSignatures), {}, { + Complex: function Complex(x) { + return x.round(); + }, + 'Complex, number': function ComplexNumber(x, n) { + if (n % 1) { + throw new TypeError(NO_INT); + } + + return x.round(n); + }, + 'Complex, BigNumber': function ComplexBigNumber(x, n) { + if (!n.isInteger()) { + throw new TypeError(NO_INT); + } + + var _n = n.toNumber(); + + return x.round(_n); + }, + 'number, BigNumber': function numberBigNumber(x, n) { + if (!n.isInteger()) { + throw new TypeError(NO_INT); + } + + return new BigNumber(x).toDecimalPlaces(n.toNumber()); + }, + BigNumber: function BigNumber(x) { + return x.toDecimalPlaces(0); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, n) { + if (!n.isInteger()) { + throw new TypeError(NO_INT); + } + + return x.toDecimalPlaces(n.toNumber()); + }, + Fraction: function Fraction(x) { + return x.round(); + }, + 'Fraction, number': function FractionNumber(x, n) { + if (n % 1) { + throw new TypeError(NO_INT); + } + + return x.round(n); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since round(0) = 0 + return deepMap(x, round, true); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + return algorithm11(x, y, round, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + return algorithm14(x, y, round, false); + }, + 'number | Complex | BigNumber, SparseMatrix': function numberComplexBigNumberSparseMatrix(x, y) { + // check scalar is zero + if (equalScalar(x, 0)) { + // do not execute algorithm, result will be a zero matrix + return zeros(y.size(), y.storage()); + } + + return algorithm12(y, x, round, true); + }, + 'number | Complex | BigNumber, DenseMatrix': function numberComplexBigNumberDenseMatrix(x, y) { + // check scalar is zero + if (equalScalar(x, 0)) { + // do not execute algorithm, result will be a zero matrix + return zeros(y.size(), y.storage()); + } + + return algorithm14(y, x, round, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, round, false).valueOf(); + }, + 'number | Complex | BigNumber, Array': function numberComplexBigNumberArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, round, true).valueOf(); + } + })); + return round; +}); +var roundNumberSignatures = { + number: roundNumber, + 'number, number': function numberNumber(x, n) { + if (!Object(utils_number["i" /* isInteger */])(n)) { + throw new TypeError(NO_INT); + } + + if (n < 0 || n > 15) { + throw new Error('Number of decimals in function round must be in te range of 0-15'); + } + + return roundNumber(x, n); + } +}; +var createRoundNumber = /* #__PURE__ */Object(factory["a" /* factory */])(round_name, ['typed'], function (_ref2) { + var typed = _ref2.typed; + return typed(round_name, roundNumberSignatures); +}); +// CONCATENATED MODULE: ./src/function/arithmetic/log.js + + + +var log_name = 'log'; +var log_dependencies = ['config', 'typed', 'divideScalar', 'Complex']; +var createLog = /* #__PURE__ */Object(factory["a" /* factory */])(log_name, log_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + divideScalar = _ref.divideScalar, + Complex = _ref.Complex; + + /** + * Calculate the logarithm of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.log(x) + * math.log(x, base) + * + * Examples: + * + * math.log(3.5) // returns 1.252762968495368 + * math.exp(math.log(2.4)) // returns 2.4 + * + * math.pow(10, 4) // returns 10000 + * math.log(10000, 10) // returns 4 + * math.log(10000) / math.log(10) // returns 4 + * + * math.log(1024, 2) // returns 10 + * math.pow(2, 10) // returns 1024 + * + * See also: + * + * exp, log2, log10, log1p + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * Value for which to calculate the logarithm. + * @param {number | BigNumber | Complex} [base=e] + * Optional base for the logarithm. If not provided, the natural + * logarithm of `x` is calculated. + * @return {number | BigNumber | Complex | Array | Matrix} + * Returns the logarithm of `x` + */ + var log = typed(log_name, { + number: function number(x) { + if (x >= 0 || config.predictable) { + return logNumber(x); + } else { + // negative value -> complex value computation + return new Complex(x, 0).log(); + } + }, + Complex: function Complex(x) { + return x.log(); + }, + BigNumber: function BigNumber(x) { + if (!x.isNegative() || config.predictable) { + return x.ln(); + } else { + // downgrade to number, return Complex valued result + return new Complex(x.toNumber(), 0).log(); + } + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, log); + }, + 'any, any': function anyAny(x, base) { + // calculate logarithm for a specified base, log(x, base) + return divideScalar(log(x), log(base)); + } + }); + return log; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/log1p.js + + + +var log1p_name = 'log1p'; +var log1p_dependencies = ['typed', 'config', 'divideScalar', 'log', 'Complex']; +var createLog1p = /* #__PURE__ */Object(factory["a" /* factory */])(log1p_name, log1p_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + divideScalar = _ref.divideScalar, + log = _ref.log, + Complex = _ref.Complex; + + /** + * Calculate the logarithm of a `value+1`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.log1p(x) + * math.log1p(x, base) + * + * Examples: + * + * math.log1p(2.5) // returns 1.252762968495368 + * math.exp(math.log1p(1.4)) // returns 2.4 + * + * math.pow(10, 4) // returns 10000 + * math.log1p(9999, 10) // returns 4 + * math.log1p(9999) / math.log(10) // returns 4 + * + * See also: + * + * exp, log, log2, log10 + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * Value for which to calculate the logarithm of `x+1`. + * @param {number | BigNumber | Complex} [base=e] + * Optional base for the logarithm. If not provided, the natural + * logarithm of `x+1` is calculated. + * @return {number | BigNumber | Complex | Array | Matrix} + * Returns the logarithm of `x+1` + */ + var log1p = typed(log1p_name, { + number: function number(x) { + if (x >= -1 || config.predictable) { + return Object(utils_number["k" /* log1p */])(x); + } else { + // negative value -> complex value computation + return _log1pComplex(new Complex(x, 0)); + } + }, + Complex: _log1pComplex, + BigNumber: function BigNumber(x) { + var y = x.plus(1); + + if (!y.isNegative() || config.predictable) { + return y.ln(); + } else { + // downgrade to number, return Complex valued result + return _log1pComplex(new Complex(x.toNumber(), 0)); + } + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, log1p); + }, + 'any, any': function anyAny(x, base) { + // calculate logarithm for a specified base, log1p(x, base) + return divideScalar(log1p(x), log(base)); + } + }); + /** + * Calculate the natural logarithm of a complex number + 1 + * @param {Complex} x + * @returns {Complex} + * @private + */ + + function _log1pComplex(x) { + var xRe1p = x.re + 1; + return new Complex(Math.log(Math.sqrt(xRe1p * xRe1p + x.im * x.im)), Math.atan2(x.im, xRe1p)); + } + + return log1p; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/nthRoots.js + +var nthRoots_name = 'nthRoots'; +var nthRoots_dependencies = ['config', 'typed', 'divideScalar', 'Complex']; +var createNthRoots = /* #__PURE__ */Object(factory["a" /* factory */])(nthRoots_name, nthRoots_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + divideScalar = _ref.divideScalar, + Complex = _ref.Complex; + + /** + * Calculate the nth roots of a value. + * An nth root of a positive real number A, + * is a positive real solution of the equation "x^root = A". + * This function returns an array of complex values. + * + * Syntax: + * + * math.nthRoots(x) + * math.nthRoots(x, root) + * + * Examples: + * + * math.nthRoots(1) + * // returns [ + * // {re: 1, im: 0}, + * // {re: -1, im: 0} + * // ] + * nthRoots(1, 3) + * // returns [ + * // { re: 1, im: 0 }, + * // { re: -0.4999999999999998, im: 0.8660254037844387 }, + * // { re: -0.5000000000000004, im: -0.8660254037844385 } + * ] + * + * See also: + * + * nthRoot, pow, sqrt + * + * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded + * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value + */ + var nthRoots = typed(nthRoots_name, { + Complex: function Complex(x) { + return _nthComplexRoots(x, 2); + }, + 'Complex, number': _nthComplexRoots + }); + /** + * Each function here returns a real multiple of i as a Complex value. + * @param {number} val + * @return {Complex} val, i*val, -val or -i*val for index 0, 1, 2, 3 + */ + // This is used to fix float artifacts for zero-valued components. + + var _calculateExactResult = [function realPos(val) { + return new Complex(val, 0); + }, function imagPos(val) { + return new Complex(0, val); + }, function realNeg(val) { + return new Complex(-val, 0); + }, function imagNeg(val) { + return new Complex(0, -val); + }]; + /** + * Calculate the nth root of a Complex Number a using De Movire's Theorem. + * @param {Complex} a + * @param {number} root + * @return {Array} array of n Complex Roots + */ + + function _nthComplexRoots(a, root) { + if (root < 0) throw new Error('Root must be greater than zero'); + if (root === 0) throw new Error('Root must be non-zero'); + if (root % 1 !== 0) throw new Error('Root must be an integer'); + if (a === 0 || a.abs() === 0) return [new Complex(0, 0)]; + var aIsNumeric = typeof a === 'number'; + var offset; // determine the offset (argument of a)/(pi/2) + + if (aIsNumeric || a.re === 0 || a.im === 0) { + if (aIsNumeric) { + offset = 2 * +(a < 0); // numeric value on the real axis + } else if (a.im === 0) { + offset = 2 * +(a.re < 0); // complex value on the real axis + } else { + offset = 2 * +(a.im < 0) + 1; // complex value on the imaginary axis + } + } + + var arg = a.arg(); + var abs = a.abs(); + var roots = []; + var r = Math.pow(abs, 1 / root); + + for (var k = 0; k < root; k++) { + var halfPiFactor = (offset + 4 * k) / root; + /** + * If (offset + 4*k)/root is an integral multiple of pi/2 + * then we can produce a more exact result. + */ + + if (halfPiFactor === Math.round(halfPiFactor)) { + roots.push(_calculateExactResult[halfPiFactor % 4](r)); + continue; + } + + roots.push(new Complex({ + r: r, + phi: (arg + 2 * Math.PI * k) / root + })); + } + + return roots; + } + + return nthRoots; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/dotPow.js + + + + + + + +var dotPow_name = 'dotPow'; +var dotPow_dependencies = ['typed', 'equalScalar', 'matrix', 'pow', 'DenseMatrix']; +var createDotPow = /* #__PURE__ */Object(factory["a" /* factory */])(dotPow_name, dotPow_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar, + matrix = _ref.matrix, + pow = _ref.pow, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Calculates the power of x to y element wise. + * + * Syntax: + * + * math.dotPow(x, y) + * + * Examples: + * + * math.dotPow(2, 3) // returns number 8 + * + * const a = [[1, 2], [4, 3]] + * math.dotPow(a, 2) // returns Array [[1, 4], [16, 9]] + * math.pow(a, 2) // returns Array [[9, 8], [16, 17]] + * + * See also: + * + * pow, sqrt, multiply + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x The base + * @param {number | BigNumber | Complex | Unit | Array | Matrix} y The exponent + * @return {number | BigNumber | Complex | Unit | Array | Matrix} The value of `x` to the power `y` + */ + + var dotPow = typed(dotPow_name, { + 'any, any': pow, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, pow, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, pow, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, pow, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, pow); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return dotPow(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return dotPow(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return dotPow(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, dotPow, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, dotPow, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, dotPow, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, dotPow, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, dotPow, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, dotPow, true).valueOf(); + } + }); + return dotPow; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/dotDivide.js + + + + + + + + +var dotDivide_name = 'dotDivide'; +var dotDivide_dependencies = ['typed', 'matrix', 'equalScalar', 'divideScalar', 'DenseMatrix']; +var createDotDivide = /* #__PURE__ */Object(factory["a" /* factory */])(dotDivide_name, dotDivide_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + divideScalar = _ref.divideScalar, + DenseMatrix = _ref.DenseMatrix; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Divide two matrices element wise. The function accepts both matrices and + * scalar values. + * + * Syntax: + * + * math.dotDivide(x, y) + * + * Examples: + * + * math.dotDivide(2, 4) // returns 0.5 + * + * a = [[9, 5], [6, 1]] + * b = [[3, 2], [5, 2]] + * + * math.dotDivide(a, b) // returns [[3, 2.5], [1.2, 0.5]] + * math.divide(a, b) // returns [[1.75, 0.75], [-1.75, 2.25]] + * + * See also: + * + * divide, multiply, dotMultiply + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Denominator + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Quotient, `x ./ y` + */ + + var dotDivide = typed(dotDivide_name, { + 'any, any': divideScalar, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, divideScalar, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, divideScalar, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, divideScalar, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, divideScalar); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return dotDivide(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return dotDivide(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return dotDivide(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, divideScalar, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, divideScalar, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, divideScalar, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, divideScalar, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, divideScalar, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, divideScalar, true).valueOf(); + } + }); + return dotDivide; +}); +// CONCATENATED MODULE: ./src/function/algebra/solver/utils/solveValidation.js + + + +function createSolveValidation(_ref) { + var DenseMatrix = _ref.DenseMatrix; + + /** + * Validates matrix and column vector b for backward/forward substitution algorithms. + * + * @param {Matrix} m An N x N matrix + * @param {Array | Matrix} b A column vector + * @param {Boolean} copy Return a copy of vector b + * + * @return {DenseMatrix} Dense column vector b + */ + return function solveValidation(m, b, copy) { + // matrix size + var size = m.size(); // validate matrix dimensions + + if (size.length !== 2) { + throw new RangeError('Matrix must be two dimensional (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } // rows & columns + + + var rows = size[0]; + var columns = size[1]; // validate rows & columns + + if (rows !== columns) { + throw new RangeError('Matrix must be square (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } // vars + + + var data, i, bdata; // check b is matrix + + if (Object(is["v" /* isMatrix */])(b)) { + // matrix size + var msize = b.size(); // vector + + if (msize.length === 1) { + // check vector length + if (msize[0] !== rows) { + throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); + } // create data array + + + data = []; // matrix data (DenseMatrix) + + bdata = b._data; // loop b data + + for (i = 0; i < rows; i++) { + // row array + data[i] = [bdata[i]]; + } // return Dense Matrix + + + return new DenseMatrix({ + data: data, + size: [rows, 1], + datatype: b._datatype + }); + } // two dimensions + + + if (msize.length === 2) { + // array must be a column vector + if (msize[0] !== rows || msize[1] !== 1) { + throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); + } // check matrix type + + + if (Object(is["n" /* isDenseMatrix */])(b)) { + // check a copy is needed + if (copy) { + // create data array + data = []; // matrix data (DenseMatrix) + + bdata = b._data; // loop b data + + for (i = 0; i < rows; i++) { + // row array + data[i] = [bdata[i][0]]; + } // return Dense Matrix + + + return new DenseMatrix({ + data: data, + size: [rows, 1], + datatype: b._datatype + }); + } // b is already a column vector + + + return b; + } // create data array + + + data = []; + + for (i = 0; i < rows; i++) { + data[i] = [0]; + } // sparse matrix arrays + + + var values = b._values; + var index = b._index; + var ptr = b._ptr; // loop values in column 0 + + for (var k1 = ptr[1], k = ptr[0]; k < k1; k++) { + // row + i = index[k]; // add to data + + data[i][0] = values[k]; + } // return Dense Matrix + + + return new DenseMatrix({ + data: data, + size: [rows, 1], + datatype: b._datatype + }); + } // throw error + + + throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); + } // check b is array + + + if (Object(is["b" /* isArray */])(b)) { + // size + var asize = Object(utils_array["a" /* arraySize */])(b); // check matrix dimensions, vector + + if (asize.length === 1) { + // check vector length + if (asize[0] !== rows) { + throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); + } // create data array + + + data = []; // loop b + + for (i = 0; i < rows; i++) { + // row array + data[i] = [b[i]]; + } // return Dense Matrix + + + return new DenseMatrix({ + data: data, + size: [rows, 1] + }); + } + + if (asize.length === 2) { + // array must be a column vector + if (asize[0] !== rows || asize[1] !== 1) { + throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); + } // create data array + + + data = []; // loop b data + + for (i = 0; i < rows; i++) { + // row array + data[i] = [b[i][0]]; + } // return Dense Matrix + + + return new DenseMatrix({ + data: data, + size: [rows, 1] + }); + } // throw error + + + throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); + } + }; +} +// CONCATENATED MODULE: ./src/function/algebra/solver/lsolve.js + + +var lsolve_name = 'lsolve'; +var lsolve_dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtract', 'equalScalar', 'DenseMatrix']; +var createLsolve = /* #__PURE__ */Object(factory["a" /* factory */])(lsolve_name, lsolve_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + divideScalar = _ref.divideScalar, + multiplyScalar = _ref.multiplyScalar, + subtract = _ref.subtract, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix; + var solveValidation = createSolveValidation({ + DenseMatrix: DenseMatrix + }); + /** + * Solves the linear equation system by forwards substitution. Matrix must be a lower triangular matrix. + * + * `L * x = b` + * + * Syntax: + * + * math.lsolve(L, b) + * + * Examples: + * + * const a = [[-2, 3], [2, 1]] + * const b = [11, 9] + * const x = lsolve(a, b) // [[-5.5], [20]] + * + * See also: + * + * lup, slu, usolve, lusolve + * + * @param {Matrix, Array} L A N x N matrix or array (L) + * @param {Matrix, Array} b A column vector with the b values + * + * @return {DenseMatrix | Array} A column vector with the linear system solution (x) + */ + + return typed(lsolve_name, { + 'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(m, b) { + // process matrix + return _sparseForwardSubstitution(m, b); + }, + 'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(m, b) { + // process matrix + return _denseForwardSubstitution(m, b); + }, + 'Array, Array | Matrix': function ArrayArrayMatrix(a, b) { + // create dense matrix from array + var m = matrix(a); // use matrix implementation + + var r = _denseForwardSubstitution(m, b); // result + + + return r.valueOf(); + } + }); + + function _denseForwardSubstitution(m, b) { + // validate matrix and vector, return copy of column vector b + b = solveValidation(m, b, true); // column vector data + + var bdata = b._data; // rows & columns + + var rows = m._size[0]; + var columns = m._size[1]; // result + + var x = []; // data + + var data = m._data; // forward solve m * x = b, loop columns + + for (var j = 0; j < columns; j++) { + // b[j] + var bj = bdata[j][0] || 0; // x[j] + + var xj = void 0; // forward substitution (outer product) avoids inner looping when bj === 0 + + if (!equalScalar(bj, 0)) { + // value @ [j, j] + var vjj = data[j][j]; // check vjj + + if (equalScalar(vjj, 0)) { + // system cannot be solved + throw new Error('Linear system cannot be solved since matrix is singular'); + } // calculate xj + + + xj = divideScalar(bj, vjj); // loop rows + + for (var i = j + 1; i < rows; i++) { + // update copy of b + bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, data[i][j]))]; + } + } else { + // zero @ j + xj = 0; + } // update x + + + x[j] = [xj]; + } // return vector + + + return new DenseMatrix({ + data: x, + size: [rows, 1] + }); + } + + function _sparseForwardSubstitution(m, b) { + // validate matrix and vector, return copy of column vector b + b = solveValidation(m, b, true); // column vector data + + var bdata = b._data; // rows & columns + + var rows = m._size[0]; + var columns = m._size[1]; // matrix arrays + + var values = m._values; + var index = m._index; + var ptr = m._ptr; // vars + + var i, k; // result + + var x = []; // forward solve m * x = b, loop columns + + for (var j = 0; j < columns; j++) { + // b[j] + var bj = bdata[j][0] || 0; // forward substitution (outer product) avoids inner looping when bj === 0 + + if (!equalScalar(bj, 0)) { + // value @ [j, j] + var vjj = 0; // lower triangular matrix values & index (column j) + + var jvalues = []; + var jindex = []; // last index in column + + var l = ptr[j + 1]; // values in column, find value @ [j, j] + + for (k = ptr[j]; k < l; k++) { + // row + i = index[k]; // check row (rows are not sorted!) + + if (i === j) { + // update vjj + vjj = values[k]; + } else if (i > j) { + // store lower triangular + jvalues.push(values[k]); + jindex.push(i); + } + } // at this point we must have a value @ [j, j] + + + if (equalScalar(vjj, 0)) { + // system cannot be solved, there is no value @ [j, j] + throw new Error('Linear system cannot be solved since matrix is singular'); + } // calculate xj + + + var xj = divideScalar(bj, vjj); // loop lower triangular + + for (k = 0, l = jindex.length; k < l; k++) { + // row + i = jindex[k]; // update copy of b + + bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, jvalues[k]))]; + } // update x + + + x[j] = [xj]; + } else { + // update x + x[j] = [0]; + } + } // return vector + + + return new DenseMatrix({ + data: x, + size: [rows, 1] + }); + } +}); +// CONCATENATED MODULE: ./src/function/algebra/solver/usolve.js + + +var usolve_name = 'usolve'; +var usolve_dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtract', 'equalScalar', 'DenseMatrix']; +var createUsolve = /* #__PURE__ */Object(factory["a" /* factory */])(usolve_name, usolve_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + divideScalar = _ref.divideScalar, + multiplyScalar = _ref.multiplyScalar, + subtract = _ref.subtract, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix; + var solveValidation = createSolveValidation({ + DenseMatrix: DenseMatrix + }); + /** + * Solves the linear equation system by backward substitution. Matrix must be an upper triangular matrix. + * + * `U * x = b` + * + * Syntax: + * + * math.usolve(U, b) + * + * Examples: + * + * const a = [[-2, 3], [2, 1]] + * const b = [11, 9] + * const x = usolve(a, b) // [[8], [9]] + * + * See also: + * + * lup, slu, usolve, lusolve + * + * @param {Matrix, Array} U A N x N matrix or array (U) + * @param {Matrix, Array} b A column vector with the b values + * + * @return {DenseMatrix | Array} A column vector with the linear system solution (x) + */ + + return typed(usolve_name, { + 'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(m, b) { + // process matrix + return _sparseBackwardSubstitution(m, b); + }, + 'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(m, b) { + // process matrix + return _denseBackwardSubstitution(m, b); + }, + 'Array, Array | Matrix': function ArrayArrayMatrix(a, b) { + // create dense matrix from array + var m = matrix(a); // use matrix implementation + + var r = _denseBackwardSubstitution(m, b); // result + + + return r.valueOf(); + } + }); + + function _denseBackwardSubstitution(m, b) { + // validate matrix and vector, return copy of column vector b + b = solveValidation(m, b, true); // column vector data + + var bdata = b._data; // rows & columns + + var rows = m._size[0]; + var columns = m._size[1]; // result + + var x = []; // arrays + + var data = m._data; // backward solve m * x = b, loop columns (backwards) + + for (var j = columns - 1; j >= 0; j--) { + // b[j] + var bj = bdata[j][0] || 0; // x[j] + + var xj = void 0; // backward substitution (outer product) avoids inner looping when bj === 0 + + if (!equalScalar(bj, 0)) { + // value @ [j, j] + var vjj = data[j][j]; // check vjj + + if (equalScalar(vjj, 0)) { + // system cannot be solved + throw new Error('Linear system cannot be solved since matrix is singular'); + } // calculate xj + + + xj = divideScalar(bj, vjj); // loop rows + + for (var i = j - 1; i >= 0; i--) { + // update copy of b + bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, data[i][j]))]; + } + } else { + // zero value @ j + xj = 0; + } // update x + + + x[j] = [xj]; + } // return column vector + + + return new DenseMatrix({ + data: x, + size: [rows, 1] + }); + } + + function _sparseBackwardSubstitution(m, b) { + // validate matrix and vector, return copy of column vector b + b = solveValidation(m, b, true); // column vector data + + var bdata = b._data; // rows & columns + + var rows = m._size[0]; + var columns = m._size[1]; // matrix arrays + + var values = m._values; + var index = m._index; + var ptr = m._ptr; // vars + + var i, k; // result + + var x = []; // backward solve m * x = b, loop columns (backwards) + + for (var j = columns - 1; j >= 0; j--) { + // b[j] + var bj = bdata[j][0] || 0; // backward substitution (outer product) avoids inner looping when bj === 0 + + if (!equalScalar(bj, 0)) { + // value @ [j, j] + var vjj = 0; // upper triangular matrix values & index (column j) + + var jvalues = []; + var jindex = []; // first & last indeces in column + + var f = ptr[j]; + var l = ptr[j + 1]; // values in column, find value @ [j, j], loop backwards + + for (k = l - 1; k >= f; k--) { + // row + i = index[k]; // check row + + if (i === j) { + // update vjj + vjj = values[k]; + } else if (i < j) { + // store upper triangular + jvalues.push(values[k]); + jindex.push(i); + } + } // at this point we must have a value @ [j, j] + + + if (equalScalar(vjj, 0)) { + // system cannot be solved, there is no value @ [j, j] + throw new Error('Linear system cannot be solved since matrix is singular'); + } // calculate xj + + + var xj = divideScalar(bj, vjj); // loop upper triangular + + for (k = 0, l = jindex.length; k < l; k++) { + // row + i = jindex[k]; // update copy of b + + bdata[i] = [subtract(bdata[i][0], multiplyScalar(xj, jvalues[k]))]; + } // update x + + + x[j] = [xj]; + } else { + // update x + x[j] = [0]; + } + } // return vector + + + return new DenseMatrix({ + data: x, + size: [rows, 1] + }); + } +}); +// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm08.js + + +var algorithm08_name = 'algorithm08'; +var algorithm08_dependencies = ['typed', 'equalScalar']; +var createAlgorithm08 = /* #__PURE__ */Object(factory["a" /* factory */])(algorithm08_name, algorithm08_dependencies, function (_ref) { + var typed = _ref.typed, + equalScalar = _ref.equalScalar; + + /** + * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij). + * Callback function invoked MAX(NNZA, NNZB) times + * + * + * ┌ f(Aij, Bij) ; A(i,j) !== 0 && B(i,j) !== 0 + * C(i,j) = ┤ A(i,j) ; A(i,j) !== 0 + * └ 0 ; otherwise + * + * + * @param {Matrix} a The SparseMatrix instance (A) + * @param {Matrix} b The SparseMatrix instance (B) + * @param {Function} callback The f(Aij,Bij) operation to invoke + * + * @return {Matrix} SparseMatrix (C) + * + * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294 + */ + return function algorithm08(a, b, callback) { + // sparse matrix arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; + var adt = a._datatype; // sparse matrix arrays + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; + var bsize = b._size; + var bdt = b._datatype; // validate dimensions + + if (asize.length !== bsize.length) { + throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length); + } // check rows & columns + + + if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { + throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')'); + } // sparse matrix cannot be a Pattern matrix + + + if (!avalues || !bvalues) { + throw new Error('Cannot perform operation on Pattern Sparse Matrices'); + } // rows & columns + + + var rows = asize[0]; + var columns = asize[1]; // datatype + + var dt; // equal signature to use + + var eq = equalScalar; // zero value + + var zero = 0; // callback signature to use + + var cf = callback; // process data types + + if (typeof adt === 'string' && adt === bdt) { + // datatype + dt = adt; // find signature that matches (dt, dt) + + eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype + + zero = typed.convert(0, dt); // callback + + cf = typed.find(callback, [dt, dt]); + } // result arrays + + + var cvalues = []; + var cindex = []; + var cptr = []; // workspace + + var x = []; // marks indicating we have a value in x for a given column + + var w = []; // vars + + var k, k0, k1, i; // loop columns + + for (var j = 0; j < columns; j++) { + // update cptr + cptr[j] = cindex.length; // columns mark + + var mark = j + 1; // loop values in a + + for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) { + // row + i = aindex[k]; // mark workspace + + w[i] = mark; // set value + + x[i] = avalues[k]; // add index + + cindex.push(i); + } // loop values in b + + + for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) { + // row + i = bindex[k]; // check value exists in workspace + + if (w[i] === mark) { + // evaluate callback + x[i] = cf(x[i], bvalues[k]); + } + } // initialize first index in j + + + k = cptr[j]; // loop index in j + + while (k < cindex.length) { + // row + i = cindex[k]; // value @ i + + var v = x[i]; // check for zero value + + if (!eq(v, zero)) { + // push value + cvalues.push(v); // increment pointer + + k++; + } else { + // remove value @ i, do not increment pointer + cindex.splice(k, 1); + } + } + } // update cptr + + + cptr[columns] = cindex.length; // return sparse matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [rows, columns], + datatype: dt + }); + }; +}); +// CONCATENATED MODULE: ./src/function/bitwise/leftShift.js + + + + + + + + + + +var leftShift_name = 'leftShift'; +var leftShift_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix']; +var createLeftShift = /* #__PURE__ */Object(factory["a" /* factory */])(leftShift_name, leftShift_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + zeros = _ref.zeros, + DenseMatrix = _ref.DenseMatrix; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm08 = createAlgorithm08({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Bitwise left logical shift of a value x by y number of bits, `x << y`. + * For matrices, the function is evaluated element wise. + * For units, the function is evaluated on the best prefix base. + * + * Syntax: + * + * math.leftShift(x, y) + * + * Examples: + * + * math.leftShift(1, 2) // returns number 4 + * + * math.leftShift([1, 2, 3], 4) // returns Array [16, 32, 64] + * + * See also: + * + * leftShift, bitNot, bitOr, bitXor, rightArithShift, rightLogShift + * + * @param {number | BigNumber | Array | Matrix} x Value to be shifted + * @param {number | BigNumber} y Amount of shifts + * @return {number | BigNumber | Array | Matrix} `x` shifted left `y` times + */ + + var leftShift = typed(leftShift_name, { + 'number, number': leftShiftNumber, + 'BigNumber, BigNumber': leftShiftBigNumber, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm08(x, y, leftShift, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, leftShift, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm01(x, y, leftShift, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, leftShift); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return leftShift(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return leftShift(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return leftShift(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + // check scalar + if (equalScalar(y, 0)) { + return x.clone(); + } + + return algorithm11(x, y, leftShift, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + // check scalar + if (equalScalar(y, 0)) { + return x.clone(); + } + + return algorithm14(x, y, leftShift, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + // check scalar + if (equalScalar(x, 0)) { + return zeros(y.size(), y.storage()); + } + + return algorithm10(y, x, leftShift, true); + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + // check scalar + if (equalScalar(x, 0)) { + return zeros(y.size(), y.storage()); + } + + return algorithm14(y, x, leftShift, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return leftShift(matrix(x), y).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + // use matrix implementation + return leftShift(x, matrix(y)).valueOf(); + } + }); + return leftShift; +}); +// CONCATENATED MODULE: ./src/function/bitwise/rightArithShift.js + + + + + + + + + + +var rightArithShift_name = 'rightArithShift'; +var rightArithShift_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix']; +var createRightArithShift = /* #__PURE__ */Object(factory["a" /* factory */])(rightArithShift_name, rightArithShift_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + zeros = _ref.zeros, + DenseMatrix = _ref.DenseMatrix; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm08 = createAlgorithm08({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Bitwise right arithmetic shift of a value x by y number of bits, `x >> y`. + * For matrices, the function is evaluated element wise. + * For units, the function is evaluated on the best prefix base. + * + * Syntax: + * + * math.rightArithShift(x, y) + * + * Examples: + * + * math.rightArithShift(4, 2) // returns number 1 + * + * math.rightArithShift([16, -32, 64], 4) // returns Array [1, -2, 3] + * + * See also: + * + * bitAnd, bitNot, bitOr, bitXor, rightArithShift, rightLogShift + * + * @param {number | BigNumber | Array | Matrix} x Value to be shifted + * @param {number | BigNumber} y Amount of shifts + * @return {number | BigNumber | Array | Matrix} `x` sign-filled shifted right `y` times + */ + + var rightArithShift = typed(rightArithShift_name, { + 'number, number': rightArithShiftNumber, + 'BigNumber, BigNumber': rightArithShiftBigNumber, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm08(x, y, rightArithShift, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, rightArithShift, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm01(x, y, rightArithShift, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, rightArithShift); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return rightArithShift(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return rightArithShift(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return rightArithShift(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + // check scalar + if (equalScalar(y, 0)) { + return x.clone(); + } + + return algorithm11(x, y, rightArithShift, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + // check scalar + if (equalScalar(y, 0)) { + return x.clone(); + } + + return algorithm14(x, y, rightArithShift, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + // check scalar + if (equalScalar(x, 0)) { + return zeros(y.size(), y.storage()); + } + + return algorithm10(y, x, rightArithShift, true); + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + // check scalar + if (equalScalar(x, 0)) { + return zeros(y.size(), y.storage()); + } + + return algorithm14(y, x, rightArithShift, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return rightArithShift(matrix(x), y).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + // use matrix implementation + return rightArithShift(x, matrix(y)).valueOf(); + } + }); + return rightArithShift; +}); +// CONCATENATED MODULE: ./src/function/bitwise/rightLogShift.js + + + + + + + + + +var rightLogShift_name = 'rightLogShift'; +var rightLogShift_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix']; +var createRightLogShift = /* #__PURE__ */Object(factory["a" /* factory */])(rightLogShift_name, rightLogShift_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + zeros = _ref.zeros, + DenseMatrix = _ref.DenseMatrix; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm08 = createAlgorithm08({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Bitwise right logical shift of value x by y number of bits, `x >>> y`. + * For matrices, the function is evaluated element wise. + * For units, the function is evaluated on the best prefix base. + * + * Syntax: + * + * math.rightLogShift(x, y) + * + * Examples: + * + * math.rightLogShift(4, 2) // returns number 1 + * + * math.rightLogShift([16, -32, 64], 4) // returns Array [1, 2, 3] + * + * See also: + * + * bitAnd, bitNot, bitOr, bitXor, leftShift, rightLogShift + * + * @param {number | Array | Matrix} x Value to be shifted + * @param {number} y Amount of shifts + * @return {number | Array | Matrix} `x` zero-filled shifted right `y` times + */ + + var rightLogShift = typed(rightLogShift_name, { + 'number, number': rightLogShiftNumber, + // 'BigNumber, BigNumber': ..., // TODO: implement BigNumber support for rightLogShift + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm08(x, y, rightLogShift, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, rightLogShift, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm01(x, y, rightLogShift, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, rightLogShift); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return rightLogShift(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return rightLogShift(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return rightLogShift(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + // check scalar + if (equalScalar(y, 0)) { + return x.clone(); + } + + return algorithm11(x, y, rightLogShift, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + // check scalar + if (equalScalar(y, 0)) { + return x.clone(); + } + + return algorithm14(x, y, rightLogShift, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + // check scalar + if (equalScalar(x, 0)) { + return zeros(y.size(), y.storage()); + } + + return algorithm10(y, x, rightLogShift, true); + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + // check scalar + if (equalScalar(x, 0)) { + return zeros(y.size(), y.storage()); + } + + return algorithm14(y, x, rightLogShift, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + // use matrix implementation + return rightLogShift(matrix(x), y).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + // use matrix implementation + return rightLogShift(x, matrix(y)).valueOf(); + } + }); + return rightLogShift; +}); +// CONCATENATED MODULE: ./src/function/logical/and.js + + + + + + + +var and_name = 'and'; +var and_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'not']; +var createAnd = /* #__PURE__ */Object(factory["a" /* factory */])(and_name, and_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + zeros = _ref.zeros, + not = _ref.not; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm06 = createAlgorithm06({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Logical `and`. Test whether two values are both defined with a nonzero/nonempty value. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.and(x, y) + * + * Examples: + * + * math.and(2, 4) // returns true + * + * a = [2, 0, 0] + * b = [3, 7, 0] + * c = 0 + * + * math.and(a, b) // returns [true, false, false] + * math.and(a, c) // returns [false, false, false] + * + * See also: + * + * not, or, xor + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check + * @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check + * @return {boolean | Array | Matrix} + * Returns true when both inputs are defined with a nonzero/nonempty value. + */ + + var and = typed(and_name, { + 'number, number': andNumber, + 'Complex, Complex': function ComplexComplex(x, y) { + return (x.re !== 0 || x.im !== 0) && (y.re !== 0 || y.im !== 0); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return !x.isZero() && !y.isZero() && !x.isNaN() && !y.isNaN(); + }, + 'Unit, Unit': function UnitUnit(x, y) { + return and(x.value || 0, y.value || 0); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm06(x, y, and, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm02(y, x, and, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm02(x, y, and, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, and); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return and(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return and(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return and(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + // check scalar + if (not(y)) { + // return zero matrix + return zeros(x.size(), x.storage()); + } + + return algorithm11(x, y, and, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + // check scalar + if (not(y)) { + // return zero matrix + return zeros(x.size(), x.storage()); + } + + return algorithm14(x, y, and, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + // check scalar + if (not(x)) { + // return zero matrix + return zeros(x.size(), x.storage()); + } + + return algorithm11(y, x, and, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + // check scalar + if (not(x)) { + // return zero matrix + return zeros(x.size(), x.storage()); + } + + return algorithm14(y, x, and, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return and(matrix(x), y).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return and(x, matrix(y)).valueOf(); + } + }); + return and; +}); +// CONCATENATED MODULE: ./src/function/relational/compare.js + + + + + + + + +var compare_name = 'compare'; +var compare_dependencies = ['typed', 'config', 'matrix', 'equalScalar', 'BigNumber', 'Fraction', 'DenseMatrix']; +var createCompare = /* #__PURE__ */Object(factory["a" /* factory */])(compare_name, compare_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + equalScalar = _ref.equalScalar, + matrix = _ref.matrix, + BigNumber = _ref.BigNumber, + Fraction = _ref.Fraction, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm05 = createAlgorithm05({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y. + * + * x and y are considered equal when the relative difference between x and y + * is smaller than the configured epsilon. The function cannot be used to + * compare values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * Strings are compared by their numerical value. + * + * Syntax: + * + * math.compare(x, y) + * + * Examples: + * + * math.compare(6, 1) // returns 1 + * math.compare(2, 3) // returns -1 + * math.compare(7, 7) // returns 0 + * math.compare('10', '2') // returns 1 + * math.compare('1000', '1e3') // returns 0 + * + * const a = math.unit('5 cm') + * const b = math.unit('40 mm') + * math.compare(a, b) // returns 1 + * + * math.compare(2, [1, 2, 3]) // returns [1, 0, -1] + * + * See also: + * + * equal, unequal, smaller, smallerEq, larger, largerEq, compareNatural, compareText + * + * @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} x First value to compare + * @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} y Second value to compare + * @return {number | BigNumber | Fraction | Array | Matrix} Returns the result of the comparison: + * 1 when x > y, -1 when x < y, and 0 when x == y. + */ + + var compare = typed(compare_name, { + 'boolean, boolean': function booleanBoolean(x, y) { + return x === y ? 0 : x > y ? 1 : -1; + }, + 'number, number': function numberNumber(x, y) { + return Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon) ? 0 : x > y ? 1 : -1; + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return nearlyEqual(x, y, config.epsilon) ? new BigNumber(0) : new BigNumber(x.cmp(y)); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return new Fraction(x.compare(y)); + }, + 'Complex, Complex': function ComplexComplex() { + throw new TypeError('No ordering relation is defined for complex numbers'); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (!x.equalBase(y)) { + throw new Error('Cannot compare units with different base'); + } + + return compare(x.value, y.value); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm05(x, y, compare); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, compare, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, compare, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, compare); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return compare(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return compare(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return compare(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, compare, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, compare, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, compare, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, compare, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, compare, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, compare, true).valueOf(); + } + }); + return compare; +}); +var createCompareNumber = /* #__PURE__ */Object(factory["a" /* factory */])(compare_name, ['typed', 'config'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config; + return typed(compare_name, { + 'number, number': function numberNumber(x, y) { + return Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon) ? 0 : x > y ? 1 : -1; + } + }); +}); +// EXTERNAL MODULE: ./node_modules/javascript-natural-sort/naturalSort.js +var naturalSort = __webpack_require__(12); +var naturalSort_default = /*#__PURE__*/__webpack_require__.n(naturalSort); + +// CONCATENATED MODULE: ./src/function/relational/compareNatural.js + + + +var compareNatural_name = 'compareNatural'; +var compareNatural_dependencies = ['typed', 'compare']; +var createCompareNatural = /* #__PURE__ */Object(factory["a" /* factory */])(compareNatural_name, compareNatural_dependencies, function (_ref) { + var typed = _ref.typed, + compare = _ref.compare; + var compareBooleans = compare.signatures['boolean,boolean']; + /** + * Compare two values of any type in a deterministic, natural way. + * + * For numeric values, the function works the same as `math.compare`. + * For types of values that can't be compared mathematically, + * the function compares in a natural way. + * + * For numeric values, x and y are considered equal when the relative + * difference between x and y is smaller than the configured epsilon. + * The function cannot be used to compare values smaller than + * approximately 2.22e-16. + * + * For Complex numbers, first the real parts are compared. If equal, + * the imaginary parts are compared. + * + * Strings are compared with a natural sorting algorithm, which + * orders strings in a "logic" way following some heuristics. + * This differs from the function `compare`, which converts the string + * into a numeric value and compares that. The function `compareText` + * on the other hand compares text lexically. + * + * Arrays and Matrices are compared value by value until there is an + * unequal pair of values encountered. Objects are compared by sorted + * keys until the keys or their values are unequal. + * + * Syntax: + * + * math.compareNatural(x, y) + * + * Examples: + * + * math.compareNatural(6, 1) // returns 1 + * math.compareNatural(2, 3) // returns -1 + * math.compareNatural(7, 7) // returns 0 + * + * math.compareNatural('10', '2') // returns 1 + * math.compareText('10', '2') // returns -1 + * math.compare('10', '2') // returns 1 + * + * math.compareNatural('Answer: 10', 'Answer: 2') // returns 1 + * math.compareText('Answer: 10', 'Answer: 2') // returns -1 + * math.compare('Answer: 10', 'Answer: 2') + * // Error: Cannot convert "Answer: 10" to a number + * + * const a = math.unit('5 cm') + * const b = math.unit('40 mm') + * math.compareNatural(a, b) // returns 1 + * + * const c = math.complex('2 + 3i') + * const d = math.complex('2 + 4i') + * math.compareNatural(c, d) // returns -1 + * + * math.compareNatural([1, 2, 4], [1, 2, 3]) // returns 1 + * math.compareNatural([1, 2, 3], [1, 2]) // returns 1 + * math.compareNatural([1, 5], [1, 2, 3]) // returns 1 + * math.compareNatural([1, 2], [1, 2]) // returns 0 + * + * math.compareNatural({a: 2}, {a: 4}) // returns -1 + * + * See also: + * + * compare, compareText + * + * @param {*} x First value to compare + * @param {*} y Second value to compare + * @return {number} Returns the result of the comparison: + * 1 when x > y, -1 when x < y, and 0 when x == y. + */ + + var compareNatural = typed(compareNatural_name, { + 'any, any': function anyAny(x, y) { + var typeX = Object(is["M" /* typeOf */])(x); + var typeY = Object(is["M" /* typeOf */])(y); + var c; // numeric types + + if ((typeX === 'number' || typeX === 'BigNumber' || typeX === 'Fraction') && (typeY === 'number' || typeY === 'BigNumber' || typeY === 'Fraction')) { + c = compare(x, y); + + if (c.toString() !== '0') { + // c can be number, BigNumber, or Fraction + return c > 0 ? 1 : -1; // return a number + } else { + return naturalSort_default()(typeX, typeY); + } + } // matrix types + + + if (typeX === 'Array' || typeX === 'Matrix' || typeY === 'Array' || typeY === 'Matrix') { + c = compareMatricesAndArrays(x, y); + + if (c !== 0) { + return c; + } else { + return naturalSort_default()(typeX, typeY); + } + } // in case of different types, order by name of type, i.e. 'BigNumber' < 'Complex' + + + if (typeX !== typeY) { + return naturalSort_default()(typeX, typeY); + } + + if (typeX === 'Complex') { + return compareComplexNumbers(x, y); + } + + if (typeX === 'Unit') { + if (x.equalBase(y)) { + return compareNatural(x.value, y.value); + } // compare by units + + + return compareArrays(x.formatUnits(), y.formatUnits()); + } + + if (typeX === 'boolean') { + return compareBooleans(x, y); + } + + if (typeX === 'string') { + return naturalSort_default()(x, y); + } + + if (typeX === 'Object') { + return compareObjects(x, y); + } + + if (typeX === 'null') { + return 0; + } + + if (typeX === 'undefined') { + return 0; + } // this should not occur... + + + throw new TypeError('Unsupported type of value "' + typeX + '"'); + } + }); + /** + * Compare mixed matrix/array types, by converting to same-shaped array. + * This comparator is non-deterministic regarding input types. + * @param {Array | SparseMatrix | DenseMatrix | *} x + * @param {Array | SparseMatrix | DenseMatrix | *} y + * @returns {number} Returns the comparison result: -1, 0, or 1 + */ + + function compareMatricesAndArrays(x, y) { + if (Object(is["H" /* isSparseMatrix */])(x) && Object(is["H" /* isSparseMatrix */])(y)) { + return compareArrays(x.toJSON().values, y.toJSON().values); + } + + if (Object(is["H" /* isSparseMatrix */])(x)) { + // note: convert to array is expensive + return compareMatricesAndArrays(x.toArray(), y); + } + + if (Object(is["H" /* isSparseMatrix */])(y)) { + // note: convert to array is expensive + return compareMatricesAndArrays(x, y.toArray()); + } // convert DenseArray into Array + + + if (Object(is["n" /* isDenseMatrix */])(x)) { + return compareMatricesAndArrays(x.toJSON().data, y); + } + + if (Object(is["n" /* isDenseMatrix */])(y)) { + return compareMatricesAndArrays(x, y.toJSON().data); + } // convert scalars to array + + + if (!Array.isArray(x)) { + return compareMatricesAndArrays([x], y); + } + + if (!Array.isArray(y)) { + return compareMatricesAndArrays(x, [y]); + } + + return compareArrays(x, y); + } + /** + * Compare two Arrays + * + * - First, compares value by value + * - Next, if all corresponding values are equal, + * look at the length: longest array will be considered largest + * + * @param {Array} x + * @param {Array} y + * @returns {number} Returns the comparison result: -1, 0, or 1 + */ + + + function compareArrays(x, y) { + // compare each value + for (var i = 0, ii = Math.min(x.length, y.length); i < ii; i++) { + var v = compareNatural(x[i], y[i]); + + if (v !== 0) { + return v; + } + } // compare the size of the arrays + + + if (x.length > y.length) { + return 1; + } + + if (x.length < y.length) { + return -1; + } // both Arrays have equal size and content + + + return 0; + } + /** + * Compare two objects + * + * - First, compare sorted property names + * - Next, compare the property values + * + * @param {Object} x + * @param {Object} y + * @returns {number} Returns the comparison result: -1, 0, or 1 + */ + + + function compareObjects(x, y) { + var keysX = Object.keys(x); + var keysY = Object.keys(y); // compare keys + + keysX.sort(naturalSort_default.a); + keysY.sort(naturalSort_default.a); + var c = compareArrays(keysX, keysY); + + if (c !== 0) { + return c; + } // compare values + + + for (var i = 0; i < keysX.length; i++) { + var v = compareNatural(x[keysX[i]], y[keysY[i]]); + + if (v !== 0) { + return v; + } + } + + return 0; + } + + return compareNatural; +}); +/** + * Compare two complex numbers, `x` and `y`: + * + * - First, compare the real values of `x` and `y` + * - If equal, compare the imaginary values of `x` and `y` + * + * @params {Complex} x + * @params {Complex} y + * @returns {number} Returns the comparison result: -1, 0, or 1 + */ + +function compareComplexNumbers(x, y) { + if (x.re > y.re) { + return 1; + } + + if (x.re < y.re) { + return -1; + } + + if (x.im > y.im) { + return 1; + } + + if (x.im < y.im) { + return -1; + } + + return 0; +} +// CONCATENATED MODULE: ./src/function/relational/compareText.js + + + + +var compareText_name = 'compareText'; +var compareText_dependencies = ['typed', 'matrix']; +var createCompareText = /* #__PURE__ */Object(factory["a" /* factory */])(compareText_name, compareText_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Compare two strings lexically. Comparison is case sensitive. + * Returns 1 when x > y, -1 when x < y, and 0 when x == y. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.compareText(x, y) + * + * Examples: + * + * math.compareText('B', 'A') // returns 1 + * math.compareText('2', '10') // returns 1 + * math.compare('2', '10') // returns -1 + * math.compareNatural('2', '10') // returns -1 + * + * math.compareText('B', ['A', 'B', 'C']) // returns [1, 0, -1] + * + * See also: + * + * equal, equalText, compare, compareNatural + * + * @param {string | Array | DenseMatrix} x First string to compare + * @param {string | Array | DenseMatrix} y Second string to compare + * @return {number | Array | DenseMatrix} Returns the result of the comparison: + * 1 when x > y, -1 when x < y, and 0 when x == y. + */ + + var compareText = typed(compareText_name, { + 'any, any': utils_string["a" /* compareText */], + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, utils_string["a" /* compareText */]); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return compareText(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return compareText(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return compareText(x, matrix(y)); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, utils_string["a" /* compareText */], false); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, utils_string["a" /* compareText */], true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, utils_string["a" /* compareText */], false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, utils_string["a" /* compareText */], true).valueOf(); + } + }); + return compareText; +}); +var createCompareTextNumber = /* #__PURE__ */Object(factory["a" /* factory */])(compareText_name, ['typed'], function (_ref2) { + var typed = _ref2.typed; + return typed(compareText_name, { + 'any, any': utils_string["a" /* compareText */] + }); +}); +// CONCATENATED MODULE: ./src/function/relational/equal.js + + + + + + +var equal_name = 'equal'; +var equal_dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix']; +var createEqual = /* #__PURE__ */Object(factory["a" /* factory */])(equal_name, equal_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Test whether two values are equal. + * + * The function tests whether the relative difference between x and y is + * smaller than the configured epsilon. The function cannot be used to + * compare values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * In case of complex numbers, x.re must equal y.re, and x.im must equal y.im. + * + * Values `null` and `undefined` are compared strictly, thus `null` is only + * equal to `null` and nothing else, and `undefined` is only equal to + * `undefined` and nothing else. Strings are compared by their numerical value. + * + * Syntax: + * + * math.equal(x, y) + * + * Examples: + * + * math.equal(2 + 2, 3) // returns false + * math.equal(2 + 2, 4) // returns true + * + * const a = math.unit('50 cm') + * const b = math.unit('5 m') + * math.equal(a, b) // returns true + * + * const c = [2, 5, 1] + * const d = [2, 7, 1] + * + * math.equal(c, d) // returns [true, false, true] + * math.deepEqual(c, d) // returns false + * + * math.equal("1000", "1e3") // returns true + * math.equal(0, null) // returns false + * + * See also: + * + * unequal, smaller, smallerEq, larger, largerEq, compare, deepEqual, equalText + * + * @param {number | BigNumber | boolean | Complex | Unit | string | Array | Matrix} x First value to compare + * @param {number | BigNumber | boolean | Complex | Unit | string | Array | Matrix} y Second value to compare + * @return {boolean | Array | Matrix} Returns true when the compared values are equal, else returns false + */ + + var equal = typed(equal_name, { + 'any, any': function anyAny(x, y) { + // strict equality for null and undefined? + if (x === null) { + return y === null; + } + + if (y === null) { + return x === null; + } + + if (x === undefined) { + return y === undefined; + } + + if (y === undefined) { + return x === undefined; + } + + return equalScalar(x, y); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, equalScalar); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, equalScalar, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, equalScalar, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, equalScalar); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return equal(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return equal(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return equal(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, equalScalar, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, equalScalar, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, equalScalar, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, equalScalar, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, equalScalar, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, equalScalar, true).valueOf(); + } + }); + return equal; +}); +var createEqualNumber = Object(factory["a" /* factory */])(equal_name, ['typed', 'equalScalar'], function (_ref2) { + var typed = _ref2.typed, + equalScalar = _ref2.equalScalar; + return typed(equal_name, { + 'any, any': function anyAny(x, y) { + // strict equality for null and undefined? + if (x === null) { + return y === null; + } + + if (y === null) { + return x === null; + } + + if (x === undefined) { + return y === undefined; + } + + if (y === undefined) { + return x === undefined; + } + + return equalScalar(x, y); + } + }); +}); +// CONCATENATED MODULE: ./src/function/relational/equalText.js + +var equalText_name = 'equalText'; +var equalText_dependencies = ['typed', 'compareText', 'isZero']; +var createEqualText = /* #__PURE__ */Object(factory["a" /* factory */])(equalText_name, equalText_dependencies, function (_ref) { + var typed = _ref.typed, + compareText = _ref.compareText, + isZero = _ref.isZero; + + /** + * Check equality of two strings. Comparison is case sensitive. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.equalText(x, y) + * + * Examples: + * + * math.equalText('Hello', 'Hello') // returns true + * math.equalText('a', 'A') // returns false + * math.equal('2e3', '2000') // returns true + * math.equalText('2e3', '2000') // returns false + * + * math.equalText('B', ['A', 'B', 'C']) // returns [false, true, false] + * + * See also: + * + * equal, compareText, compare, compareNatural + * + * @param {string | Array | DenseMatrix} x First string to compare + * @param {string | Array | DenseMatrix} y Second string to compare + * @return {number | Array | DenseMatrix} Returns true if the values are equal, and false if not. + */ + return typed(equalText_name, { + 'any, any': function anyAny(x, y) { + return isZero(compareText(x, y)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/relational/smaller.js + + + + + + + + +var smaller_name = 'smaller'; +var smaller_dependencies = ['typed', 'config', 'matrix', 'DenseMatrix']; +var createSmaller = /* #__PURE__ */Object(factory["a" /* factory */])(smaller_name, smaller_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Test whether value x is smaller than y. + * + * The function returns true when x is smaller than y and the relative + * difference between x and y is smaller than the configured epsilon. The + * function cannot be used to compare values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * Strings are compared by their numerical value. + * + * Syntax: + * + * math.smaller(x, y) + * + * Examples: + * + * math.smaller(2, 3) // returns true + * math.smaller(5, 2 * 2) // returns false + * + * const a = math.unit('5 cm') + * const b = math.unit('2 inch') + * math.smaller(a, b) // returns true + * + * See also: + * + * equal, unequal, smallerEq, smaller, smallerEq, compare + * + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare + * @return {boolean | Array | Matrix} Returns true when the x is smaller than y, else returns false + */ + + var smaller = typed(smaller_name, { + 'boolean, boolean': function booleanBoolean(x, y) { + return x < y; + }, + 'number, number': function numberNumber(x, y) { + return x < y && !Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.lt(y) && !nearlyEqual(x, y, config.epsilon); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.compare(y) === -1; + }, + 'Complex, Complex': function ComplexComplex(x, y) { + throw new TypeError('No ordering relation is defined for complex numbers'); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (!x.equalBase(y)) { + throw new Error('Cannot compare units with different base'); + } + + return smaller(x.value, y.value); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, smaller); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, smaller, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, smaller, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, smaller); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return smaller(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return smaller(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return smaller(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, smaller, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, smaller, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, smaller, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, smaller, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, smaller, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, smaller, true).valueOf(); + } + }); + return smaller; +}); +var createSmallerNumber = /* #__PURE__ */Object(factory["a" /* factory */])(smaller_name, ['typed', 'config'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config; + return typed(smaller_name, { + 'number, number': function numberNumber(x, y) { + return x < y && !Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + } + }); +}); +// CONCATENATED MODULE: ./src/function/relational/smallerEq.js + + + + + + + + +var smallerEq_name = 'smallerEq'; +var smallerEq_dependencies = ['typed', 'config', 'matrix', 'DenseMatrix']; +var createSmallerEq = /* #__PURE__ */Object(factory["a" /* factory */])(smallerEq_name, smallerEq_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Test whether value x is smaller or equal to y. + * + * The function returns true when x is smaller than y or the relative + * difference between x and y is smaller than the configured epsilon. The + * function cannot be used to compare values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * Strings are compared by their numerical value. + * + * Syntax: + * + * math.smallerEq(x, y) + * + * Examples: + * + * math.smaller(1 + 2, 3) // returns false + * math.smallerEq(1 + 2, 3) // returns true + * + * See also: + * + * equal, unequal, smaller, larger, largerEq, compare + * + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare + * @return {boolean | Array | Matrix} Returns true when the x is smaller than y, else returns false + */ + + var smallerEq = typed(smallerEq_name, { + 'boolean, boolean': function booleanBoolean(x, y) { + return x <= y; + }, + 'number, number': function numberNumber(x, y) { + return x <= y || Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.lte(y) || nearlyEqual(x, y, config.epsilon); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.compare(y) !== 1; + }, + 'Complex, Complex': function ComplexComplex() { + throw new TypeError('No ordering relation is defined for complex numbers'); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (!x.equalBase(y)) { + throw new Error('Cannot compare units with different base'); + } + + return smallerEq(x.value, y.value); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, smallerEq); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, smallerEq, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, smallerEq, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, smallerEq); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return smallerEq(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return smallerEq(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return smallerEq(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, smallerEq, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, smallerEq, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, smallerEq, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, smallerEq, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, smallerEq, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, smallerEq, true).valueOf(); + } + }); + return smallerEq; +}); +var createSmallerEqNumber = /* #__PURE__ */Object(factory["a" /* factory */])(smallerEq_name, ['typed', 'config'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config; + return typed(smallerEq_name, { + 'number, number': function numberNumber(x, y) { + return x <= y || Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + } + }); +}); +// CONCATENATED MODULE: ./src/function/relational/larger.js + + + + + + + + +var larger_name = 'larger'; +var larger_dependencies = ['typed', 'config', 'matrix', 'DenseMatrix']; +var createLarger = /* #__PURE__ */Object(factory["a" /* factory */])(larger_name, larger_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Test whether value x is larger than y. + * + * The function returns true when x is larger than y and the relative + * difference between x and y is larger than the configured epsilon. The + * function cannot be used to compare values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * Strings are compared by their numerical value. + * + * Syntax: + * + * math.larger(x, y) + * + * Examples: + * + * math.larger(2, 3) // returns false + * math.larger(5, 2 + 2) // returns true + * + * const a = math.unit('5 cm') + * const b = math.unit('2 inch') + * math.larger(a, b) // returns false + * + * See also: + * + * equal, unequal, smaller, smallerEq, largerEq, compare + * + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare + * @return {boolean | Array | Matrix} Returns true when the x is larger than y, else returns false + */ + + var larger = typed(larger_name, { + 'boolean, boolean': function booleanBoolean(x, y) { + return x > y; + }, + 'number, number': function numberNumber(x, y) { + return x > y && !Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.gt(y) && !nearlyEqual(x, y, config.epsilon); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.compare(y) === 1; + }, + 'Complex, Complex': function ComplexComplex() { + throw new TypeError('No ordering relation is defined for complex numbers'); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (!x.equalBase(y)) { + throw new Error('Cannot compare units with different base'); + } + + return larger(x.value, y.value); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, larger); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, larger, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, larger, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, larger); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return larger(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return larger(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return larger(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, larger, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, larger, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, larger, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, larger, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, larger, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, larger, true).valueOf(); + } + }); + return larger; +}); +var createLargerNumber = /* #__PURE__ */Object(factory["a" /* factory */])(larger_name, ['typed', 'config'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config; + return typed(larger_name, { + 'number, number': function numberNumber(x, y) { + return x > y && !Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + } + }); +}); +// CONCATENATED MODULE: ./src/function/relational/largerEq.js + + + + + + + + +var largerEq_name = 'largerEq'; +var largerEq_dependencies = ['typed', 'config', 'matrix', 'DenseMatrix']; +var createLargerEq = /* #__PURE__ */Object(factory["a" /* factory */])(largerEq_name, largerEq_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Test whether value x is larger or equal to y. + * + * The function returns true when x is larger than y or the relative + * difference between x and y is smaller than the configured epsilon. The + * function cannot be used to compare values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * Strings are compared by their numerical value. + * + * Syntax: + * + * math.largerEq(x, y) + * + * Examples: + * + * math.larger(2, 1 + 1) // returns false + * math.largerEq(2, 1 + 1) // returns true + * + * See also: + * + * equal, unequal, smaller, smallerEq, larger, compare + * + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare + * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare + * @return {boolean | Array | Matrix} Returns true when the x is larger or equal to y, else returns false + */ + + var largerEq = typed(largerEq_name, { + 'boolean, boolean': function booleanBoolean(x, y) { + return x >= y; + }, + 'number, number': function numberNumber(x, y) { + return x >= y || Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) { + return x.gte(y) || nearlyEqual(x, y, config.epsilon); + }, + 'Fraction, Fraction': function FractionFraction(x, y) { + return x.compare(y) !== -1; + }, + 'Complex, Complex': function ComplexComplex() { + throw new TypeError('No ordering relation is defined for complex numbers'); + }, + 'Unit, Unit': function UnitUnit(x, y) { + if (!x.equalBase(y)) { + throw new Error('Cannot compare units with different base'); + } + + return largerEq(x.value, y.value); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, largerEq); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, largerEq, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, largerEq, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, largerEq); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return largerEq(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return largerEq(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return largerEq(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, largerEq, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, largerEq, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, largerEq, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, largerEq, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, largerEq, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, largerEq, true).valueOf(); + } + }); + return largerEq; +}); +var createLargerEqNumber = /* #__PURE__ */Object(factory["a" /* factory */])(largerEq_name, ['typed', 'config'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config; + return typed(largerEq_name, { + 'number, number': function numberNumber(x, y) { + return x >= y || Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon); + } + }); +}); +// CONCATENATED MODULE: ./src/function/relational/deepEqual.js + +var deepEqual_name = 'deepEqual'; +var deepEqual_dependencies = ['typed', 'equal']; +var createDeepEqual = /* #__PURE__ */Object(factory["a" /* factory */])(deepEqual_name, deepEqual_dependencies, function (_ref) { + var typed = _ref.typed, + equal = _ref.equal; + + /** + * Test element wise whether two matrices are equal. + * The function accepts both matrices and scalar values. + * + * Strings are compared by their numerical value. + * + * Syntax: + * + * math.deepEqual(x, y) + * + * Examples: + * + * math.deepEqual(2, 4) // returns false + * + * a = [2, 5, 1] + * b = [2, 7, 1] + * + * math.deepEqual(a, b) // returns false + * math.equal(a, b) // returns [true, false, true] + * + * See also: + * + * equal, unequal + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First matrix to compare + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second matrix to compare + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} + * Returns true when the input matrices have the same size and each of their elements is equal. + */ + return typed(deepEqual_name, { + 'any, any': function anyAny(x, y) { + return _deepEqual(x.valueOf(), y.valueOf()); + } + }); + /** + * Test whether two arrays have the same size and all elements are equal + * @param {Array | *} x + * @param {Array | *} y + * @return {boolean} Returns true if both arrays are deep equal + */ + + function _deepEqual(x, y) { + if (Array.isArray(x)) { + if (Array.isArray(y)) { + var len = x.length; + + if (len !== y.length) { + return false; + } + + for (var i = 0; i < len; i++) { + if (!_deepEqual(x[i], y[i])) { + return false; + } + } + + return true; + } else { + return false; + } + } else { + if (Array.isArray(y)) { + return false; + } else { + return equal(x, y); + } + } + } +}); +// CONCATENATED MODULE: ./src/function/relational/unequal.js + + + + + + +var unequal_name = 'unequal'; +var unequal_dependencies = ['typed', 'config', 'equalScalar', 'matrix', 'DenseMatrix']; +var createUnequal = /* #__PURE__ */Object(factory["a" /* factory */])(unequal_name, unequal_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + equalScalar = _ref.equalScalar, + matrix = _ref.matrix, + DenseMatrix = _ref.DenseMatrix; + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm07 = createAlgorithm07({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Test whether two values are unequal. + * + * The function tests whether the relative difference between x and y is + * larger than the configured epsilon. The function cannot be used to compare + * values smaller than approximately 2.22e-16. + * + * For matrices, the function is evaluated element wise. + * In case of complex numbers, x.re must unequal y.re, or x.im must unequal y.im. + * Strings are compared by their numerical value. + * + * Values `null` and `undefined` are compared strictly, thus `null` is unequal + * with everything except `null`, and `undefined` is unequal with everything + * except `undefined`. + * + * Syntax: + * + * math.unequal(x, y) + * + * Examples: + * + * math.unequal(2 + 2, 3) // returns true + * math.unequal(2 + 2, 4) // returns false + * + * const a = math.unit('50 cm') + * const b = math.unit('5 m') + * math.unequal(a, b) // returns false + * + * const c = [2, 5, 1] + * const d = [2, 7, 1] + * + * math.unequal(c, d) // returns [false, true, false] + * math.deepEqual(c, d) // returns false + * + * math.unequal(0, null) // returns true + * See also: + * + * equal, deepEqual, smaller, smallerEq, larger, largerEq, compare + * + * @param {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} x First value to compare + * @param {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} y Second value to compare + * @return {boolean | Array | Matrix} Returns true when the compared values are unequal, else returns false + */ + + var unequal = typed('unequal', { + 'any, any': function anyAny(x, y) { + // strict equality for null and undefined? + if (x === null) { + return y !== null; + } + + if (y === null) { + return x !== null; + } + + if (x === undefined) { + return y !== undefined; + } + + if (y === undefined) { + return x !== undefined; + } + + return _unequal(x, y); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm07(x, y, _unequal); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm03(y, x, _unequal, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, _unequal, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, _unequal); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return unequal(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return unequal(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return unequal(x, matrix(y)); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm12(x, y, _unequal, false); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, _unequal, false); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm12(y, x, _unequal, true); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, _unequal, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, _unequal, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, _unequal, true).valueOf(); + } + }); + + function _unequal(x, y) { + return !equalScalar(x, y); + } + + return unequal; +}); +var createUnequalNumber = Object(factory["a" /* factory */])(unequal_name, ['typed', 'equalScalar'], function (_ref2) { + var typed = _ref2.typed, + equalScalar = _ref2.equalScalar; + return typed(unequal_name, { + 'any, any': function anyAny(x, y) { + // strict equality for null and undefined? + if (x === null) { + return y !== null; + } + + if (y === null) { + return x !== null; + } + + if (x === undefined) { + return y !== undefined; + } + + if (y === undefined) { + return x !== undefined; + } + + return !equalScalar(x, y); + } + }); +}); +// CONCATENATED MODULE: ./src/function/matrix/partitionSelect.js + + + +var partitionSelect_name = 'partitionSelect'; +var partitionSelect_dependencies = ['typed', 'isNumeric', 'isNaN', 'compare']; +var createPartitionSelect = /* #__PURE__ */Object(factory["a" /* factory */])(partitionSelect_name, partitionSelect_dependencies, function (_ref) { + var typed = _ref.typed, + isNumeric = _ref.isNumeric, + isNaN = _ref.isNaN, + compare = _ref.compare; + var asc = compare; + + var desc = function desc(a, b) { + return -compare(a, b); + }; + /** + * Partition-based selection of an array or 1D matrix. + * Will find the kth smallest value, and mutates the input array. + * Uses Quickselect. + * + * Syntax: + * + * math.partitionSelect(x, k) + * math.partitionSelect(x, k, compare) + * + * Examples: + * + * math.partitionSelect([5, 10, 1], 2) // returns 10 + * math.partitionSelect(['C', 'B', 'A', 'D'], 1) // returns 'B' + * + * function sortByLength (a, b) { + * return a.length - b.length + * } + * math.partitionSelect(['Langdon', 'Tom', 'Sara'], 2, sortByLength) // returns 'Langdon' + * + * See also: + * + * sort + * + * @param {Matrix | Array} x A one dimensional matrix or array to sort + * @param {Number} k The kth smallest value to be retrieved zero-based index + * @param {Function | 'asc' | 'desc'} [compare='asc'] + * An optional comparator function. The function is called as + * `compare(a, b)`, and must return 1 when a > b, -1 when a < b, + * and 0 when a == b. + * @return {*} Returns the kth lowest value. + */ + + + return typed(partitionSelect_name, { + 'Array | Matrix, number': function ArrayMatrixNumber(x, k) { + return _partitionSelect(x, k, asc); + }, + 'Array | Matrix, number, string': function ArrayMatrixNumberString(x, k, compare) { + if (compare === 'asc') { + return _partitionSelect(x, k, asc); + } else if (compare === 'desc') { + return _partitionSelect(x, k, desc); + } else { + throw new Error('Compare string must be "asc" or "desc"'); + } + }, + 'Array | Matrix, number, function': _partitionSelect + }); + + function _partitionSelect(x, k, compare) { + if (!Object(utils_number["i" /* isInteger */])(k) || k < 0) { + throw new Error('k must be a non-negative integer'); + } + + if (Object(is["v" /* isMatrix */])(x)) { + var size = x.size(); + + if (size.length > 1) { + throw new Error('Only one dimensional matrices supported'); + } + + return quickSelect(x.valueOf(), k, compare); + } + + if (Array.isArray(x)) { + return quickSelect(x, k, compare); + } + } + /** + * Quickselect algorithm. + * Code adapted from: + * https://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html + * + * @param {Array} arr + * @param {Number} k + * @param {Function} compare + * @private + */ + + + function quickSelect(arr, k, compare) { + if (k >= arr.length) { + throw new Error('k out of bounds'); + } // check for NaN values since these can cause an infinite while loop + + + for (var i = 0; i < arr.length; i++) { + if (isNumeric(arr[i]) && isNaN(arr[i])) { + return arr[i]; // return NaN + } + } + + var from = 0; + var to = arr.length - 1; // if from == to we reached the kth element + + while (from < to) { + var r = from; + var w = to; + var pivot = arr[Math.floor(Math.random() * (to - from + 1)) + from]; // stop if the reader and writer meets + + while (r < w) { + // arr[r] >= pivot + if (compare(arr[r], pivot) >= 0) { + // put the large values at the end + var tmp = arr[w]; + arr[w] = arr[r]; + arr[r] = tmp; + --w; + } else { + // the value is smaller than the pivot, skip + ++r; + } + } // if we stepped up (r++) we need to step one down (arr[r] > pivot) + + + if (compare(arr[r], pivot) > 0) { + --r; + } // the r pointer is on the end of the first k elements + + + if (k <= r) { + to = r; + } else { + from = r + 1; + } + } + + return arr[k]; + } +}); +// CONCATENATED MODULE: ./src/function/matrix/sort.js + + +var sort_name = 'sort'; +var sort_dependencies = ['typed', 'matrix', 'compare', 'compareNatural']; +var createSort = /* #__PURE__ */Object(factory["a" /* factory */])(sort_name, sort_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + compare = _ref.compare, + compareNatural = _ref.compareNatural; + var compareAsc = compare; + + var compareDesc = function compareDesc(a, b) { + return -compare(a, b); + }; + /** + * Sort the items in a matrix. + * + * Syntax: + * + * math.sort(x) + * math.sort(x, compare) + * + * Examples: + * + * math.sort([5, 10, 1]) // returns [1, 5, 10] + * math.sort(['C', 'B', 'A', 'D'], math.compareNatural) + * // returns ['A', 'B', 'C', 'D'] + * + * function sortByLength (a, b) { + * return a.length - b.length + * } + * math.sort(['Langdon', 'Tom', 'Sara'], sortByLength) + * // returns ['Tom', 'Sara', 'Langdon'] + * + * See also: + * + * filter, forEach, map, compare, compareNatural + * + * @param {Matrix | Array} x A one dimensional matrix or array to sort + * @param {Function | 'asc' | 'desc' | 'natural'} [compare='asc'] + * An optional _comparator function or name. The function is called as + * `compare(a, b)`, and must return 1 when a > b, -1 when a < b, + * and 0 when a == b. + * @return {Matrix | Array} Returns the sorted matrix. + */ + + + return typed(sort_name, { + Array: function Array(x) { + _arrayIsVector(x); + + return x.sort(compareAsc); + }, + Matrix: function Matrix(x) { + _matrixIsVector(x); + + return matrix(x.toArray().sort(compareAsc), x.storage()); + }, + 'Array, function': function ArrayFunction(x, _comparator) { + _arrayIsVector(x); + + return x.sort(_comparator); + }, + 'Matrix, function': function MatrixFunction(x, _comparator) { + _matrixIsVector(x); + + return matrix(x.toArray().sort(_comparator), x.storage()); + }, + 'Array, string': function ArrayString(x, order) { + _arrayIsVector(x); + + return x.sort(_comparator(order)); + }, + 'Matrix, string': function MatrixString(x, order) { + _matrixIsVector(x); + + return matrix(x.toArray().sort(_comparator(order)), x.storage()); + } + }); + /** + * Get the comparator for given order ('asc', 'desc', 'natural') + * @param {'asc' | 'desc' | 'natural'} order + * @return {Function} Returns a _comparator function + */ + + function _comparator(order) { + if (order === 'asc') { + return compareAsc; + } else if (order === 'desc') { + return compareDesc; + } else if (order === 'natural') { + return compareNatural; + } else { + throw new Error('String "asc", "desc", or "natural" expected'); + } + } + /** + * Validate whether an array is one dimensional + * Throws an error when this is not the case + * @param {Array} array + * @private + */ + + + function _arrayIsVector(array) { + if (Object(utils_array["a" /* arraySize */])(array).length !== 1) { + throw new Error('One dimensional array expected'); + } + } + /** + * Validate whether a matrix is one dimensional + * Throws an error when this is not the case + * @param {Matrix} matrix + * @private + */ + + + function _matrixIsVector(matrix) { + if (matrix.size().length !== 1) { + throw new Error('One dimensional matrix expected'); + } + } +}); +// CONCATENATED MODULE: ./src/function/statistics/max.js + + + +var max_name = 'max'; +var max_dependencies = ['typed', 'larger']; +var createMax = /* #__PURE__ */Object(factory["a" /* factory */])(max_name, max_dependencies, function (_ref) { + var typed = _ref.typed, + larger = _ref.larger; + + /** + * Compute the maximum value of a matrix or a list with values. + * In case of a multi dimensional array, the maximum of the flattened array + * will be calculated. When `dim` is provided, the maximum over the selected + * dimension will be calculated. Parameter `dim` is zero-based. + * + * Syntax: + * + * math.max(a, b, c, ...) + * math.max(A) + * math.max(A, dim) + * + * Examples: + * + * math.max(2, 1, 4, 3) // returns 4 + * math.max([2, 1, 4, 3]) // returns 4 + * + * // maximum over a specified dimension (zero-based) + * math.max([[2, 5], [4, 3], [1, 7]], 0) // returns [4, 7] + * math.max([[2, 5], [4, 3]], [1, 7], 1) // returns [5, 4, 7] + * + * math.max(2.7, 7.1, -4.5, 2.0, 4.1) // returns 7.1 + * math.min(2.7, 7.1, -4.5, 2.0, 4.1) // returns -4.5 + * + * See also: + * + * mean, median, min, prod, std, sum, variance + * + * @param {... *} args A single matrix or or multiple scalar values + * @return {*} The maximum value + */ + return typed(max_name, { + // max([a, b, c, d, ...]) + 'Array | Matrix': _max, + // max([a, b, c, d, ...], dim) + 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) { + return reduce(array, dim.valueOf(), _largest); + }, + // max(a, b, c, d, ...) + '...': function _(args) { + if (containsCollections(args)) { + throw new TypeError('Scalar values expected in function max'); + } + + return _max(args); + } + }); + /** + * Return the largest of two values + * @param {*} x + * @param {*} y + * @returns {*} Returns x when x is largest, or y when y is largest + * @private + */ + + function _largest(x, y) { + try { + return larger(x, y) ? x : y; + } catch (err) { + throw improveErrorMessage(err, 'max', y); + } + } + /** + * Recursively calculate the maximum value in an n-dimensional array + * @param {Array} array + * @return {number} max + * @private + */ + + + function _max(array) { + var res; + deepForEach(array, function (value) { + try { + if (isNaN(value) && typeof value === 'number') { + res = NaN; + } else if (res === undefined || larger(value, res)) { + res = value; + } + } catch (err) { + throw improveErrorMessage(err, 'max', value); + } + }); + + if (res === undefined) { + throw new Error('Cannot calculate max of an empty array'); + } + + return res; + } +}); +// CONCATENATED MODULE: ./src/function/statistics/min.js + + + +var min_name = 'min'; +var min_dependencies = ['typed', 'smaller']; +var createMin = /* #__PURE__ */Object(factory["a" /* factory */])(min_name, min_dependencies, function (_ref) { + var typed = _ref.typed, + smaller = _ref.smaller; + + /** + * Compute the minimum value of a matrix or a list of values. + * In case of a multi dimensional array, the minimum of the flattened array + * will be calculated. When `dim` is provided, the minimum over the selected + * dimension will be calculated. Parameter `dim` is zero-based. + * + * Syntax: + * + * math.min(a, b, c, ...) + * math.min(A) + * math.min(A, dim) + * + * Examples: + * + * math.min(2, 1, 4, 3) // returns 1 + * math.min([2, 1, 4, 3]) // returns 1 + * + * // minimum over a specified dimension (zero-based) + * math.min([[2, 5], [4, 3], [1, 7]], 0) // returns [1, 3] + * math.min([[2, 5], [4, 3], [1, 7]], 1) // returns [2, 3, 1] + * + * math.max(2.7, 7.1, -4.5, 2.0, 4.1) // returns 7.1 + * math.min(2.7, 7.1, -4.5, 2.0, 4.1) // returns -4.5 + * + * See also: + * + * mean, median, max, prod, std, sum, variance + * + * @param {... *} args A single matrix or or multiple scalar values + * @return {*} The minimum value + */ + return typed(min_name, { + // min([a, b, c, d, ...]) + 'Array | Matrix': _min, + // min([a, b, c, d, ...], dim) + 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) { + return reduce(array, dim.valueOf(), _smallest); + }, + // min(a, b, c, d, ...) + '...': function _(args) { + if (containsCollections(args)) { + throw new TypeError('Scalar values expected in function min'); + } + + return _min(args); + } + }); + /** + * Return the smallest of two values + * @param {*} x + * @param {*} y + * @returns {*} Returns x when x is smallest, or y when y is smallest + * @private + */ + + function _smallest(x, y) { + try { + return smaller(x, y) ? x : y; + } catch (err) { + throw improveErrorMessage(err, 'min', y); + } + } + /** + * Recursively calculate the minimum value in an n-dimensional array + * @param {Array} array + * @return {number} min + * @private + */ + + + function _min(array) { + var min; + deepForEach(array, function (value) { + try { + if (isNaN(value) && typeof value === 'number') { + min = NaN; + } else if (min === undefined || smaller(value, min)) { + min = value; + } + } catch (err) { + throw improveErrorMessage(err, 'min', value); + } + }); + + if (min === undefined) { + throw new Error('Cannot calculate min of an empty array'); + } + + return min; + } +}); +// CONCATENATED MODULE: ./src/type/matrix/ImmutableDenseMatrix.js + + + +var ImmutableDenseMatrix_name = 'ImmutableDenseMatrix'; +var ImmutableDenseMatrix_dependencies = ['smaller', 'DenseMatrix']; +var createImmutableDenseMatrixClass = /* #__PURE__ */Object(factory["a" /* factory */])(ImmutableDenseMatrix_name, ImmutableDenseMatrix_dependencies, function (_ref) { + var smaller = _ref.smaller, + DenseMatrix = _ref.DenseMatrix; + + function ImmutableDenseMatrix(data, datatype) { + if (!(this instanceof ImmutableDenseMatrix)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (datatype && !Object(is["I" /* isString */])(datatype)) { + throw new Error('Invalid datatype: ' + datatype); + } + + if (Object(is["v" /* isMatrix */])(data) || Object(is["b" /* isArray */])(data)) { + // use DenseMatrix implementation + var matrix = new DenseMatrix(data, datatype); // internal structures + + this._data = matrix._data; + this._size = matrix._size; + this._datatype = matrix._datatype; + this._min = null; + this._max = null; + } else if (data && Object(is["b" /* isArray */])(data.data) && Object(is["b" /* isArray */])(data.size)) { + // initialize fields from JSON representation + this._data = data.data; + this._size = data.size; + this._datatype = data.datatype; + this._min = typeof data.min !== 'undefined' ? data.min : null; + this._max = typeof data.max !== 'undefined' ? data.max : null; + } else if (data) { + // unsupported type + throw new TypeError('Unsupported type of data (' + Object(is["M" /* typeOf */])(data) + ')'); + } else { + // nothing provided + this._data = []; + this._size = [0]; + this._datatype = datatype; + this._min = null; + this._max = null; + } + } + + ImmutableDenseMatrix.prototype = new DenseMatrix(); + /** + * Attach type information + */ + + ImmutableDenseMatrix.prototype.type = 'ImmutableDenseMatrix'; + ImmutableDenseMatrix.prototype.isImmutableDenseMatrix = true; + /** + * Get a subset of the matrix, or replace a subset of the matrix. + * + * Usage: + * const subset = matrix.subset(index) // retrieve subset + * const value = matrix.subset(index, replacement) // replace subset + * + * @param {Index} index + * @param {Array | ImmutableDenseMatrix | *} [replacement] + * @param {*} [defaultValue=0] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be filled with zeros. + */ + + ImmutableDenseMatrix.prototype.subset = function (index) { + switch (arguments.length) { + case 1: + { + // use base implementation + var m = DenseMatrix.prototype.subset.call(this, index); // check result is a matrix + + if (Object(is["v" /* isMatrix */])(m)) { + // return immutable matrix + return new ImmutableDenseMatrix({ + data: m._data, + size: m._size, + datatype: m._datatype + }); + } + + return m; + } + // intentional fall through + + case 2: + case 3: + throw new Error('Cannot invoke set subset on an Immutable Matrix instance'); + + default: + throw new SyntaxError('Wrong number of arguments'); + } + }; + /** + * Replace a single element in the matrix. + * @param {Number[]} index Zero-based index + * @param {*} value + * @param {*} [defaultValue] Default value, filled in on new entries when + * the matrix is resized. If not provided, + * new matrix elements will be left undefined. + * @return {ImmutableDenseMatrix} self + */ + + + ImmutableDenseMatrix.prototype.set = function () { + throw new Error('Cannot invoke set on an Immutable Matrix instance'); + }; + /** + * Resize the matrix to the given size. Returns a copy of the matrix when + * `copy=true`, otherwise return the matrix itself (resize in place). + * + * @param {Number[]} size The new size the matrix should have. + * @param {*} [defaultValue=0] Default value, filled in on new entries. + * If not provided, the matrix elements will + * be filled with zeros. + * @param {boolean} [copy] Return a resized copy of the matrix + * + * @return {Matrix} The resized matrix + */ + + + ImmutableDenseMatrix.prototype.resize = function () { + throw new Error('Cannot invoke resize on an Immutable Matrix instance'); + }; + /** + * Disallows reshaping in favor of immutability. + * + * @throws {Error} Operation not allowed + */ + + + ImmutableDenseMatrix.prototype.reshape = function () { + throw new Error('Cannot invoke reshape on an Immutable Matrix instance'); + }; + /** + * Create a clone of the matrix + * @return {ImmutableDenseMatrix} clone + */ + + + ImmutableDenseMatrix.prototype.clone = function () { + return new ImmutableDenseMatrix({ + data: Object(utils_object["a" /* clone */])(this._data), + size: Object(utils_object["a" /* clone */])(this._size), + datatype: this._datatype + }); + }; + /** + * Get a JSON representation of the matrix + * @returns {Object} + */ + + + ImmutableDenseMatrix.prototype.toJSON = function () { + return { + mathjs: 'ImmutableDenseMatrix', + data: this._data, + size: this._size, + datatype: this._datatype + }; + }; + /** + * Generate a matrix from a JSON object + * @param {Object} json An object structured like + * `{"mathjs": "ImmutableDenseMatrix", data: [], size: []}`, + * where mathjs is optional + * @returns {ImmutableDenseMatrix} + */ + + + ImmutableDenseMatrix.fromJSON = function (json) { + return new ImmutableDenseMatrix(json); + }; + /** + * Swap rows i and j in Matrix. + * + * @param {Number} i Matrix row index 1 + * @param {Number} j Matrix row index 2 + * + * @return {Matrix} The matrix reference + */ + + + ImmutableDenseMatrix.prototype.swapRows = function () { + throw new Error('Cannot invoke swapRows on an Immutable Matrix instance'); + }; + /** + * Calculate the minimum value in the set + * @return {Number | undefined} min + */ + + + ImmutableDenseMatrix.prototype.min = function () { + // check min has been calculated before + if (this._min === null) { + // minimum + var m = null; // compute min + + this.forEach(function (v) { + if (m === null || smaller(v, m)) { + m = v; + } + }); + this._min = m !== null ? m : undefined; + } + + return this._min; + }; + /** + * Calculate the maximum value in the set + * @return {Number | undefined} max + */ + + + ImmutableDenseMatrix.prototype.max = function () { + // check max has been calculated before + if (this._max === null) { + // maximum + var m = null; // compute max + + this.forEach(function (v) { + if (m === null || smaller(m, v)) { + m = v; + } + }); + this._max = m !== null ? m : undefined; + } + + return this._max; + }; + + return ImmutableDenseMatrix; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/matrix/MatrixIndex.js + + + + +var MatrixIndex_name = 'Index'; +var MatrixIndex_dependencies = ['ImmutableDenseMatrix']; +var createIndexClass = /* #__PURE__ */Object(factory["a" /* factory */])(MatrixIndex_name, MatrixIndex_dependencies, function (_ref) { + var ImmutableDenseMatrix = _ref.ImmutableDenseMatrix; + + /** + * Create an index. An Index can store ranges and sets for multiple dimensions. + * Matrix.get, Matrix.set, and math.subset accept an Index as input. + * + * Usage: + * const index = new Index(range1, range2, matrix1, array1, ...) + * + * Where each parameter can be any of: + * A number + * A string (containing a name of an object property) + * An instance of Range + * An Array with the Set values + * A Matrix with the Set values + * + * The parameters start, end, and step must be integer numbers. + * + * @class Index + * @Constructor Index + * @param {...*} ranges + */ + function Index(ranges) { + if (!(this instanceof Index)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this._dimensions = []; + this._isScalar = true; + + for (var i = 0, ii = arguments.length; i < ii; i++) { + var arg = arguments[i]; + + if (Object(is["D" /* isRange */])(arg)) { + this._dimensions.push(arg); + + this._isScalar = false; + } else if (Array.isArray(arg) || Object(is["v" /* isMatrix */])(arg)) { + // create matrix + var m = _createImmutableMatrix(arg.valueOf()); + + this._dimensions.push(m); // size + + + var size = m.size(); // scalar + + if (size.length !== 1 || size[0] !== 1) { + this._isScalar = false; + } + } else if (typeof arg === 'number') { + this._dimensions.push(_createImmutableMatrix([arg])); + } else if (typeof arg === 'string') { + // object property (arguments.count should be 1) + this._dimensions.push(arg); + } else { + throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range'); + } // TODO: implement support for wildcard '*' + + } + } + /** + * Attach type information + */ + + + Index.prototype.type = 'Index'; + Index.prototype.isIndex = true; + + function _createImmutableMatrix(arg) { + // loop array elements + for (var i = 0, l = arg.length; i < l; i++) { + if (typeof arg[i] !== 'number' || !Object(utils_number["i" /* isInteger */])(arg[i])) { + throw new TypeError('Index parameters must be positive integer numbers'); + } + } // create matrix + + + return new ImmutableDenseMatrix(arg); + } + /** + * Create a clone of the index + * @memberof Index + * @return {Index} clone + */ + + + Index.prototype.clone = function () { + var index = new Index(); + index._dimensions = Object(utils_object["a" /* clone */])(this._dimensions); + index._isScalar = this._isScalar; + return index; + }; + /** + * Create an index from an array with ranges/numbers + * @memberof Index + * @param {Array.} ranges + * @return {Index} index + * @private + */ + + + Index.create = function (ranges) { + var index = new Index(); + Index.apply(index, ranges); + return index; + }; + /** + * Retrieve the size of the index, the number of elements for each dimension. + * @memberof Index + * @returns {number[]} size + */ + + + Index.prototype.size = function () { + var size = []; + + for (var i = 0, ii = this._dimensions.length; i < ii; i++) { + var d = this._dimensions[i]; + size[i] = typeof d === 'string' ? 1 : d.size()[0]; + } + + return size; + }; + /** + * Get the maximum value for each of the indexes ranges. + * @memberof Index + * @returns {number[]} max + */ + + + Index.prototype.max = function () { + var values = []; + + for (var i = 0, ii = this._dimensions.length; i < ii; i++) { + var range = this._dimensions[i]; + values[i] = typeof range === 'string' ? range : range.max(); + } + + return values; + }; + /** + * Get the minimum value for each of the indexes ranges. + * @memberof Index + * @returns {number[]} min + */ + + + Index.prototype.min = function () { + var values = []; + + for (var i = 0, ii = this._dimensions.length; i < ii; i++) { + var range = this._dimensions[i]; + values[i] = typeof range === 'string' ? range : range.min(); + } + + return values; + }; + /** + * Loop over each of the ranges of the index + * @memberof Index + * @param {Function} callback Called for each range with a Range as first + * argument, the dimension as second, and the + * index object as third. + */ + + + Index.prototype.forEach = function (callback) { + for (var i = 0, ii = this._dimensions.length; i < ii; i++) { + callback(this._dimensions[i], i, this); + } + }; + /** + * Retrieve the dimension for the given index + * @memberof Index + * @param {Number} dim Number of the dimension + * @returns {Range | null} range + */ + + + Index.prototype.dimension = function (dim) { + return this._dimensions[dim] || null; + }; + /** + * Test whether this index contains an object property + * @returns {boolean} Returns true if the index is an object property + */ + + + Index.prototype.isObjectProperty = function () { + return this._dimensions.length === 1 && typeof this._dimensions[0] === 'string'; + }; + /** + * Returns the object property name when the Index holds a single object property, + * else returns null + * @returns {string | null} + */ + + + Index.prototype.getObjectProperty = function () { + return this.isObjectProperty() ? this._dimensions[0] : null; + }; + /** + * Test whether this index contains only a single value. + * + * This is the case when the index is created with only scalar values as ranges, + * not for ranges resolving into a single value. + * @memberof Index + * @return {boolean} isScalar + */ + + + Index.prototype.isScalar = function () { + return this._isScalar; + }; + /** + * Expand the Index into an array. + * For example new Index([0,3], [2,7]) returns [[0,1,2], [2,3,4,5,6]] + * @memberof Index + * @returns {Array} array + */ + + + Index.prototype.toArray = function () { + var array = []; + + for (var i = 0, ii = this._dimensions.length; i < ii; i++) { + var dimension = this._dimensions[i]; + array.push(typeof dimension === 'string' ? dimension : dimension.toArray()); + } + + return array; + }; + /** + * Get the primitive value of the Index, a two dimensional array. + * Equivalent to Index.toArray(). + * @memberof Index + * @returns {Array} array + */ + + + Index.prototype.valueOf = Index.prototype.toArray; + /** + * Get the string representation of the index, for example '[2:6]' or '[0:2:10, 4:7, [1,2,3]]' + * @memberof Index + * @returns {String} str + */ + + Index.prototype.toString = function () { + var strings = []; + + for (var i = 0, ii = this._dimensions.length; i < ii; i++) { + var dimension = this._dimensions[i]; + + if (typeof dimension === 'string') { + strings.push(JSON.stringify(dimension)); + } else { + strings.push(dimension.toString()); + } + } + + return '[' + strings.join(', ') + ']'; + }; + /** + * Get a JSON representation of the Index + * @memberof Index + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "Index", "ranges": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}` + */ + + + Index.prototype.toJSON = function () { + return { + mathjs: 'Index', + dimensions: this._dimensions + }; + }; + /** + * Instantiate an Index from a JSON object + * @memberof Index + * @param {Object} json A JSON object structured as: + * `{"mathjs": "Index", "dimensions": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}` + * @return {Index} + */ + + + Index.fromJSON = function (json) { + return Index.create(json.dimensions); + }; + + return Index; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/matrix/FibonacciHeap.js + +var FibonacciHeap_name = 'FibonacciHeap'; +var FibonacciHeap_dependencies = ['smaller', 'larger']; +var createFibonacciHeapClass = /* #__PURE__ */Object(factory["a" /* factory */])(FibonacciHeap_name, FibonacciHeap_dependencies, function (_ref) { + var smaller = _ref.smaller, + larger = _ref.larger; + var oneOverLogPhi = 1.0 / Math.log((1.0 + Math.sqrt(5.0)) / 2.0); + /** + * Fibonacci Heap implementation, used interally for Matrix math. + * @class FibonacciHeap + * @constructor FibonacciHeap + */ + + function FibonacciHeap() { + if (!(this instanceof FibonacciHeap)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // initialize fields + + + this._minimum = null; + this._size = 0; + } + /** + * Attach type information + */ + + + FibonacciHeap.prototype.type = 'FibonacciHeap'; + FibonacciHeap.prototype.isFibonacciHeap = true; + /** + * Inserts a new data element into the heap. No heap consolidation is + * performed at this time, the new node is simply inserted into the root + * list of this heap. Running time: O(1) actual. + * @memberof FibonacciHeap + */ + + FibonacciHeap.prototype.insert = function (key, value) { + // create node + var node = { + key: key, + value: value, + degree: 0 + }; // check we have a node in the minimum + + if (this._minimum) { + // minimum node + var minimum = this._minimum; // update left & right of node + + node.left = minimum; + node.right = minimum.right; + minimum.right = node; + node.right.left = node; // update minimum node in heap if needed + + if (smaller(key, minimum.key)) { + // node has a smaller key, use it as minimum + this._minimum = node; + } + } else { + // set left & right + node.left = node; + node.right = node; // this is the first node + + this._minimum = node; + } // increment number of nodes in heap + + + this._size++; // return node + + return node; + }; + /** + * Returns the number of nodes in heap. Running time: O(1) actual. + * @memberof FibonacciHeap + */ + + + FibonacciHeap.prototype.size = function () { + return this._size; + }; + /** + * Removes all elements from this heap. + * @memberof FibonacciHeap + */ + + + FibonacciHeap.prototype.clear = function () { + this._minimum = null; + this._size = 0; + }; + /** + * Returns true if the heap is empty, otherwise false. + * @memberof FibonacciHeap + */ + + + FibonacciHeap.prototype.isEmpty = function () { + return this._size === 0; + }; + /** + * Extracts the node with minimum key from heap. Amortized running + * time: O(log n). + * @memberof FibonacciHeap + */ + + + FibonacciHeap.prototype.extractMinimum = function () { + // node to remove + var node = this._minimum; // check we have a minimum + + if (node === null) { + return node; + } // current minimum + + + var minimum = this._minimum; // get number of children + + var numberOfChildren = node.degree; // pointer to the first child + + var x = node.child; // for each child of node do... + + while (numberOfChildren > 0) { + // store node in right side + var tempRight = x.right; // remove x from child list + + x.left.right = x.right; + x.right.left = x.left; // add x to root list of heap + + x.left = minimum; + x.right = minimum.right; + minimum.right = x; + x.right.left = x; // set Parent[x] to null + + x.parent = null; + x = tempRight; + numberOfChildren--; + } // remove node from root list of heap + + + node.left.right = node.right; + node.right.left = node.left; // update minimum + + if (node === node.right) { + // empty + minimum = null; + } else { + // update minimum + minimum = node.right; // we need to update the pointer to the root with minimum key + + minimum = _findMinimumNode(minimum, this._size); + } // decrement size of heap + + + this._size--; // update minimum + + this._minimum = minimum; // return node + + return node; + }; + /** + * Removes a node from the heap given the reference to the node. The trees + * in the heap will be consolidated, if necessary. This operation may fail + * to remove the correct element if there are nodes with key value -Infinity. + * Running time: O(log n) amortized. + * @memberof FibonacciHeap + */ + + + FibonacciHeap.prototype.remove = function (node) { + // decrease key value + this._minimum = _decreaseKey(this._minimum, node, -1); // remove the smallest + + this.extractMinimum(); + }; + /** + * Decreases the key value for a heap node, given the new value to take on. + * The structure of the heap may be changed and will not be consolidated. + * Running time: O(1) amortized. + * @memberof FibonacciHeap + */ + + + function _decreaseKey(minimum, node, key) { + // set node key + node.key = key; // get parent node + + var parent = node.parent; + + if (parent && smaller(node.key, parent.key)) { + // remove node from parent + _cut(minimum, node, parent); // remove all nodes from parent to the root parent + + + _cascadingCut(minimum, parent); + } // update minimum node if needed + + + if (smaller(node.key, minimum.key)) { + minimum = node; + } // return minimum + + + return minimum; + } + /** + * The reverse of the link operation: removes node from the child list of parent. + * This method assumes that min is non-null. Running time: O(1). + * @memberof FibonacciHeap + */ + + + function _cut(minimum, node, parent) { + // remove node from parent children and decrement Degree[parent] + node.left.right = node.right; + node.right.left = node.left; + parent.degree--; // reset y.child if necessary + + if (parent.child === node) { + parent.child = node.right; + } // remove child if degree is 0 + + + if (parent.degree === 0) { + parent.child = null; + } // add node to root list of heap + + + node.left = minimum; + node.right = minimum.right; + minimum.right = node; + node.right.left = node; // set parent[node] to null + + node.parent = null; // set mark[node] to false + + node.mark = false; + } + /** + * Performs a cascading cut operation. This cuts node from its parent and then + * does the same for its parent, and so on up the tree. + * Running time: O(log n); O(1) excluding the recursion. + * @memberof FibonacciHeap + */ + + + function _cascadingCut(minimum, node) { + // store parent node + var parent = node.parent; // if there's a parent... + + if (!parent) { + return; + } // if node is unmarked, set it marked + + + if (!node.mark) { + node.mark = true; + } else { + // it's marked, cut it from parent + _cut(minimum, node, parent); // cut its parent as well + + + _cascadingCut(parent); + } + } + /** + * Make the first node a child of the second one. Running time: O(1) actual. + * @memberof FibonacciHeap + */ + + + var _linkNodes = function _linkNodes(node, parent) { + // remove node from root list of heap + node.left.right = node.right; + node.right.left = node.left; // make node a Child of parent + + node.parent = parent; + + if (!parent.child) { + parent.child = node; + node.right = node; + node.left = node; + } else { + node.left = parent.child; + node.right = parent.child.right; + parent.child.right = node; + node.right.left = node; + } // increase degree[parent] + + + parent.degree++; // set mark[node] false + + node.mark = false; + }; + + function _findMinimumNode(minimum, size) { + // to find trees of the same degree efficiently we use an array of length O(log n) in which we keep a pointer to one root of each degree + var arraySize = Math.floor(Math.log(size) * oneOverLogPhi) + 1; // create list with initial capacity + + var array = new Array(arraySize); // find the number of root nodes. + + var numRoots = 0; + var x = minimum; + + if (x) { + numRoots++; + x = x.right; + + while (x !== minimum) { + numRoots++; + x = x.right; + } + } // vars + + + var y; // For each node in root list do... + + while (numRoots > 0) { + // access this node's degree.. + var d = x.degree; // get next node + + var next = x.right; // check if there is a node already in array with the same degree + + while (true) { + // get node with the same degree is any + y = array[d]; + + if (!y) { + break; + } // make one node with the same degree a child of the other, do this based on the key value. + + + if (larger(x.key, y.key)) { + var temp = y; + y = x; + x = temp; + } // make y a child of x + + + _linkNodes(y, x); // we have handled this degree, go to next one. + + + array[d] = null; + d++; + } // save this node for later when we might encounter another of the same degree. + + + array[d] = x; // move forward through list. + + x = next; + numRoots--; + } // Set min to null (effectively losing the root list) and reconstruct the root list from the array entries in array[]. + + + minimum = null; // loop nodes in array + + for (var i = 0; i < arraySize; i++) { + // get current node + y = array[i]; + + if (!y) { + continue; + } // check if we have a linked list + + + if (minimum) { + // First remove node from root list. + y.left.right = y.right; + y.right.left = y.left; // now add to root list, again. + + y.left = minimum; + y.right = minimum.right; + minimum.right = y; + y.right.left = y; // check if this is a new min. + + if (smaller(y.key, minimum.key)) { + minimum = y; + } + } else { + minimum = y; + } + } + + return minimum; + } + + return FibonacciHeap; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/matrix/Spa.js + +var Spa_name = 'Spa'; +var Spa_dependencies = ['addScalar', 'equalScalar', 'FibonacciHeap']; +var createSpaClass = /* #__PURE__ */Object(factory["a" /* factory */])(Spa_name, Spa_dependencies, function (_ref) { + var addScalar = _ref.addScalar, + equalScalar = _ref.equalScalar, + FibonacciHeap = _ref.FibonacciHeap; + + /** + * An ordered Sparse Accumulator is a representation for a sparse vector that includes a dense array + * of the vector elements and an ordered list of non-zero elements. + */ + function Spa() { + if (!(this instanceof Spa)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // allocate vector, TODO use typed arrays + + + this._values = []; + this._heap = new FibonacciHeap(); + } + /** + * Attach type information + */ + + + Spa.prototype.type = 'Spa'; + Spa.prototype.isSpa = true; + /** + * Set the value for index i. + * + * @param {number} i The index + * @param {number | BigNumber | Complex} The value at index i + */ + + Spa.prototype.set = function (i, v) { + // check we have a value @ i + if (!this._values[i]) { + // insert in heap + var node = this._heap.insert(i, v); // set the value @ i + + + this._values[i] = node; + } else { + // update the value @ i + this._values[i].value = v; + } + }; + + Spa.prototype.get = function (i) { + var node = this._values[i]; + + if (node) { + return node.value; + } + + return 0; + }; + + Spa.prototype.accumulate = function (i, v) { + // node @ i + var node = this._values[i]; + + if (!node) { + // insert in heap + node = this._heap.insert(i, v); // initialize value + + this._values[i] = node; + } else { + // accumulate value + node.value = addScalar(node.value, v); + } + }; + + Spa.prototype.forEach = function (from, to, callback) { + // references + var heap = this._heap; + var values = this._values; // nodes + + var nodes = []; // node with minimum key, save it + + var node = heap.extractMinimum(); + + if (node) { + nodes.push(node); + } // extract nodes from heap (ordered) + + + while (node && node.key <= to) { + // check it is in range + if (node.key >= from) { + // check value is not zero + if (!equalScalar(node.value, 0)) { + // invoke callback + callback(node.key, node.value, this); + } + } // extract next node, save it + + + node = heap.extractMinimum(); + + if (node) { + nodes.push(node); + } + } // reinsert all nodes in heap + + + for (var i = 0; i < nodes.length; i++) { + // current node + var n = nodes[i]; // insert node in heap + + node = heap.insert(n.key, n.value); // update values + + values[node.key] = node; + } + }; + + Spa.prototype.swap = function (i, j) { + // node @ i and j + var nodei = this._values[i]; + var nodej = this._values[j]; // check we need to insert indeces + + if (!nodei && nodej) { + // insert in heap + nodei = this._heap.insert(i, nodej.value); // remove from heap + + this._heap.remove(nodej); // set values + + + this._values[i] = nodei; + this._values[j] = undefined; + } else if (nodei && !nodej) { + // insert in heap + nodej = this._heap.insert(j, nodei.value); // remove from heap + + this._heap.remove(nodei); // set values + + + this._values[j] = nodej; + this._values[i] = undefined; + } else if (nodei && nodej) { + // swap values + var v = nodei.value; + nodei.value = nodej.value; + nodej.value = v; + } + }; + + return Spa; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/utils/bignumber/constants.js + +/** + * Calculate BigNumber e + * @param {function} BigNumber BigNumber constructor + * @returns {BigNumber} Returns e + */ + +var createBigNumberE = memoize(function (BigNumber) { + return new BigNumber(1).exp(); +}, hasher); +/** + * Calculate BigNumber golden ratio, phi = (1+sqrt(5))/2 + * @param {function} BigNumber BigNumber constructor + * @returns {BigNumber} Returns phi + */ + +var createBigNumberPhi = memoize(function (BigNumber) { + return new BigNumber(1).plus(new BigNumber(5).sqrt()).div(2); +}, hasher); +/** + * Calculate BigNumber pi. + * @param {function} BigNumber BigNumber constructor + * @returns {BigNumber} Returns pi + */ + +var createBigNumberPi = memoize(function (BigNumber) { + return BigNumber.acos(-1); +}, hasher); +/** + * Calculate BigNumber tau, tau = 2 * pi + * @param {function} BigNumber BigNumber constructor + * @returns {BigNumber} Returns tau + */ + +var createBigNumberTau = memoize(function (BigNumber) { + return createBigNumberPi(BigNumber).times(2); +}, hasher); +/** + * Create a hash for a BigNumber constructor function. The created has is + * the configured precision + * @param {Array} args Supposed to contain a single entry with + * a BigNumber constructor + * @return {number} precision + * @private + */ + +function hasher(args) { + return args[0].precision; +} +// CONCATENATED MODULE: ./src/type/unit/Unit.js +function Unit_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { Unit_typeof = function _typeof(obj) { return typeof obj; }; } else { Unit_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return Unit_typeof(obj); } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + + + + + + +var Unit_name = 'Unit'; +var Unit_dependencies = ['?on', 'config', 'addScalar', 'subtract', 'multiplyScalar', 'divideScalar', 'pow', 'abs', 'fix', 'round', 'equal', 'isNumeric', 'format', 'number', 'Complex', 'BigNumber', 'Fraction']; +var createUnitClass = /* #__PURE__ */Object(factory["a" /* factory */])(Unit_name, Unit_dependencies, function (_ref) { + var on = _ref.on, + config = _ref.config, + addScalar = _ref.addScalar, + subtract = _ref.subtract, + multiplyScalar = _ref.multiplyScalar, + divideScalar = _ref.divideScalar, + pow = _ref.pow, + abs = _ref.abs, + fix = _ref.fix, + round = _ref.round, + equal = _ref.equal, + isNumeric = _ref.isNumeric, + format = _ref.format, + number = _ref.number, + Complex = _ref.Complex, + _BigNumber = _ref.BigNumber, + _Fraction = _ref.Fraction; + var toNumber = number; + /** + * A unit can be constructed in the following ways: + * + * const a = new Unit(value, name) + * const b = new Unit(null, name) + * const c = Unit.parse(str) + * + * Example usage: + * + * const a = new Unit(5, 'cm') // 50 mm + * const b = Unit.parse('23 kg') // 23 kg + * const c = math.in(a, new Unit(null, 'm') // 0.05 m + * const d = new Unit(9.81, "m/s^2") // 9.81 m/s^2 + * + * @class Unit + * @constructor Unit + * @param {number | BigNumber | Fraction | Complex | boolean} [value] A value like 5.2 + * @param {string} [name] A unit name like "cm" or "inch", or a derived unit of the form: "u1[^ex1] [u2[^ex2] ...] [/ u3[^ex3] [u4[^ex4]]]", such as "kg m^2/s^2", where each unit appearing after the forward slash is taken to be in the denominator. "kg m^2 s^-2" is a synonym and is also acceptable. Any of the units can include a prefix. + */ + + function Unit(value, name) { + if (!(this instanceof Unit)) { + throw new Error('Constructor must be called with the new operator'); + } + + if (!(value === null || value === undefined || isNumeric(value) || Object(is["j" /* isComplex */])(value))) { + throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined'); + } + + if (name !== undefined && (typeof name !== 'string' || name === '')) { + throw new TypeError('Second parameter in Unit constructor must be a string'); + } + + if (name !== undefined) { + var u = Unit.parse(name); + this.units = u.units; + this.dimensions = u.dimensions; + } else { + this.units = [{ + unit: UNIT_NONE, + prefix: PREFIXES.NONE, + // link to a list with supported prefixes + power: 0 + }]; + this.dimensions = []; + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + this.dimensions[i] = 0; + } + } + + this.value = value !== undefined && value !== null ? this._normalize(value) : null; + this.fixPrefix = false; // if true, function format will not search for the + // best prefix but leave it as initially provided. + // fixPrefix is set true by the method Unit.to + // The justification behind this is that if the constructor is explicitly called, + // the caller wishes the units to be returned exactly as he supplied. + + this.skipAutomaticSimplification = true; + } + /** + * Attach type information + */ + + + Unit.prototype.type = 'Unit'; + Unit.prototype.isUnit = true; // private variables and functions for the Unit parser + + var text, index, c; + + function skipWhitespace() { + while (c === ' ' || c === '\t') { + next(); + } + } + + function isDigitDot(c) { + return c >= '0' && c <= '9' || c === '.'; + } + + function isDigit(c) { + return c >= '0' && c <= '9'; + } + + function next() { + index++; + c = text.charAt(index); + } + + function revert(oldIndex) { + index = oldIndex; + c = text.charAt(index); + } + + function parseNumber() { + var number = ''; + var oldIndex = index; + + if (c === '+') { + next(); + } else if (c === '-') { + number += c; + next(); + } + + if (!isDigitDot(c)) { + // a + or - must be followed by a digit + revert(oldIndex); + return null; + } // get number, can have a single dot + + + if (c === '.') { + number += c; + next(); + + if (!isDigit(c)) { + // this is no legal number, it is just a dot + revert(oldIndex); + return null; + } + } else { + while (isDigit(c)) { + number += c; + next(); + } + + if (c === '.') { + number += c; + next(); + } + } + + while (isDigit(c)) { + number += c; + next(); + } // check for exponential notation like "2.3e-4" or "1.23e50" + + + if (c === 'E' || c === 'e') { + // The grammar branches here. This could either be part of an exponent or the start of a unit that begins with the letter e, such as "4exabytes" + var tentativeNumber = ''; + var tentativeIndex = index; + tentativeNumber += c; + next(); + + if (c === '+' || c === '-') { + tentativeNumber += c; + next(); + } // Scientific notation MUST be followed by an exponent (otherwise we assume it is not scientific notation) + + + if (!isDigit(c)) { + // The e or E must belong to something else, so return the number without the e or E. + revert(tentativeIndex); + return number; + } // We can now safely say that this is scientific notation. + + + number = number + tentativeNumber; + + while (isDigit(c)) { + number += c; + next(); + } + } + + return number; + } + + function parseUnit() { + var unitName = ''; // Alphanumeric characters only; matches [a-zA-Z0-9] + + var code = text.charCodeAt(index); + + while (code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122) { + unitName += c; + next(); + code = text.charCodeAt(index); + } // Must begin with [a-zA-Z] + + + code = unitName.charCodeAt(0); + + if (code >= 65 && code <= 90 || code >= 97 && code <= 122) { + return unitName || null; + } else { + return null; + } + } + + function parseCharacter(toFind) { + if (c === toFind) { + next(); + return toFind; + } else { + return null; + } + } + /** + * Parse a string into a unit. The value of the unit is parsed as number, + * BigNumber, or Fraction depending on the math.js config setting `number`. + * + * Throws an exception if the provided string does not contain a valid unit or + * cannot be parsed. + * @memberof Unit + * @param {string} str A string like "5.2 inch", "4e2 cm/s^2" + * @return {Unit} unit + */ + + + Unit.parse = function (str, options) { + options = options || {}; + text = str; + index = -1; + c = ''; + + if (typeof text !== 'string') { + throw new TypeError('Invalid argument in Unit.parse, string expected'); + } + + var unit = new Unit(); + unit.units = []; + var powerMultiplierCurrent = 1; + var expectingUnit = false; // A unit should follow this pattern: + // [number] ...[ [*/] unit[^number] ] + // unit[^number] ... [ [*/] unit[^number] ] + // Rules: + // number is any floating point number. + // unit is any alphanumeric string beginning with an alpha. Units with names like e3 should be avoided because they look like the exponent of a floating point number! + // The string may optionally begin with a number. + // Each unit may optionally be followed by ^number. + // Whitespace or a forward slash is recommended between consecutive units, although the following technically is parseable: + // 2m^2kg/s^2 + // it is not good form. If a unit starts with e, then it could be confused as a floating point number: + // 4erg + + next(); + skipWhitespace(); // Optional number at the start of the string + + var valueStr = parseNumber(); + var value = null; + + if (valueStr) { + if (config.number === 'BigNumber') { + value = new _BigNumber(valueStr); + } else if (config.number === 'Fraction') { + try { + // not all numbers can be turned in Fractions, for example very small numbers not + value = new _Fraction(valueStr); + } catch (err) { + value = parseFloat(valueStr); + } + } else { + // number + value = parseFloat(valueStr); + } + + skipWhitespace(); // Whitespace is not required here + // handle multiplication or division right after the value, like '1/s' + + if (parseCharacter('*')) { + powerMultiplierCurrent = 1; + expectingUnit = true; + } else if (parseCharacter('/')) { + powerMultiplierCurrent = -1; + expectingUnit = true; + } + } // Stack to keep track of powerMultipliers applied to each parentheses group + + + var powerMultiplierStack = []; // Running product of all elements in powerMultiplierStack + + var powerMultiplierStackProduct = 1; + + while (true) { + skipWhitespace(); // Check for and consume opening parentheses, pushing powerMultiplierCurrent to the stack + // A '(' will always appear directly before a unit. + + while (c === '(') { + powerMultiplierStack.push(powerMultiplierCurrent); + powerMultiplierStackProduct *= powerMultiplierCurrent; + powerMultiplierCurrent = 1; + next(); + skipWhitespace(); + } // Is there something here? + + + var uStr = void 0; + + if (c) { + var oldC = c; + uStr = parseUnit(); + + if (uStr === null) { + throw new SyntaxError('Unexpected "' + oldC + '" in "' + text + '" at index ' + index.toString()); + } + } else { + // End of input. + break; + } // Verify the unit exists and get the prefix (if any) + + + var res = _findUnit(uStr); + + if (res === null) { + // Unit not found. + throw new SyntaxError('Unit "' + uStr + '" not found.'); + } + + var power = powerMultiplierCurrent * powerMultiplierStackProduct; // Is there a "^ number"? + + skipWhitespace(); + + if (parseCharacter('^')) { + skipWhitespace(); + var p = parseNumber(); + + if (p === null) { + // No valid number found for the power! + throw new SyntaxError('In "' + str + '", "^" must be followed by a floating-point number'); + } + + power *= p; + } // Add the unit to the list + + + unit.units.push({ + unit: res.unit, + prefix: res.prefix, + power: power + }); + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + unit.dimensions[i] += (res.unit.dimensions[i] || 0) * power; + } // Check for and consume closing parentheses, popping from the stack. + // A ')' will always follow a unit. + + + skipWhitespace(); + + while (c === ')') { + if (powerMultiplierStack.length === 0) { + throw new SyntaxError('Unmatched ")" in "' + text + '" at index ' + index.toString()); + } + + powerMultiplierStackProduct /= powerMultiplierStack.pop(); + next(); + skipWhitespace(); + } // "*" and "/" should mean we are expecting something to come next. + // Is there a forward slash? If so, negate powerMultiplierCurrent. The next unit or paren group is in the denominator. + + + expectingUnit = false; + + if (parseCharacter('*')) { + // explicit multiplication + powerMultiplierCurrent = 1; + expectingUnit = true; + } else if (parseCharacter('/')) { + // division + powerMultiplierCurrent = -1; + expectingUnit = true; + } else { + // implicit multiplication + powerMultiplierCurrent = 1; + } // Replace the unit into the auto unit system + + + if (res.unit.base) { + var baseDim = res.unit.base.key; + UNIT_SYSTEMS.auto[baseDim] = { + unit: res.unit, + prefix: res.prefix + }; + } + } // Has the string been entirely consumed? + + + skipWhitespace(); + + if (c) { + throw new SyntaxError('Could not parse: "' + str + '"'); + } // Is there a trailing slash? + + + if (expectingUnit) { + throw new SyntaxError('Trailing characters: "' + str + '"'); + } // Is the parentheses stack empty? + + + if (powerMultiplierStack.length !== 0) { + throw new SyntaxError('Unmatched "(" in "' + text + '"'); + } // Are there any units at all? + + + if (unit.units.length === 0 && !options.allowNoUnits) { + throw new SyntaxError('"' + str + '" contains no units'); + } + + unit.value = value !== undefined ? unit._normalize(value) : null; + return unit; + }; + /** + * create a copy of this unit + * @memberof Unit + * @return {Unit} Returns a cloned version of the unit + */ + + + Unit.prototype.clone = function () { + var unit = new Unit(); + unit.fixPrefix = this.fixPrefix; + unit.skipAutomaticSimplification = this.skipAutomaticSimplification; + unit.value = Object(utils_object["a" /* clone */])(this.value); + unit.dimensions = this.dimensions.slice(0); + unit.units = []; + + for (var i = 0; i < this.units.length; i++) { + unit.units[i] = {}; + + for (var p in this.units[i]) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.units[i], p)) { + unit.units[i][p] = this.units[i][p]; + } + } + } + + return unit; + }; + /** + * Return whether the unit is derived (such as m/s, or cm^2, but not N) + * @memberof Unit + * @return {boolean} True if the unit is derived + */ + + + Unit.prototype._isDerived = function () { + if (this.units.length === 0) { + return false; + } + + return this.units.length > 1 || Math.abs(this.units[0].power - 1.0) > 1e-15; + }; + /** + * Normalize a value, based on its currently set unit(s) + * @memberof Unit + * @param {number | BigNumber | Fraction | boolean} value + * @return {number | BigNumber | Fraction | boolean} normalized value + * @private + */ + + + Unit.prototype._normalize = function (value) { + var unitValue, unitOffset, unitPower, unitPrefixValue; + var convert; + + if (value === null || value === undefined || this.units.length === 0) { + return value; + } else if (this._isDerived()) { + // This is a derived unit, so do not apply offsets. + // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset. + var res = value; + convert = Unit._getNumberConverter(Object(is["M" /* typeOf */])(value)); // convert to Fraction or BigNumber if needed + + for (var i = 0; i < this.units.length; i++) { + unitValue = convert(this.units[i].unit.value); + unitPrefixValue = convert(this.units[i].prefix.value); + unitPower = convert(this.units[i].power); + res = multiplyScalar(res, pow(multiplyScalar(unitValue, unitPrefixValue), unitPower)); + } + + return res; + } else { + // This is a single unit of power 1, like kg or degC + convert = Unit._getNumberConverter(Object(is["M" /* typeOf */])(value)); // convert to Fraction or BigNumber if needed + + unitValue = convert(this.units[0].unit.value); + unitOffset = convert(this.units[0].unit.offset); + unitPrefixValue = convert(this.units[0].prefix.value); + return multiplyScalar(addScalar(value, unitOffset), multiplyScalar(unitValue, unitPrefixValue)); + } + }; + /** + * Denormalize a value, based on its currently set unit(s) + * @memberof Unit + * @param {number} value + * @param {number} [prefixValue] Optional prefix value to be used (ignored if this is a derived unit) + * @return {number} denormalized value + * @private + */ + + + Unit.prototype._denormalize = function (value, prefixValue) { + var unitValue, unitOffset, unitPower, unitPrefixValue; + var convert; + + if (value === null || value === undefined || this.units.length === 0) { + return value; + } else if (this._isDerived()) { + // This is a derived unit, so do not apply offsets. + // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset. + // Also, prefixValue is ignored--but we will still use the prefix value stored in each unit, since kg is usually preferable to g unless the user decides otherwise. + var res = value; + convert = Unit._getNumberConverter(Object(is["M" /* typeOf */])(value)); // convert to Fraction or BigNumber if needed + + for (var i = 0; i < this.units.length; i++) { + unitValue = convert(this.units[i].unit.value); + unitPrefixValue = convert(this.units[i].prefix.value); + unitPower = convert(this.units[i].power); + res = divideScalar(res, pow(multiplyScalar(unitValue, unitPrefixValue), unitPower)); + } + + return res; + } else { + // This is a single unit of power 1, like kg or degC + convert = Unit._getNumberConverter(Object(is["M" /* typeOf */])(value)); // convert to Fraction or BigNumber if needed + + unitValue = convert(this.units[0].unit.value); + unitPrefixValue = convert(this.units[0].prefix.value); + unitOffset = convert(this.units[0].unit.offset); + + if (prefixValue === undefined || prefixValue === null) { + return subtract(divideScalar(divideScalar(value, unitValue), unitPrefixValue), unitOffset); + } else { + return subtract(divideScalar(divideScalar(value, unitValue), prefixValue), unitOffset); + } + } + }; + /** + * Find a unit from a string + * @memberof Unit + * @param {string} str A string like 'cm' or 'inch' + * @returns {Object | null} result When found, an object with fields unit and + * prefix is returned. Else, null is returned. + * @private + */ + + + function _findUnit(str) { + // First, match units names exactly. For example, a user could define 'mm' as 10^-4 m, which is silly, but then we would want 'mm' to match the user-defined unit. + if (Object(utils_object["f" /* hasOwnProperty */])(UNITS, str)) { + var unit = UNITS[str]; + var prefix = unit.prefixes['']; + return { + unit: unit, + prefix: prefix + }; + } + + for (var _name in UNITS) { + if (Object(utils_object["f" /* hasOwnProperty */])(UNITS, _name)) { + if (Object(utils_string["b" /* endsWith */])(str, _name)) { + var _unit = UNITS[_name]; + var prefixLen = str.length - _name.length; + var prefixName = str.substring(0, prefixLen); + + var _prefix = Object(utils_object["f" /* hasOwnProperty */])(_unit.prefixes, prefixName) ? _unit.prefixes[prefixName] : undefined; + + if (_prefix !== undefined) { + // store unit, prefix, and value + return { + unit: _unit, + prefix: _prefix + }; + } + } + } + } + + return null; + } + /** + * Test if the given expression is a unit. + * The unit can have a prefix but cannot have a value. + * @memberof Unit + * @param {string} name A string to be tested whether it is a value less unit. + * The unit can have prefix, like "cm" + * @return {boolean} true if the given string is a unit + */ + + + Unit.isValuelessUnit = function (name) { + return _findUnit(name) !== null; + }; + /** + * check if this unit has given base unit + * If this unit is a derived unit, this will ALWAYS return false, since by definition base units are not derived. + * @memberof Unit + * @param {BASE_UNITS | string | undefined} base + */ + + + Unit.prototype.hasBase = function (base) { + if (typeof base === 'string') { + base = BASE_UNITS[base]; + } + + if (!base) { + return false; + } // All dimensions must be the same + + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + if (Math.abs((this.dimensions[i] || 0) - (base.dimensions[i] || 0)) > 1e-12) { + return false; + } + } + + return true; + }; + /** + * Check if this unit has a base or bases equal to another base or bases + * For derived units, the exponent on each base also must match + * @memberof Unit + * @param {Unit} other + * @return {boolean} true if equal base + */ + + + Unit.prototype.equalBase = function (other) { + // All dimensions must be the same + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + if (Math.abs((this.dimensions[i] || 0) - (other.dimensions[i] || 0)) > 1e-12) { + return false; + } + } + + return true; + }; + /** + * Check if this unit equals another unit + * @memberof Unit + * @param {Unit} other + * @return {boolean} true if both units are equal + */ + + + Unit.prototype.equals = function (other) { + return this.equalBase(other) && equal(this.value, other.value); + }; + /** + * Multiply this unit with another one + * @memberof Unit + * @param {Unit} other + * @return {Unit} product of this unit and the other unit + */ + + + Unit.prototype.multiply = function (other) { + var res = this.clone(); + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + // Dimensions arrays may be of different lengths. Default to 0. + res.dimensions[i] = (this.dimensions[i] || 0) + (other.dimensions[i] || 0); + } // Append other's units list onto res + + + for (var _i = 0; _i < other.units.length; _i++) { + // Make a deep copy + var inverted = {}; + + for (var key in other.units[_i]) { + inverted[key] = other.units[_i][key]; + } + + res.units.push(inverted); + } // If at least one operand has a value, then the result should also have a value + + + if (this.value !== null || other.value !== null) { + var valThis = this.value === null ? this._normalize(1) : this.value; + var valOther = other.value === null ? other._normalize(1) : other.value; + res.value = multiplyScalar(valThis, valOther); + } else { + res.value = null; + } + + res.skipAutomaticSimplification = false; + return getNumericIfUnitless(res); + }; + /** + * Divide this unit by another one + * @memberof Unit + * @param {Unit} other + * @return {Unit} result of dividing this unit by the other unit + */ + + + Unit.prototype.divide = function (other) { + var res = this.clone(); + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + // Dimensions arrays may be of different lengths. Default to 0. + res.dimensions[i] = (this.dimensions[i] || 0) - (other.dimensions[i] || 0); + } // Invert and append other's units list onto res + + + for (var _i2 = 0; _i2 < other.units.length; _i2++) { + // Make a deep copy + var inverted = {}; + + for (var key in other.units[_i2]) { + inverted[key] = other.units[_i2][key]; + } + + inverted.power = -inverted.power; + res.units.push(inverted); + } // If at least one operand has a value, the result should have a value + + + if (this.value !== null || other.value !== null) { + var valThis = this.value === null ? this._normalize(1) : this.value; + var valOther = other.value === null ? other._normalize(1) : other.value; + res.value = divideScalar(valThis, valOther); + } else { + res.value = null; + } + + res.skipAutomaticSimplification = false; + return getNumericIfUnitless(res); + }; + /** + * Calculate the power of a unit + * @memberof Unit + * @param {number | Fraction | BigNumber} p + * @returns {Unit} The result: this^p + */ + + + Unit.prototype.pow = function (p) { + var res = this.clone(); + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + // Dimensions arrays may be of different lengths. Default to 0. + res.dimensions[i] = (this.dimensions[i] || 0) * p; + } // Adjust the power of each unit in the list + + + for (var _i3 = 0; _i3 < res.units.length; _i3++) { + res.units[_i3].power *= p; + } + + if (res.value !== null) { + res.value = pow(res.value, p); // only allow numeric output, we don't want to return a Complex number + // if (!isNumeric(res.value)) { + // res.value = NaN + // } + // Update: Complex supported now + } else { + res.value = null; + } + + res.skipAutomaticSimplification = false; + return getNumericIfUnitless(res); + }; + /** + * Return the numeric value of this unit if it is dimensionless, has a value, and config.predictable == false; or the original unit otherwise + * @param {Unit} unit + * @returns {number | Fraction | BigNumber | Unit} The numeric value of the unit if conditions are met, or the original unit otherwise + */ + + + function getNumericIfUnitless(unit) { + if (unit.equalBase(BASE_UNITS.NONE) && unit.value !== null && !config.predictable) { + return unit.value; + } else { + return unit; + } + } + /** + * Calculate the absolute value of a unit + * @memberof Unit + * @param {number | Fraction | BigNumber} x + * @returns {Unit} The result: |x|, absolute value of x + */ + + + Unit.prototype.abs = function () { + // This gives correct, but unexpected, results for units with an offset. + // For example, abs(-283.15 degC) = -263.15 degC !!! + var ret = this.clone(); + ret.value = ret.value !== null ? abs(ret.value) : null; + + for (var i in ret.units) { + if (ret.units[i].unit.name === 'VA' || ret.units[i].unit.name === 'VAR') { + ret.units[i].unit = UNITS.W; + } + } + + return ret; + }; + /** + * Convert the unit to a specific unit name. + * @memberof Unit + * @param {string | Unit} valuelessUnit A unit without value. Can have prefix, like "cm" + * @returns {Unit} Returns a clone of the unit with a fixed prefix and unit. + */ + + + Unit.prototype.to = function (valuelessUnit) { + var other; + var value = this.value === null ? this._normalize(1) : this.value; + + if (typeof valuelessUnit === 'string') { + // other = new Unit(null, valuelessUnit) + other = Unit.parse(valuelessUnit); + + if (!this.equalBase(other)) { + throw new Error("Units do not match ('".concat(other.toString(), "' != '").concat(this.toString(), "')")); + } + + if (other.value !== null) { + throw new Error('Cannot convert to a unit with a value'); + } + + other.value = Object(utils_object["a" /* clone */])(value); + other.fixPrefix = true; + other.skipAutomaticSimplification = true; + return other; + } else if (Object(is["L" /* isUnit */])(valuelessUnit)) { + if (!this.equalBase(valuelessUnit)) { + throw new Error("Units do not match ('".concat(valuelessUnit.toString(), "' != '").concat(this.toString(), "')")); + } + + if (valuelessUnit.value !== null) { + throw new Error('Cannot convert to a unit with a value'); + } + + other = valuelessUnit.clone(); + other.value = Object(utils_object["a" /* clone */])(value); + other.fixPrefix = true; + other.skipAutomaticSimplification = true; + return other; + } else { + throw new Error('String or Unit expected as parameter'); + } + }; + /** + * Return the value of the unit when represented with given valueless unit + * @memberof Unit + * @param {string | Unit} valuelessUnit For example 'cm' or 'inch' + * @return {number} Returns the unit value as number. + */ + // TODO: deprecate Unit.toNumber? It's always better to use toNumeric + + + Unit.prototype.toNumber = function (valuelessUnit) { + return toNumber(this.toNumeric(valuelessUnit)); + }; + /** + * Return the value of the unit in the original numeric type + * @memberof Unit + * @param {string | Unit} valuelessUnit For example 'cm' or 'inch' + * @return {number | BigNumber | Fraction} Returns the unit value + */ + + + Unit.prototype.toNumeric = function (valuelessUnit) { + var other; + + if (valuelessUnit) { + // Allow getting the numeric value without converting to a different unit + other = this.to(valuelessUnit); + } else { + other = this.clone(); + } + + if (other._isDerived() || other.units.length === 0) { + return other._denormalize(other.value); + } else { + return other._denormalize(other.value, other.units[0].prefix.value); + } + }; + /** + * Get a string representation of the unit. + * @memberof Unit + * @return {string} + */ + + + Unit.prototype.toString = function () { + return this.format(); + }; + /** + * Get a JSON representation of the unit + * @memberof Unit + * @returns {Object} Returns a JSON object structured as: + * `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}` + */ + + + Unit.prototype.toJSON = function () { + return { + mathjs: 'Unit', + value: this._denormalize(this.value), + unit: this.formatUnits(), + fixPrefix: this.fixPrefix + }; + }; + /** + * Instantiate a Unit from a JSON object + * @memberof Unit + * @param {Object} json A JSON object structured as: + * `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}` + * @return {Unit} + */ + + + Unit.fromJSON = function (json) { + var unit = new Unit(json.value, json.unit); + unit.fixPrefix = json.fixPrefix || false; + return unit; + }; + /** + * Returns the string representation of the unit. + * @memberof Unit + * @return {string} + */ + + + Unit.prototype.valueOf = Unit.prototype.toString; + /** + * Simplify this Unit's unit list and return a new Unit with the simplified list. + * The returned Unit will contain a list of the "best" units for formatting. + */ + + Unit.prototype.simplify = function () { + var ret = this.clone(); + var proposedUnitList = []; // Search for a matching base + + var matchingBase; + + for (var key in currentUnitSystem) { + if (ret.hasBase(BASE_UNITS[key])) { + matchingBase = key; + break; + } + } + + if (matchingBase === 'NONE') { + ret.units = []; + } else { + var matchingUnit; + + if (matchingBase) { + // Does the unit system have a matching unit? + if (Object(utils_object["f" /* hasOwnProperty */])(currentUnitSystem, matchingBase)) { + matchingUnit = currentUnitSystem[matchingBase]; + } + } + + if (matchingUnit) { + ret.units = [{ + unit: matchingUnit.unit, + prefix: matchingUnit.prefix, + power: 1.0 + }]; + } else { + // Multiple units or units with powers are formatted like this: + // 5 (kg m^2) / (s^3 mol) + // Build an representation from the base units of the current unit system + var missingBaseDim = false; + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + var baseDim = BASE_DIMENSIONS[i]; + + if (Math.abs(ret.dimensions[i] || 0) > 1e-12) { + if (Object(utils_object["f" /* hasOwnProperty */])(currentUnitSystem, baseDim)) { + proposedUnitList.push({ + unit: currentUnitSystem[baseDim].unit, + prefix: currentUnitSystem[baseDim].prefix, + power: ret.dimensions[i] || 0 + }); + } else { + missingBaseDim = true; + } + } + } // Is the proposed unit list "simpler" than the existing one? + + + if (proposedUnitList.length < ret.units.length && !missingBaseDim) { + // Replace this unit list with the proposed list + ret.units = proposedUnitList; + } + } + } + + return ret; + }; + /** + * Returns a new Unit in the SI system with the same value as this one + */ + + + Unit.prototype.toSI = function () { + var ret = this.clone(); + var proposedUnitList = []; // Multiple units or units with powers are formatted like this: + // 5 (kg m^2) / (s^3 mol) + // Build an representation from the base units of the SI unit system + + for (var i = 0; i < BASE_DIMENSIONS.length; i++) { + var baseDim = BASE_DIMENSIONS[i]; + + if (Math.abs(ret.dimensions[i] || 0) > 1e-12) { + if (Object(utils_object["f" /* hasOwnProperty */])(UNIT_SYSTEMS.si, baseDim)) { + proposedUnitList.push({ + unit: UNIT_SYSTEMS.si[baseDim].unit, + prefix: UNIT_SYSTEMS.si[baseDim].prefix, + power: ret.dimensions[i] || 0 + }); + } else { + throw new Error('Cannot express custom unit ' + baseDim + ' in SI units'); + } + } + } // Replace this unit list with the proposed list + + + ret.units = proposedUnitList; + ret.fixPrefix = true; + ret.skipAutomaticSimplification = true; + return ret; + }; + /** + * Get a string representation of the units of this Unit, without the value. The unit list is formatted as-is without first being simplified. + * @memberof Unit + * @return {string} + */ + + + Unit.prototype.formatUnits = function () { + var strNum = ''; + var strDen = ''; + var nNum = 0; + var nDen = 0; + + for (var i = 0; i < this.units.length; i++) { + if (this.units[i].power > 0) { + nNum++; + strNum += ' ' + this.units[i].prefix.name + this.units[i].unit.name; + + if (Math.abs(this.units[i].power - 1.0) > 1e-15) { + strNum += '^' + this.units[i].power; + } + } else if (this.units[i].power < 0) { + nDen++; + } + } + + if (nDen > 0) { + for (var _i4 = 0; _i4 < this.units.length; _i4++) { + if (this.units[_i4].power < 0) { + if (nNum > 0) { + strDen += ' ' + this.units[_i4].prefix.name + this.units[_i4].unit.name; + + if (Math.abs(this.units[_i4].power + 1.0) > 1e-15) { + strDen += '^' + -this.units[_i4].power; + } + } else { + strDen += ' ' + this.units[_i4].prefix.name + this.units[_i4].unit.name; + strDen += '^' + this.units[_i4].power; + } + } + } + } // Remove leading " " + + + strNum = strNum.substr(1); + strDen = strDen.substr(1); // Add parans for better copy/paste back into evaluate, for example, or for better pretty print formatting + + if (nNum > 1 && nDen > 0) { + strNum = '(' + strNum + ')'; + } + + if (nDen > 1 && nNum > 0) { + strDen = '(' + strDen + ')'; + } + + var str = strNum; + + if (nNum > 0 && nDen > 0) { + str += ' / '; + } + + str += strDen; + return str; + }; + /** + * Get a string representation of the Unit, with optional formatting options. + * @memberof Unit + * @param {Object | number | Function} [options] Formatting options. See + * lib/utils/number:format for a + * description of the available + * options. + * @return {string} + */ + + + Unit.prototype.format = function (options) { + // Simplfy the unit list, unless it is valueless or was created directly in the + // constructor or as the result of to or toSI + var simp = this.skipAutomaticSimplification || this.value === null ? this.clone() : this.simplify(); // Apply some custom logic for handling VA and VAR. The goal is to express the value of the unit as a real value, if possible. Otherwise, use a real-valued unit instead of a complex-valued one. + + var isImaginary = false; + + if (typeof simp.value !== 'undefined' && simp.value !== null && Object(is["j" /* isComplex */])(simp.value)) { + // TODO: Make this better, for example, use relative magnitude of re and im rather than absolute + isImaginary = Math.abs(simp.value.re) < 1e-14; + } + + for (var i in simp.units) { + if (simp.units[i].unit) { + if (simp.units[i].unit.name === 'VA' && isImaginary) { + simp.units[i].unit = UNITS.VAR; + } else if (simp.units[i].unit.name === 'VAR' && !isImaginary) { + simp.units[i].unit = UNITS.VA; + } + } + } // Now apply the best prefix + // Units must have only one unit and not have the fixPrefix flag set + + + if (simp.units.length === 1 && !simp.fixPrefix) { + // Units must have integer powers, otherwise the prefix will change the + // outputted value by not-an-integer-power-of-ten + if (Math.abs(simp.units[0].power - Math.round(simp.units[0].power)) < 1e-14) { + // Apply the best prefix + simp.units[0].prefix = simp._bestPrefix(); + } + } + + var value = simp._denormalize(simp.value); + + var str = simp.value !== null ? format(value, options || {}) : ''; + var unitStr = simp.formatUnits(); + + if (simp.value && Object(is["j" /* isComplex */])(simp.value)) { + str = '(' + str + ')'; // Surround complex values with ( ) to enable better parsing + } + + if (unitStr.length > 0 && str.length > 0) { + str += ' '; + } + + str += unitStr; + return str; + }; + /** + * Calculate the best prefix using current value. + * @memberof Unit + * @returns {Object} prefix + * @private + */ + + + Unit.prototype._bestPrefix = function () { + if (this.units.length !== 1) { + throw new Error('Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!'); + } + + if (Math.abs(this.units[0].power - Math.round(this.units[0].power)) >= 1e-14) { + throw new Error('Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!'); + } // find the best prefix value (resulting in the value of which + // the absolute value of the log10 is closest to zero, + // though with a little offset of 1.2 for nicer values: you get a + // sequence 1mm 100mm 500mm 0.6m 1m 10m 100m 500m 0.6km 1km ... + // Note: the units value can be any numeric type, but to find the best + // prefix it's enough to work with limited precision of a regular number + // Update: using mathjs abs since we also allow complex numbers + + + var absValue = this.value !== null ? abs(this.value) : 0; + var absUnitValue = abs(this.units[0].unit.value); + var bestPrefix = this.units[0].prefix; + + if (absValue === 0) { + return bestPrefix; + } + + var power = this.units[0].power; + var bestDiff = Math.log(absValue / Math.pow(bestPrefix.value * absUnitValue, power)) / Math.LN10 - 1.2; + if (bestDiff > -2.200001 && bestDiff < 1.800001) return bestPrefix; // Allow the original prefix + + bestDiff = Math.abs(bestDiff); + var prefixes = this.units[0].unit.prefixes; + + for (var p in prefixes) { + if (Object(utils_object["f" /* hasOwnProperty */])(prefixes, p)) { + var prefix = prefixes[p]; + + if (prefix.scientific) { + var diff = Math.abs(Math.log(absValue / Math.pow(prefix.value * absUnitValue, power)) / Math.LN10 - 1.2); + + if (diff < bestDiff || diff === bestDiff && prefix.name.length < bestPrefix.name.length) { + // choose the prefix with the smallest diff, or if equal, choose the one + // with the shortest name (can happen with SHORTLONG for example) + bestPrefix = prefix; + bestDiff = diff; + } + } + } + } + + return bestPrefix; + }; + /** + * Returns an array of units whose sum is equal to this unit + * @memberof Unit + * @param {Array} [parts] An array of strings or valueless units. + * + * Example: + * + * const u = new Unit(1, 'm') + * u.splitUnit(['feet', 'inch']) + * [ 3 feet, 3.3700787401575 inch ] + * + * @return {Array} An array of units. + */ + + + Unit.prototype.splitUnit = function (parts) { + var x = this.clone(); + var ret = []; + + for (var i = 0; i < parts.length; i++) { + // Convert x to the requested unit + x = x.to(parts[i]); + if (i === parts.length - 1) break; // Get the numeric value of this unit + + var xNumeric = x.toNumeric(); // Check to see if xNumeric is nearly equal to an integer, + // since fix can incorrectly round down if there is round-off error + + var xRounded = round(xNumeric); + var xFixed = void 0; + var isNearlyEqual = equal(xRounded, xNumeric); + + if (isNearlyEqual) { + xFixed = xRounded; + } else { + xFixed = fix(x.toNumeric()); + } + + var y = new Unit(xFixed, parts[i].toString()); + ret.push(y); + x = subtract(x, y); + } // This little bit fixes a bug where the remainder should be 0 but is a little bit off. + // But instead of comparing x, the remainder, with zero--we will compare the sum of + // all the parts so far with the original value. If they are nearly equal, + // we set the remainder to 0. + + + var testSum = 0; + + for (var _i5 = 0; _i5 < ret.length; _i5++) { + testSum = addScalar(testSum, ret[_i5].value); + } + + if (equal(testSum, this.value)) { + x.value = 0; + } + + ret.push(x); + return ret; + }; + + var PREFIXES = { + NONE: { + '': { + name: '', + value: 1, + scientific: true + } + }, + SHORT: { + '': { + name: '', + value: 1, + scientific: true + }, + da: { + name: 'da', + value: 1e1, + scientific: false + }, + h: { + name: 'h', + value: 1e2, + scientific: false + }, + k: { + name: 'k', + value: 1e3, + scientific: true + }, + M: { + name: 'M', + value: 1e6, + scientific: true + }, + G: { + name: 'G', + value: 1e9, + scientific: true + }, + T: { + name: 'T', + value: 1e12, + scientific: true + }, + P: { + name: 'P', + value: 1e15, + scientific: true + }, + E: { + name: 'E', + value: 1e18, + scientific: true + }, + Z: { + name: 'Z', + value: 1e21, + scientific: true + }, + Y: { + name: 'Y', + value: 1e24, + scientific: true + }, + d: { + name: 'd', + value: 1e-1, + scientific: false + }, + c: { + name: 'c', + value: 1e-2, + scientific: false + }, + m: { + name: 'm', + value: 1e-3, + scientific: true + }, + u: { + name: 'u', + value: 1e-6, + scientific: true + }, + n: { + name: 'n', + value: 1e-9, + scientific: true + }, + p: { + name: 'p', + value: 1e-12, + scientific: true + }, + f: { + name: 'f', + value: 1e-15, + scientific: true + }, + a: { + name: 'a', + value: 1e-18, + scientific: true + }, + z: { + name: 'z', + value: 1e-21, + scientific: true + }, + y: { + name: 'y', + value: 1e-24, + scientific: true + } + }, + LONG: { + '': { + name: '', + value: 1, + scientific: true + }, + deca: { + name: 'deca', + value: 1e1, + scientific: false + }, + hecto: { + name: 'hecto', + value: 1e2, + scientific: false + }, + kilo: { + name: 'kilo', + value: 1e3, + scientific: true + }, + mega: { + name: 'mega', + value: 1e6, + scientific: true + }, + giga: { + name: 'giga', + value: 1e9, + scientific: true + }, + tera: { + name: 'tera', + value: 1e12, + scientific: true + }, + peta: { + name: 'peta', + value: 1e15, + scientific: true + }, + exa: { + name: 'exa', + value: 1e18, + scientific: true + }, + zetta: { + name: 'zetta', + value: 1e21, + scientific: true + }, + yotta: { + name: 'yotta', + value: 1e24, + scientific: true + }, + deci: { + name: 'deci', + value: 1e-1, + scientific: false + }, + centi: { + name: 'centi', + value: 1e-2, + scientific: false + }, + milli: { + name: 'milli', + value: 1e-3, + scientific: true + }, + micro: { + name: 'micro', + value: 1e-6, + scientific: true + }, + nano: { + name: 'nano', + value: 1e-9, + scientific: true + }, + pico: { + name: 'pico', + value: 1e-12, + scientific: true + }, + femto: { + name: 'femto', + value: 1e-15, + scientific: true + }, + atto: { + name: 'atto', + value: 1e-18, + scientific: true + }, + zepto: { + name: 'zepto', + value: 1e-21, + scientific: true + }, + yocto: { + name: 'yocto', + value: 1e-24, + scientific: true + } + }, + SQUARED: { + '': { + name: '', + value: 1, + scientific: true + }, + da: { + name: 'da', + value: 1e2, + scientific: false + }, + h: { + name: 'h', + value: 1e4, + scientific: false + }, + k: { + name: 'k', + value: 1e6, + scientific: true + }, + M: { + name: 'M', + value: 1e12, + scientific: true + }, + G: { + name: 'G', + value: 1e18, + scientific: true + }, + T: { + name: 'T', + value: 1e24, + scientific: true + }, + P: { + name: 'P', + value: 1e30, + scientific: true + }, + E: { + name: 'E', + value: 1e36, + scientific: true + }, + Z: { + name: 'Z', + value: 1e42, + scientific: true + }, + Y: { + name: 'Y', + value: 1e48, + scientific: true + }, + d: { + name: 'd', + value: 1e-2, + scientific: false + }, + c: { + name: 'c', + value: 1e-4, + scientific: false + }, + m: { + name: 'm', + value: 1e-6, + scientific: true + }, + u: { + name: 'u', + value: 1e-12, + scientific: true + }, + n: { + name: 'n', + value: 1e-18, + scientific: true + }, + p: { + name: 'p', + value: 1e-24, + scientific: true + }, + f: { + name: 'f', + value: 1e-30, + scientific: true + }, + a: { + name: 'a', + value: 1e-36, + scientific: true + }, + z: { + name: 'z', + value: 1e-42, + scientific: true + }, + y: { + name: 'y', + value: 1e-48, + scientific: true + } + }, + CUBIC: { + '': { + name: '', + value: 1, + scientific: true + }, + da: { + name: 'da', + value: 1e3, + scientific: false + }, + h: { + name: 'h', + value: 1e6, + scientific: false + }, + k: { + name: 'k', + value: 1e9, + scientific: true + }, + M: { + name: 'M', + value: 1e18, + scientific: true + }, + G: { + name: 'G', + value: 1e27, + scientific: true + }, + T: { + name: 'T', + value: 1e36, + scientific: true + }, + P: { + name: 'P', + value: 1e45, + scientific: true + }, + E: { + name: 'E', + value: 1e54, + scientific: true + }, + Z: { + name: 'Z', + value: 1e63, + scientific: true + }, + Y: { + name: 'Y', + value: 1e72, + scientific: true + }, + d: { + name: 'd', + value: 1e-3, + scientific: false + }, + c: { + name: 'c', + value: 1e-6, + scientific: false + }, + m: { + name: 'm', + value: 1e-9, + scientific: true + }, + u: { + name: 'u', + value: 1e-18, + scientific: true + }, + n: { + name: 'n', + value: 1e-27, + scientific: true + }, + p: { + name: 'p', + value: 1e-36, + scientific: true + }, + f: { + name: 'f', + value: 1e-45, + scientific: true + }, + a: { + name: 'a', + value: 1e-54, + scientific: true + }, + z: { + name: 'z', + value: 1e-63, + scientific: true + }, + y: { + name: 'y', + value: 1e-72, + scientific: true + } + }, + BINARY_SHORT_SI: { + '': { + name: '', + value: 1, + scientific: true + }, + k: { + name: 'k', + value: 1e3, + scientific: true + }, + M: { + name: 'M', + value: 1e6, + scientific: true + }, + G: { + name: 'G', + value: 1e9, + scientific: true + }, + T: { + name: 'T', + value: 1e12, + scientific: true + }, + P: { + name: 'P', + value: 1e15, + scientific: true + }, + E: { + name: 'E', + value: 1e18, + scientific: true + }, + Z: { + name: 'Z', + value: 1e21, + scientific: true + }, + Y: { + name: 'Y', + value: 1e24, + scientific: true + } + }, + BINARY_SHORT_IEC: { + '': { + name: '', + value: 1, + scientific: true + }, + Ki: { + name: 'Ki', + value: 1024, + scientific: true + }, + Mi: { + name: 'Mi', + value: Math.pow(1024, 2), + scientific: true + }, + Gi: { + name: 'Gi', + value: Math.pow(1024, 3), + scientific: true + }, + Ti: { + name: 'Ti', + value: Math.pow(1024, 4), + scientific: true + }, + Pi: { + name: 'Pi', + value: Math.pow(1024, 5), + scientific: true + }, + Ei: { + name: 'Ei', + value: Math.pow(1024, 6), + scientific: true + }, + Zi: { + name: 'Zi', + value: Math.pow(1024, 7), + scientific: true + }, + Yi: { + name: 'Yi', + value: Math.pow(1024, 8), + scientific: true + } + }, + BINARY_LONG_SI: { + '': { + name: '', + value: 1, + scientific: true + }, + kilo: { + name: 'kilo', + value: 1e3, + scientific: true + }, + mega: { + name: 'mega', + value: 1e6, + scientific: true + }, + giga: { + name: 'giga', + value: 1e9, + scientific: true + }, + tera: { + name: 'tera', + value: 1e12, + scientific: true + }, + peta: { + name: 'peta', + value: 1e15, + scientific: true + }, + exa: { + name: 'exa', + value: 1e18, + scientific: true + }, + zetta: { + name: 'zetta', + value: 1e21, + scientific: true + }, + yotta: { + name: 'yotta', + value: 1e24, + scientific: true + } + }, + BINARY_LONG_IEC: { + '': { + name: '', + value: 1, + scientific: true + }, + kibi: { + name: 'kibi', + value: 1024, + scientific: true + }, + mebi: { + name: 'mebi', + value: Math.pow(1024, 2), + scientific: true + }, + gibi: { + name: 'gibi', + value: Math.pow(1024, 3), + scientific: true + }, + tebi: { + name: 'tebi', + value: Math.pow(1024, 4), + scientific: true + }, + pebi: { + name: 'pebi', + value: Math.pow(1024, 5), + scientific: true + }, + exi: { + name: 'exi', + value: Math.pow(1024, 6), + scientific: true + }, + zebi: { + name: 'zebi', + value: Math.pow(1024, 7), + scientific: true + }, + yobi: { + name: 'yobi', + value: Math.pow(1024, 8), + scientific: true + } + }, + BTU: { + '': { + name: '', + value: 1, + scientific: true + }, + MM: { + name: 'MM', + value: 1e6, + scientific: true + } + } + }; + PREFIXES.SHORTLONG = _extends({}, PREFIXES.SHORT, PREFIXES.LONG); + PREFIXES.BINARY_SHORT = _extends({}, PREFIXES.BINARY_SHORT_SI, PREFIXES.BINARY_SHORT_IEC); + PREFIXES.BINARY_LONG = _extends({}, PREFIXES.BINARY_LONG_SI, PREFIXES.BINARY_LONG_IEC); + /* Internally, each unit is represented by a value and a dimension array. The elements of the dimensions array have the following meaning: + * Index Dimension + * ----- --------- + * 0 Length + * 1 Mass + * 2 Time + * 3 Current + * 4 Temperature + * 5 Luminous intensity + * 6 Amount of substance + * 7 Angle + * 8 Bit (digital) + * For example, the unit "298.15 K" is a pure temperature and would have a value of 298.15 and a dimension array of [0, 0, 0, 0, 1, 0, 0, 0, 0]. The unit "1 cal / (gm °C)" can be written in terms of the 9 fundamental dimensions as [length^2] / ([time^2] * [temperature]), and would a value of (after conversion to SI) 4184.0 and a dimensions array of [2, 0, -2, 0, -1, 0, 0, 0, 0]. + * + */ + + var BASE_DIMENSIONS = ['MASS', 'LENGTH', 'TIME', 'CURRENT', 'TEMPERATURE', 'LUMINOUS_INTENSITY', 'AMOUNT_OF_SUBSTANCE', 'ANGLE', 'BIT']; + var BASE_UNITS = { + NONE: { + dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 0] + }, + MASS: { + dimensions: [1, 0, 0, 0, 0, 0, 0, 0, 0] + }, + LENGTH: { + dimensions: [0, 1, 0, 0, 0, 0, 0, 0, 0] + }, + TIME: { + dimensions: [0, 0, 1, 0, 0, 0, 0, 0, 0] + }, + CURRENT: { + dimensions: [0, 0, 0, 1, 0, 0, 0, 0, 0] + }, + TEMPERATURE: { + dimensions: [0, 0, 0, 0, 1, 0, 0, 0, 0] + }, + LUMINOUS_INTENSITY: { + dimensions: [0, 0, 0, 0, 0, 1, 0, 0, 0] + }, + AMOUNT_OF_SUBSTANCE: { + dimensions: [0, 0, 0, 0, 0, 0, 1, 0, 0] + }, + FORCE: { + dimensions: [1, 1, -2, 0, 0, 0, 0, 0, 0] + }, + SURFACE: { + dimensions: [0, 2, 0, 0, 0, 0, 0, 0, 0] + }, + VOLUME: { + dimensions: [0, 3, 0, 0, 0, 0, 0, 0, 0] + }, + ENERGY: { + dimensions: [1, 2, -2, 0, 0, 0, 0, 0, 0] + }, + POWER: { + dimensions: [1, 2, -3, 0, 0, 0, 0, 0, 0] + }, + PRESSURE: { + dimensions: [1, -1, -2, 0, 0, 0, 0, 0, 0] + }, + ELECTRIC_CHARGE: { + dimensions: [0, 0, 1, 1, 0, 0, 0, 0, 0] + }, + ELECTRIC_CAPACITANCE: { + dimensions: [-1, -2, 4, 2, 0, 0, 0, 0, 0] + }, + ELECTRIC_POTENTIAL: { + dimensions: [1, 2, -3, -1, 0, 0, 0, 0, 0] + }, + ELECTRIC_RESISTANCE: { + dimensions: [1, 2, -3, -2, 0, 0, 0, 0, 0] + }, + ELECTRIC_INDUCTANCE: { + dimensions: [1, 2, -2, -2, 0, 0, 0, 0, 0] + }, + ELECTRIC_CONDUCTANCE: { + dimensions: [-1, -2, 3, 2, 0, 0, 0, 0, 0] + }, + MAGNETIC_FLUX: { + dimensions: [1, 2, -2, -1, 0, 0, 0, 0, 0] + }, + MAGNETIC_FLUX_DENSITY: { + dimensions: [1, 0, -2, -1, 0, 0, 0, 0, 0] + }, + FREQUENCY: { + dimensions: [0, 0, -1, 0, 0, 0, 0, 0, 0] + }, + ANGLE: { + dimensions: [0, 0, 0, 0, 0, 0, 0, 1, 0] + }, + BIT: { + dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 1] + } + }; + + for (var key in BASE_UNITS) { + BASE_UNITS[key].key = key; + } + + var BASE_UNIT_NONE = {}; + var UNIT_NONE = { + name: '', + base: BASE_UNIT_NONE, + value: 1, + offset: 0, + dimensions: BASE_DIMENSIONS.map(function (x) { + return 0; + }) + }; + var UNITS = { + // length + meter: { + name: 'meter', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + inch: { + name: 'inch', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.0254, + offset: 0 + }, + foot: { + name: 'foot', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.3048, + offset: 0 + }, + yard: { + name: 'yard', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.9144, + offset: 0 + }, + mile: { + name: 'mile', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 1609.344, + offset: 0 + }, + link: { + name: 'link', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.201168, + offset: 0 + }, + rod: { + name: 'rod', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 5.0292, + offset: 0 + }, + chain: { + name: 'chain', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 20.1168, + offset: 0 + }, + angstrom: { + name: 'angstrom', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 1e-10, + offset: 0 + }, + m: { + name: 'm', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + "in": { + name: 'in', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.0254, + offset: 0 + }, + ft: { + name: 'ft', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.3048, + offset: 0 + }, + yd: { + name: 'yd', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.9144, + offset: 0 + }, + mi: { + name: 'mi', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 1609.344, + offset: 0 + }, + li: { + name: 'li', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.201168, + offset: 0 + }, + rd: { + name: 'rd', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 5.029210, + offset: 0 + }, + ch: { + name: 'ch', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 20.1168, + offset: 0 + }, + mil: { + name: 'mil', + base: BASE_UNITS.LENGTH, + prefixes: PREFIXES.NONE, + value: 0.0000254, + offset: 0 + }, + // 1/1000 inch + // Surface + m2: { + name: 'm2', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.SQUARED, + value: 1, + offset: 0 + }, + sqin: { + name: 'sqin', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 0.00064516, + offset: 0 + }, + // 645.16 mm2 + sqft: { + name: 'sqft', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 0.09290304, + offset: 0 + }, + // 0.09290304 m2 + sqyd: { + name: 'sqyd', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 0.83612736, + offset: 0 + }, + // 0.83612736 m2 + sqmi: { + name: 'sqmi', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 2589988.110336, + offset: 0 + }, + // 2.589988110336 km2 + sqrd: { + name: 'sqrd', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 25.29295, + offset: 0 + }, + // 25.29295 m2 + sqch: { + name: 'sqch', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 404.6873, + offset: 0 + }, + // 404.6873 m2 + sqmil: { + name: 'sqmil', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 6.4516e-10, + offset: 0 + }, + // 6.4516 * 10^-10 m2 + acre: { + name: 'acre', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 4046.86, + offset: 0 + }, + // 4046.86 m2 + hectare: { + name: 'hectare', + base: BASE_UNITS.SURFACE, + prefixes: PREFIXES.NONE, + value: 10000, + offset: 0 + }, + // 10000 m2 + // Volume + m3: { + name: 'm3', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.CUBIC, + value: 1, + offset: 0 + }, + L: { + name: 'L', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.SHORT, + value: 0.001, + offset: 0 + }, + // litre + l: { + name: 'l', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.SHORT, + value: 0.001, + offset: 0 + }, + // litre + litre: { + name: 'litre', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.LONG, + value: 0.001, + offset: 0 + }, + cuin: { + name: 'cuin', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 1.6387064e-5, + offset: 0 + }, + // 1.6387064e-5 m3 + cuft: { + name: 'cuft', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.028316846592, + offset: 0 + }, + // 28.316 846 592 L + cuyd: { + name: 'cuyd', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.764554857984, + offset: 0 + }, + // 764.554 857 984 L + teaspoon: { + name: 'teaspoon', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.000005, + offset: 0 + }, + // 5 mL + tablespoon: { + name: 'tablespoon', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.000015, + offset: 0 + }, + // 15 mL + // {name: 'cup', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.000240, offset: 0}, // 240 mL // not possible, we have already another cup + drop: { + name: 'drop', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 5e-8, + offset: 0 + }, + // 0.05 mL = 5e-8 m3 + gtt: { + name: 'gtt', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 5e-8, + offset: 0 + }, + // 0.05 mL = 5e-8 m3 + // Liquid volume + minim: { + name: 'minim', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.00000006161152, + offset: 0 + }, + // 0.06161152 mL + fluiddram: { + name: 'fluiddram', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0000036966911, + offset: 0 + }, + // 3.696691 mL + fluidounce: { + name: 'fluidounce', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.00002957353, + offset: 0 + }, + // 29.57353 mL + gill: { + name: 'gill', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0001182941, + offset: 0 + }, + // 118.2941 mL + cc: { + name: 'cc', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 1e-6, + offset: 0 + }, + // 1e-6 L + cup: { + name: 'cup', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0002365882, + offset: 0 + }, + // 236.5882 mL + pint: { + name: 'pint', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0004731765, + offset: 0 + }, + // 473.1765 mL + quart: { + name: 'quart', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0009463529, + offset: 0 + }, + // 946.3529 mL + gallon: { + name: 'gallon', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.003785412, + offset: 0 + }, + // 3.785412 L + beerbarrel: { + name: 'beerbarrel', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.1173478, + offset: 0 + }, + // 117.3478 L + oilbarrel: { + name: 'oilbarrel', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.1589873, + offset: 0 + }, + // 158.9873 L + hogshead: { + name: 'hogshead', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.2384810, + offset: 0 + }, + // 238.4810 L + // {name: 'min', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.00000006161152, offset: 0}, // 0.06161152 mL // min is already in use as minute + fldr: { + name: 'fldr', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0000036966911, + offset: 0 + }, + // 3.696691 mL + floz: { + name: 'floz', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.00002957353, + offset: 0 + }, + // 29.57353 mL + gi: { + name: 'gi', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0001182941, + offset: 0 + }, + // 118.2941 mL + cp: { + name: 'cp', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0002365882, + offset: 0 + }, + // 236.5882 mL + pt: { + name: 'pt', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0004731765, + offset: 0 + }, + // 473.1765 mL + qt: { + name: 'qt', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.0009463529, + offset: 0 + }, + // 946.3529 mL + gal: { + name: 'gal', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.003785412, + offset: 0 + }, + // 3.785412 L + bbl: { + name: 'bbl', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.1173478, + offset: 0 + }, + // 117.3478 L + obl: { + name: 'obl', + base: BASE_UNITS.VOLUME, + prefixes: PREFIXES.NONE, + value: 0.1589873, + offset: 0 + }, + // 158.9873 L + // {name: 'hogshead', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.2384810, offset: 0}, // 238.4810 L // TODO: hh? + // Mass + g: { + name: 'g', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.SHORT, + value: 0.001, + offset: 0 + }, + gram: { + name: 'gram', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.LONG, + value: 0.001, + offset: 0 + }, + ton: { + name: 'ton', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.SHORT, + value: 907.18474, + offset: 0 + }, + t: { + name: 't', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.SHORT, + value: 1000, + offset: 0 + }, + tonne: { + name: 'tonne', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.LONG, + value: 1000, + offset: 0 + }, + grain: { + name: 'grain', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 64.79891e-6, + offset: 0 + }, + dram: { + name: 'dram', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 1.7718451953125e-3, + offset: 0 + }, + ounce: { + name: 'ounce', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 28.349523125e-3, + offset: 0 + }, + poundmass: { + name: 'poundmass', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 453.59237e-3, + offset: 0 + }, + hundredweight: { + name: 'hundredweight', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 45.359237, + offset: 0 + }, + stick: { + name: 'stick', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 115e-3, + offset: 0 + }, + stone: { + name: 'stone', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 6.35029318, + offset: 0 + }, + gr: { + name: 'gr', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 64.79891e-6, + offset: 0 + }, + dr: { + name: 'dr', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 1.7718451953125e-3, + offset: 0 + }, + oz: { + name: 'oz', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 28.349523125e-3, + offset: 0 + }, + lbm: { + name: 'lbm', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 453.59237e-3, + offset: 0 + }, + cwt: { + name: 'cwt', + base: BASE_UNITS.MASS, + prefixes: PREFIXES.NONE, + value: 45.359237, + offset: 0 + }, + // Time + s: { + name: 's', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + min: { + name: 'min', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 60, + offset: 0 + }, + h: { + name: 'h', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 3600, + offset: 0 + }, + second: { + name: 'second', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + sec: { + name: 'sec', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + minute: { + name: 'minute', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 60, + offset: 0 + }, + hour: { + name: 'hour', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 3600, + offset: 0 + }, + day: { + name: 'day', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 86400, + offset: 0 + }, + week: { + name: 'week', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 7 * 86400, + offset: 0 + }, + month: { + name: 'month', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 2629800, + // 1/12th of Julian year + offset: 0 + }, + year: { + name: 'year', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 31557600, + // Julian year + offset: 0 + }, + decade: { + name: 'decade', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 315576000, + // Julian decade + offset: 0 + }, + century: { + name: 'century', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 3155760000, + // Julian century + offset: 0 + }, + millennium: { + name: 'millennium', + base: BASE_UNITS.TIME, + prefixes: PREFIXES.NONE, + value: 31557600000, + // Julian millennium + offset: 0 + }, + // Frequency + hertz: { + name: 'Hertz', + base: BASE_UNITS.FREQUENCY, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0, + reciprocal: true + }, + Hz: { + name: 'Hz', + base: BASE_UNITS.FREQUENCY, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0, + reciprocal: true + }, + // Angle + rad: { + name: 'rad', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + radian: { + name: 'radian', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + // deg = rad / (2*pi) * 360 = rad / 0.017453292519943295769236907684888 + deg: { + name: 'deg', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.SHORT, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + degree: { + name: 'degree', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.LONG, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + // grad = rad / (2*pi) * 400 = rad / 0.015707963267948966192313216916399 + grad: { + name: 'grad', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.SHORT, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + gradian: { + name: 'gradian', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.LONG, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + // cycle = rad / (2*pi) = rad / 6.2831853071795864769252867665793 + cycle: { + name: 'cycle', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.NONE, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + // arcsec = rad / (3600 * (360 / 2 * pi)) = rad / 0.0000048481368110953599358991410235795 + arcsec: { + name: 'arcsec', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.NONE, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + // arcmin = rad / (60 * (360 / 2 * pi)) = rad / 0.00029088820866572159615394846141477 + arcmin: { + name: 'arcmin', + base: BASE_UNITS.ANGLE, + prefixes: PREFIXES.NONE, + value: null, + // will be filled in by calculateAngleValues() + offset: 0 + }, + // Electric current + A: { + name: 'A', + base: BASE_UNITS.CURRENT, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + ampere: { + name: 'ampere', + base: BASE_UNITS.CURRENT, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + // Temperature + // K(C) = °C + 273.15 + // K(F) = (°F + 459.67) / 1.8 + // K(R) = °R / 1.8 + K: { + name: 'K', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1, + offset: 0 + }, + degC: { + name: 'degC', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1, + offset: 273.15 + }, + degF: { + name: 'degF', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1 / 1.8, + offset: 459.67 + }, + degR: { + name: 'degR', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1 / 1.8, + offset: 0 + }, + kelvin: { + name: 'kelvin', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1, + offset: 0 + }, + celsius: { + name: 'celsius', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1, + offset: 273.15 + }, + fahrenheit: { + name: 'fahrenheit', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1 / 1.8, + offset: 459.67 + }, + rankine: { + name: 'rankine', + base: BASE_UNITS.TEMPERATURE, + prefixes: PREFIXES.NONE, + value: 1 / 1.8, + offset: 0 + }, + // amount of substance + mol: { + name: 'mol', + base: BASE_UNITS.AMOUNT_OF_SUBSTANCE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + mole: { + name: 'mole', + base: BASE_UNITS.AMOUNT_OF_SUBSTANCE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + // luminous intensity + cd: { + name: 'cd', + base: BASE_UNITS.LUMINOUS_INTENSITY, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + candela: { + name: 'candela', + base: BASE_UNITS.LUMINOUS_INTENSITY, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + // TODO: units STERADIAN + // {name: 'sr', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0}, + // {name: 'steradian', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0}, + // Force + N: { + name: 'N', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + newton: { + name: 'newton', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + dyn: { + name: 'dyn', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.SHORT, + value: 0.00001, + offset: 0 + }, + dyne: { + name: 'dyne', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.LONG, + value: 0.00001, + offset: 0 + }, + lbf: { + name: 'lbf', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.NONE, + value: 4.4482216152605, + offset: 0 + }, + poundforce: { + name: 'poundforce', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.NONE, + value: 4.4482216152605, + offset: 0 + }, + kip: { + name: 'kip', + base: BASE_UNITS.FORCE, + prefixes: PREFIXES.LONG, + value: 4448.2216, + offset: 0 + }, + // Energy + J: { + name: 'J', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + joule: { + name: 'joule', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + erg: { + name: 'erg', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.NONE, + value: 1e-7, + offset: 0 + }, + Wh: { + name: 'Wh', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.SHORT, + value: 3600, + offset: 0 + }, + BTU: { + name: 'BTU', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.BTU, + value: 1055.05585262, + offset: 0 + }, + eV: { + name: 'eV', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.SHORT, + value: 1.602176565e-19, + offset: 0 + }, + electronvolt: { + name: 'electronvolt', + base: BASE_UNITS.ENERGY, + prefixes: PREFIXES.LONG, + value: 1.602176565e-19, + offset: 0 + }, + // Power + W: { + name: 'W', + base: BASE_UNITS.POWER, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + watt: { + name: 'watt', + base: BASE_UNITS.POWER, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + hp: { + name: 'hp', + base: BASE_UNITS.POWER, + prefixes: PREFIXES.NONE, + value: 745.6998715386, + offset: 0 + }, + // Electrical power units + VAR: { + name: 'VAR', + base: BASE_UNITS.POWER, + prefixes: PREFIXES.SHORT, + value: Complex.I, + offset: 0 + }, + VA: { + name: 'VA', + base: BASE_UNITS.POWER, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Pressure + Pa: { + name: 'Pa', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + psi: { + name: 'psi', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.NONE, + value: 6894.75729276459, + offset: 0 + }, + atm: { + name: 'atm', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.NONE, + value: 101325, + offset: 0 + }, + bar: { + name: 'bar', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.SHORTLONG, + value: 100000, + offset: 0 + }, + torr: { + name: 'torr', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.NONE, + value: 133.322, + offset: 0 + }, + mmHg: { + name: 'mmHg', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.NONE, + value: 133.322, + offset: 0 + }, + mmH2O: { + name: 'mmH2O', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.NONE, + value: 9.80665, + offset: 0 + }, + cmH2O: { + name: 'cmH2O', + base: BASE_UNITS.PRESSURE, + prefixes: PREFIXES.NONE, + value: 98.0665, + offset: 0 + }, + // Electric charge + coulomb: { + name: 'coulomb', + base: BASE_UNITS.ELECTRIC_CHARGE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + C: { + name: 'C', + base: BASE_UNITS.ELECTRIC_CHARGE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Electric capacitance + farad: { + name: 'farad', + base: BASE_UNITS.ELECTRIC_CAPACITANCE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + F: { + name: 'F', + base: BASE_UNITS.ELECTRIC_CAPACITANCE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Electric potential + volt: { + name: 'volt', + base: BASE_UNITS.ELECTRIC_POTENTIAL, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + V: { + name: 'V', + base: BASE_UNITS.ELECTRIC_POTENTIAL, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Electric resistance + ohm: { + name: 'ohm', + base: BASE_UNITS.ELECTRIC_RESISTANCE, + prefixes: PREFIXES.SHORTLONG, + // Both Mohm and megaohm are acceptable + value: 1, + offset: 0 + }, + + /* + * Unicode breaks in browsers if charset is not specified + Ω: { + name: 'Ω', + base: BASE_UNITS.ELECTRIC_RESISTANCE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + */ + // Electric inductance + henry: { + name: 'henry', + base: BASE_UNITS.ELECTRIC_INDUCTANCE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + H: { + name: 'H', + base: BASE_UNITS.ELECTRIC_INDUCTANCE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Electric conductance + siemens: { + name: 'siemens', + base: BASE_UNITS.ELECTRIC_CONDUCTANCE, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + S: { + name: 'S', + base: BASE_UNITS.ELECTRIC_CONDUCTANCE, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Magnetic flux + weber: { + name: 'weber', + base: BASE_UNITS.MAGNETIC_FLUX, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + Wb: { + name: 'Wb', + base: BASE_UNITS.MAGNETIC_FLUX, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Magnetic flux density + tesla: { + name: 'tesla', + base: BASE_UNITS.MAGNETIC_FLUX_DENSITY, + prefixes: PREFIXES.LONG, + value: 1, + offset: 0 + }, + T: { + name: 'T', + base: BASE_UNITS.MAGNETIC_FLUX_DENSITY, + prefixes: PREFIXES.SHORT, + value: 1, + offset: 0 + }, + // Binary + b: { + name: 'b', + base: BASE_UNITS.BIT, + prefixes: PREFIXES.BINARY_SHORT, + value: 1, + offset: 0 + }, + bits: { + name: 'bits', + base: BASE_UNITS.BIT, + prefixes: PREFIXES.BINARY_LONG, + value: 1, + offset: 0 + }, + B: { + name: 'B', + base: BASE_UNITS.BIT, + prefixes: PREFIXES.BINARY_SHORT, + value: 8, + offset: 0 + }, + bytes: { + name: 'bytes', + base: BASE_UNITS.BIT, + prefixes: PREFIXES.BINARY_LONG, + value: 8, + offset: 0 + } + }; // aliases (formerly plurals) + + var ALIASES = { + meters: 'meter', + inches: 'inch', + feet: 'foot', + yards: 'yard', + miles: 'mile', + links: 'link', + rods: 'rod', + chains: 'chain', + angstroms: 'angstrom', + lt: 'l', + litres: 'litre', + liter: 'litre', + liters: 'litre', + teaspoons: 'teaspoon', + tablespoons: 'tablespoon', + minims: 'minim', + fluiddrams: 'fluiddram', + fluidounces: 'fluidounce', + gills: 'gill', + cups: 'cup', + pints: 'pint', + quarts: 'quart', + gallons: 'gallon', + beerbarrels: 'beerbarrel', + oilbarrels: 'oilbarrel', + hogsheads: 'hogshead', + gtts: 'gtt', + grams: 'gram', + tons: 'ton', + tonnes: 'tonne', + grains: 'grain', + drams: 'dram', + ounces: 'ounce', + poundmasses: 'poundmass', + hundredweights: 'hundredweight', + sticks: 'stick', + lb: 'lbm', + lbs: 'lbm', + kips: 'kip', + acres: 'acre', + hectares: 'hectare', + sqfeet: 'sqft', + sqyard: 'sqyd', + sqmile: 'sqmi', + sqmiles: 'sqmi', + mmhg: 'mmHg', + mmh2o: 'mmH2O', + cmh2o: 'cmH2O', + seconds: 'second', + secs: 'second', + minutes: 'minute', + mins: 'minute', + hours: 'hour', + hr: 'hour', + hrs: 'hour', + days: 'day', + weeks: 'week', + months: 'month', + years: 'year', + decades: 'decade', + centuries: 'century', + millennia: 'millennium', + hertz: 'hertz', + radians: 'radian', + degrees: 'degree', + gradians: 'gradian', + cycles: 'cycle', + arcsecond: 'arcsec', + arcseconds: 'arcsec', + arcminute: 'arcmin', + arcminutes: 'arcmin', + BTUs: 'BTU', + watts: 'watt', + joules: 'joule', + amperes: 'ampere', + coulombs: 'coulomb', + volts: 'volt', + ohms: 'ohm', + farads: 'farad', + webers: 'weber', + teslas: 'tesla', + electronvolts: 'electronvolt', + moles: 'mole', + bit: 'bits', + "byte": 'bytes' + }; + /** + * Calculate the values for the angle units. + * Value is calculated as number or BigNumber depending on the configuration + * @param {{number: 'number' | 'BigNumber'}} config + */ + + function calculateAngleValues(config) { + if (config.number === 'BigNumber') { + var pi = createBigNumberPi(_BigNumber); + UNITS.rad.value = new _BigNumber(1); + UNITS.deg.value = pi.div(180); // 2 * pi / 360 + + UNITS.grad.value = pi.div(200); // 2 * pi / 400 + + UNITS.cycle.value = pi.times(2); // 2 * pi + + UNITS.arcsec.value = pi.div(648000); // 2 * pi / 360 / 3600 + + UNITS.arcmin.value = pi.div(10800); // 2 * pi / 360 / 60 + } else { + // number + UNITS.rad.value = 1; + UNITS.deg.value = Math.PI / 180; // 2 * pi / 360 + + UNITS.grad.value = Math.PI / 200; // 2 * pi / 400 + + UNITS.cycle.value = Math.PI * 2; // 2 * pi + + UNITS.arcsec.value = Math.PI / 648000; // 2 * pi / 360 / 3600 + + UNITS.arcmin.value = Math.PI / 10800; // 2 * pi / 360 / 60 + } // copy to the full names of the angles + + + UNITS.radian.value = UNITS.rad.value; + UNITS.degree.value = UNITS.deg.value; + UNITS.gradian.value = UNITS.grad.value; + } // apply the angle values now + + + calculateAngleValues(config); + + if (on) { + // recalculate the values on change of configuration + on('config', function (curr, prev) { + if (curr.number !== prev.number) { + calculateAngleValues(curr); + } + }); + } + /** + * A unit system is a set of dimensionally independent base units plus a set of derived units, formed by multiplication and division of the base units, that are by convention used with the unit system. + * A user perhaps could issue a command to select a preferred unit system, or use the default (see below). + * Auto unit system: The default unit system is updated on the fly anytime a unit is parsed. The corresponding unit in the default unit system is updated, so that answers are given in the same units the user supplies. + */ + + + var UNIT_SYSTEMS = { + si: { + // Base units + NONE: { + unit: UNIT_NONE, + prefix: PREFIXES.NONE[''] + }, + LENGTH: { + unit: UNITS.m, + prefix: PREFIXES.SHORT[''] + }, + MASS: { + unit: UNITS.g, + prefix: PREFIXES.SHORT.k + }, + TIME: { + unit: UNITS.s, + prefix: PREFIXES.SHORT[''] + }, + CURRENT: { + unit: UNITS.A, + prefix: PREFIXES.SHORT[''] + }, + TEMPERATURE: { + unit: UNITS.K, + prefix: PREFIXES.SHORT[''] + }, + LUMINOUS_INTENSITY: { + unit: UNITS.cd, + prefix: PREFIXES.SHORT[''] + }, + AMOUNT_OF_SUBSTANCE: { + unit: UNITS.mol, + prefix: PREFIXES.SHORT[''] + }, + ANGLE: { + unit: UNITS.rad, + prefix: PREFIXES.SHORT[''] + }, + BIT: { + unit: UNITS.bits, + prefix: PREFIXES.SHORT[''] + }, + // Derived units + FORCE: { + unit: UNITS.N, + prefix: PREFIXES.SHORT[''] + }, + ENERGY: { + unit: UNITS.J, + prefix: PREFIXES.SHORT[''] + }, + POWER: { + unit: UNITS.W, + prefix: PREFIXES.SHORT[''] + }, + PRESSURE: { + unit: UNITS.Pa, + prefix: PREFIXES.SHORT[''] + }, + ELECTRIC_CHARGE: { + unit: UNITS.C, + prefix: PREFIXES.SHORT[''] + }, + ELECTRIC_CAPACITANCE: { + unit: UNITS.F, + prefix: PREFIXES.SHORT[''] + }, + ELECTRIC_POTENTIAL: { + unit: UNITS.V, + prefix: PREFIXES.SHORT[''] + }, + ELECTRIC_RESISTANCE: { + unit: UNITS.ohm, + prefix: PREFIXES.SHORT[''] + }, + ELECTRIC_INDUCTANCE: { + unit: UNITS.H, + prefix: PREFIXES.SHORT[''] + }, + ELECTRIC_CONDUCTANCE: { + unit: UNITS.S, + prefix: PREFIXES.SHORT[''] + }, + MAGNETIC_FLUX: { + unit: UNITS.Wb, + prefix: PREFIXES.SHORT[''] + }, + MAGNETIC_FLUX_DENSITY: { + unit: UNITS.T, + prefix: PREFIXES.SHORT[''] + }, + FREQUENCY: { + unit: UNITS.Hz, + prefix: PREFIXES.SHORT[''] + } + } + }; // Clone to create the other unit systems + + UNIT_SYSTEMS.cgs = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si)); + UNIT_SYSTEMS.cgs.LENGTH = { + unit: UNITS.m, + prefix: PREFIXES.SHORT.c + }; + UNIT_SYSTEMS.cgs.MASS = { + unit: UNITS.g, + prefix: PREFIXES.SHORT[''] + }; + UNIT_SYSTEMS.cgs.FORCE = { + unit: UNITS.dyn, + prefix: PREFIXES.SHORT[''] + }; + UNIT_SYSTEMS.cgs.ENERGY = { + unit: UNITS.erg, + prefix: PREFIXES.NONE[''] + }; // there are wholly 4 unique cgs systems for electricity and magnetism, + // so let's not worry about it unless somebody complains + + UNIT_SYSTEMS.us = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si)); + UNIT_SYSTEMS.us.LENGTH = { + unit: UNITS.ft, + prefix: PREFIXES.NONE[''] + }; + UNIT_SYSTEMS.us.MASS = { + unit: UNITS.lbm, + prefix: PREFIXES.NONE[''] + }; + UNIT_SYSTEMS.us.TEMPERATURE = { + unit: UNITS.degF, + prefix: PREFIXES.NONE[''] + }; + UNIT_SYSTEMS.us.FORCE = { + unit: UNITS.lbf, + prefix: PREFIXES.NONE[''] + }; + UNIT_SYSTEMS.us.ENERGY = { + unit: UNITS.BTU, + prefix: PREFIXES.BTU[''] + }; + UNIT_SYSTEMS.us.POWER = { + unit: UNITS.hp, + prefix: PREFIXES.NONE[''] + }; + UNIT_SYSTEMS.us.PRESSURE = { + unit: UNITS.psi, + prefix: PREFIXES.NONE[''] + }; // Add additional unit systems here. + // Choose a unit system to seed the auto unit system. + + UNIT_SYSTEMS.auto = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si)); // Set the current unit system + + var currentUnitSystem = UNIT_SYSTEMS.auto; + /** + * Set a unit system for formatting derived units. + * @param {string} [name] The name of the unit system. + */ + + Unit.setUnitSystem = function (name) { + if (Object(utils_object["f" /* hasOwnProperty */])(UNIT_SYSTEMS, name)) { + currentUnitSystem = UNIT_SYSTEMS[name]; + } else { + throw new Error('Unit system ' + name + ' does not exist. Choices are: ' + Object.keys(UNIT_SYSTEMS).join(', ')); + } + }; + /** + * Return the current unit system. + * @return {string} The current unit system. + */ + + + Unit.getUnitSystem = function () { + for (var _key in UNIT_SYSTEMS) { + if (UNIT_SYSTEMS[_key] === currentUnitSystem) { + return _key; + } + } + }; + /** + * Converters to convert from number to an other numeric type like BigNumber + * or Fraction + */ + + + Unit.typeConverters = { + BigNumber: function BigNumber(x) { + return new _BigNumber(x + ''); // stringify to prevent constructor error + }, + Fraction: function Fraction(x) { + return new _Fraction(x); + }, + Complex: function Complex(x) { + return x; + }, + number: function number(x) { + return x; + } + }; + /** + * Retrieve the right convertor function corresponding with the type + * of provided exampleValue. + * + * @param {string} type A string 'number', 'BigNumber', or 'Fraction' + * In case of an unknown type, + * @return {Function} + */ + + Unit._getNumberConverter = function (type) { + if (!Unit.typeConverters[type]) { + throw new TypeError('Unsupported type "' + type + '"'); + } + + return Unit.typeConverters[type]; + }; // Add dimensions to each built-in unit + + + for (var _key2 in UNITS) { + var unit = UNITS[_key2]; + unit.dimensions = unit.base.dimensions; + } // Create aliases + + + for (var _name2 in ALIASES) { + if (Object(utils_object["f" /* hasOwnProperty */])(ALIASES, _name2)) { + var _unit2 = UNITS[ALIASES[_name2]]; + var alias = {}; + + for (var _key3 in _unit2) { + if (Object(utils_object["f" /* hasOwnProperty */])(_unit2, _key3)) { + alias[_key3] = _unit2[_key3]; + } + } + + alias.name = _name2; + UNITS[_name2] = alias; + } + } + + function assertUnitNameIsValid(name) { + for (var i = 0; i < name.length; i++) { + var _c = name.charAt(i); + + var isValidAlpha = function isValidAlpha(p) { + return /^[a-zA-Z]$/.test(p); + }; + + var _isDigit = function _isDigit(c) { + return c >= '0' && c <= '9'; + }; + + if (i === 0 && !isValidAlpha(_c)) { + throw new Error('Invalid unit name (must begin with alpha character): "' + name + '"'); + } + + if (i > 0 && !(isValidAlpha(_c) || _isDigit(_c))) { + throw new Error('Invalid unit name (only alphanumeric characters are allowed): "' + name + '"'); + } + } + } + /** + * Wrapper around createUnitSingle. + * Example: + * createUnit({ + * foo: { }, + * bar: { + * definition: 'kg/foo', + * aliases: ['ba', 'barr', 'bars'], + * offset: 200 + * }, + * baz: '4 bar' + * }, + * { + * override: true + * }) + * @param {object} obj Object map. Each key becomes a unit which is defined by its value. + * @param {object} options + */ + + + Unit.createUnit = function (obj, options) { + if (Unit_typeof(obj) !== 'object') { + throw new TypeError("createUnit expects first parameter to be of type 'Object'"); + } // Remove all units and aliases we are overriding + + + if (options && options.override) { + for (var _key4 in obj) { + if (Object(utils_object["f" /* hasOwnProperty */])(obj, _key4)) { + Unit.deleteUnit(_key4); + } + + if (obj[_key4].aliases) { + for (var i = 0; i < obj[_key4].aliases.length; i++) { + Unit.deleteUnit(obj[_key4].aliases[i]); + } + } + } + } // TODO: traverse multiple times until all units have been added + + + var lastUnit; + + for (var _key5 in obj) { + if (Object(utils_object["f" /* hasOwnProperty */])(obj, _key5)) { + lastUnit = Unit.createUnitSingle(_key5, obj[_key5]); + } + } + + return lastUnit; + }; + /** + * Create a user-defined unit and register it with the Unit type. + * Example: + * createUnitSingle('knot', '0.514444444 m/s') + * createUnitSingle('acre', new Unit(43560, 'ft^2')) + * + * @param {string} name The name of the new unit. Must be unique. Example: 'knot' + * @param {string, Unit, Object} definition Definition of the unit in terms + * of existing units. For example, '0.514444444 m / s'. Can be a Unit, a string, + * or an Object. If an Object, may have the following properties: + * - definition {string|Unit} The definition of this unit. + * - prefixes {string} "none", "short", "long", "binary_short", or "binary_long". + * The default is "none". + * - aliases {Array} Array of strings. Example: ['knots', 'kt', 'kts'] + * - offset {Numeric} An offset to apply when converting from the unit. For + * example, the offset for celsius is 273.15 and the offset for farhenheit + * is 459.67. Default is 0. + * - baseName {string} If the unit's dimension does not match that of any other + * base unit, the name of the newly create base unit. Otherwise, this property + * has no effect. + * + * @param {Object} options (optional) An object containing any of the following + * properties: + * - override {boolean} Whether this unit should be allowed to override existing + * units. + * + * @return {Unit} + */ + + + Unit.createUnitSingle = function (name, obj, options) { + if (typeof obj === 'undefined' || obj === null) { + obj = {}; + } + + if (typeof name !== 'string') { + throw new TypeError("createUnitSingle expects first parameter to be of type 'string'"); + } // Check collisions with existing units + + + if (Object(utils_object["f" /* hasOwnProperty */])(UNITS, name)) { + throw new Error('Cannot create unit "' + name + '": a unit with that name already exists'); + } // TODO: Validate name for collisions with other built-in functions (like abs or cos, for example), and for acceptable variable names. For example, '42' is probably not a valid unit. Nor is '%', since it is also an operator. + + + assertUnitNameIsValid(name); + var defUnit = null; // The Unit from which the new unit will be created. + + var aliases = []; + var offset = 0; + var definition; + var prefixes; + var baseName; + + if (obj && obj.type === 'Unit') { + defUnit = obj.clone(); + } else if (typeof obj === 'string') { + if (obj !== '') { + definition = obj; + } + } else if (Unit_typeof(obj) === 'object') { + definition = obj.definition; + prefixes = obj.prefixes; + offset = obj.offset; + baseName = obj.baseName; + + if (obj.aliases) { + aliases = obj.aliases.valueOf(); // aliases could be a Matrix, so convert to Array + } + } else { + throw new TypeError('Cannot create unit "' + name + '" from "' + obj.toString() + '": expecting "string" or "Unit" or "Object"'); + } + + if (aliases) { + for (var i = 0; i < aliases.length; i++) { + if (Object(utils_object["f" /* hasOwnProperty */])(UNITS, aliases[i])) { + throw new Error('Cannot create alias "' + aliases[i] + '": a unit with that name already exists'); + } + } + } + + if (definition && typeof definition === 'string' && !defUnit) { + try { + defUnit = Unit.parse(definition, { + allowNoUnits: true + }); + } catch (ex) { + ex.message = 'Could not create unit "' + name + '" from "' + definition + '": ' + ex.message; + throw ex; + } + } else if (definition && definition.type === 'Unit') { + defUnit = definition.clone(); + } + + aliases = aliases || []; + offset = offset || 0; + + if (prefixes && prefixes.toUpperCase) { + prefixes = PREFIXES[prefixes.toUpperCase()] || PREFIXES.NONE; + } else { + prefixes = PREFIXES.NONE; + } // If defUnit is null, it is because the user did not + // specify a defintion. So create a new base dimension. + + + var newUnit = {}; + + if (!defUnit) { + // Add a new base dimension + baseName = baseName || name + '_STUFF'; // foo --> foo_STUFF, or the essence of foo + + if (BASE_DIMENSIONS.indexOf(baseName) >= 0) { + throw new Error('Cannot create new base unit "' + name + '": a base unit with that name already exists (and cannot be overridden)'); + } + + BASE_DIMENSIONS.push(baseName); // Push 0 onto existing base units + + for (var b in BASE_UNITS) { + if (Object(utils_object["f" /* hasOwnProperty */])(BASE_UNITS, b)) { + BASE_UNITS[b].dimensions[BASE_DIMENSIONS.length - 1] = 0; + } + } // Add the new base unit + + + var newBaseUnit = { + dimensions: [] + }; + + for (var _i6 = 0; _i6 < BASE_DIMENSIONS.length; _i6++) { + newBaseUnit.dimensions[_i6] = 0; + } + + newBaseUnit.dimensions[BASE_DIMENSIONS.length - 1] = 1; + newBaseUnit.key = baseName; + BASE_UNITS[baseName] = newBaseUnit; + newUnit = { + name: name, + value: 1, + dimensions: BASE_UNITS[baseName].dimensions.slice(0), + prefixes: prefixes, + offset: offset, + base: BASE_UNITS[baseName] + }; + currentUnitSystem[baseName] = { + unit: newUnit, + prefix: PREFIXES.NONE[''] + }; + } else { + newUnit = { + name: name, + value: defUnit.value, + dimensions: defUnit.dimensions.slice(0), + prefixes: prefixes, + offset: offset + }; // Create a new base if no matching base exists + + var anyMatch = false; + + for (var _i7 in BASE_UNITS) { + if (Object(utils_object["f" /* hasOwnProperty */])(BASE_UNITS, _i7)) { + var match = true; + + for (var j = 0; j < BASE_DIMENSIONS.length; j++) { + if (Math.abs((newUnit.dimensions[j] || 0) - (BASE_UNITS[_i7].dimensions[j] || 0)) > 1e-12) { + match = false; + break; + } + } + + if (match) { + anyMatch = true; + newUnit.base = BASE_UNITS[_i7]; + break; + } + } + } + + if (!anyMatch) { + baseName = baseName || name + '_STUFF'; // foo --> foo_STUFF, or the essence of foo + // Add the new base unit + + var _newBaseUnit = { + dimensions: defUnit.dimensions.slice(0) + }; + _newBaseUnit.key = baseName; + BASE_UNITS[baseName] = _newBaseUnit; + currentUnitSystem[baseName] = { + unit: newUnit, + prefix: PREFIXES.NONE[''] + }; + newUnit.base = BASE_UNITS[baseName]; + } + } + + Unit.UNITS[name] = newUnit; + + for (var _i8 = 0; _i8 < aliases.length; _i8++) { + var aliasName = aliases[_i8]; + var _alias = {}; + + for (var _key6 in newUnit) { + if (Object(utils_object["f" /* hasOwnProperty */])(newUnit, _key6)) { + _alias[_key6] = newUnit[_key6]; + } + } + + _alias.name = aliasName; + Unit.UNITS[aliasName] = _alias; + } + + return new Unit(null, name); + }; + + Unit.deleteUnit = function (name) { + delete Unit.UNITS[name]; + }; // expose arrays with prefixes, dimensions, units, systems + + + Unit.PREFIXES = PREFIXES; + Unit.BASE_DIMENSIONS = BASE_DIMENSIONS; + Unit.BASE_UNITS = BASE_UNITS; + Unit.UNIT_SYSTEMS = UNIT_SYSTEMS; + Unit.UNITS = UNITS; + return Unit; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/unit/function/unit.js + + +var unit_name = 'unit'; +var unit_dependencies = ['typed', 'Unit']; // This function is named createUnitFunction to prevent a naming conflict with createUnit + +var createUnitFunction = /* #__PURE__ */Object(factory["a" /* factory */])(unit_name, unit_dependencies, function (_ref) { + var typed = _ref.typed, + Unit = _ref.Unit; + + /** + * Create a unit. Depending on the passed arguments, the function + * will create and return a new math.Unit object. + * When a matrix is provided, all elements will be converted to units. + * + * Syntax: + * + * math.unit(unit : string) + * math.unit(value : number, unit : string) + * + * Examples: + * + * const a = math.unit(5, 'cm') // returns Unit 50 mm + * const b = math.unit('23 kg') // returns Unit 23 kg + * a.to('m') // returns Unit 0.05 m + * + * See also: + * + * bignumber, boolean, complex, index, matrix, number, string, createUnit + * + * @param {* | Array | Matrix} args A number and unit. + * @return {Unit | Array | Matrix} The created unit + */ + var unit = typed(unit_name, { + Unit: function Unit(x) { + return x.clone(); + }, + string: function string(x) { + if (Unit.isValuelessUnit(x)) { + return new Unit(null, x); // a pure unit + } + + return Unit.parse(x, { + allowNoUnits: true + }); // a unit with value, like '5cm' + }, + 'number | BigNumber | Fraction | Complex, string': function numberBigNumberFractionComplexString(value, unit) { + return new Unit(value, unit); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, unit); + } + }); + return unit; +}); +// CONCATENATED MODULE: ./src/type/matrix/function/sparse.js + +var sparse_name = 'sparse'; +var sparse_dependencies = ['typed', 'SparseMatrix']; +var createSparse = /* #__PURE__ */Object(factory["a" /* factory */])(sparse_name, sparse_dependencies, function (_ref) { + var typed = _ref.typed, + SparseMatrix = _ref.SparseMatrix; + + /** + * Create a Sparse Matrix. The function creates a new `math.Matrix` object from + * an `Array`. A Matrix has utility functions to manipulate the data in the + * matrix, like getting the size and getting or setting values in the matrix. + * + * Syntax: + * + * math.sparse() // creates an empty sparse matrix. + * math.sparse(data) // creates a sparse matrix with initial data. + * math.sparse(data, 'number') // creates a sparse matrix with initial data, number datatype. + * + * Examples: + * + * let m = math.sparse([[1, 2], [3, 4]]) + * m.size() // Array [2, 2] + * m.resize([3, 2], 5) + * m.valueOf() // Array [[1, 2], [3, 4], [5, 5]] + * m.get([1, 0]) // number 3 + * + * See also: + * + * bignumber, boolean, complex, index, number, string, unit, matrix + * + * @param {Array | Matrix} [data] A two dimensional array + * + * @return {Matrix} The created matrix + */ + return typed(sparse_name, { + '': function _() { + return new SparseMatrix([]); + }, + string: function string(datatype) { + return new SparseMatrix([], datatype); + }, + 'Array | Matrix': function ArrayMatrix(data) { + return new SparseMatrix(data); + }, + 'Array | Matrix, string': function ArrayMatrixString(data, datatype) { + return new SparseMatrix(data, datatype); + } + }); +}); +// CONCATENATED MODULE: ./src/type/unit/function/createUnit.js + +var createUnit_name = 'createUnit'; +var createUnit_dependencies = ['typed', 'Unit']; +var createCreateUnit = /* #__PURE__ */Object(factory["a" /* factory */])(createUnit_name, createUnit_dependencies, function (_ref) { + var typed = _ref.typed, + Unit = _ref.Unit; + + /** + * Create a user-defined unit and register it with the Unit type. + * + * Syntax: + * + * math.createUnit({ + * baseUnit1: { + * aliases: [string, ...] + * prefixes: object + * }, + * unit2: { + * definition: string, + * aliases: [string, ...] + * prefixes: object, + * offset: number + * }, + * unit3: string // Shortcut + * }) + * + * // Another shortcut: + * math.createUnit(string, unit : string, [object]) + * + * Examples: + * + * math.createUnit('foo') + * math.createUnit('knot', {definition: '0.514444444 m/s', aliases: ['knots', 'kt', 'kts']}) + * math.createUnit('mph', '1 mile/hour') + * + * @param {string} name The name of the new unit. Must be unique. Example: 'knot' + * @param {string, Unit} definition Definition of the unit in terms of existing units. For example, '0.514444444 m / s'. + * @param {Object} options (optional) An object containing any of the following properties: + * - `prefixes {string}` "none", "short", "long", "binary_short", or "binary_long". The default is "none". + * - `aliases {Array}` Array of strings. Example: ['knots', 'kt', 'kts'] + * - `offset {Numeric}` An offset to apply when converting from the unit. For example, the offset for celsius is 273.15. Default is 0. + * + * See also: + * + * unit + * + * @return {Unit} The new unit + */ + return typed(createUnit_name, { + // General function signature. First parameter is an object where each property is the definition of a new unit. The object keys are the unit names and the values are the definitions. The values can be objects, strings, or Units. If a property is an empty object or an empty string, a new base unit is created. The second parameter is the options. + 'Object, Object': function ObjectObject(obj, options) { + return Unit.createUnit(obj, options); + }, + // Same as above but without the options. + Object: function Object(obj) { + return Unit.createUnit(obj, {}); + }, + // Shortcut method for creating one unit. + 'string, Unit | string | Object, Object': function stringUnitStringObjectObject(name, def, options) { + var obj = {}; + obj[name] = def; + return Unit.createUnit(obj, options); + }, + // Same as above but without the options. + 'string, Unit | string | Object': function stringUnitStringObject(name, def) { + var obj = {}; + obj[name] = def; + return Unit.createUnit(obj, {}); + }, + // Without a definition, creates a base unit. + string: function string(name) { + var obj = {}; + obj[name] = {}; + return Unit.createUnit(obj, {}); + } + }); +}); +// CONCATENATED MODULE: ./src/function/trigonometry/acos.js + + +var acos_name = 'acos'; +var acos_dependencies = ['typed', 'config', 'Complex']; +var createAcos = /* #__PURE__ */Object(factory["a" /* factory */])(acos_name, acos_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex; + + /** + * Calculate the inverse cosine of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.acos(x) + * + * Examples: + * + * math.acos(0.5) // returns number 1.0471975511965979 + * math.acos(math.cos(1.5)) // returns number 1.5 + * + * math.acos(2) // returns Complex 0 + 1.3169578969248166 i + * + * See also: + * + * cos, atan, asin + * + * @param {number | BigNumber | Complex | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} The arc cosine of x + */ + var acos = typed(acos_name, { + number: function number(x) { + if (x >= -1 && x <= 1 || config.predictable) { + return Math.acos(x); + } else { + return new Complex(x, 0).acos(); + } + }, + Complex: function Complex(x) { + return x.acos(); + }, + BigNumber: function BigNumber(x) { + return x.acos(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, acos); + } + }); + return acos; +}); +// CONCATENATED MODULE: ./src/plain/number/trigonometry.js + +var trigonometry_n1 = 'number'; +var trigonometry_n2 = 'number, number'; +function acosNumber(x) { + return Math.acos(x); +} +acosNumber.signature = trigonometry_n1; +function acoshNumber(x) { + return Object(utils_number["a" /* acosh */])(x); +} +acoshNumber.signature = trigonometry_n1; +function acotNumber(x) { + return Math.atan(1 / x); +} +acotNumber.signature = trigonometry_n1; +function acothNumber(x) { + return isFinite(x) ? (Math.log((x + 1) / x) + Math.log(x / (x - 1))) / 2 : 0; +} +acothNumber.signature = trigonometry_n1; +function acscNumber(x) { + return Math.asin(1 / x); +} +acscNumber.signature = trigonometry_n1; +function acschNumber(x) { + var xInv = 1 / x; + return Math.log(xInv + Math.sqrt(xInv * xInv + 1)); +} +acschNumber.signature = trigonometry_n1; +function asecNumber(x) { + return Math.acos(1 / x); +} +asecNumber.signature = trigonometry_n1; +function asechNumber(x) { + var xInv = 1 / x; + var ret = Math.sqrt(xInv * xInv - 1); + return Math.log(ret + xInv); +} +asechNumber.signature = trigonometry_n1; +function asinNumber(x) { + return Math.asin(x); +} +asinNumber.signature = trigonometry_n1; +function asinhNumber(x) { + return Object(utils_number["b" /* asinh */])(x); +} +asinhNumber.signature = trigonometry_n1; +function atanNumber(x) { + return Math.atan(x); +} +atanNumber.signature = trigonometry_n1; +function atan2Number(y, x) { + return Math.atan2(y, x); +} +atan2Number.signature = trigonometry_n2; +function atanhNumber(x) { + return Object(utils_number["c" /* atanh */])(x); +} +atanhNumber.signature = trigonometry_n1; +function cosNumber(x) { + return Math.cos(x); +} +cosNumber.signature = trigonometry_n1; +function coshNumber(x) { + return Object(utils_number["e" /* cosh */])(x); +} +coshNumber.signature = trigonometry_n1; +function cotNumber(x) { + return 1 / Math.tan(x); +} +cotNumber.signature = trigonometry_n1; +function cothNumber(x) { + var e = Math.exp(2 * x); + return (e + 1) / (e - 1); +} +cothNumber.signature = trigonometry_n1; +function cscNumber(x) { + return 1 / Math.sin(x); +} +cscNumber.signature = trigonometry_n1; +function cschNumber(x) { + // consider values close to zero (+/-) + if (x === 0) { + return Number.POSITIVE_INFINITY; + } else { + return Math.abs(2 / (Math.exp(x) - Math.exp(-x))) * Object(utils_number["n" /* sign */])(x); + } +} +cschNumber.signature = trigonometry_n1; +function secNumber(x) { + return 1 / Math.cos(x); +} +secNumber.signature = trigonometry_n1; +function sechNumber(x) { + return 2 / (Math.exp(x) + Math.exp(-x)); +} +sechNumber.signature = trigonometry_n1; +function sinNumber(x) { + return Math.sin(x); +} +sinNumber.signature = trigonometry_n1; +function sinhNumber(x) { + return Object(utils_number["o" /* sinh */])(x); +} +sinhNumber.signature = trigonometry_n1; +function tanNumber(x) { + return Math.tan(x); +} +tanNumber.signature = trigonometry_n1; +function tanhNumber(x) { + return Object(utils_number["p" /* tanh */])(x); +} +tanhNumber.signature = trigonometry_n1; +// CONCATENATED MODULE: ./src/function/trigonometry/acosh.js + + + +var acosh_name = 'acosh'; +var acosh_dependencies = ['typed', 'config', 'Complex']; +var createAcosh = /* #__PURE__ */Object(factory["a" /* factory */])(acosh_name, acosh_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex; + + /** + * Calculate the hyperbolic arccos of a value, + * defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.acosh(x) + * + * Examples: + * + * math.acosh(1.5) // returns 0.9624236501192069 + * + * See also: + * + * cosh, asinh, atanh + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic arccosine of x + */ + var acosh = typed(acosh_name, { + number: function number(x) { + if (x >= 1 || config.predictable) { + return acoshNumber(x); + } + + if (x <= -1) { + return new Complex(Math.log(Math.sqrt(x * x - 1) - x), Math.PI); + } + + return new Complex(x, 0).acosh(); + }, + Complex: function Complex(x) { + return x.acosh(); + }, + BigNumber: function BigNumber(x) { + return x.acosh(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, acosh); + } + }); + return acosh; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/acot.js + + + +var acot_name = 'acot'; +var acot_dependencies = ['typed', 'BigNumber']; +var createAcot = /* #__PURE__ */Object(factory["a" /* factory */])(acot_name, acot_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.acot(x) + * + * Examples: + * + * math.acot(0.5) // returns number 0.4636476090008061 + * math.acot(math.cot(1.5)) // returns number 1.5 + * + * math.acot(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i + * + * See also: + * + * cot, atan + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} The arc cotangent of x + */ + var acot = typed(acot_name, { + number: acotNumber, + Complex: function Complex(x) { + return x.acot(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x).atan(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, acot); + } + }); + return acot; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/acoth.js + + + +var acoth_name = 'acoth'; +var acoth_dependencies = ['typed', 'config', 'Complex', 'BigNumber']; +var createAcoth = /* #__PURE__ */Object(factory["a" /* factory */])(acoth_name, acoth_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the hyperbolic arccotangent of a value, + * defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.acoth(x) + * + * Examples: + * + * math.acoth(0.5) // returns 0.8047189562170503 + * + * See also: + * + * acsch, asech + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic arccotangent of x + */ + var acoth = typed(acoth_name, { + number: function number(x) { + if (x >= 1 || x <= -1 || config.predictable) { + return acothNumber(x); + } + + return new Complex(x, 0).acoth(); + }, + Complex: function Complex(x) { + return x.acoth(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x).atanh(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, acoth); + } + }); + return acoth; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/acsc.js + + + +var acsc_name = 'acsc'; +var acsc_dependencies = ['typed', 'config', 'Complex', 'BigNumber']; +var createAcsc = /* #__PURE__ */Object(factory["a" /* factory */])(acsc_name, acsc_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.acsc(x) + * + * Examples: + * + * math.acsc(0.5) // returns number 0.5235987755982989 + * math.acsc(math.csc(1.5)) // returns number ~1.5 + * + * math.acsc(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i + * + * See also: + * + * csc, asin, asec + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} The arc cosecant of x + */ + var acsc = typed(acsc_name, { + number: function number(x) { + if (x <= -1 || x >= 1 || config.predictable) { + return acscNumber(x); + } + + return new Complex(x, 0).acsc(); + }, + Complex: function Complex(x) { + return x.acsc(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x).asin(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, acsc); + } + }); + return acsc; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/acsch.js + + + +var acsch_name = 'acsch'; +var acsch_dependencies = ['typed', 'BigNumber']; +var createAcsch = /* #__PURE__ */Object(factory["a" /* factory */])(acsch_name, acsch_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the hyperbolic arccosecant of a value, + * defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.acsch(x) + * + * Examples: + * + * math.acsch(0.5) // returns 1.4436354751788103 + * + * See also: + * + * asech, acoth + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic arccosecant of x + */ + var acsch = typed(acsch_name, { + number: acschNumber, + Complex: function Complex(x) { + return x.acsch(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x).asinh(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, acsch); + } + }); + return acsch; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/asec.js + + + +var asec_name = 'asec'; +var asec_dependencies = ['typed', 'config', 'Complex', 'BigNumber']; +var createAsec = /* #__PURE__ */Object(factory["a" /* factory */])(asec_name, asec_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the inverse secant of a value. Defined as `asec(x) = acos(1/x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.asec(x) + * + * Examples: + * + * math.asec(0.5) // returns 1.0471975511965979 + * math.asec(math.sec(1.5)) // returns 1.5 + * + * math.asec(2) // returns 0 + 1.3169578969248166 i + * + * See also: + * + * acos, acot, acsc + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} The arc secant of x + */ + var asec = typed(asec_name, { + number: function number(x) { + if (x <= -1 || x >= 1 || config.predictable) { + return asecNumber(x); + } + + return new Complex(x, 0).asec(); + }, + Complex: function Complex(x) { + return x.asec(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x).acos(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, asec); + } + }); + return asec; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/asech.js + + + +var asech_name = 'asech'; +var asech_dependencies = ['typed', 'config', 'Complex', 'BigNumber']; +var createAsech = /* #__PURE__ */Object(factory["a" /* factory */])(asech_name, asech_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the hyperbolic arcsecant of a value, + * defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.asech(x) + * + * Examples: + * + * math.asech(0.5) // returns 1.3169578969248166 + * + * See also: + * + * acsch, acoth + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic arcsecant of x + */ + var asech = typed(asech_name, { + number: function number(x) { + if (x <= 1 && x >= -1 || config.predictable) { + var xInv = 1 / x; + + if (xInv > 0 || config.predictable) { + return asechNumber(x); + } + + var ret = Math.sqrt(xInv * xInv - 1); + return new Complex(Math.log(ret - xInv), Math.PI); + } + + return new Complex(x, 0).asech(); + }, + Complex: function Complex(x) { + return x.asech(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x).acosh(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, asech); + } + }); + return asech; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/asin.js + + +var asin_name = 'asin'; +var asin_dependencies = ['typed', 'config', 'Complex']; +var createAsin = /* #__PURE__ */Object(factory["a" /* factory */])(asin_name, asin_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex; + + /** + * Calculate the inverse sine of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.asin(x) + * + * Examples: + * + * math.asin(0.5) // returns number 0.5235987755982989 + * math.asin(math.sin(1.5)) // returns number ~1.5 + * + * math.asin(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i + * + * See also: + * + * sin, atan, acos + * + * @param {number | BigNumber | Complex | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} The arc sine of x + */ + var asin = typed(asin_name, { + number: function number(x) { + if (x >= -1 && x <= 1 || config.predictable) { + return Math.asin(x); + } else { + return new Complex(x, 0).asin(); + } + }, + Complex: function Complex(x) { + return x.asin(); + }, + BigNumber: function BigNumber(x) { + return x.asin(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since asin(0) = 0 + return deepMap(x, asin, true); + } + }); + return asin; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/asinh.js + + + +var asinh_name = 'asinh'; +var asinh_dependencies = ['typed']; +var createAsinh = /* #__PURE__ */Object(factory["a" /* factory */])(asinh_name, asinh_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the hyperbolic arcsine of a value, + * defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.asinh(x) + * + * Examples: + * + * math.asinh(0.5) // returns 0.48121182505960347 + * + * See also: + * + * acosh, atanh + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic arcsine of x + */ + var asinh = typed('asinh', { + number: asinhNumber, + Complex: function Complex(x) { + return x.asinh(); + }, + BigNumber: function BigNumber(x) { + return x.asinh(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since asinh(0) = 0 + return deepMap(x, asinh, true); + } + }); + return asinh; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/atan.js + + +var atan_name = 'atan'; +var atan_dependencies = ['typed']; +var createAtan = /* #__PURE__ */Object(factory["a" /* factory */])(atan_name, atan_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the inverse tangent of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.atan(x) + * + * Examples: + * + * math.atan(0.5) // returns number 0.4636476090008061 + * math.atan(math.tan(1.5)) // returns number 1.5 + * + * math.atan(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i + * + * See also: + * + * tan, asin, acos + * + * @param {number | BigNumber | Complex | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} The arc tangent of x + */ + var atan = typed('atan', { + number: function number(x) { + return Math.atan(x); + }, + Complex: function Complex(x) { + return x.atan(); + }, + BigNumber: function BigNumber(x) { + return x.atan(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since atan(0) = 0 + return deepMap(x, atan, true); + } + }); + return atan; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/atan2.js + + + + + + + + +var atan2_name = 'atan2'; +var atan2_dependencies = ['typed', 'matrix', 'equalScalar', 'BigNumber', 'DenseMatrix']; +var createAtan2 = /* #__PURE__ */Object(factory["a" /* factory */])(atan2_name, atan2_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + equalScalar = _ref.equalScalar, + BigNumber = _ref.BigNumber, + DenseMatrix = _ref.DenseMatrix; + var algorithm02 = createAlgorithm02({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm03 = createAlgorithm03({ + typed: typed + }); + var algorithm09 = createAlgorithm09({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm12 = createAlgorithm12({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Calculate the inverse tangent function with two arguments, y/x. + * By providing two arguments, the right quadrant of the computed angle can be + * determined. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.atan2(y, x) + * + * Examples: + * + * math.atan2(2, 2) / math.pi // returns number 0.25 + * + * const angle = math.unit(60, 'deg') // returns Unit 60 deg + * const x = math.cos(angle) + * const y = math.sin(angle) + * + * math.atan(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i + * + * See also: + * + * tan, atan, sin, cos + * + * @param {number | Array | Matrix} y Second dimension + * @param {number | Array | Matrix} x First dimension + * @return {number | Array | Matrix} Four-quadrant inverse tangent + */ + + var atan2 = typed(atan2_name, { + 'number, number': Math.atan2, + // Complex numbers doesn't seem to have a reasonable implementation of + // atan2(). Even Matlab removed the support, after they only calculated + // the atan only on base of the real part of the numbers and ignored the imaginary. + 'BigNumber, BigNumber': function BigNumberBigNumber(y, x) { + return BigNumber.atan2(y, x); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm09(x, y, atan2, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + // mind the order of y and x! + return algorithm02(y, x, atan2, true); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm03(x, y, atan2, false); + }, + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, atan2); + }, + 'Array, Array': function ArrayArray(x, y) { + return atan2(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + return atan2(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + return atan2(x, matrix(y)); + }, + 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) { + return algorithm11(x, y, atan2, false); + }, + 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) { + return algorithm14(x, y, atan2, false); + }, + 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) { + // mind the order of y and x + return algorithm12(y, x, atan2, true); + }, + 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) { + // mind the order of y and x + return algorithm14(y, x, atan2, true); + }, + 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) { + return algorithm14(matrix(x), y, atan2, false).valueOf(); + }, + 'number | BigNumber, Array': function numberBigNumberArray(x, y) { + return algorithm14(matrix(y), x, atan2, true).valueOf(); + } + }); + return atan2; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/atanh.js + + + +var atanh_name = 'atanh'; +var atanh_dependencies = ['typed', 'config', 'Complex']; +var createAtanh = /* #__PURE__ */Object(factory["a" /* factory */])(atanh_name, atanh_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + Complex = _ref.Complex; + + /** + * Calculate the hyperbolic arctangent of a value, + * defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.atanh(x) + * + * Examples: + * + * math.atanh(0.5) // returns 0.5493061443340549 + * + * See also: + * + * acosh, asinh + * + * @param {number | Complex | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic arctangent of x + */ + var atanh = typed(atanh_name, { + number: function number(x) { + if (x <= 1 && x >= -1 || config.predictable) { + return atanhNumber(x); + } + + return new Complex(x, 0).atanh(); + }, + Complex: function Complex(x) { + return x.atanh(); + }, + BigNumber: function BigNumber(x) { + return x.atanh(); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since atanh(0) = 0 + return deepMap(x, atanh, true); + } + }); + return atanh; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/cos.js + + +var cos_name = 'cos'; +var cos_dependencies = ['typed']; +var createCos = /* #__PURE__ */Object(factory["a" /* factory */])(cos_name, cos_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the cosine of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.cos(x) + * + * Examples: + * + * math.cos(2) // returns number -0.4161468365471422 + * math.cos(math.pi / 4) // returns number 0.7071067811865475 + * math.cos(math.unit(180, 'deg')) // returns number -1 + * math.cos(math.unit(60, 'deg')) // returns number 0.5 + * + * const angle = 0.2 + * math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2) // returns number ~1 + * + * See also: + * + * cos, tan + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} Cosine of x + */ + var cos = typed(cos_name, { + number: Math.cos, + Complex: function Complex(x) { + return x.cos(); + }, + BigNumber: function BigNumber(x) { + return x.cos(); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function cos is no angle'); + } + + return cos(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, cos); + } + }); + return cos; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/cosh.js + + + +var cosh_name = 'cosh'; +var cosh_dependencies = ['typed']; +var createCosh = /* #__PURE__ */Object(factory["a" /* factory */])(cosh_name, cosh_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the hyperbolic cosine of a value, + * defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.cosh(x) + * + * Examples: + * + * math.cosh(0.5) // returns number 1.1276259652063807 + * + * See also: + * + * sinh, tanh + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic cosine of x + */ + var cosh = typed(cosh_name, { + number: utils_number["e" /* cosh */], + Complex: function Complex(x) { + return x.cosh(); + }, + BigNumber: function BigNumber(x) { + return x.cosh(); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function cosh is no angle'); + } + + return cosh(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, cosh); + } + }); + return cosh; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/cot.js + + + +var cot_name = 'cot'; +var cot_dependencies = ['typed', 'BigNumber']; +var createCot = /* #__PURE__ */Object(factory["a" /* factory */])(cot_name, cot_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the cotangent of a value. Defined as `cot(x) = 1 / tan(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.cot(x) + * + * Examples: + * + * math.cot(2) // returns number -0.45765755436028577 + * 1 / math.tan(2) // returns number -0.45765755436028577 + * + * See also: + * + * tan, sec, csc + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Cotangent of x + */ + var cot = typed(cot_name, { + number: cotNumber, + Complex: function Complex(x) { + return x.cot(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x.tan()); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function cot is no angle'); + } + + return cot(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, cot); + } + }); + return cot; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/coth.js + + + +var coth_name = 'coth'; +var coth_dependencies = ['typed', 'BigNumber']; +var createCoth = /* #__PURE__ */Object(factory["a" /* factory */])(coth_name, coth_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the hyperbolic cotangent of a value, + * defined as `coth(x) = 1 / tanh(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.coth(x) + * + * Examples: + * + * // coth(x) = 1 / tanh(x) + * math.coth(2) // returns 1.0373147207275482 + * 1 / math.tanh(2) // returns 1.0373147207275482 + * + * See also: + * + * sinh, tanh, cosh + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic cotangent of x + */ + var coth = typed(coth_name, { + number: cothNumber, + Complex: function Complex(x) { + return x.coth(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x.tanh()); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function coth is no angle'); + } + + return coth(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, coth); + } + }); + return coth; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/csc.js + + + +var csc_name = 'csc'; +var csc_dependencies = ['typed', 'BigNumber']; +var createCsc = /* #__PURE__ */Object(factory["a" /* factory */])(csc_name, csc_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the cosecant of a value, defined as `csc(x) = 1/sin(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.csc(x) + * + * Examples: + * + * math.csc(2) // returns number 1.099750170294617 + * 1 / math.sin(2) // returns number 1.099750170294617 + * + * See also: + * + * sin, sec, cot + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Cosecant of x + */ + var csc = typed(csc_name, { + number: cscNumber, + Complex: function Complex(x) { + return x.csc(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x.sin()); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function csc is no angle'); + } + + return csc(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, csc); + } + }); + return csc; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/csch.js + + + +var csch_name = 'csch'; +var csch_dependencies = ['typed', 'BigNumber']; +var createCsch = /* #__PURE__ */Object(factory["a" /* factory */])(csch_name, csch_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the hyperbolic cosecant of a value, + * defined as `csch(x) = 1 / sinh(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.csch(x) + * + * Examples: + * + * // csch(x) = 1/ sinh(x) + * math.csch(0.5) // returns 1.9190347513349437 + * 1 / math.sinh(0.5) // returns 1.9190347513349437 + * + * See also: + * + * sinh, sech, coth + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic cosecant of x + */ + var csch = typed(csch_name, { + number: cschNumber, + Complex: function Complex(x) { + return x.csch(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x.sinh()); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function csch is no angle'); + } + + return csch(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, csch); + } + }); + return csch; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/sec.js + + + +var sec_name = 'sec'; +var sec_dependencies = ['typed', 'BigNumber']; +var createSec = /* #__PURE__ */Object(factory["a" /* factory */])(sec_name, sec_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the secant of a value, defined as `sec(x) = 1/cos(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.sec(x) + * + * Examples: + * + * math.sec(2) // returns number -2.4029979617223822 + * 1 / math.cos(2) // returns number -2.4029979617223822 + * + * See also: + * + * cos, csc, cot + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Secant of x + */ + var sec = typed(sec_name, { + number: secNumber, + Complex: function Complex(x) { + return x.sec(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x.cos()); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function sec is no angle'); + } + + return sec(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, sec); + } + }); + return sec; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/sech.js + + + +var sech_name = 'sech'; +var sech_dependencies = ['typed', 'BigNumber']; +var createSech = /* #__PURE__ */Object(factory["a" /* factory */])(sech_name, sech_dependencies, function (_ref) { + var typed = _ref.typed, + _BigNumber = _ref.BigNumber; + + /** + * Calculate the hyperbolic secant of a value, + * defined as `sech(x) = 1 / cosh(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.sech(x) + * + * Examples: + * + * // sech(x) = 1/ cosh(x) + * math.sech(0.5) // returns 0.886818883970074 + * 1 / math.cosh(0.5) // returns 0.886818883970074 + * + * See also: + * + * cosh, csch, coth + * + * @param {number | Complex | Unit | Array | Matrix} x Function input + * @return {number | Complex | Array | Matrix} Hyperbolic secant of x + */ + var sech = typed(sech_name, { + number: sechNumber, + Complex: function Complex(x) { + return x.sech(); + }, + BigNumber: function BigNumber(x) { + return new _BigNumber(1).div(x.cosh()); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function sech is no angle'); + } + + return sech(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + return deepMap(x, sech); + } + }); + return sech; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/sin.js + + +var sin_name = 'sin'; +var sin_dependencies = ['typed']; +var createSin = /* #__PURE__ */Object(factory["a" /* factory */])(sin_name, sin_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the sine of a value. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.sin(x) + * + * Examples: + * + * math.sin(2) // returns number 0.9092974268256813 + * math.sin(math.pi / 4) // returns number 0.7071067811865475 + * math.sin(math.unit(90, 'deg')) // returns number 1 + * math.sin(math.unit(30, 'deg')) // returns number 0.5 + * + * const angle = 0.2 + * math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2) // returns number ~1 + * + * See also: + * + * cos, tan + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} Sine of x + */ + var sin = typed(sin_name, { + number: Math.sin, + Complex: function Complex(x) { + return x.sin(); + }, + BigNumber: function BigNumber(x) { + return x.sin(); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function sin is no angle'); + } + + return sin(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since sin(0) = 0 + return deepMap(x, sin, true); + } + }); + return sin; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/sinh.js + + + +var sinh_name = 'sinh'; +var sinh_dependencies = ['typed']; +var createSinh = /* #__PURE__ */Object(factory["a" /* factory */])(sinh_name, sinh_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the hyperbolic sine of a value, + * defined as `sinh(x) = 1/2 * (exp(x) - exp(-x))`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.sinh(x) + * + * Examples: + * + * math.sinh(0.5) // returns number 0.5210953054937474 + * + * See also: + * + * cosh, tanh + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic sine of x + */ + var sinh = typed(sinh_name, { + number: sinhNumber, + Complex: function Complex(x) { + return x.sinh(); + }, + BigNumber: function BigNumber(x) { + return x.sinh(); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function sinh is no angle'); + } + + return sinh(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since sinh(0) = 0 + return deepMap(x, sinh, true); + } + }); + return sinh; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/tan.js + + +var tan_name = 'tan'; +var tan_dependencies = ['typed']; +var createTan = /* #__PURE__ */Object(factory["a" /* factory */])(tan_name, tan_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the tangent of a value. `tan(x)` is equal to `sin(x) / cos(x)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.tan(x) + * + * Examples: + * + * math.tan(0.5) // returns number 0.5463024898437905 + * math.sin(0.5) / math.cos(0.5) // returns number 0.5463024898437905 + * math.tan(math.pi / 4) // returns number 1 + * math.tan(math.unit(45, 'deg')) // returns number 1 + * + * See also: + * + * atan, sin, cos + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} Tangent of x + */ + var tan = typed(tan_name, { + number: Math.tan, + Complex: function Complex(x) { + return x.tan(); + }, + BigNumber: function BigNumber(x) { + return x.tan(); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function tan is no angle'); + } + + return tan(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since tan(0) = 0 + return deepMap(x, tan, true); + } + }); + return tan; +}); +// CONCATENATED MODULE: ./src/function/trigonometry/tanh.js + + + +var tanh_name = 'tanh'; +var tanh_dependencies = ['typed']; +var createTanh = /* #__PURE__ */Object(factory["a" /* factory */])(tanh_name, tanh_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Calculate the hyperbolic tangent of a value, + * defined as `tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1)`. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.tanh(x) + * + * Examples: + * + * // tanh(x) = sinh(x) / cosh(x) = 1 / coth(x) + * math.tanh(0.5) // returns 0.46211715726000974 + * math.sinh(0.5) / math.cosh(0.5) // returns 0.46211715726000974 + * 1 / math.coth(0.5) // returns 0.46211715726000974 + * + * See also: + * + * sinh, cosh, coth + * + * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input + * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic tangent of x + */ + var tanh = typed('tanh', { + number: utils_number["p" /* tanh */], + Complex: function Complex(x) { + return x.tanh(); + }, + BigNumber: function BigNumber(x) { + return x.tanh(); + }, + Unit: function Unit(x) { + if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) { + throw new TypeError('Unit in function tanh is no angle'); + } + + return tanh(x.value); + }, + 'Array | Matrix': function ArrayMatrix(x) { + // deep map collection, skip zeros since tanh(0) = 0 + return deepMap(x, tanh, true); + } + }); + return tanh; +}); +// CONCATENATED MODULE: ./src/function/set/setCartesian.js + + +var setCartesian_name = 'setCartesian'; +var setCartesian_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix']; +var createSetCartesian = /* #__PURE__ */Object(factory["a" /* factory */])(setCartesian_name, setCartesian_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index, + DenseMatrix = _ref.DenseMatrix; + + /** + * Create the cartesian product of two (multi)sets. + * Multi-dimension arrays will be converted to single-dimension arrays before the operation. + * + * Syntax: + * + * math.setCartesian(set1, set2) + * + * Examples: + * + * math.setCartesian([1, 2], [3, 4]) // returns [[1, 3], [1, 4], [2, 3], [2, 4]] + * + * See also: + * + * setUnion, setIntersect, setDifference, setPowerset + * + * @param {Array | Matrix} a1 A (multi)set + * @param {Array | Matrix} a2 A (multi)set + * @return {Array | Matrix} The cartesian product of two (multi)sets + */ + return typed(setCartesian_name, { + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) { + var result = []; + + if (subset(size(a1), new Index(0)) !== 0 && subset(size(a2), new Index(0)) !== 0) { + // if any of them is empty, return empty + var b1 = Object(utils_array["e" /* flatten */])(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural); + var b2 = Object(utils_array["e" /* flatten */])(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural); + result = []; + + for (var i = 0; i < b1.length; i++) { + for (var j = 0; j < b2.length; j++) { + result.push([b1[i], b2[j]]); + } + } + } // return an array, if both inputs were arrays + + + if (Array.isArray(a1) && Array.isArray(a2)) { + return result; + } // return a matrix otherwise + + + return new DenseMatrix(result); + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setDifference.js + + +var setDifference_name = 'setDifference'; +var setDifference_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix']; +var createSetDifference = /* #__PURE__ */Object(factory["a" /* factory */])(setDifference_name, setDifference_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index, + DenseMatrix = _ref.DenseMatrix; + + /** + * Create the difference of two (multi)sets: every element of set1, that is not the element of set2. + * Multi-dimension arrays will be converted to single-dimension arrays before the operation. + * + * Syntax: + * + * math.setDifference(set1, set2) + * + * Examples: + * + * math.setDifference([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2] + * math.setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2] + * + * See also: + * + * setUnion, setIntersect, setSymDifference + * + * @param {Array | Matrix} a1 A (multi)set + * @param {Array | Matrix} a2 A (multi)set + * @return {Array | Matrix} The difference of two (multi)sets + */ + return typed(setDifference_name, { + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) { + var result; + + if (subset(size(a1), new Index(0)) === 0) { + // empty-anything=empty + result = []; + } else if (subset(size(a2), new Index(0)) === 0) { + // anything-empty=anything + return Object(utils_array["e" /* flatten */])(a1.toArray()); + } else { + var b1 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural)); + var b2 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural)); + result = []; + var inb2; + + for (var i = 0; i < b1.length; i++) { + inb2 = false; + + for (var j = 0; j < b2.length; j++) { + if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) { + // the identifier is always a decimal int + inb2 = true; + break; + } + } + + if (!inb2) { + result.push(b1[i]); + } + } + } // return an array, if both inputs were arrays + + + if (Array.isArray(a1) && Array.isArray(a2)) { + return Object(utils_array["g" /* generalize */])(result); + } // return a matrix otherwise + + + return new DenseMatrix(Object(utils_array["g" /* generalize */])(result)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setDistinct.js + + +var setDistinct_name = 'setDistinct'; +var setDistinct_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix']; +var createSetDistinct = /* #__PURE__ */Object(factory["a" /* factory */])(setDistinct_name, setDistinct_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index, + DenseMatrix = _ref.DenseMatrix; + + /** + * Collect the distinct elements of a multiset. + * A multi-dimension array will be converted to a single-dimension array before the operation. + * + * Syntax: + * + * math.setDistinct(set) + * + * Examples: + * + * math.setDistinct([1, 1, 1, 2, 2, 3]) // returns [1, 2, 3] + * + * See also: + * + * setMultiplicity + * + * @param {Array | Matrix} a A multiset + * @return {Array | Matrix} A set containing the distinc elements of the multiset + */ + return typed(setDistinct_name, { + 'Array | Matrix': function ArrayMatrix(a) { + var result; + + if (subset(size(a), new Index(0)) === 0) { + // if empty, return empty + result = []; + } else { + var b = Object(utils_array["e" /* flatten */])(Array.isArray(a) ? a : a.toArray()).sort(compareNatural); + result = []; + result.push(b[0]); + + for (var i = 1; i < b.length; i++) { + if (compareNatural(b[i], b[i - 1]) !== 0) { + result.push(b[i]); + } + } + } // return an array, if the input was an array + + + if (Array.isArray(a)) { + return result; + } // return a matrix otherwise + + + return new DenseMatrix(result); + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setIntersect.js + + +var setIntersect_name = 'setIntersect'; +var setIntersect_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix']; +var createSetIntersect = /* #__PURE__ */Object(factory["a" /* factory */])(setIntersect_name, setIntersect_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index, + DenseMatrix = _ref.DenseMatrix; + + /** + * Create the intersection of two (multi)sets. + * Multi-dimension arrays will be converted to single-dimension arrays before the operation. + * + * Syntax: + * + * math.setIntersect(set1, set2) + * + * Examples: + * + * math.setIntersect([1, 2, 3, 4], [3, 4, 5, 6]) // returns [3, 4] + * math.setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [3, 4] + * + * See also: + * + * setUnion, setDifference + * + * @param {Array | Matrix} a1 A (multi)set + * @param {Array | Matrix} a2 A (multi)set + * @return {Array | Matrix} The intersection of two (multi)sets + */ + return typed(setIntersect_name, { + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) { + var result; + + if (subset(size(a1), new Index(0)) === 0 || subset(size(a2), new Index(0)) === 0) { + // of any of them is empty, return empty + result = []; + } else { + var b1 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural)); + var b2 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural)); + result = []; + + for (var i = 0; i < b1.length; i++) { + for (var j = 0; j < b2.length; j++) { + if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) { + // the identifier is always a decimal int + result.push(b1[i]); + break; + } + } + } + } // return an array, if both inputs were arrays + + + if (Array.isArray(a1) && Array.isArray(a2)) { + return Object(utils_array["g" /* generalize */])(result); + } // return a matrix otherwise + + + return new DenseMatrix(Object(utils_array["g" /* generalize */])(result)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setIsSubset.js + + +var setIsSubset_name = 'setIsSubset'; +var setIsSubset_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index']; +var createSetIsSubset = /* #__PURE__ */Object(factory["a" /* factory */])(setIsSubset_name, setIsSubset_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index; + + /** + * Check whether a (multi)set is a subset of another (multi)set. (Every element of set1 is the element of set2.) + * Multi-dimension arrays will be converted to single-dimension arrays before the operation. + * + * Syntax: + * + * math.setIsSubset(set1, set2) + * + * Examples: + * + * math.setIsSubset([1, 2], [3, 4, 5, 6]) // returns false + * math.setIsSubset([3, 4], [3, 4, 5, 6]) // returns true + * + * See also: + * + * setUnion, setIntersect, setDifference + * + * @param {Array | Matrix} a1 A (multi)set + * @param {Array | Matrix} a2 A (multi)set + * @return {boolean} true | false + */ + return typed(setIsSubset_name, { + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) { + if (subset(size(a1), new Index(0)) === 0) { + // empty is a subset of anything + return true; + } else if (subset(size(a2), new Index(0)) === 0) { + // anything is not a subset of empty + return false; + } + + var b1 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural)); + var b2 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural)); + var inb2; + + for (var i = 0; i < b1.length; i++) { + inb2 = false; + + for (var j = 0; j < b2.length; j++) { + if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) { + // the identifier is always a decimal int + inb2 = true; + break; + } + } + + if (inb2 === false) { + return false; + } + } + + return true; + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setMultiplicity.js + + +var setMultiplicity_name = 'setMultiplicity'; +var setMultiplicity_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index']; +var createSetMultiplicity = /* #__PURE__ */Object(factory["a" /* factory */])(setMultiplicity_name, setMultiplicity_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index; + + /** + * Count the multiplicity of an element in a multiset. + * A multi-dimension array will be converted to a single-dimension array before the operation. + * + * Syntax: + * + * math.setMultiplicity(element, set) + * + * Examples: + * + * math.setMultiplicity(1, [1, 2, 2, 4]) // returns 1 + * math.setMultiplicity(2, [1, 2, 2, 4]) // returns 2 + * + * See also: + * + * setDistinct, setSize + * + * @param {number | BigNumber | Fraction | Complex} e An element in the multiset + * @param {Array | Matrix} a A multiset + * @return {number} The number of how many times the multiset contains the element + */ + return typed(setMultiplicity_name, { + 'number | BigNumber | Fraction | Complex, Array | Matrix': function numberBigNumberFractionComplexArrayMatrix(e, a) { + if (subset(size(a), new Index(0)) === 0) { + // if empty, return 0 + return 0; + } + + var b = Object(utils_array["e" /* flatten */])(Array.isArray(a) ? a : a.toArray()); + var count = 0; + + for (var i = 0; i < b.length; i++) { + if (compareNatural(b[i], e) === 0) { + count++; + } + } + + return count; + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setPowerset.js + + +var setPowerset_name = 'setPowerset'; +var setPowerset_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index']; +var createSetPowerset = /* #__PURE__ */Object(factory["a" /* factory */])(setPowerset_name, setPowerset_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + subset = _ref.subset, + compareNatural = _ref.compareNatural, + Index = _ref.Index; + + /** + * Create the powerset of a (multi)set. (The powerset contains very possible subsets of a (multi)set.) + * A multi-dimension array will be converted to a single-dimension array before the operation. + * + * Syntax: + * + * math.setPowerset(set) + * + * Examples: + * + * math.setPowerset([1, 2, 3]) // returns [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] + * + * See also: + * + * setCartesian + * + * @param {Array | Matrix} a A (multi)set + * @return {Array} The powerset of the (multi)set + */ + return typed(setPowerset_name, { + 'Array | Matrix': function ArrayMatrix(a) { + if (subset(size(a), new Index(0)) === 0) { + // if empty, return empty + return []; + } + + var b = Object(utils_array["e" /* flatten */])(Array.isArray(a) ? a : a.toArray()).sort(compareNatural); + var result = []; + var number = 0; + + while (number.toString(2).length <= b.length) { + result.push(_subset(b, number.toString(2).split('').reverse())); + number++; + } // can not return a matrix, because of the different size of the subarrays + + + return _sort(result); + } + }); // create subset + + function _subset(array, bitarray) { + var result = []; + + for (var i = 0; i < bitarray.length; i++) { + if (bitarray[i] === '1') { + result.push(array[i]); + } + } + + return result; + } // sort subsests by length + + + function _sort(array) { + var temp = []; + + for (var i = array.length - 1; i > 0; i--) { + for (var j = 0; j < i; j++) { + if (array[j].length > array[j + 1].length) { + temp = array[j]; + array[j] = array[j + 1]; + array[j + 1] = temp; + } + } + } + + return array; + } +}); +// CONCATENATED MODULE: ./src/function/set/setSize.js + + +var setSize_name = 'setSize'; +var setSize_dependencies = ['typed', 'compareNatural']; +var createSetSize = /* #__PURE__ */Object(factory["a" /* factory */])(setSize_name, setSize_dependencies, function (_ref) { + var typed = _ref.typed, + compareNatural = _ref.compareNatural; + + /** + * Count the number of elements of a (multi)set. When a second parameter is 'true', count only the unique values. + * A multi-dimension array will be converted to a single-dimension array before the operation. + * + * Syntax: + * + * math.setSize(set) + * math.setSize(set, unique) + * + * Examples: + * + * math.setSize([1, 2, 2, 4]) // returns 4 + * math.setSize([1, 2, 2, 4], true) // returns 3 + * + * See also: + * + * setUnion, setIntersect, setDifference + * + * @param {Array | Matrix} a A multiset + * @return {number} The number of elements of the (multi)set + */ + return typed(setSize_name, { + 'Array | Matrix': function ArrayMatrix(a) { + return Array.isArray(a) ? Object(utils_array["e" /* flatten */])(a).length : Object(utils_array["e" /* flatten */])(a.toArray()).length; + }, + 'Array | Matrix, boolean': function ArrayMatrixBoolean(a, unique) { + if (unique === false || a.length === 0) { + return Array.isArray(a) ? Object(utils_array["e" /* flatten */])(a).length : Object(utils_array["e" /* flatten */])(a.toArray()).length; + } else { + var b = Object(utils_array["e" /* flatten */])(Array.isArray(a) ? a : a.toArray()).sort(compareNatural); + var count = 1; + + for (var i = 1; i < b.length; i++) { + if (compareNatural(b[i], b[i - 1]) !== 0) { + count++; + } + } + + return count; + } + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setSymDifference.js + + +var setSymDifference_name = 'setSymDifference'; +var setSymDifference_dependencies = ['typed', 'size', 'concat', 'subset', 'setDifference', 'Index']; +var createSetSymDifference = /* #__PURE__ */Object(factory["a" /* factory */])(setSymDifference_name, setSymDifference_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + concat = _ref.concat, + subset = _ref.subset, + setDifference = _ref.setDifference, + Index = _ref.Index; + + /** + * Create the symmetric difference of two (multi)sets. + * Multi-dimension arrays will be converted to single-dimension arrays before the operation. + * + * Syntax: + * + * math.setSymDifference(set1, set2) + * + * Examples: + * + * math.setSymDifference([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2, 5, 6] + * math.setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2, 5, 6] + * + * See also: + * + * setUnion, setIntersect, setDifference + * + * @param {Array | Matrix} a1 A (multi)set + * @param {Array | Matrix} a2 A (multi)set + * @return {Array | Matrix} The symmetric difference of two (multi)sets + */ + return typed(setSymDifference_name, { + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) { + if (subset(size(a1), new Index(0)) === 0) { + // if any of them is empty, return the other one + return Object(utils_array["e" /* flatten */])(a2); + } else if (subset(size(a2), new Index(0)) === 0) { + return Object(utils_array["e" /* flatten */])(a1); + } + + var b1 = Object(utils_array["e" /* flatten */])(a1); + var b2 = Object(utils_array["e" /* flatten */])(a2); + return concat(setDifference(b1, b2), setDifference(b2, b1)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/set/setUnion.js + + +var setUnion_name = 'setUnion'; +var setUnion_dependencies = ['typed', 'size', 'concat', 'subset', 'setIntersect', 'setSymDifference', 'Index']; +var createSetUnion = /* #__PURE__ */Object(factory["a" /* factory */])(setUnion_name, setUnion_dependencies, function (_ref) { + var typed = _ref.typed, + size = _ref.size, + concat = _ref.concat, + subset = _ref.subset, + setIntersect = _ref.setIntersect, + setSymDifference = _ref.setSymDifference, + Index = _ref.Index; + + /** + * Create the union of two (multi)sets. + * Multi-dimension arrays will be converted to single-dimension arrays before the operation. + * + * Syntax: + * + * math.setUnion(set1, set2) + * + * Examples: + * + * math.setUnion([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2, 3, 4, 5, 6] + * math.setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2, 3, 4, 5, 6] + * + * See also: + * + * setIntersect, setDifference + * + * @param {Array | Matrix} a1 A (multi)set + * @param {Array | Matrix} a2 A (multi)set + * @return {Array | Matrix} The union of two (multi)sets + */ + return typed(setUnion_name, { + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) { + if (subset(size(a1), new Index(0)) === 0) { + // if any of them is empty, return the other one + return Object(utils_array["e" /* flatten */])(a2); + } else if (subset(size(a2), new Index(0)) === 0) { + return Object(utils_array["e" /* flatten */])(a1); + } + + var b1 = Object(utils_array["e" /* flatten */])(a1); + var b2 = Object(utils_array["e" /* flatten */])(a2); + return concat(setSymDifference(b1, b2), setIntersect(b1, b2)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/arithmetic/add.js + + + + + + + +var add_name = 'add'; +var add_dependencies = ['typed', 'matrix', 'addScalar', 'equalScalar', 'DenseMatrix', 'SparseMatrix']; +var createAdd = /* #__PURE__ */Object(factory["a" /* factory */])(add_name, add_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + addScalar = _ref.addScalar, + equalScalar = _ref.equalScalar, + DenseMatrix = _ref.DenseMatrix, + SparseMatrix = _ref.SparseMatrix; + var algorithm01 = createAlgorithm01({ + typed: typed + }); + var algorithm04 = createAlgorithm04({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm10 = createAlgorithm10({ + typed: typed, + DenseMatrix: DenseMatrix + }); + var algorithm13 = createAlgorithm13({ + typed: typed + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Add two or more values, `x + y`. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.add(x, y) + * math.add(x, y, z, ...) + * + * Examples: + * + * math.add(2, 3) // returns number 5 + * math.add(2, 3, 4) // returns number 9 + * + * const a = math.complex(2, 3) + * const b = math.complex(-4, 1) + * math.add(a, b) // returns Complex -2 + 4i + * + * math.add([1, 2, 3], 4) // returns Array [5, 6, 7] + * + * const c = math.unit('5 cm') + * const d = math.unit('2.1 mm') + * math.add(c, d) // returns Unit 52.1 mm + * + * math.add("2.3", "4") // returns number 6.3 + * + * See also: + * + * subtract, sum + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First value to add + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second value to add + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Sum of `x` and `y` + */ + + var add = typed(add_name, Object(utils_object["e" /* extend */])({ + // we extend the signatures of addScalar with signatures dealing with matrices + 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) { + return algorithm13(x, y, addScalar); + }, + 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) { + return algorithm01(x, y, addScalar, false); + }, + 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) { + return algorithm01(y, x, addScalar, true); + }, + 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) { + return algorithm04(x, y, addScalar); + }, + 'Array, Array': function ArrayArray(x, y) { + // use matrix implementation + return add(matrix(x), matrix(y)).valueOf(); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + // use matrix implementation + return add(matrix(x), y); + }, + 'Matrix, Array': function MatrixArray(x, y) { + // use matrix implementation + return add(x, matrix(y)); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, addScalar, false); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm10(x, y, addScalar, false); + }, + 'any, DenseMatrix': function anyDenseMatrix(x, y) { + return algorithm14(y, x, addScalar, true); + }, + 'any, SparseMatrix': function anySparseMatrix(x, y) { + return algorithm10(y, x, addScalar, true); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, addScalar, false).valueOf(); + }, + 'any, Array': function anyArray(x, y) { + // use matrix implementation + return algorithm14(matrix(y), x, addScalar, true).valueOf(); + }, + 'any, any': addScalar, + 'any, any, ...any': function anyAnyAny(x, y, rest) { + var result = add(x, y); + + for (var i = 0; i < rest.length; i++) { + result = add(result, rest[i]); + } + + return result; + } + }, addScalar.signatures)); + return add; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/hypot.js + + +var hypot_name = 'hypot'; +var hypot_dependencies = ['typed', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'sqrt', 'smaller', 'isPositive']; +var createHypot = /* #__PURE__ */Object(factory["a" /* factory */])(hypot_name, hypot_dependencies, function (_ref) { + var typed = _ref.typed, + abs = _ref.abs, + addScalar = _ref.addScalar, + divideScalar = _ref.divideScalar, + multiplyScalar = _ref.multiplyScalar, + sqrt = _ref.sqrt, + smaller = _ref.smaller, + isPositive = _ref.isPositive; + + /** + * Calculate the hypotenusa of a list with values. The hypotenusa is defined as: + * + * hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...) + * + * For matrix input, the hypotenusa is calculated for all values in the matrix. + * + * Syntax: + * + * math.hypot(a, b, ...) + * math.hypot([a, b, c, ...]) + * + * Examples: + * + * math.hypot(3, 4) // 5 + * math.hypot(3, 4, 5) // 7.0710678118654755 + * math.hypot([3, 4, 5]) // 7.0710678118654755 + * math.hypot(-2) // 2 + * + * See also: + * + * abs, norm + * + * @param {... number | BigNumber | Array | Matrix} args A list with numeric values or an Array or Matrix. + * Matrix and Array input is flattened and returns a + * single number for the whole matrix. + * @return {number | BigNumber} Returns the hypothenusa of the input values. + */ + var hypot = typed(hypot_name, { + '... number | BigNumber': _hypot, + Array: function Array(x) { + return hypot.apply(hypot, Object(utils_array["e" /* flatten */])(x)); + }, + Matrix: function Matrix(x) { + return hypot.apply(hypot, Object(utils_array["e" /* flatten */])(x.toArray())); + } + }); + /** + * Calculate the hypotenusa for an Array with values + * @param {Array.} args + * @return {number | BigNumber} Returns the result + * @private + */ + + function _hypot(args) { + // code based on `hypot` from es6-shim: + // https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1619-L1633 + var result = 0; + var largest = 0; + + for (var i = 0; i < args.length; i++) { + var value = abs(args[i]); + + if (smaller(largest, value)) { + result = multiplyScalar(result, multiplyScalar(divideScalar(largest, value), divideScalar(largest, value))); + result = addScalar(result, 1); + largest = value; + } else { + result = addScalar(result, isPositive(value) ? multiplyScalar(divideScalar(value, largest), divideScalar(value, largest)) : value); + } + } + + return multiplyScalar(largest, sqrt(result)); + } + + return hypot; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/norm.js + +var norm_name = 'norm'; +var norm_dependencies = ['typed', 'abs', 'add', 'pow', 'conj', 'sqrt', 'multiply', 'equalScalar', 'larger', 'smaller', 'matrix']; +var createNorm = /* #__PURE__ */Object(factory["a" /* factory */])(norm_name, norm_dependencies, function (_ref) { + var typed = _ref.typed, + abs = _ref.abs, + add = _ref.add, + pow = _ref.pow, + conj = _ref.conj, + sqrt = _ref.sqrt, + multiply = _ref.multiply, + equalScalar = _ref.equalScalar, + larger = _ref.larger, + smaller = _ref.smaller, + matrix = _ref.matrix; + + /** + * Calculate the norm of a number, vector or matrix. + * + * The second parameter p is optional. If not provided, it defaults to 2. + * + * Syntax: + * + * math.norm(x) + * math.norm(x, p) + * + * Examples: + * + * math.abs(-3.5) // returns 3.5 + * math.norm(-3.5) // returns 3.5 + * + * math.norm(math.complex(3, -4)) // returns 5 + * + * math.norm([1, 2, -3], Infinity) // returns 3 + * math.norm([1, 2, -3], -Infinity) // returns 1 + * + * math.norm([3, 4], 2) // returns 5 + * + * math.norm([[1, 2], [3, 4]], 1) // returns 6 + * math.norm([[1, 2], [3, 4]], 'inf') // returns 7 + * math.norm([[1, 2], [3, 4]], 'fro') // returns 5.477225575051661 + * + * See also: + * + * abs, hypot + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * Value for which to calculate the norm + * @param {number | BigNumber | string} [p=2] + * Vector space. + * Supported numbers include Infinity and -Infinity. + * Supported strings are: 'inf', '-inf', and 'fro' (The Frobenius norm) + * @return {number | BigNumber} the p-norm + */ + var norm = typed(norm_name, { + number: Math.abs, + Complex: function Complex(x) { + return x.abs(); + }, + BigNumber: function BigNumber(x) { + // norm(x) = abs(x) + return x.abs(); + }, + "boolean": function boolean(x) { + // norm(x) = abs(x) + return Math.abs(x); + }, + Array: function Array(x) { + return _norm(matrix(x), 2); + }, + Matrix: function Matrix(x) { + return _norm(x, 2); + }, + 'number | Complex | BigNumber | boolean, number | BigNumber | string': function numberComplexBigNumberBooleanNumberBigNumberString(x) { + // ignore second parameter, TODO: remove the option of second parameter for these types + return norm(x); + }, + 'Array, number | BigNumber | string': function ArrayNumberBigNumberString(x, p) { + return _norm(matrix(x), p); + }, + 'Matrix, number | BigNumber | string': function MatrixNumberBigNumberString(x, p) { + return _norm(x, p); + } + }); + /** + * Calculate the norm for an array + * @param {Matrix} x + * @param {number | string} p + * @returns {number} Returns the norm + * @private + */ + + function _norm(x, p) { + // size + var sizeX = x.size(); // check if it is a vector + + if (sizeX.length === 1) { + // check p + if (p === Number.POSITIVE_INFINITY || p === 'inf') { + // norm(x, Infinity) = max(abs(x)) + var pinf = 0; // skip zeros since abs(0) === 0 + + x.forEach(function (value) { + var v = abs(value); + + if (larger(v, pinf)) { + pinf = v; + } + }, true); + return pinf; + } + + if (p === Number.NEGATIVE_INFINITY || p === '-inf') { + // norm(x, -Infinity) = min(abs(x)) + var ninf; // skip zeros since abs(0) === 0 + + x.forEach(function (value) { + var v = abs(value); + + if (!ninf || smaller(v, ninf)) { + ninf = v; + } + }, true); + return ninf || 0; + } + + if (p === 'fro') { + return _norm(x, 2); + } + + if (typeof p === 'number' && !isNaN(p)) { + // check p != 0 + if (!equalScalar(p, 0)) { + // norm(x, p) = sum(abs(xi) ^ p) ^ 1/p + var n = 0; // skip zeros since abs(0) === 0 + + x.forEach(function (value) { + n = add(pow(abs(value), p), n); + }, true); + return pow(n, 1 / p); + } + + return Number.POSITIVE_INFINITY; + } // invalid parameter value + + + throw new Error('Unsupported parameter value'); + } // MxN matrix + + + if (sizeX.length === 2) { + // check p + if (p === 1) { + // norm(x) = the largest column sum + var c = []; // result + + var maxc = 0; // skip zeros since abs(0) == 0 + + x.forEach(function (value, index) { + var j = index[1]; + var cj = add(c[j] || 0, abs(value)); + + if (larger(cj, maxc)) { + maxc = cj; + } + + c[j] = cj; + }, true); + return maxc; + } + + if (p === Number.POSITIVE_INFINITY || p === 'inf') { + // norm(x) = the largest row sum + var r = []; // result + + var maxr = 0; // skip zeros since abs(0) == 0 + + x.forEach(function (value, index) { + var i = index[0]; + var ri = add(r[i] || 0, abs(value)); + + if (larger(ri, maxr)) { + maxr = ri; + } + + r[i] = ri; + }, true); + return maxr; + } + + if (p === 'fro') { + // norm(x) = sqrt(sum(diag(x'x))) + var fro = 0; + x.forEach(function (value, index) { + fro = add(fro, multiply(value, conj(value))); + }); + return abs(sqrt(fro)); + } + + if (p === 2) { + // not implemented + throw new Error('Unsupported parameter value, missing implementation of matrix singular value decomposition'); + } // invalid parameter value + + + throw new Error('Unsupported parameter value'); + } + } + + return norm; +}); +// CONCATENATED MODULE: ./src/function/matrix/dot.js + + +var dot_name = 'dot'; +var dot_dependencies = ['typed', 'add', 'multiply']; +var createDot = /* #__PURE__ */Object(factory["a" /* factory */])(dot_name, dot_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + multiply = _ref.multiply; + + /** + * Calculate the dot product of two vectors. The dot product of + * `A = [a1, a2, a3, ..., an]` and `B = [b1, b2, b3, ..., bn]` is defined as: + * + * dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn + * + * Syntax: + * + * math.dot(x, y) + * + * Examples: + * + * math.dot([2, 4, 1], [2, 2, 3]) // returns number 15 + * math.multiply([2, 4, 1], [2, 2, 3]) // returns number 15 + * + * See also: + * + * multiply, cross + * + * @param {Array | Matrix} x First vector + * @param {Array | Matrix} y Second vector + * @return {number} Returns the dot product of `x` and `y` + */ + return typed(dot_name, { + 'Matrix, Matrix': function MatrixMatrix(x, y) { + return _dot(x.toArray(), y.toArray()); + }, + 'Matrix, Array': function MatrixArray(x, y) { + return _dot(x.toArray(), y); + }, + 'Array, Matrix': function ArrayMatrix(x, y) { + return _dot(x, y.toArray()); + }, + 'Array, Array': _dot + }); + /** + * Calculate the dot product for two arrays + * @param {Array} x First vector + * @param {Array} y Second vector + * @returns {number} Returns the dot product of x and y + * @private + */ + // TODO: double code with math.multiply + + function _dot(x, y) { + var xSize = Object(utils_array["a" /* arraySize */])(x); + var ySize = Object(utils_array["a" /* arraySize */])(y); + var len = xSize[0]; + if (xSize.length !== 1 || ySize.length !== 1) throw new RangeError('Vector expected'); // TODO: better error message + + if (xSize[0] !== ySize[0]) throw new RangeError('Vectors must have equal length (' + xSize[0] + ' != ' + ySize[0] + ')'); + if (len === 0) throw new RangeError('Cannot calculate the dot product of empty vectors'); + var prod = 0; + + for (var i = 0; i < len; i++) { + prod = add(prod, multiply(x[i], y[i])); + } + + return prod; + } +}); +// CONCATENATED MODULE: ./src/function/matrix/trace.js + + + +var trace_name = 'trace'; +var trace_dependencies = ['typed', 'matrix', 'add']; +var createTrace = /* #__PURE__ */Object(factory["a" /* factory */])(trace_name, trace_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + add = _ref.add; + + /** + * Calculate the trace of a matrix: the sum of the elements on the main + * diagonal of a square matrix. + * + * Syntax: + * + * math.trace(x) + * + * Examples: + * + * math.trace([[1, 2], [3, 4]]) // returns 5 + * + * const A = [ + * [1, 2, 3], + * [-1, 2, 3], + * [2, 0, 3] + * ] + * math.trace(A) // returns 6 + * + * See also: + * + * diag + * + * @param {Array | Matrix} x A matrix + * + * @return {number} The trace of `x` + */ + return typed('trace', { + Array: function _arrayTrace(x) { + // use dense matrix implementation + return _denseTrace(matrix(x)); + }, + SparseMatrix: _sparseTrace, + DenseMatrix: _denseTrace, + any: utils_object["a" /* clone */] + }); + + function _denseTrace(m) { + // matrix size & data + var size = m._size; + var data = m._data; // process dimensions + + switch (size.length) { + case 1: + // vector + if (size[0] === 1) { + // return data[0] + return Object(utils_object["a" /* clone */])(data[0]); + } + + throw new RangeError('Matrix must be square (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + + case 2: + { + // two dimensional + var rows = size[0]; + var cols = size[1]; + + if (rows === cols) { + // calulate sum + var sum = 0; // loop diagonal + + for (var i = 0; i < rows; i++) { + sum = add(sum, data[i][i]); + } // return trace + + + return sum; + } else { + throw new RangeError('Matrix must be square (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + } + + default: + // multi dimensional + throw new RangeError('Matrix must be two dimensional (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + } + + function _sparseTrace(m) { + // matrix arrays + var values = m._values; + var index = m._index; + var ptr = m._ptr; + var size = m._size; // check dimensions + + var rows = size[0]; + var columns = size[1]; // matrix must be square + + if (rows === columns) { + // calulate sum + var sum = 0; // check we have data (avoid looping columns) + + if (values.length > 0) { + // loop columns + for (var j = 0; j < columns; j++) { + // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + var k0 = ptr[j]; + var k1 = ptr[j + 1]; // loop k within [k0, k1[ + + for (var k = k0; k < k1; k++) { + // row index + var i = index[k]; // check row + + if (i === j) { + // accumulate value + sum = add(sum, values[k]); // exit loop + + break; + } + + if (i > j) { + // exit loop, no value on the diagonal for column j + break; + } + } + } + } // return trace + + + return sum; + } + + throw new RangeError('Matrix must be square (size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } +}); +// CONCATENATED MODULE: ./src/type/matrix/function/index.js + + +var function_name = 'index'; +var function_dependencies = ['typed', 'Index']; +var createIndex = /* #__PURE__ */Object(factory["a" /* factory */])(function_name, function_dependencies, function (_ref) { + var typed = _ref.typed, + Index = _ref.Index; + + /** + * Create an index. An Index can store ranges having start, step, and end + * for multiple dimensions. + * Matrix.get, Matrix.set, and math.subset accept an Index as input. + * + * Syntax: + * + * math.index(range1, range2, ...) + * + * Where each range can be any of: + * + * - A number + * - A string for getting/setting an object property + * - An instance of `Range` + * - A one-dimensional Array or a Matrix with numbers + * + * Indexes must be zero-based, integer numbers. + * + * Examples: + * + * const b = [1, 2, 3, 4, 5] + * math.subset(b, math.index([1, 2, 3])) // returns [2, 3, 4] + * + * const a = math.matrix([[1, 2], [3, 4]]) + * a.subset(math.index(0, 1)) // returns 2 + * + * See also: + * + * bignumber, boolean, complex, matrix, number, string, unit + * + * @param {...*} ranges Zero or more ranges or numbers. + * @return {Index} Returns the created index + */ + return typed(function_name, { + '...number | string | BigNumber | Range | Array | Matrix': function numberStringBigNumberRangeArrayMatrix(args) { + var ranges = args.map(function (arg) { + if (Object(is["e" /* isBigNumber */])(arg)) { + return arg.toNumber(); // convert BigNumber to Number + } else if (Array.isArray(arg) || Object(is["v" /* isMatrix */])(arg)) { + return arg.map(function (elem) { + // convert BigNumber to Number + return Object(is["e" /* isBigNumber */])(elem) ? elem.toNumber() : elem; + }); + } else { + return arg; + } + }); + var res = new Index(); + Index.apply(res, ranges); + return res; + } + }); +}); +// CONCATENATED MODULE: ./src/expression/keywords.js +// Reserved keywords not allowed to use in the parser +var keywords = { + end: true +}; +// CONCATENATED MODULE: ./src/expression/node/Node.js +function Node_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { Node_typeof = function _typeof(obj) { return typeof obj; }; } else { Node_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return Node_typeof(obj); } + + + + + + +var Node_name = 'Node'; +var Node_dependencies = ['mathWithTransform']; +var createNode = /* #__PURE__ */Object(factory["a" /* factory */])(Node_name, Node_dependencies, function (_ref) { + var mathWithTransform = _ref.mathWithTransform; + + /** + * Node + */ + function Node() { + if (!(this instanceof Node)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + } + /** + * Evaluate the node + * @param {Object} [scope] Scope to read/write variables + * @return {*} Returns the result + */ + + + Node.prototype.evaluate = function (scope) { + return this.compile().evaluate(scope); + }; + /** + * Evaluate the node + * @param {Object} [scope] Scope to read/write variables + * @return {*} Returns the result + */ + // TODO: Deprecated since v6.0.0. Clean up some day + + + Node.prototype.eval = function (scope) { + Object(utils_log["a" /* warnOnce */])('Method Node.eval is renamed to Node.evaluate. Please use the new method name.'); + return this.evaluate(scope); + }; + + Node.prototype.type = 'Node'; + Node.prototype.isNode = true; + Node.prototype.comment = ''; + /** + * Compile the node into an optimized, evauatable JavaScript function + * @return {{evaluate: function([Object])}} object + * Returns an object with a function 'evaluate', + * which can be invoked as expr.evaluate([scope: Object]), + * where scope is an optional object with + * variables. + */ + + Node.prototype.compile = function () { + var expr = this._compile(mathWithTransform, {}); + + var args = {}; + var context = null; + + function evaluate(scope) { + var s = scope || {}; + + _validateScope(s); + + return expr(s, args, context); + } + + return { + evaluate: evaluate, + // TODO: Deprecated since v6.0.0. Clean up some day + eval: function deprecatedEval(scope) { + Object(utils_log["a" /* warnOnce */])('Method eval is renamed to evaluate. Please use the new method.'); + return evaluate(scope); + } + }; + }; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + + Node.prototype._compile = function (math, argNames) { + throw new Error('Method _compile should be implemented by type ' + this.type); + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + Node.prototype.forEach = function (callback) { + // must be implemented by each of the Node implementations + throw new Error('Cannot run forEach on a Node interface'); + }; + /** + * Create a new Node having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {OperatorNode} Returns a transformed copy of the node + */ + + + Node.prototype.map = function (callback) { + // must be implemented by each of the Node implementations + throw new Error('Cannot run map on a Node interface'); + }; + /** + * Validate whether an object is a Node, for use with map + * @param {Node} node + * @returns {Node} Returns the input if it's a node, else throws an Error + * @protected + */ + + + Node.prototype._ifNode = function (node) { + if (!Object(is["w" /* isNode */])(node)) { + throw new TypeError('Callback function must return a Node'); + } + + return node; + }; + /** + * Recursively traverse all nodes in a node tree. Executes given callback for + * this node and each of its child nodes. + * @param {function(node: Node, path: string, parent: Node)} callback + * A callback called for every node in the node tree. + */ + + + Node.prototype.traverse = function (callback) { + // execute callback for itself + callback(this, null, null); // eslint-disable-line standard/no-callback-literal + // recursively traverse over all childs of a node + + function _traverse(node, callback) { + node.forEach(function (child, path, parent) { + callback(child, path, parent); + + _traverse(child, callback); + }); + } + + _traverse(this, callback); + }; + /** + * Recursively transform a node tree via a transform function. + * + * For example, to replace all nodes of type SymbolNode having name 'x' with a + * ConstantNode with value 2: + * + * const res = Node.transform(function (node, path, parent) { + * if (node && node.isSymbolNode) && (node.name === 'x')) { + * return new ConstantNode(2) + * } + * else { + * return node + * } + * }) + * + * @param {function(node: Node, path: string, parent: Node) : Node} callback + * A mapping function accepting a node, and returning + * a replacement for the node or the original node. + * Signature: callback(node: Node, index: string, parent: Node) : Node + * @return {Node} Returns the original node or its replacement + */ + + + Node.prototype.transform = function (callback) { + function _transform(child, path, parent) { + var replacement = callback(child, path, parent); + + if (replacement !== child) { + // stop iterating when the node is replaced + return replacement; + } + + return child.map(_transform); + } + + return _transform(this, null, null); + }; + /** + * Find any node in the node tree matching given filter function. For example, to + * find all nodes of type SymbolNode having name 'x': + * + * const results = Node.filter(function (node) { + * return (node && node.isSymbolNode) && (node.name === 'x') + * }) + * + * @param {function(node: Node, path: string, parent: Node) : Node} callback + * A test function returning true when a node matches, and false + * otherwise. Function signature: + * callback(node: Node, index: string, parent: Node) : boolean + * @return {Node[]} nodes An array with nodes matching given filter criteria + */ + + + Node.prototype.filter = function (callback) { + var nodes = []; + this.traverse(function (node, path, parent) { + if (callback(node, path, parent)) { + nodes.push(node); + } + }); + return nodes; + }; // TODO: deprecated since version 1.1.0, remove this some day + + + Node.prototype.find = function () { + throw new Error('Function Node.find is deprecated. Use Node.filter instead.'); + }; // TODO: deprecated since version 1.1.0, remove this some day + + + Node.prototype.match = function () { + throw new Error('Function Node.match is deprecated. See functions Node.filter, Node.transform, Node.traverse.'); + }; + /** + * Create a shallow clone of this node + * @return {Node} + */ + + + Node.prototype.clone = function () { + // must be implemented by each of the Node implementations + throw new Error('Cannot clone a Node interface'); + }; + /** + * Create a deep clone of this node + * @return {Node} + */ + + + Node.prototype.cloneDeep = function () { + return this.map(function (node) { + return node.cloneDeep(); + }); + }; + /** + * Deep compare this node with another node. + * @param {Node} other + * @return {boolean} Returns true when both nodes are of the same type and + * contain the same values (as do their childs) + */ + + + Node.prototype.equals = function (other) { + return other ? Object(utils_object["d" /* deepStrictEqual */])(this, other) : false; + }; + /** + * Get string representation. (wrapper function) + * + * This function can get an object of the following form: + * { + * handler: //This can be a callback function of the form + * // "function callback(node, options)"or + * // a map that maps function names (used in FunctionNodes) + * // to callbacks + * parenthesis: "keep" //the parenthesis option (This is optional) + * } + * + * @param {Object} [options] + * @return {string} + */ + + + Node.prototype.toString = function (options) { + var customString; + + if (options && Node_typeof(options) === 'object') { + switch (Node_typeof(options.handler)) { + case 'object': + case 'undefined': + break; + + case 'function': + customString = options.handler(this, options); + break; + + default: + throw new TypeError('Object or function expected as callback'); + } + } + + if (typeof customString !== 'undefined') { + return customString; + } + + return this._toString(options); + }; + /** + * Get a JSON representation of the node + * Both .toJSON() and the static .fromJSON(json) should be implemented by all + * implementations of Node + * @returns {Object} + */ + + + Node.prototype.toJSON = function () { + throw new Error('Cannot serialize object: toJSON not implemented by ' + this.type); + }; + /** + * Get HTML representation. (wrapper function) + * + * This function can get an object of the following form: + * { + * handler: //This can be a callback function of the form + * // "function callback(node, options)" or + * // a map that maps function names (used in FunctionNodes) + * // to callbacks + * parenthesis: "keep" //the parenthesis option (This is optional) + * } + * + * @param {Object} [options] + * @return {string} + */ + + + Node.prototype.toHTML = function (options) { + var customString; + + if (options && Node_typeof(options) === 'object') { + switch (Node_typeof(options.handler)) { + case 'object': + case 'undefined': + break; + + case 'function': + customString = options.handler(this, options); + break; + + default: + throw new TypeError('Object or function expected as callback'); + } + } + + if (typeof customString !== 'undefined') { + return customString; + } + + return this.toHTML(options); + }; + /** + * Internal function to generate the string output. + * This has to be implemented by every Node + * + * @throws {Error} + */ + + + Node.prototype._toString = function () { + // must be implemented by each of the Node implementations + throw new Error('_toString not implemented for ' + this.type); + }; + /** + * Get LaTeX representation. (wrapper function) + * + * This function can get an object of the following form: + * { + * handler: //This can be a callback function of the form + * // "function callback(node, options)"or + * // a map that maps function names (used in FunctionNodes) + * // to callbacks + * parenthesis: "keep" //the parenthesis option (This is optional) + * } + * + * @param {Object} [options] + * @return {string} + */ + + + Node.prototype.toTex = function (options) { + var customTex; + + if (options && Node_typeof(options) === 'object') { + switch (Node_typeof(options.handler)) { + case 'object': + case 'undefined': + break; + + case 'function': + customTex = options.handler(this, options); + break; + + default: + throw new TypeError('Object or function expected as callback'); + } + } + + if (typeof customTex !== 'undefined') { + return customTex; + } + + return this._toTex(options); + }; + /** + * Internal function to generate the LaTeX output. + * This has to be implemented by every Node + * + * @param {Object} [options] + * @throws {Error} + */ + + + Node.prototype._toTex = function (options) { + // must be implemented by each of the Node implementations + throw new Error('_toTex not implemented for ' + this.type); + }; + /** + * Get identifier. + * @return {string} + */ + + + Node.prototype.getIdentifier = function () { + return this.type; + }; + /** + * Get the content of the current Node. + * @return {Node} node + **/ + + + Node.prototype.getContent = function () { + return this; + }; + /** + * Validate the symbol names of a scope. + * Throws an error when the scope contains an illegal symbol. + * @param {Object} scope + */ + + + function _validateScope(scope) { + for (var symbol in scope) { + if (Object(utils_object["f" /* hasOwnProperty */])(scope, symbol)) { + if (symbol in keywords) { + throw new Error('Scope contains an illegal symbol, "' + symbol + '" is a reserved keyword'); + } + } + } + } + + return Node; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/transform/utils/errorTransform.js + +/** + * Transform zero-based indices to one-based indices in errors + * @param {Error} err + * @returns {Error | IndexError} Returns the transformed error + */ + +function errorTransform(err) { + if (err && err.isIndexError) { + return new IndexError["a" /* IndexError */](err.index + 1, err.min + 1, err.max !== undefined ? err.max + 1 : undefined); + } + + return err; +} +// CONCATENATED MODULE: ./src/expression/node/utils/access.js +function access_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { access_typeof = function _typeof(obj) { return typeof obj; }; } else { access_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return access_typeof(obj); } + + + +function accessFactory(_ref) { + var subset = _ref.subset; + + /** + * Retrieve part of an object: + * + * - Retrieve a property from an object + * - Retrieve a part of a string + * - Retrieve a matrix subset + * + * @param {Object | Array | Matrix | string} object + * @param {Index} index + * @return {Object | Array | Matrix | string} Returns the subset + */ + return function access(object, index) { + try { + if (Array.isArray(object)) { + return subset(object, index); + } else if (object && typeof object.subset === 'function') { + // Matrix + return object.subset(index); + } else if (typeof object === 'string') { + // TODO: move getStringSubset into a separate util file, use that + return subset(object, index); + } else if (access_typeof(object) === 'object') { + if (!index.isObjectProperty()) { + throw new TypeError('Cannot apply a numeric index as object property'); + } + + return getSafeProperty(object, index.getObjectProperty()); + } else { + throw new TypeError('Cannot apply index: unsupported type of object'); + } + } catch (err) { + throw errorTransform(err); + } + }; +} +// CONCATENATED MODULE: ./src/expression/node/AccessorNode.js + + + + +var AccessorNode_name = 'AccessorNode'; +var AccessorNode_dependencies = ['subset', 'Node']; +var createAccessorNode = /* #__PURE__ */Object(factory["a" /* factory */])(AccessorNode_name, AccessorNode_dependencies, function (_ref) { + var subset = _ref.subset, + Node = _ref.Node; + var access = accessFactory({ + subset: subset + }); + /** + * @constructor AccessorNode + * @extends {Node} + * Access an object property or get a matrix subset + * + * @param {Node} object The object from which to retrieve + * a property or subset. + * @param {IndexNode} index IndexNode containing ranges + */ + + function AccessorNode(object, index) { + if (!(this instanceof AccessorNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (!Object(is["w" /* isNode */])(object)) { + throw new TypeError('Node expected for parameter "object"'); + } + + if (!Object(is["u" /* isIndexNode */])(index)) { + throw new TypeError('IndexNode expected for parameter "index"'); + } + + this.object = object || null; + this.index = index; // readonly property name + + Object.defineProperty(this, 'name', { + get: function () { + if (this.index) { + return this.index.isObjectProperty() ? this.index.getObjectProperty() : ''; + } else { + return this.object.name || ''; + } + }.bind(this), + set: function set() { + throw new Error('Cannot assign a new name, name is read-only'); + } + }); + } + + AccessorNode.prototype = new Node(); + AccessorNode.prototype.type = 'AccessorNode'; + AccessorNode.prototype.isAccessorNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + AccessorNode.prototype._compile = function (math, argNames) { + var evalObject = this.object._compile(math, argNames); + + var evalIndex = this.index._compile(math, argNames); + + if (this.index.isObjectProperty()) { + var prop = this.index.getObjectProperty(); + return function evalAccessorNode(scope, args, context) { + return getSafeProperty(evalObject(scope, args, context), prop); + }; + } else { + return function evalAccessorNode(scope, args, context) { + var object = evalObject(scope, args, context); + var index = evalIndex(scope, args, object); // we pass object here instead of context + + return access(object, index); + }; + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + AccessorNode.prototype.forEach = function (callback) { + callback(this.object, 'object', this); + callback(this.index, 'index', this); + }; + /** + * Create a new AccessorNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {AccessorNode} Returns a transformed copy of the node + */ + + + AccessorNode.prototype.map = function (callback) { + return new AccessorNode(this._ifNode(callback(this.object, 'object', this)), this._ifNode(callback(this.index, 'index', this))); + }; + /** + * Create a clone of this node, a shallow copy + * @return {AccessorNode} + */ + + + AccessorNode.prototype.clone = function () { + return new AccessorNode(this.object, this.index); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} + */ + + + AccessorNode.prototype._toString = function (options) { + var object = this.object.toString(options); + + if (needParenthesis(this.object)) { + object = '(' + object + ')'; + } + + return object + this.index.toString(options); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} + */ + + + AccessorNode.prototype.toHTML = function (options) { + var object = this.object.toHTML(options); + + if (needParenthesis(this.object)) { + object = '(' + object + ')'; + } + + return object + this.index.toHTML(options); + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} + */ + + + AccessorNode.prototype._toTex = function (options) { + var object = this.object.toTex(options); + + if (needParenthesis(this.object)) { + object = '\\left(\' + object + \'\\right)'; + } + + return object + this.index.toTex(options); + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + AccessorNode.prototype.toJSON = function () { + return { + mathjs: 'AccessorNode', + object: this.object, + index: this.index + }; + }; + /** + * Instantiate an AccessorNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "AccessorNode", object: ..., index: ...}`, + * where mathjs is optional + * @returns {AccessorNode} + */ + + + AccessorNode.fromJSON = function (json) { + return new AccessorNode(json.object, json.index); + }; + /** + * Are parenthesis needed? + * @private + */ + + + function needParenthesis(node) { + // TODO: maybe make a method on the nodes which tells whether they need parenthesis? + return !(Object(is["a" /* isAccessorNode */])(node) || Object(is["c" /* isArrayNode */])(node) || Object(is["l" /* isConstantNode */])(node) || Object(is["r" /* isFunctionNode */])(node) || Object(is["A" /* isObjectNode */])(node) || Object(is["C" /* isParenthesisNode */])(node) || Object(is["J" /* isSymbolNode */])(node)); + } + + return AccessorNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/ArrayNode.js + + + +var ArrayNode_name = 'ArrayNode'; +var ArrayNode_dependencies = ['Node']; +var createArrayNode = /* #__PURE__ */Object(factory["a" /* factory */])(ArrayNode_name, ArrayNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * @constructor ArrayNode + * @extends {Node} + * Holds an 1-dimensional array with items + * @param {Node[]} [items] 1 dimensional array with items + */ + function ArrayNode(items) { + if (!(this instanceof ArrayNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.items = items || []; // validate input + + if (!Array.isArray(this.items) || !this.items.every(is["w" /* isNode */])) { + throw new TypeError('Array containing Nodes expected'); + } // TODO: deprecated since v3, remove some day + + + var deprecated = function deprecated() { + throw new Error('Property `ArrayNode.nodes` is deprecated, use `ArrayNode.items` instead'); + }; + + Object.defineProperty(this, 'nodes', { + get: deprecated, + set: deprecated + }); + } + + ArrayNode.prototype = new Node(); + ArrayNode.prototype.type = 'ArrayNode'; + ArrayNode.prototype.isArrayNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + ArrayNode.prototype._compile = function (math, argNames) { + var evalItems = Object(utils_array["m" /* map */])(this.items, function (item) { + return item._compile(math, argNames); + }); + var asMatrix = math.config.matrix !== 'Array'; + + if (asMatrix) { + var matrix = math.matrix; + return function evalArrayNode(scope, args, context) { + return matrix(Object(utils_array["m" /* map */])(evalItems, function (evalItem) { + return evalItem(scope, args, context); + })); + }; + } else { + return function evalArrayNode(scope, args, context) { + return Object(utils_array["m" /* map */])(evalItems, function (evalItem) { + return evalItem(scope, args, context); + }); + }; + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + ArrayNode.prototype.forEach = function (callback) { + for (var i = 0; i < this.items.length; i++) { + var node = this.items[i]; + callback(node, 'items[' + i + ']', this); + } + }; + /** + * Create a new ArrayNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {ArrayNode} Returns a transformed copy of the node + */ + + + ArrayNode.prototype.map = function (callback) { + var items = []; + + for (var i = 0; i < this.items.length; i++) { + items[i] = this._ifNode(callback(this.items[i], 'items[' + i + ']', this)); + } + + return new ArrayNode(items); + }; + /** + * Create a clone of this node, a shallow copy + * @return {ArrayNode} + */ + + + ArrayNode.prototype.clone = function () { + return new ArrayNode(this.items.slice(0)); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ArrayNode.prototype._toString = function (options) { + var items = this.items.map(function (node) { + return node.toString(options); + }); + return '[' + items.join(', ') + ']'; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + ArrayNode.prototype.toJSON = function () { + return { + mathjs: 'ArrayNode', + items: this.items + }; + }; + /** + * Instantiate an ArrayNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "ArrayNode", items: [...]}`, + * where mathjs is optional + * @returns {ArrayNode} + */ + + + ArrayNode.fromJSON = function (json) { + return new ArrayNode(json.items); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ArrayNode.prototype.toHTML = function (options) { + var items = this.items.map(function (node) { + return node.toHTML(options); + }); + return '[' + items.join(',') + ']'; + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + ArrayNode.prototype._toTex = function (options) { + var s = '\\begin{bmatrix}'; + this.items.forEach(function (node) { + if (node.items) { + s += node.items.map(function (childNode) { + return childNode.toTex(options); + }).join('&'); + } else { + s += node.toTex(options); + } // new line + + + s += '\\\\'; + }); + s += '\\end{bmatrix}'; + return s; + }; + + return ArrayNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/utils/assign.js +function assign_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { assign_typeof = function _typeof(obj) { return typeof obj; }; } else { assign_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return assign_typeof(obj); } + + + +function assignFactory(_ref) { + var subset = _ref.subset, + matrix = _ref.matrix; + + /** + * Replace part of an object: + * + * - Assign a property to an object + * - Replace a part of a string + * - Replace a matrix subset + * + * @param {Object | Array | Matrix | string} object + * @param {Index} index + * @param {*} value + * @return {Object | Array | Matrix | string} Returns the original object + * except in case of a string + */ + // TODO: change assign to return the value instead of the object + return function assign(object, index, value) { + try { + if (Array.isArray(object)) { + // we use matrix.subset here instead of the function subset because we must not clone the contents + return matrix(object).subset(index, value).valueOf(); + } else if (object && typeof object.subset === 'function') { + // Matrix + return object.subset(index, value); + } else if (typeof object === 'string') { + // TODO: move setStringSubset into a separate util file, use that + return subset(object, index, value); + } else if (assign_typeof(object) === 'object') { + if (!index.isObjectProperty()) { + throw TypeError('Cannot apply a numeric index as object property'); + } + + setSafeProperty(object, index.getObjectProperty(), value); + return object; + } else { + throw new TypeError('Cannot apply index: unsupported type of object'); + } + } catch (err) { + throw errorTransform(err); + } + }; +} +// CONCATENATED MODULE: ./src/expression/operators.js +// list of identifiers of nodes in order of their precedence +// also contains information about left/right associativity +// and which other operator the operator is associative with +// Example: +// addition is associative with addition and subtraction, because: +// (a+b)+c=a+(b+c) +// (a+b)-c=a+(b-c) +// +// postfix operators are left associative, prefix operators +// are right associative +// +// It's also possible to set the following properties: +// latexParens: if set to false, this node doesn't need to be enclosed +// in parentheses when using LaTeX +// latexLeftParens: if set to false, this !OperatorNode's! +// left argument doesn't need to be enclosed +// in parentheses +// latexRightParens: the same for the right argument + +var operators_properties = [{ + // assignment + AssignmentNode: {}, + FunctionAssignmentNode: {} +}, { + // conditional expression + ConditionalNode: { + latexLeftParens: false, + latexRightParens: false, + latexParens: false // conditionals don't need parentheses in LaTeX because + // they are 2 dimensional + + } +}, { + // logical or + 'OperatorNode:or': { + associativity: 'left', + associativeWith: [] + } +}, { + // logical xor + 'OperatorNode:xor': { + associativity: 'left', + associativeWith: [] + } +}, { + // logical and + 'OperatorNode:and': { + associativity: 'left', + associativeWith: [] + } +}, { + // bitwise or + 'OperatorNode:bitOr': { + associativity: 'left', + associativeWith: [] + } +}, { + // bitwise xor + 'OperatorNode:bitXor': { + associativity: 'left', + associativeWith: [] + } +}, { + // bitwise and + 'OperatorNode:bitAnd': { + associativity: 'left', + associativeWith: [] + } +}, { + // relational operators + 'OperatorNode:equal': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:unequal': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:smaller': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:larger': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:smallerEq': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:largerEq': { + associativity: 'left', + associativeWith: [] + }, + RelationalNode: { + associativity: 'left', + associativeWith: [] + } +}, { + // bitshift operators + 'OperatorNode:leftShift': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:rightArithShift': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:rightLogShift': { + associativity: 'left', + associativeWith: [] + } +}, { + // unit conversion + 'OperatorNode:to': { + associativity: 'left', + associativeWith: [] + } +}, { + // range + RangeNode: {} +}, { + // addition, subtraction + 'OperatorNode:add': { + associativity: 'left', + associativeWith: ['OperatorNode:add', 'OperatorNode:subtract'] + }, + 'OperatorNode:subtract': { + associativity: 'left', + associativeWith: [] + } +}, { + // multiply, divide, modulus + 'OperatorNode:multiply': { + associativity: 'left', + associativeWith: ['OperatorNode:multiply', 'OperatorNode:divide', 'Operator:dotMultiply', 'Operator:dotDivide'] + }, + 'OperatorNode:divide': { + associativity: 'left', + associativeWith: [], + latexLeftParens: false, + latexRightParens: false, + latexParens: false // fractions don't require parentheses because + // they're 2 dimensional, so parens aren't needed + // in LaTeX + + }, + 'OperatorNode:dotMultiply': { + associativity: 'left', + associativeWith: ['OperatorNode:multiply', 'OperatorNode:divide', 'OperatorNode:dotMultiply', 'OperatorNode:doDivide'] + }, + 'OperatorNode:dotDivide': { + associativity: 'left', + associativeWith: [] + }, + 'OperatorNode:mod': { + associativity: 'left', + associativeWith: [] + } +}, { + // unary prefix operators + 'OperatorNode:unaryPlus': { + associativity: 'right' + }, + 'OperatorNode:unaryMinus': { + associativity: 'right' + }, + 'OperatorNode:bitNot': { + associativity: 'right' + }, + 'OperatorNode:not': { + associativity: 'right' + } +}, { + // exponentiation + 'OperatorNode:pow': { + associativity: 'right', + associativeWith: [], + latexRightParens: false // the exponent doesn't need parentheses in + // LaTeX because it's 2 dimensional + // (it's on top) + + }, + 'OperatorNode:dotPow': { + associativity: 'right', + associativeWith: [] + } +}, { + // factorial + 'OperatorNode:factorial': { + associativity: 'left' + } +}, { + // matrix transpose + 'OperatorNode:transpose': { + associativity: 'left' + } +}]; +/** + * Get the precedence of a Node. + * Higher number for higher precedence, starting with 0. + * Returns null if the precedence is undefined. + * + * @param {Node} _node + * @param {string} parenthesis + * @return {number | null} + */ + +function getPrecedence(_node, parenthesis) { + var node = _node; + + if (parenthesis !== 'keep') { + // ParenthesisNodes are only ignored when not in 'keep' mode + node = _node.getContent(); + } + + var identifier = node.getIdentifier(); + + for (var i = 0; i < operators_properties.length; i++) { + if (identifier in operators_properties[i]) { + return i; + } + } + + return null; +} +/** + * Get the associativity of an operator (left or right). + * Returns a string containing 'left' or 'right' or null if + * the associativity is not defined. + * + * @param {Node} + * @param {string} parenthesis + * @return {string|null} + * @throws {Error} + */ + +function getAssociativity(_node, parenthesis) { + var node = _node; + + if (parenthesis !== 'keep') { + // ParenthesisNodes are only ignored when not in 'keep' mode + node = _node.getContent(); + } + + var identifier = node.getIdentifier(); + var index = getPrecedence(node, parenthesis); + + if (index === null) { + // node isn't in the list + return null; + } + + var property = operators_properties[index][identifier]; + + if (Object(utils_object["f" /* hasOwnProperty */])(property, 'associativity')) { + if (property.associativity === 'left') { + return 'left'; + } + + if (property.associativity === 'right') { + return 'right'; + } // associativity is invalid + + + throw Error('\'' + identifier + '\' has the invalid associativity \'' + property.associativity + '\'.'); + } // associativity is undefined + + + return null; +} +/** + * Check if an operator is associative with another operator. + * Returns either true or false or null if not defined. + * + * @param {Node} nodeA + * @param {Node} nodeB + * @param {string} parenthesis + * @return {boolean | null} + */ + +function isAssociativeWith(nodeA, nodeB, parenthesis) { + // ParenthesisNodes are only ignored when not in 'keep' mode + var a = parenthesis !== 'keep' ? nodeA.getContent() : nodeA; + var b = parenthesis !== 'keep' ? nodeA.getContent() : nodeB; + var identifierA = a.getIdentifier(); + var identifierB = b.getIdentifier(); + var index = getPrecedence(a, parenthesis); + + if (index === null) { + // node isn't in the list + return null; + } + + var property = operators_properties[index][identifierA]; + + if (Object(utils_object["f" /* hasOwnProperty */])(property, 'associativeWith') && property.associativeWith instanceof Array) { + for (var i = 0; i < property.associativeWith.length; i++) { + if (property.associativeWith[i] === identifierB) { + return true; + } + } + + return false; + } // associativeWith is not defined + + + return null; +} +// CONCATENATED MODULE: ./src/expression/node/AssignmentNode.js + + + + + + +var AssignmentNode_name = 'AssignmentNode'; +var AssignmentNode_dependencies = ['subset', '?matrix', // FIXME: should not be needed at all, should be handled by subset +'Node']; +var createAssignmentNode = /* #__PURE__ */Object(factory["a" /* factory */])(AssignmentNode_name, AssignmentNode_dependencies, function (_ref) { + var subset = _ref.subset, + matrix = _ref.matrix, + Node = _ref.Node; + var access = accessFactory({ + subset: subset + }); + var assign = assignFactory({ + subset: subset, + matrix: matrix + }); + /** + * @constructor AssignmentNode + * @extends {Node} + * + * Define a symbol, like `a=3.2`, update a property like `a.b=3.2`, or + * replace a subset of a matrix like `A[2,2]=42`. + * + * Syntax: + * + * new AssignmentNode(symbol, value) + * new AssignmentNode(object, index, value) + * + * Usage: + * + * new AssignmentNode(new SymbolNode('a'), new ConstantNode(2)) // a=2 + * new AssignmentNode(new SymbolNode('a'), new IndexNode('b'), new ConstantNode(2)) // a.b=2 + * new AssignmentNode(new SymbolNode('a'), new IndexNode(1, 2), new ConstantNode(3)) // a[1,2]=3 + * + * @param {SymbolNode | AccessorNode} object Object on which to assign a value + * @param {IndexNode} [index=null] Index, property name or matrix + * index. Optional. If not provided + * and `object` is a SymbolNode, + * the property is assigned to the + * global scope. + * @param {Node} value The value to be assigned + */ + + function AssignmentNode(object, index, value) { + if (!(this instanceof AssignmentNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.object = object; + this.index = value ? index : null; + this.value = value || index; // validate input + + if (!Object(is["J" /* isSymbolNode */])(object) && !Object(is["a" /* isAccessorNode */])(object)) { + throw new TypeError('SymbolNode or AccessorNode expected as "object"'); + } + + if (Object(is["J" /* isSymbolNode */])(object) && object.name === 'end') { + throw new Error('Cannot assign to symbol "end"'); + } + + if (this.index && !Object(is["u" /* isIndexNode */])(this.index)) { + // index is optional + throw new TypeError('IndexNode expected as "index"'); + } + + if (!Object(is["w" /* isNode */])(this.value)) { + throw new TypeError('Node expected as "value"'); + } // readonly property name + + + Object.defineProperty(this, 'name', { + get: function () { + if (this.index) { + return this.index.isObjectProperty() ? this.index.getObjectProperty() : ''; + } else { + return this.object.name || ''; + } + }.bind(this), + set: function set() { + throw new Error('Cannot assign a new name, name is read-only'); + } + }); + } + + AssignmentNode.prototype = new Node(); + AssignmentNode.prototype.type = 'AssignmentNode'; + AssignmentNode.prototype.isAssignmentNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + AssignmentNode.prototype._compile = function (math, argNames) { + var evalObject = this.object._compile(math, argNames); + + var evalIndex = this.index ? this.index._compile(math, argNames) : null; + + var evalValue = this.value._compile(math, argNames); + + var name = this.object.name; + + if (!this.index) { + // apply a variable to the scope, for example `a=2` + if (!Object(is["J" /* isSymbolNode */])(this.object)) { + throw new TypeError('SymbolNode expected as object'); + } + + return function evalAssignmentNode(scope, args, context) { + return setSafeProperty(scope, name, evalValue(scope, args, context)); + }; + } else if (this.index.isObjectProperty()) { + // apply an object property for example `a.b=2` + var prop = this.index.getObjectProperty(); + return function evalAssignmentNode(scope, args, context) { + var object = evalObject(scope, args, context); + var value = evalValue(scope, args, context); + return setSafeProperty(object, prop, value); + }; + } else if (Object(is["J" /* isSymbolNode */])(this.object)) { + // update a matrix subset, for example `a[2]=3` + return function evalAssignmentNode(scope, args, context) { + var childObject = evalObject(scope, args, context); + var value = evalValue(scope, args, context); + var index = evalIndex(scope, args, childObject); // Important: we pass childObject instead of context + + setSafeProperty(scope, name, assign(childObject, index, value)); + return value; + }; + } else { + // isAccessorNode(node.object) === true + // update a matrix subset, for example `a.b[2]=3` + // we will not use the compile function of the AccessorNode, but compile it + // ourselves here as we need the parent object of the AccessorNode: + // wee need to apply the updated object to parent object + var evalParentObject = this.object.object._compile(math, argNames); + + if (this.object.index.isObjectProperty()) { + var parentProp = this.object.index.getObjectProperty(); + return function evalAssignmentNode(scope, args, context) { + var parent = evalParentObject(scope, args, context); + var childObject = getSafeProperty(parent, parentProp); + var index = evalIndex(scope, args, childObject); // Important: we pass childObject instead of context + + var value = evalValue(scope, args, context); + setSafeProperty(parent, parentProp, assign(childObject, index, value)); + return value; + }; + } else { + // if some parameters use the 'end' parameter, we need to calculate the size + var evalParentIndex = this.object.index._compile(math, argNames); + + return function evalAssignmentNode(scope, args, context) { + var parent = evalParentObject(scope, args, context); + var parentIndex = evalParentIndex(scope, args, parent); // Important: we pass parent instead of context + + var childObject = access(parent, parentIndex); + var index = evalIndex(scope, args, childObject); // Important: we pass childObject instead of context + + var value = evalValue(scope, args, context); + assign(parent, parentIndex, assign(childObject, index, value)); + return value; + }; + } + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + AssignmentNode.prototype.forEach = function (callback) { + callback(this.object, 'object', this); + + if (this.index) { + callback(this.index, 'index', this); + } + + callback(this.value, 'value', this); + }; + /** + * Create a new AssignmentNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {AssignmentNode} Returns a transformed copy of the node + */ + + + AssignmentNode.prototype.map = function (callback) { + var object = this._ifNode(callback(this.object, 'object', this)); + + var index = this.index ? this._ifNode(callback(this.index, 'index', this)) : null; + + var value = this._ifNode(callback(this.value, 'value', this)); + + return new AssignmentNode(object, index, value); + }; + /** + * Create a clone of this node, a shallow copy + * @return {AssignmentNode} + */ + + + AssignmentNode.prototype.clone = function () { + return new AssignmentNode(this.object, this.index, this.value); + }; + /* + * Is parenthesis needed? + * @param {node} node + * @param {string} [parenthesis='keep'] + * @private + */ + + + function needParenthesis(node, parenthesis) { + if (!parenthesis) { + parenthesis = 'keep'; + } + + var precedence = getPrecedence(node, parenthesis); + var exprPrecedence = getPrecedence(node.value, parenthesis); + return parenthesis === 'all' || exprPrecedence !== null && exprPrecedence <= precedence; + } + /** + * Get string representation + * @param {Object} options + * @return {string} + */ + + + AssignmentNode.prototype._toString = function (options) { + var object = this.object.toString(options); + var index = this.index ? this.index.toString(options) : ''; + var value = this.value.toString(options); + + if (needParenthesis(this, options && options.parenthesis)) { + value = '(' + value + ')'; + } + + return object + index + ' = ' + value; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + AssignmentNode.prototype.toJSON = function () { + return { + mathjs: 'AssignmentNode', + object: this.object, + index: this.index, + value: this.value + }; + }; + /** + * Instantiate an AssignmentNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "AssignmentNode", object: ..., index: ..., value: ...}`, + * where mathjs is optional + * @returns {AssignmentNode} + */ + + + AssignmentNode.fromJSON = function (json) { + return new AssignmentNode(json.object, json.index, json.value); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} + */ + + + AssignmentNode.prototype.toHTML = function (options) { + var object = this.object.toHTML(options); + var index = this.index ? this.index.toHTML(options) : ''; + var value = this.value.toHTML(options); + + if (needParenthesis(this, options && options.parenthesis)) { + value = '(' + value + ')'; + } + + return object + index + '=' + value; + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} + */ + + + AssignmentNode.prototype._toTex = function (options) { + var object = this.object.toTex(options); + var index = this.index ? this.index.toTex(options) : ''; + var value = this.value.toTex(options); + + if (needParenthesis(this, options && options.parenthesis)) { + value = "\\left(".concat(value, "\\right)"); + } + + return object + index + ':=' + value; + }; + + return AssignmentNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/BlockNode.js + + + +var BlockNode_name = 'BlockNode'; +var BlockNode_dependencies = ['ResultSet', 'Node']; +var createBlockNode = /* #__PURE__ */Object(factory["a" /* factory */])(BlockNode_name, BlockNode_dependencies, function (_ref) { + var ResultSet = _ref.ResultSet, + Node = _ref.Node; + + /** + * @constructor BlockNode + * @extends {Node} + * Holds a set with blocks + * @param {Array.<{node: Node} | {node: Node, visible: boolean}>} blocks + * An array with blocks, where a block is constructed as an Object + * with properties block, which is a Node, and visible, which is + * a boolean. The property visible is optional and is true by default + */ + function BlockNode(blocks) { + if (!(this instanceof BlockNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // validate input, copy blocks + + + if (!Array.isArray(blocks)) throw new Error('Array expected'); + this.blocks = blocks.map(function (block) { + var node = block && block.node; + var visible = block && block.visible !== undefined ? block.visible : true; + if (!Object(is["w" /* isNode */])(node)) throw new TypeError('Property "node" must be a Node'); + if (typeof visible !== 'boolean') throw new TypeError('Property "visible" must be a boolean'); + return { + node: node, + visible: visible + }; + }); + } + + BlockNode.prototype = new Node(); + BlockNode.prototype.type = 'BlockNode'; + BlockNode.prototype.isBlockNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + BlockNode.prototype._compile = function (math, argNames) { + var evalBlocks = Object(utils_array["m" /* map */])(this.blocks, function (block) { + return { + evaluate: block.node._compile(math, argNames), + visible: block.visible + }; + }); + return function evalBlockNodes(scope, args, context) { + var results = []; + Object(utils_array["f" /* forEach */])(evalBlocks, function evalBlockNode(block) { + var result = block.evaluate(scope, args, context); + + if (block.visible) { + results.push(result); + } + }); + return new ResultSet(results); + }; + }; + /** + * Execute a callback for each of the child blocks of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + BlockNode.prototype.forEach = function (callback) { + for (var i = 0; i < this.blocks.length; i++) { + callback(this.blocks[i].node, 'blocks[' + i + '].node', this); + } + }; + /** + * Create a new BlockNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {BlockNode} Returns a transformed copy of the node + */ + + + BlockNode.prototype.map = function (callback) { + var blocks = []; + + for (var i = 0; i < this.blocks.length; i++) { + var block = this.blocks[i]; + + var node = this._ifNode(callback(block.node, 'blocks[' + i + '].node', this)); + + blocks[i] = { + node: node, + visible: block.visible + }; + } + + return new BlockNode(blocks); + }; + /** + * Create a clone of this node, a shallow copy + * @return {BlockNode} + */ + + + BlockNode.prototype.clone = function () { + var blocks = this.blocks.map(function (block) { + return { + node: block.node, + visible: block.visible + }; + }); + return new BlockNode(blocks); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + * @override + */ + + + BlockNode.prototype._toString = function (options) { + return this.blocks.map(function (param) { + return param.node.toString(options) + (param.visible ? '' : ';'); + }).join('\n'); + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + BlockNode.prototype.toJSON = function () { + return { + mathjs: 'BlockNode', + blocks: this.blocks + }; + }; + /** + * Instantiate an BlockNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "BlockNode", blocks: [{node: ..., visible: false}, ...]}`, + * where mathjs is optional + * @returns {BlockNode} + */ + + + BlockNode.fromJSON = function (json) { + return new BlockNode(json.blocks); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + * @override + */ + + + BlockNode.prototype.toHTML = function (options) { + return this.blocks.map(function (param) { + return param.node.toHTML(options) + (param.visible ? '' : ';'); + }).join('
'); + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + BlockNode.prototype._toTex = function (options) { + return this.blocks.map(function (param) { + return param.node.toTex(options) + (param.visible ? '' : ';'); + }).join('\\;\\;\n'); + }; + + return BlockNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/ConditionalNode.js + + + +var ConditionalNode_name = 'ConditionalNode'; +var ConditionalNode_dependencies = ['Node']; +var createConditionalNode = /* #__PURE__ */Object(factory["a" /* factory */])(ConditionalNode_name, ConditionalNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * A lazy evaluating conditional operator: 'condition ? trueExpr : falseExpr' + * + * @param {Node} condition Condition, must result in a boolean + * @param {Node} trueExpr Expression evaluated when condition is true + * @param {Node} falseExpr Expression evaluated when condition is true + * + * @constructor ConditionalNode + * @extends {Node} + */ + function ConditionalNode(condition, trueExpr, falseExpr) { + if (!(this instanceof ConditionalNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (!Object(is["w" /* isNode */])(condition)) throw new TypeError('Parameter condition must be a Node'); + if (!Object(is["w" /* isNode */])(trueExpr)) throw new TypeError('Parameter trueExpr must be a Node'); + if (!Object(is["w" /* isNode */])(falseExpr)) throw new TypeError('Parameter falseExpr must be a Node'); + this.condition = condition; + this.trueExpr = trueExpr; + this.falseExpr = falseExpr; + } + + ConditionalNode.prototype = new Node(); + ConditionalNode.prototype.type = 'ConditionalNode'; + ConditionalNode.prototype.isConditionalNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + ConditionalNode.prototype._compile = function (math, argNames) { + var evalCondition = this.condition._compile(math, argNames); + + var evalTrueExpr = this.trueExpr._compile(math, argNames); + + var evalFalseExpr = this.falseExpr._compile(math, argNames); + + return function evalConditionalNode(scope, args, context) { + return testCondition(evalCondition(scope, args, context)) ? evalTrueExpr(scope, args, context) : evalFalseExpr(scope, args, context); + }; + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + ConditionalNode.prototype.forEach = function (callback) { + callback(this.condition, 'condition', this); + callback(this.trueExpr, 'trueExpr', this); + callback(this.falseExpr, 'falseExpr', this); + }; + /** + * Create a new ConditionalNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {ConditionalNode} Returns a transformed copy of the node + */ + + + ConditionalNode.prototype.map = function (callback) { + return new ConditionalNode(this._ifNode(callback(this.condition, 'condition', this)), this._ifNode(callback(this.trueExpr, 'trueExpr', this)), this._ifNode(callback(this.falseExpr, 'falseExpr', this))); + }; + /** + * Create a clone of this node, a shallow copy + * @return {ConditionalNode} + */ + + + ConditionalNode.prototype.clone = function () { + return new ConditionalNode(this.condition, this.trueExpr, this.falseExpr); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + */ + + + ConditionalNode.prototype._toString = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var precedence = getPrecedence(this, parenthesis); // Enclose Arguments in parentheses if they are an OperatorNode + // or have lower or equal precedence + // NOTE: enclosing all OperatorNodes in parentheses is a decision + // purely based on aesthetics and readability + + var condition = this.condition.toString(options); + var conditionPrecedence = getPrecedence(this.condition, parenthesis); + + if (parenthesis === 'all' || this.condition.type === 'OperatorNode' || conditionPrecedence !== null && conditionPrecedence <= precedence) { + condition = '(' + condition + ')'; + } + + var trueExpr = this.trueExpr.toString(options); + var truePrecedence = getPrecedence(this.trueExpr, parenthesis); + + if (parenthesis === 'all' || this.trueExpr.type === 'OperatorNode' || truePrecedence !== null && truePrecedence <= precedence) { + trueExpr = '(' + trueExpr + ')'; + } + + var falseExpr = this.falseExpr.toString(options); + var falsePrecedence = getPrecedence(this.falseExpr, parenthesis); + + if (parenthesis === 'all' || this.falseExpr.type === 'OperatorNode' || falsePrecedence !== null && falsePrecedence <= precedence) { + falseExpr = '(' + falseExpr + ')'; + } + + return condition + ' ? ' + trueExpr + ' : ' + falseExpr; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + ConditionalNode.prototype.toJSON = function () { + return { + mathjs: 'ConditionalNode', + condition: this.condition, + trueExpr: this.trueExpr, + falseExpr: this.falseExpr + }; + }; + /** + * Instantiate an ConditionalNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "ConditionalNode", "condition": ..., "trueExpr": ..., "falseExpr": ...}`, + * where mathjs is optional + * @returns {ConditionalNode} + */ + + + ConditionalNode.fromJSON = function (json) { + return new ConditionalNode(json.condition, json.trueExpr, json.falseExpr); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + */ + + + ConditionalNode.prototype.toHTML = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var precedence = getPrecedence(this, parenthesis); // Enclose Arguments in parentheses if they are an OperatorNode + // or have lower or equal precedence + // NOTE: enclosing all OperatorNodes in parentheses is a decision + // purely based on aesthetics and readability + + var condition = this.condition.toHTML(options); + var conditionPrecedence = getPrecedence(this.condition, parenthesis); + + if (parenthesis === 'all' || this.condition.type === 'OperatorNode' || conditionPrecedence !== null && conditionPrecedence <= precedence) { + condition = '(' + condition + ')'; + } + + var trueExpr = this.trueExpr.toHTML(options); + var truePrecedence = getPrecedence(this.trueExpr, parenthesis); + + if (parenthesis === 'all' || this.trueExpr.type === 'OperatorNode' || truePrecedence !== null && truePrecedence <= precedence) { + trueExpr = '(' + trueExpr + ')'; + } + + var falseExpr = this.falseExpr.toHTML(options); + var falsePrecedence = getPrecedence(this.falseExpr, parenthesis); + + if (parenthesis === 'all' || this.falseExpr.type === 'OperatorNode' || falsePrecedence !== null && falsePrecedence <= precedence) { + falseExpr = '(' + falseExpr + ')'; + } + + return condition + '?' + trueExpr + ':' + falseExpr; + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + ConditionalNode.prototype._toTex = function (options) { + return '\\begin{cases} {' + this.trueExpr.toTex(options) + '}, &\\quad{\\text{if }\\;' + this.condition.toTex(options) + '}\\\\{' + this.falseExpr.toTex(options) + '}, &\\quad{\\text{otherwise}}\\end{cases}'; + }; + /** + * Test whether a condition is met + * @param {*} condition + * @returns {boolean} true if condition is true or non-zero, else false + */ + + + function testCondition(condition) { + if (typeof condition === 'number' || typeof condition === 'boolean' || typeof condition === 'string') { + return !!condition; + } + + if (condition) { + if (Object(is["e" /* isBigNumber */])(condition)) { + return !condition.isZero(); + } + + if (Object(is["j" /* isComplex */])(condition)) { + return !!(condition.re || condition.im); + } + + if (Object(is["L" /* isUnit */])(condition)) { + return !!condition.value; + } + } + + if (condition === null || condition === undefined) { + return false; + } + + throw new TypeError('Unsupported type of condition "' + Object(is["M" /* typeOf */])(condition) + '"'); + } + + return ConditionalNode; +}, { + isClass: true, + isNode: true +}); +// EXTERNAL MODULE: ./node_modules/escape-latex/dist/index.js +var dist = __webpack_require__(17); +var dist_default = /*#__PURE__*/__webpack_require__.n(dist); + +// CONCATENATED MODULE: ./src/utils/latex.js +/* eslint no-template-curly-in-string: "off" */ + + +var latexSymbols = { + // GREEK LETTERS + Alpha: 'A', + alpha: '\\alpha', + Beta: 'B', + beta: '\\beta', + Gamma: '\\Gamma', + gamma: '\\gamma', + Delta: '\\Delta', + delta: '\\delta', + Epsilon: 'E', + epsilon: '\\epsilon', + varepsilon: '\\varepsilon', + Zeta: 'Z', + zeta: '\\zeta', + Eta: 'H', + eta: '\\eta', + Theta: '\\Theta', + theta: '\\theta', + vartheta: '\\vartheta', + Iota: 'I', + iota: '\\iota', + Kappa: 'K', + kappa: '\\kappa', + varkappa: '\\varkappa', + Lambda: '\\Lambda', + lambda: '\\lambda', + Mu: 'M', + mu: '\\mu', + Nu: 'N', + nu: '\\nu', + Xi: '\\Xi', + xi: '\\xi', + Omicron: 'O', + omicron: 'o', + Pi: '\\Pi', + pi: '\\pi', + varpi: '\\varpi', + Rho: 'P', + rho: '\\rho', + varrho: '\\varrho', + Sigma: '\\Sigma', + sigma: '\\sigma', + varsigma: '\\varsigma', + Tau: 'T', + tau: '\\tau', + Upsilon: "\\Upsilon", + upsilon: "\\upsilon", + Phi: '\\Phi', + phi: '\\phi', + varphi: '\\varphi', + Chi: 'X', + chi: '\\chi', + Psi: '\\Psi', + psi: '\\psi', + Omega: '\\Omega', + omega: '\\omega', + // logic + "true": '\\mathrm{True}', + "false": '\\mathrm{False}', + // other + i: 'i', + // TODO use \i ?? + inf: '\\infty', + Inf: '\\infty', + infinity: '\\infty', + Infinity: '\\infty', + oo: '\\infty', + lim: '\\lim', + undefined: '\\mathbf{?}' +}; +var latexOperators = { + transpose: '^\\top', + ctranspose: '^H', + factorial: '!', + pow: '^', + dotPow: '.^\\wedge', + // TODO find ideal solution + unaryPlus: '+', + unaryMinus: '-', + bitNot: '\\~', + // TODO find ideal solution + not: '\\neg', + multiply: '\\cdot', + divide: '\\frac', + // TODO how to handle that properly? + dotMultiply: '.\\cdot', + // TODO find ideal solution + dotDivide: '.:', + // TODO find ideal solution + mod: '\\mod', + add: '+', + subtract: '-', + to: '\\rightarrow', + leftShift: '<<', + rightArithShift: '>>', + rightLogShift: '>>>', + equal: '=', + unequal: '\\neq', + smaller: '<', + larger: '>', + smallerEq: '\\leq', + largerEq: '\\geq', + bitAnd: '\\&', + bitXor: "\\underline{|}", + bitOr: '|', + and: '\\wedge', + xor: '\\veebar', + or: '\\vee' +}; +var latexFunctions = { + // arithmetic + abs: { + 1: '\\left|${args[0]}\\right|' + }, + add: { + 2: "\\left(${args[0]}".concat(latexOperators.add, "${args[1]}\\right)") + }, + cbrt: { + 1: '\\sqrt[3]{${args[0]}}' + }, + ceil: { + 1: '\\left\\lceil${args[0]}\\right\\rceil' + }, + cube: { + 1: '\\left(${args[0]}\\right)^3' + }, + divide: { + 2: '\\frac{${args[0]}}{${args[1]}}' + }, + dotDivide: { + 2: "\\left(${args[0]}".concat(latexOperators.dotDivide, "${args[1]}\\right)") + }, + dotMultiply: { + 2: "\\left(${args[0]}".concat(latexOperators.dotMultiply, "${args[1]}\\right)") + }, + dotPow: { + 2: "\\left(${args[0]}".concat(latexOperators.dotPow, "${args[1]}\\right)") + }, + exp: { + 1: '\\exp\\left(${args[0]}\\right)' + }, + expm1: "\\left(e".concat(latexOperators.pow, "{${args[0]}}-1\\right)"), + fix: { + 1: '\\mathrm{${name}}\\left(${args[0]}\\right)' + }, + floor: { + 1: '\\left\\lfloor${args[0]}\\right\\rfloor' + }, + gcd: '\\gcd\\left(${args}\\right)', + hypot: '\\hypot\\left(${args}\\right)', + log: { + 1: '\\ln\\left(${args[0]}\\right)', + 2: '\\log_{${args[1]}}\\left(${args[0]}\\right)' + }, + log10: { + 1: '\\log_{10}\\left(${args[0]}\\right)' + }, + log1p: { + 1: '\\ln\\left(${args[0]}+1\\right)', + 2: '\\log_{${args[1]}}\\left(${args[0]}+1\\right)' + }, + log2: '\\log_{2}\\left(${args[0]}\\right)', + mod: { + 2: "\\left(${args[0]}".concat(latexOperators.mod, "${args[1]}\\right)") + }, + multiply: { + 2: "\\left(${args[0]}".concat(latexOperators.multiply, "${args[1]}\\right)") + }, + norm: { + 1: '\\left\\|${args[0]}\\right\\|', + 2: undefined // use default template + + }, + nthRoot: { + 2: '\\sqrt[${args[1]}]{${args[0]}}' + }, + nthRoots: { + 2: '\\{y : $y^{args[1]} = {${args[0]}}\\}' + }, + pow: { + 2: "\\left(${args[0]}\\right)".concat(latexOperators.pow, "{${args[1]}}") + }, + round: { + 1: '\\left\\lfloor${args[0]}\\right\\rceil', + 2: undefined // use default template + + }, + sign: { + 1: '\\mathrm{${name}}\\left(${args[0]}\\right)' + }, + sqrt: { + 1: '\\sqrt{${args[0]}}' + }, + square: { + 1: '\\left(${args[0]}\\right)^2' + }, + subtract: { + 2: "\\left(${args[0]}".concat(latexOperators.subtract, "${args[1]}\\right)") + }, + unaryMinus: { + 1: "".concat(latexOperators.unaryMinus, "\\left(${args[0]}\\right)") + }, + unaryPlus: { + 1: "".concat(latexOperators.unaryPlus, "\\left(${args[0]}\\right)") + }, + // bitwise + bitAnd: { + 2: "\\left(${args[0]}".concat(latexOperators.bitAnd, "${args[1]}\\right)") + }, + bitNot: { + 1: latexOperators.bitNot + '\\left(${args[0]}\\right)' + }, + bitOr: { + 2: "\\left(${args[0]}".concat(latexOperators.bitOr, "${args[1]}\\right)") + }, + bitXor: { + 2: "\\left(${args[0]}".concat(latexOperators.bitXor, "${args[1]}\\right)") + }, + leftShift: { + 2: "\\left(${args[0]}".concat(latexOperators.leftShift, "${args[1]}\\right)") + }, + rightArithShift: { + 2: "\\left(${args[0]}".concat(latexOperators.rightArithShift, "${args[1]}\\right)") + }, + rightLogShift: { + 2: "\\left(${args[0]}".concat(latexOperators.rightLogShift, "${args[1]}\\right)") + }, + // combinatorics + bellNumbers: { + 1: '\\mathrm{B}_{${args[0]}}' + }, + catalan: { + 1: '\\mathrm{C}_{${args[0]}}' + }, + stirlingS2: { + 2: '\\mathrm{S}\\left(${args}\\right)' + }, + // complex + arg: { + 1: '\\arg\\left(${args[0]}\\right)' + }, + conj: { + 1: '\\left(${args[0]}\\right)^*' + }, + im: { + 1: '\\Im\\left\\lbrace${args[0]}\\right\\rbrace' + }, + re: { + 1: '\\Re\\left\\lbrace${args[0]}\\right\\rbrace' + }, + // logical + and: { + 2: "\\left(${args[0]}".concat(latexOperators.and, "${args[1]}\\right)") + }, + not: { + 1: latexOperators.not + '\\left(${args[0]}\\right)' + }, + or: { + 2: "\\left(${args[0]}".concat(latexOperators.or, "${args[1]}\\right)") + }, + xor: { + 2: "\\left(${args[0]}".concat(latexOperators.xor, "${args[1]}\\right)") + }, + // matrix + cross: { + 2: '\\left(${args[0]}\\right)\\times\\left(${args[1]}\\right)' + }, + ctranspose: { + 1: "\\left(${args[0]}\\right)".concat(latexOperators.ctranspose) + }, + det: { + 1: '\\det\\left(${args[0]}\\right)' + }, + dot: { + 2: '\\left(${args[0]}\\cdot${args[1]}\\right)' + }, + expm: { + 1: '\\exp\\left(${args[0]}\\right)' + }, + inv: { + 1: '\\left(${args[0]}\\right)^{-1}' + }, + sqrtm: { + 1: "{${args[0]}}".concat(latexOperators.pow, "{\\frac{1}{2}}") + }, + trace: { + 1: '\\mathrm{tr}\\left(${args[0]}\\right)' + }, + transpose: { + 1: "\\left(${args[0]}\\right)".concat(latexOperators.transpose) + }, + // probability + combinations: { + 2: '\\binom{${args[0]}}{${args[1]}}' + }, + combinationsWithRep: { + 2: '\\left(\\!\\!{\\binom{${args[0]}}{${args[1]}}}\\!\\!\\right)' + }, + factorial: { + 1: "\\left(${args[0]}\\right)".concat(latexOperators.factorial) + }, + gamma: { + 1: '\\Gamma\\left(${args[0]}\\right)' + }, + // relational + equal: { + 2: "\\left(${args[0]}".concat(latexOperators.equal, "${args[1]}\\right)") + }, + larger: { + 2: "\\left(${args[0]}".concat(latexOperators.larger, "${args[1]}\\right)") + }, + largerEq: { + 2: "\\left(${args[0]}".concat(latexOperators.largerEq, "${args[1]}\\right)") + }, + smaller: { + 2: "\\left(${args[0]}".concat(latexOperators.smaller, "${args[1]}\\right)") + }, + smallerEq: { + 2: "\\left(${args[0]}".concat(latexOperators.smallerEq, "${args[1]}\\right)") + }, + unequal: { + 2: "\\left(${args[0]}".concat(latexOperators.unequal, "${args[1]}\\right)") + }, + // special + erf: { + 1: 'erf\\left(${args[0]}\\right)' + }, + // statistics + max: '\\max\\left(${args}\\right)', + min: '\\min\\left(${args}\\right)', + variance: '\\mathrm{Var}\\left(${args}\\right)', + // trigonometry + acos: { + 1: '\\cos^{-1}\\left(${args[0]}\\right)' + }, + acosh: { + 1: '\\cosh^{-1}\\left(${args[0]}\\right)' + }, + acot: { + 1: '\\cot^{-1}\\left(${args[0]}\\right)' + }, + acoth: { + 1: '\\coth^{-1}\\left(${args[0]}\\right)' + }, + acsc: { + 1: '\\csc^{-1}\\left(${args[0]}\\right)' + }, + acsch: { + 1: '\\mathrm{csch}^{-1}\\left(${args[0]}\\right)' + }, + asec: { + 1: '\\sec^{-1}\\left(${args[0]}\\right)' + }, + asech: { + 1: '\\mathrm{sech}^{-1}\\left(${args[0]}\\right)' + }, + asin: { + 1: '\\sin^{-1}\\left(${args[0]}\\right)' + }, + asinh: { + 1: '\\sinh^{-1}\\left(${args[0]}\\right)' + }, + atan: { + 1: '\\tan^{-1}\\left(${args[0]}\\right)' + }, + atan2: { + 2: '\\mathrm{atan2}\\left(${args}\\right)' + }, + atanh: { + 1: '\\tanh^{-1}\\left(${args[0]}\\right)' + }, + cos: { + 1: '\\cos\\left(${args[0]}\\right)' + }, + cosh: { + 1: '\\cosh\\left(${args[0]}\\right)' + }, + cot: { + 1: '\\cot\\left(${args[0]}\\right)' + }, + coth: { + 1: '\\coth\\left(${args[0]}\\right)' + }, + csc: { + 1: '\\csc\\left(${args[0]}\\right)' + }, + csch: { + 1: '\\mathrm{csch}\\left(${args[0]}\\right)' + }, + sec: { + 1: '\\sec\\left(${args[0]}\\right)' + }, + sech: { + 1: '\\mathrm{sech}\\left(${args[0]}\\right)' + }, + sin: { + 1: '\\sin\\left(${args[0]}\\right)' + }, + sinh: { + 1: '\\sinh\\left(${args[0]}\\right)' + }, + tan: { + 1: '\\tan\\left(${args[0]}\\right)' + }, + tanh: { + 1: '\\tanh\\left(${args[0]}\\right)' + }, + // unit + to: { + 2: "\\left(${args[0]}".concat(latexOperators.to, "${args[1]}\\right)") + }, + // utils + numeric: function numeric(node, options) { + // Not sure if this is strictly right but should work correctly for the vast majority of use cases. + return node.args[0].toTex(); + }, + // type + number: { + 0: '0', + 1: '\\left(${args[0]}\\right)', + 2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)' + }, + string: { + 0: '\\mathtt{""}', + 1: '\\mathrm{string}\\left(${args[0]}\\right)' + }, + bignumber: { + 0: '0', + 1: '\\left(${args[0]}\\right)' + }, + complex: { + 0: '0', + 1: '\\left(${args[0]}\\right)', + 2: "\\left(\\left(${args[0]}\\right)+".concat(latexSymbols.i, "\\cdot\\left(${args[1]}\\right)\\right)") + }, + matrix: { + 0: '\\begin{bmatrix}\\end{bmatrix}', + 1: '\\left(${args[0]}\\right)', + 2: '\\left(${args[0]}\\right)' + }, + sparse: { + 0: '\\begin{bsparse}\\end{bsparse}', + 1: '\\left(${args[0]}\\right)' + }, + unit: { + 1: '\\left(${args[0]}\\right)', + 2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)' + } +}; +var defaultTemplate = '\\mathrm{${name}}\\left(${args}\\right)'; +var latexUnits = { + deg: '^\\circ' +}; +function escapeLatex(string) { + return dist_default()(string, { + preserveFormatting: true + }); +} // @param {string} name +// @param {boolean} isUnit + +function toSymbol(name, isUnit) { + isUnit = typeof isUnit === 'undefined' ? false : isUnit; + + if (isUnit) { + if (Object(utils_object["f" /* hasOwnProperty */])(latexUnits, name)) { + return latexUnits[name]; + } + + return '\\mathrm{' + escapeLatex(name) + '}'; + } + + if (Object(utils_object["f" /* hasOwnProperty */])(latexSymbols, name)) { + return latexSymbols[name]; + } + + return escapeLatex(name); +} +// CONCATENATED MODULE: ./src/expression/node/ConstantNode.js + + + + +var ConstantNode_name = 'ConstantNode'; +var ConstantNode_dependencies = ['Node']; +var ConstantNode_createConstantNode = /* #__PURE__ */Object(factory["a" /* factory */])(ConstantNode_name, ConstantNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * A ConstantNode holds a constant value like a number or string. + * + * Usage: + * + * new ConstantNode(2.3) + * new ConstantNode('hello') + * + * @param {*} value Value can be any type (number, BigNumber, string, ...) + * @constructor ConstantNode + * @extends {Node} + */ + function ConstantNode(value) { + if (!(this instanceof ConstantNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (arguments.length === 2) { + // TODO: remove deprecation error some day (created 2018-01-23) + throw new SyntaxError('new ConstantNode(valueStr, valueType) is not supported anymore since math v4.0.0. Use new ConstantNode(value) instead, where value is a non-stringified value.'); + } + + this.value = value; + } + + ConstantNode.prototype = new Node(); + ConstantNode.prototype.type = 'ConstantNode'; + ConstantNode.prototype.isConstantNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + ConstantNode.prototype._compile = function (math, argNames) { + var value = this.value; + return function evalConstantNode() { + return value; + }; + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + ConstantNode.prototype.forEach = function (callback) {} // nothing to do, we don't have childs + + /** + * Create a new ConstantNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node) : Node} callback + * @returns {ConstantNode} Returns a clone of the node + */ + ; + + ConstantNode.prototype.map = function (callback) { + return this.clone(); + }; + /** + * Create a clone of this node, a shallow copy + * @return {ConstantNode} + */ + + + ConstantNode.prototype.clone = function () { + return new ConstantNode(this.value); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + */ + + + ConstantNode.prototype._toString = function (options) { + return Object(utils_string["d" /* format */])(this.value, options); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + */ + + + ConstantNode.prototype.toHTML = function (options) { + var value = this._toString(options); + + switch (Object(is["M" /* typeOf */])(this.value)) { + case 'number': + case 'BigNumber': + case 'Fraction': + return '' + value + ''; + + case 'string': + return '' + value + ''; + + case 'boolean': + return '' + value + ''; + + case 'null': + return '' + value + ''; + + case 'undefined': + return '' + value + ''; + + default: + return '' + value + ''; + } + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + ConstantNode.prototype.toJSON = function () { + return { + mathjs: 'ConstantNode', + value: this.value + }; + }; + /** + * Instantiate a ConstantNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "SymbolNode", value: 2.3}`, + * where mathjs is optional + * @returns {ConstantNode} + */ + + + ConstantNode.fromJSON = function (json) { + return new ConstantNode(json.value); + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + ConstantNode.prototype._toTex = function (options) { + var value = this._toString(options); + + switch (Object(is["M" /* typeOf */])(this.value)) { + case 'string': + return '\\mathtt{' + escapeLatex(value) + '}'; + + case 'number': + case 'BigNumber': + { + if (!isFinite(this.value)) { + return this.value.valueOf() < 0 ? '-\\infty' : '\\infty'; + } + + var index = value.toLowerCase().indexOf('e'); + + if (index !== -1) { + return value.substring(0, index) + '\\cdot10^{' + value.substring(index + 1) + '}'; + } + } + return value; + + case 'Fraction': + return this.value.toLatex(); + + default: + return value; + } + }; + + return ConstantNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/FunctionAssignmentNode.js + + + + + + + + +var FunctionAssignmentNode_name = 'FunctionAssignmentNode'; +var FunctionAssignmentNode_dependencies = ['typed', 'Node']; +var createFunctionAssignmentNode = /* #__PURE__ */Object(factory["a" /* factory */])(FunctionAssignmentNode_name, FunctionAssignmentNode_dependencies, function (_ref) { + var typed = _ref.typed, + Node = _ref.Node; + + /** + * @constructor FunctionAssignmentNode + * @extends {Node} + * Function assignment + * + * @param {string} name Function name + * @param {string[] | Array.<{name: string, type: string}>} params + * Array with function parameter names, or an + * array with objects containing the name + * and type of the parameter + * @param {Node} expr The function expression + */ + function FunctionAssignmentNode(name, params, expr) { + if (!(this instanceof FunctionAssignmentNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // validate input + + + if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"'); + if (!Array.isArray(params)) throw new TypeError('Array containing strings or objects expected for parameter "params"'); + if (!Object(is["w" /* isNode */])(expr)) throw new TypeError('Node expected for parameter "expr"'); + if (name in keywords) throw new Error('Illegal function name, "' + name + '" is a reserved keyword'); + this.name = name; + this.params = params.map(function (param) { + return param && param.name || param; + }); + this.types = params.map(function (param) { + return param && param.type || 'any'; + }); + this.expr = expr; + } + + FunctionAssignmentNode.prototype = new Node(); + FunctionAssignmentNode.prototype.type = 'FunctionAssignmentNode'; + FunctionAssignmentNode.prototype.isFunctionAssignmentNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + FunctionAssignmentNode.prototype._compile = function (math, argNames) { + var childArgNames = Object.create(argNames); + Object(utils_array["f" /* forEach */])(this.params, function (param) { + childArgNames[param] = true; + }); // compile the function expression with the child args + + var evalExpr = this.expr._compile(math, childArgNames); + + var name = this.name; + var params = this.params; + var signature = Object(utils_array["k" /* join */])(this.types, ','); + var syntax = name + '(' + Object(utils_array["k" /* join */])(this.params, ', ') + ')'; + return function evalFunctionAssignmentNode(scope, args, context) { + var signatures = {}; + + signatures[signature] = function () { + var childArgs = Object.create(args); + + for (var i = 0; i < params.length; i++) { + childArgs[params[i]] = arguments[i]; + } + + return evalExpr(scope, childArgs, context); + }; + + var fn = typed(name, signatures); + fn.syntax = syntax; + setSafeProperty(scope, name, fn); + return fn; + }; + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + FunctionAssignmentNode.prototype.forEach = function (callback) { + callback(this.expr, 'expr', this); + }; + /** + * Create a new FunctionAssignmentNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {FunctionAssignmentNode} Returns a transformed copy of the node + */ + + + FunctionAssignmentNode.prototype.map = function (callback) { + var expr = this._ifNode(callback(this.expr, 'expr', this)); + + return new FunctionAssignmentNode(this.name, this.params.slice(0), expr); + }; + /** + * Create a clone of this node, a shallow copy + * @return {FunctionAssignmentNode} + */ + + + FunctionAssignmentNode.prototype.clone = function () { + return new FunctionAssignmentNode(this.name, this.params.slice(0), this.expr); + }; + /** + * Is parenthesis needed? + * @param {Node} node + * @param {Object} parenthesis + * @private + */ + + + function needParenthesis(node, parenthesis) { + var precedence = getPrecedence(node, parenthesis); + var exprPrecedence = getPrecedence(node.expr, parenthesis); + return parenthesis === 'all' || exprPrecedence !== null && exprPrecedence <= precedence; + } + /** + * get string representation + * @param {Object} options + * @return {string} str + */ + + + FunctionAssignmentNode.prototype._toString = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var expr = this.expr.toString(options); + + if (needParenthesis(this, parenthesis)) { + expr = '(' + expr + ')'; + } + + return this.name + '(' + this.params.join(', ') + ') = ' + expr; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + FunctionAssignmentNode.prototype.toJSON = function () { + var types = this.types; + return { + mathjs: 'FunctionAssignmentNode', + name: this.name, + params: this.params.map(function (param, index) { + return { + name: param, + type: types[index] + }; + }), + expr: this.expr + }; + }; + /** + * Instantiate an FunctionAssignmentNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "FunctionAssignmentNode", name: ..., params: ..., expr: ...}`, + * where mathjs is optional + * @returns {FunctionAssignmentNode} + */ + + + FunctionAssignmentNode.fromJSON = function (json) { + return new FunctionAssignmentNode(json.name, json.params, json.expr); + }; + /** + * get HTML representation + * @param {Object} options + * @return {string} str + */ + + + FunctionAssignmentNode.prototype.toHTML = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var params = []; + + for (var i = 0; i < this.params.length; i++) { + params.push('' + Object(utils_string["c" /* escape */])(this.params[i]) + ''); + } + + var expr = this.expr.toHTML(options); + + if (needParenthesis(this, parenthesis)) { + expr = '(' + expr + ')'; + } + + return '' + Object(utils_string["c" /* escape */])(this.name) + '' + '(' + params.join(',') + ')=' + expr; + }; + /** + * get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + FunctionAssignmentNode.prototype._toTex = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var expr = this.expr.toTex(options); + + if (needParenthesis(this, parenthesis)) { + expr = "\\left(".concat(expr, "\\right)"); + } + + return '\\mathrm{' + this.name + '}\\left(' + this.params.map(toSymbol).join(',') + '\\right):=' + expr; + }; + + return FunctionAssignmentNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/IndexNode.js +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + + + + + + +var IndexNode_name = 'IndexNode'; +var IndexNode_dependencies = ['Range', 'Node', 'size']; +var createIndexNode = /* #__PURE__ */Object(factory["a" /* factory */])(IndexNode_name, IndexNode_dependencies, function (_ref) { + var Range = _ref.Range, + Node = _ref.Node, + size = _ref.size; + + /** + * @constructor IndexNode + * @extends Node + * + * Describes a subset of a matrix or an object property. + * Cannot be used on its own, needs to be used within an AccessorNode or + * AssignmentNode. + * + * @param {Node[]} dimensions + * @param {boolean} [dotNotation=false] Optional property describing whether + * this index was written using dot + * notation like `a.b`, or using bracket + * notation like `a["b"]` (default). + * Used to stringify an IndexNode. + */ + function IndexNode(dimensions, dotNotation) { + if (!(this instanceof IndexNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.dimensions = dimensions; + this.dotNotation = dotNotation || false; // validate input + + if (!Array.isArray(dimensions) || !dimensions.every(is["w" /* isNode */])) { + throw new TypeError('Array containing Nodes expected for parameter "dimensions"'); + } + + if (this.dotNotation && !this.isObjectProperty()) { + throw new Error('dotNotation only applicable for object properties'); + } // TODO: deprecated since v3, remove some day + + + var deprecated = function deprecated() { + throw new Error('Property `IndexNode.object` is deprecated, use `IndexNode.fn` instead'); + }; + + Object.defineProperty(this, 'object', { + get: deprecated, + set: deprecated + }); + } + + IndexNode.prototype = new Node(); + IndexNode.prototype.type = 'IndexNode'; + IndexNode.prototype.isIndexNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + IndexNode.prototype._compile = function (math, argNames) { + // TODO: implement support for bignumber (currently bignumbers are silently + // reduced to numbers when changing the value to zero-based) + // TODO: Optimization: when the range values are ConstantNodes, + // we can beforehand resolve the zero-based value + // optimization for a simple object property + var evalDimensions = Object(utils_array["m" /* map */])(this.dimensions, function (range, i) { + if (Object(is["E" /* isRangeNode */])(range)) { + if (range.needsEnd()) { + // create a range containing end (like '4:end') + var childArgNames = Object.create(argNames); + childArgNames.end = true; + + var evalStart = range.start._compile(math, childArgNames); + + var evalEnd = range.end._compile(math, childArgNames); + + var evalStep = range.step ? range.step._compile(math, childArgNames) : function () { + return 1; + }; + return function evalDimension(scope, args, context) { + var s = size(context).valueOf(); + var childArgs = Object.create(args); + childArgs.end = s[i]; + return createRange(evalStart(scope, childArgs, context), evalEnd(scope, childArgs, context), evalStep(scope, childArgs, context)); + }; + } else { + // create range + var _evalStart = range.start._compile(math, argNames); + + var _evalEnd = range.end._compile(math, argNames); + + var _evalStep = range.step ? range.step._compile(math, argNames) : function () { + return 1; + }; + + return function evalDimension(scope, args, context) { + return createRange(_evalStart(scope, args, context), _evalEnd(scope, args, context), _evalStep(scope, args, context)); + }; + } + } else if (Object(is["J" /* isSymbolNode */])(range) && range.name === 'end') { + // SymbolNode 'end' + var _childArgNames = Object.create(argNames); + + _childArgNames.end = true; + + var evalRange = range._compile(math, _childArgNames); + + return function evalDimension(scope, args, context) { + var s = size(context).valueOf(); + var childArgs = Object.create(args); + childArgs.end = s[i]; + return evalRange(scope, childArgs, context); + }; + } else { + // ConstantNode + var _evalRange = range._compile(math, argNames); + + return function evalDimension(scope, args, context) { + return _evalRange(scope, args, context); + }; + } + }); + var index = getSafeProperty(math, 'index'); + return function evalIndexNode(scope, args, context) { + var dimensions = Object(utils_array["m" /* map */])(evalDimensions, function (evalDimension) { + return evalDimension(scope, args, context); + }); + return index.apply(void 0, _toConsumableArray(dimensions)); + }; + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + IndexNode.prototype.forEach = function (callback) { + for (var i = 0; i < this.dimensions.length; i++) { + callback(this.dimensions[i], 'dimensions[' + i + ']', this); + } + }; + /** + * Create a new IndexNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {IndexNode} Returns a transformed copy of the node + */ + + + IndexNode.prototype.map = function (callback) { + var dimensions = []; + + for (var i = 0; i < this.dimensions.length; i++) { + dimensions[i] = this._ifNode(callback(this.dimensions[i], 'dimensions[' + i + ']', this)); + } + + return new IndexNode(dimensions, this.dotNotation); + }; + /** + * Create a clone of this node, a shallow copy + * @return {IndexNode} + */ + + + IndexNode.prototype.clone = function () { + return new IndexNode(this.dimensions.slice(0), this.dotNotation); + }; + /** + * Test whether this IndexNode contains a single property name + * @return {boolean} + */ + + + IndexNode.prototype.isObjectProperty = function () { + return this.dimensions.length === 1 && Object(is["l" /* isConstantNode */])(this.dimensions[0]) && typeof this.dimensions[0].value === 'string'; + }; + /** + * Returns the property name if IndexNode contains a property. + * If not, returns null. + * @return {string | null} + */ + + + IndexNode.prototype.getObjectProperty = function () { + return this.isObjectProperty() ? this.dimensions[0].value : null; + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + */ + + + IndexNode.prototype._toString = function (options) { + // format the parameters like "[1, 0:5]" + return this.dotNotation ? '.' + this.getObjectProperty() : '[' + this.dimensions.join(', ') + ']'; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + IndexNode.prototype.toJSON = function () { + return { + mathjs: 'IndexNode', + dimensions: this.dimensions, + dotNotation: this.dotNotation + }; + }; + /** + * Instantiate an IndexNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "IndexNode", dimensions: [...], dotNotation: false}`, + * where mathjs is optional + * @returns {IndexNode} + */ + + + IndexNode.fromJSON = function (json) { + return new IndexNode(json.dimensions, json.dotNotation); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + */ + + + IndexNode.prototype.toHTML = function (options) { + // format the parameters like "[1, 0:5]" + var dimensions = []; + + for (var i = 0; i < this.dimensions.length; i++) { + dimensions[i] = this.dimensions[i].toHTML(); + } + + if (this.dotNotation) { + return '.' + '' + Object(utils_string["c" /* escape */])(this.getObjectProperty()) + ''; + } else { + return '[' + dimensions.join(',') + ']'; + } + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + IndexNode.prototype._toTex = function (options) { + var dimensions = this.dimensions.map(function (range) { + return range.toTex(options); + }); + return this.dotNotation ? '.' + this.getObjectProperty() + '' : '_{' + dimensions.join(',') + '}'; + }; // helper function to create a Range from start, step and end + + + function createRange(start, end, step) { + return new Range(Object(is["e" /* isBigNumber */])(start) ? start.toNumber() : start, Object(is["e" /* isBigNumber */])(end) ? end.toNumber() : end, Object(is["e" /* isBigNumber */])(step) ? step.toNumber() : step); + } + + return IndexNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/ObjectNode.js +function ObjectNode_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { ObjectNode_typeof = function _typeof(obj) { return typeof obj; }; } else { ObjectNode_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return ObjectNode_typeof(obj); } + + + + + + +var ObjectNode_name = 'ObjectNode'; +var ObjectNode_dependencies = ['Node']; +var createObjectNode = /* #__PURE__ */Object(factory["a" /* factory */])(ObjectNode_name, ObjectNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * @constructor ObjectNode + * @extends {Node} + * Holds an object with keys/values + * @param {Object.} [properties] object with key/value pairs + */ + function ObjectNode(properties) { + if (!(this instanceof ObjectNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.properties = properties || {}; // validate input + + if (properties) { + if (!(ObjectNode_typeof(properties) === 'object') || !Object.keys(properties).every(function (key) { + return Object(is["w" /* isNode */])(properties[key]); + })) { + throw new TypeError('Object containing Nodes expected'); + } + } + } + + ObjectNode.prototype = new Node(); + ObjectNode.prototype.type = 'ObjectNode'; + ObjectNode.prototype.isObjectNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + ObjectNode.prototype._compile = function (math, argNames) { + var evalEntries = {}; + + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + // we stringify/parse the key here to resolve unicode characters, + // so you cannot create a key like {"co\\u006Estructor": null} + var stringifiedKey = Object(utils_string["e" /* stringify */])(key); + var parsedKey = JSON.parse(stringifiedKey); + + if (!isSafeProperty(this.properties, parsedKey)) { + throw new Error('No access to property "' + parsedKey + '"'); + } + + evalEntries[parsedKey] = this.properties[key]._compile(math, argNames); + } + } + + return function evalObjectNode(scope, args, context) { + var obj = {}; + + for (var _key in evalEntries) { + if (Object(utils_object["f" /* hasOwnProperty */])(evalEntries, _key)) { + obj[_key] = evalEntries[_key](scope, args, context); + } + } + + return obj; + }; + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + ObjectNode.prototype.forEach = function (callback) { + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + callback(this.properties[key], 'properties[' + Object(utils_string["e" /* stringify */])(key) + ']', this); + } + } + }; + /** + * Create a new ObjectNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {ObjectNode} Returns a transformed copy of the node + */ + + + ObjectNode.prototype.map = function (callback) { + var properties = {}; + + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + properties[key] = this._ifNode(callback(this.properties[key], 'properties[' + Object(utils_string["e" /* stringify */])(key) + ']', this)); + } + } + + return new ObjectNode(properties); + }; + /** + * Create a clone of this node, a shallow copy + * @return {ObjectNode} + */ + + + ObjectNode.prototype.clone = function () { + var properties = {}; + + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + properties[key] = this.properties[key]; + } + } + + return new ObjectNode(properties); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ObjectNode.prototype._toString = function (options) { + var entries = []; + + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + entries.push(Object(utils_string["e" /* stringify */])(key) + ': ' + this.properties[key].toString(options)); + } + } + + return '{' + entries.join(', ') + '}'; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + ObjectNode.prototype.toJSON = function () { + return { + mathjs: 'ObjectNode', + properties: this.properties + }; + }; + /** + * Instantiate an OperatorNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "ObjectNode", "properties": {...}}`, + * where mathjs is optional + * @returns {ObjectNode} + */ + + + ObjectNode.fromJSON = function (json) { + return new ObjectNode(json.properties); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ObjectNode.prototype.toHTML = function (options) { + var entries = []; + + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + entries.push('' + Object(utils_string["c" /* escape */])(key) + '' + ':' + this.properties[key].toHTML(options)); + } + } + + return '{' + entries.join(',') + '}'; + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + ObjectNode.prototype._toTex = function (options) { + var entries = []; + + for (var key in this.properties) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) { + entries.push('\\mathbf{' + key + ':} & ' + this.properties[key].toTex(options) + '\\\\'); + } + } + + return "\\left\\{\\begin{array}{ll}".concat(entries.join('\n'), "\\end{array}\\right\\}"); + }; + + return ObjectNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/OperatorNode.js + + + + + + + +var OperatorNode_name = 'OperatorNode'; +var OperatorNode_dependencies = ['Node']; +var createOperatorNode = /* #__PURE__ */Object(factory["a" /* factory */])(OperatorNode_name, OperatorNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * @constructor OperatorNode + * @extends {Node} + * An operator with two arguments, like 2+3 + * + * @param {string} op Operator name, for example '+' + * @param {string} fn Function name, for example 'add' + * @param {Node[]} args Operator arguments + * @param {boolean} [implicit] Is this an implicit multiplication? + */ + function OperatorNode(op, fn, args, implicit) { + if (!(this instanceof OperatorNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // validate input + + + if (typeof op !== 'string') { + throw new TypeError('string expected for parameter "op"'); + } + + if (typeof fn !== 'string') { + throw new TypeError('string expected for parameter "fn"'); + } + + if (!Array.isArray(args) || !args.every(is["w" /* isNode */])) { + throw new TypeError('Array containing Nodes expected for parameter "args"'); + } + + this.implicit = implicit === true; + this.op = op; + this.fn = fn; + this.args = args || []; + } + + OperatorNode.prototype = new Node(); + OperatorNode.prototype.type = 'OperatorNode'; + OperatorNode.prototype.isOperatorNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + OperatorNode.prototype._compile = function (math, argNames) { + // validate fn + if (typeof this.fn !== 'string' || !isSafeMethod(math, this.fn)) { + if (!math[this.fn]) { + throw new Error('Function ' + this.fn + ' missing in provided namespace "math"'); + } else { + throw new Error('No access to function "' + this.fn + '"'); + } + } + + var fn = getSafeProperty(math, this.fn); + var evalArgs = Object(utils_array["m" /* map */])(this.args, function (arg) { + return arg._compile(math, argNames); + }); + + if (evalArgs.length === 1) { + var evalArg0 = evalArgs[0]; + return function evalOperatorNode(scope, args, context) { + return fn(evalArg0(scope, args, context)); + }; + } else if (evalArgs.length === 2) { + var _evalArg = evalArgs[0]; + var evalArg1 = evalArgs[1]; + return function evalOperatorNode(scope, args, context) { + return fn(_evalArg(scope, args, context), evalArg1(scope, args, context)); + }; + } else { + return function evalOperatorNode(scope, args, context) { + return fn.apply(null, Object(utils_array["m" /* map */])(evalArgs, function (evalArg) { + return evalArg(scope, args, context); + })); + }; + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + OperatorNode.prototype.forEach = function (callback) { + for (var i = 0; i < this.args.length; i++) { + callback(this.args[i], 'args[' + i + ']', this); + } + }; + /** + * Create a new OperatorNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {OperatorNode} Returns a transformed copy of the node + */ + + + OperatorNode.prototype.map = function (callback) { + var args = []; + + for (var i = 0; i < this.args.length; i++) { + args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this)); + } + + return new OperatorNode(this.op, this.fn, args, this.implicit); + }; + /** + * Create a clone of this node, a shallow copy + * @return {OperatorNode} + */ + + + OperatorNode.prototype.clone = function () { + return new OperatorNode(this.op, this.fn, this.args.slice(0), this.implicit); + }; + /** + * Check whether this is an unary OperatorNode: + * has exactly one argument, like `-a`. + * @return {boolean} Returns true when an unary operator node, false otherwise. + */ + + + OperatorNode.prototype.isUnary = function () { + return this.args.length === 1; + }; + /** + * Check whether this is a binary OperatorNode: + * has exactly two arguments, like `a + b`. + * @return {boolean} Returns true when a binary operator node, false otherwise. + */ + + + OperatorNode.prototype.isBinary = function () { + return this.args.length === 2; + }; + /** + * Calculate which parentheses are necessary. Gets an OperatorNode + * (which is the root of the tree) and an Array of Nodes + * (this.args) and returns an array where 'true' means that an argument + * has to be enclosed in parentheses whereas 'false' means the opposite. + * + * @param {OperatorNode} root + * @param {string} parenthesis + * @param {Node[]} args + * @param {boolean} latex + * @return {boolean[]} + * @private + */ + + + function calculateNecessaryParentheses(root, parenthesis, implicit, args, latex) { + // precedence of the root OperatorNode + var precedence = getPrecedence(root, parenthesis); + var associativity = getAssociativity(root, parenthesis); + + if (parenthesis === 'all' || args.length > 2 && root.getIdentifier() !== 'OperatorNode:add' && root.getIdentifier() !== 'OperatorNode:multiply') { + return args.map(function (arg) { + switch (arg.getContent().type) { + // Nodes that don't need extra parentheses + case 'ArrayNode': + case 'ConstantNode': + case 'SymbolNode': + case 'ParenthesisNode': + return false; + + default: + return true; + } + }); + } + + var result; + + switch (args.length) { + case 0: + result = []; + break; + + case 1: + // unary operators + { + // precedence of the operand + var operandPrecedence = getPrecedence(args[0], parenthesis); // handle special cases for LaTeX, where some of the parentheses aren't needed + + if (latex && operandPrecedence !== null) { + var operandIdentifier; + var rootIdentifier; + + if (parenthesis === 'keep') { + operandIdentifier = args[0].getIdentifier(); + rootIdentifier = root.getIdentifier(); + } else { + // Ignore Parenthesis Nodes when not in 'keep' mode + operandIdentifier = args[0].getContent().getIdentifier(); + rootIdentifier = root.getContent().getIdentifier(); + } + + if (operators_properties[precedence][rootIdentifier].latexLeftParens === false) { + result = [false]; + break; + } + + if (operators_properties[operandPrecedence][operandIdentifier].latexParens === false) { + result = [false]; + break; + } + } + + if (operandPrecedence === null) { + // if the operand has no defined precedence, no parens are needed + result = [false]; + break; + } + + if (operandPrecedence <= precedence) { + // if the operands precedence is lower, parens are needed + result = [true]; + break; + } // otherwise, no parens needed + + + result = [false]; + } + break; + + case 2: + // binary operators + { + var lhsParens; // left hand side needs parenthesis? + // precedence of the left hand side + + var lhsPrecedence = getPrecedence(args[0], parenthesis); // is the root node associative with the left hand side + + var assocWithLhs = isAssociativeWith(root, args[0], parenthesis); + + if (lhsPrecedence === null) { + // if the left hand side has no defined precedence, no parens are needed + // FunctionNode for example + lhsParens = false; + } else if (lhsPrecedence === precedence && associativity === 'right' && !assocWithLhs) { + // In case of equal precedence, if the root node is left associative + // parens are **never** necessary for the left hand side. + // If it is right associative however, parens are necessary + // if the root node isn't associative with the left hand side + lhsParens = true; + } else if (lhsPrecedence < precedence) { + lhsParens = true; + } else { + lhsParens = false; + } + + var rhsParens; // right hand side needs parenthesis? + // precedence of the right hand side + + var rhsPrecedence = getPrecedence(args[1], parenthesis); // is the root node associative with the right hand side? + + var assocWithRhs = isAssociativeWith(root, args[1], parenthesis); + + if (rhsPrecedence === null) { + // if the right hand side has no defined precedence, no parens are needed + // FunctionNode for example + rhsParens = false; + } else if (rhsPrecedence === precedence && associativity === 'left' && !assocWithRhs) { + // In case of equal precedence, if the root node is right associative + // parens are **never** necessary for the right hand side. + // If it is left associative however, parens are necessary + // if the root node isn't associative with the right hand side + rhsParens = true; + } else if (rhsPrecedence < precedence) { + rhsParens = true; + } else { + rhsParens = false; + } // handle special cases for LaTeX, where some of the parentheses aren't needed + + + if (latex) { + var _rootIdentifier; + + var lhsIdentifier; + var rhsIdentifier; + + if (parenthesis === 'keep') { + _rootIdentifier = root.getIdentifier(); + lhsIdentifier = root.args[0].getIdentifier(); + rhsIdentifier = root.args[1].getIdentifier(); + } else { + // Ignore ParenthesisNodes when not in 'keep' mode + _rootIdentifier = root.getContent().getIdentifier(); + lhsIdentifier = root.args[0].getContent().getIdentifier(); + rhsIdentifier = root.args[1].getContent().getIdentifier(); + } + + if (lhsPrecedence !== null) { + if (operators_properties[precedence][_rootIdentifier].latexLeftParens === false) { + lhsParens = false; + } + + if (operators_properties[lhsPrecedence][lhsIdentifier].latexParens === false) { + lhsParens = false; + } + } + + if (rhsPrecedence !== null) { + if (operators_properties[precedence][_rootIdentifier].latexRightParens === false) { + rhsParens = false; + } + + if (operators_properties[rhsPrecedence][rhsIdentifier].latexParens === false) { + rhsParens = false; + } + } + } + + result = [lhsParens, rhsParens]; + } + break; + + default: + if (root.getIdentifier() === 'OperatorNode:add' || root.getIdentifier() === 'OperatorNode:multiply') { + result = args.map(function (arg) { + var argPrecedence = getPrecedence(arg, parenthesis); + var assocWithArg = isAssociativeWith(root, arg, parenthesis); + var argAssociativity = getAssociativity(arg, parenthesis); + + if (argPrecedence === null) { + // if the argument has no defined precedence, no parens are needed + return false; + } else if (precedence === argPrecedence && associativity === argAssociativity && !assocWithArg) { + return true; + } else if (argPrecedence < precedence) { + return true; + } + + return false; + }); + } + + break; + } // handles an edge case of 'auto' parentheses with implicit multiplication of ConstantNode + // In that case print parentheses for ParenthesisNodes even though they normally wouldn't be + // printed. + + + if (args.length >= 2 && root.getIdentifier() === 'OperatorNode:multiply' && root.implicit && parenthesis === 'auto' && implicit === 'hide') { + result = args.map(function (arg, index) { + var isParenthesisNode = arg.getIdentifier() === 'ParenthesisNode'; + + if (result[index] || isParenthesisNode) { + // put in parenthesis? + return true; + } + + return false; + }); + } + + return result; + } + /** + * Get string representation. + * @param {Object} options + * @return {string} str + */ + + + OperatorNode.prototype._toString = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var implicit = options && options.implicit ? options.implicit : 'hide'; + var args = this.args; + var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, false); + + if (args.length === 1) { + // unary operators + var assoc = getAssociativity(this, parenthesis); + var operand = args[0].toString(options); + + if (parens[0]) { + operand = '(' + operand + ')'; + } // for example for "not", we want a space between operand and argument + + + var opIsNamed = /[a-zA-Z]+/.test(this.op); + + if (assoc === 'right') { + // prefix operator + return this.op + (opIsNamed ? ' ' : '') + operand; + } else if (assoc === 'left') { + // postfix + return operand + (opIsNamed ? ' ' : '') + this.op; + } // fall back to postfix + + + return operand + this.op; + } else if (args.length === 2) { + var lhs = args[0].toString(options); // left hand side + + var rhs = args[1].toString(options); // right hand side + + if (parens[0]) { + // left hand side in parenthesis? + lhs = '(' + lhs + ')'; + } + + if (parens[1]) { + // right hand side in parenthesis? + rhs = '(' + rhs + ')'; + } + + if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') { + return lhs + ' ' + rhs; + } + + return lhs + ' ' + this.op + ' ' + rhs; + } else if (args.length > 2 && (this.getIdentifier() === 'OperatorNode:add' || this.getIdentifier() === 'OperatorNode:multiply')) { + var stringifiedArgs = args.map(function (arg, index) { + arg = arg.toString(options); + + if (parens[index]) { + // put in parenthesis? + arg = '(' + arg + ')'; + } + + return arg; + }); + + if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') { + return stringifiedArgs.join(' '); + } + + return stringifiedArgs.join(' ' + this.op + ' '); + } else { + // fallback to formatting as a function call + return this.fn + '(' + this.args.join(', ') + ')'; + } + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + OperatorNode.prototype.toJSON = function () { + return { + mathjs: 'OperatorNode', + op: this.op, + fn: this.fn, + args: this.args, + implicit: this.implicit + }; + }; + /** + * Instantiate an OperatorNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "OperatorNode", "op": "+", "fn": "add", "args": [...], "implicit": false}`, + * where mathjs is optional + * @returns {OperatorNode} + */ + + + OperatorNode.fromJSON = function (json) { + return new OperatorNode(json.op, json.fn, json.args, json.implicit); + }; + /** + * Get HTML representation. + * @param {Object} options + * @return {string} str + */ + + + OperatorNode.prototype.toHTML = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var implicit = options && options.implicit ? options.implicit : 'hide'; + var args = this.args; + var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, false); + + if (args.length === 1) { + // unary operators + var assoc = getAssociativity(this, parenthesis); + var operand = args[0].toHTML(options); + + if (parens[0]) { + operand = '(' + operand + ')'; + } + + if (assoc === 'right') { + // prefix operator + return '' + Object(utils_string["c" /* escape */])(this.op) + '' + operand; + } else { + // postfix when assoc === 'left' or undefined + return operand + '' + Object(utils_string["c" /* escape */])(this.op) + ''; + } + } else if (args.length === 2) { + // binary operatoes + var lhs = args[0].toHTML(options); // left hand side + + var rhs = args[1].toHTML(options); // right hand side + + if (parens[0]) { + // left hand side in parenthesis? + lhs = '(' + lhs + ')'; + } + + if (parens[1]) { + // right hand side in parenthesis? + rhs = '(' + rhs + ')'; + } + + if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') { + return lhs + '' + rhs; + } + + return lhs + '' + Object(utils_string["c" /* escape */])(this.op) + '' + rhs; + } else { + var stringifiedArgs = args.map(function (arg, index) { + arg = arg.toHTML(options); + + if (parens[index]) { + // put in parenthesis? + arg = '(' + arg + ')'; + } + + return arg; + }); + + if (args.length > 2 && (this.getIdentifier() === 'OperatorNode:add' || this.getIdentifier() === 'OperatorNode:multiply')) { + if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') { + return stringifiedArgs.join(''); + } + + return stringifiedArgs.join('' + Object(utils_string["c" /* escape */])(this.op) + ''); + } else { + // fallback to formatting as a function call + return '' + Object(utils_string["c" /* escape */])(this.fn) + '(' + stringifiedArgs.join(',') + ')'; + } + } + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + OperatorNode.prototype._toTex = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var implicit = options && options.implicit ? options.implicit : 'hide'; + var args = this.args; + var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, true); + var op = latexOperators[this.fn]; + op = typeof op === 'undefined' ? this.op : op; // fall back to using this.op + + if (args.length === 1) { + // unary operators + var assoc = getAssociativity(this, parenthesis); + var operand = args[0].toTex(options); + + if (parens[0]) { + operand = "\\left(".concat(operand, "\\right)"); + } + + if (assoc === 'right') { + // prefix operator + return op + operand; + } else if (assoc === 'left') { + // postfix operator + return operand + op; + } // fall back to postfix + + + return operand + op; + } else if (args.length === 2) { + // binary operators + var lhs = args[0]; // left hand side + + var lhsTex = lhs.toTex(options); + + if (parens[0]) { + lhsTex = "\\left(".concat(lhsTex, "\\right)"); + } + + var rhs = args[1]; // right hand side + + var rhsTex = rhs.toTex(options); + + if (parens[1]) { + rhsTex = "\\left(".concat(rhsTex, "\\right)"); + } // handle some exceptions (due to the way LaTeX works) + + + var lhsIdentifier; + + if (parenthesis === 'keep') { + lhsIdentifier = lhs.getIdentifier(); + } else { + // Ignore ParenthesisNodes if in 'keep' mode + lhsIdentifier = lhs.getContent().getIdentifier(); + } + + switch (this.getIdentifier()) { + case 'OperatorNode:divide': + // op contains '\\frac' at this point + return op + '{' + lhsTex + '}' + '{' + rhsTex + '}'; + + case 'OperatorNode:pow': + lhsTex = '{' + lhsTex + '}'; + rhsTex = '{' + rhsTex + '}'; + + switch (lhsIdentifier) { + case 'ConditionalNode': // + + case 'OperatorNode:divide': + lhsTex = "\\left(".concat(lhsTex, "\\right)"); + } + + break; + + case 'OperatorNode:multiply': + if (this.implicit && implicit === 'hide') { + return lhsTex + '~' + rhsTex; + } + + } + + return lhsTex + op + rhsTex; + } else if (args.length > 2 && (this.getIdentifier() === 'OperatorNode:add' || this.getIdentifier() === 'OperatorNode:multiply')) { + var texifiedArgs = args.map(function (arg, index) { + arg = arg.toTex(options); + + if (parens[index]) { + arg = "\\left(".concat(arg, "\\right)"); + } + + return arg; + }); + + if (this.getIdentifier() === 'OperatorNode:multiply' && this.implicit) { + return texifiedArgs.join('~'); + } + + return texifiedArgs.join(op); + } else { + // fall back to formatting as a function call + // as this is a fallback, it doesn't use + // fancy function names + return '\\mathrm{' + this.fn + '}\\left(' + args.map(function (arg) { + return arg.toTex(options); + }).join(',') + '\\right)'; + } + }; + /** + * Get identifier. + * @return {string} + */ + + + OperatorNode.prototype.getIdentifier = function () { + return this.type + ':' + this.fn; + }; + + return OperatorNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/ParenthesisNode.js + + +var ParenthesisNode_name = 'ParenthesisNode'; +var ParenthesisNode_dependencies = ['Node']; +var createParenthesisNode = /* #__PURE__ */Object(factory["a" /* factory */])(ParenthesisNode_name, ParenthesisNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * @constructor ParenthesisNode + * @extends {Node} + * A parenthesis node describes manual parenthesis from the user input + * @param {Node} content + * @extends {Node} + */ + function ParenthesisNode(content) { + if (!(this instanceof ParenthesisNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // validate input + + + if (!Object(is["w" /* isNode */])(content)) { + throw new TypeError('Node expected for parameter "content"'); + } + + this.content = content; + } + + ParenthesisNode.prototype = new Node(); + ParenthesisNode.prototype.type = 'ParenthesisNode'; + ParenthesisNode.prototype.isParenthesisNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + ParenthesisNode.prototype._compile = function (math, argNames) { + return this.content._compile(math, argNames); + }; + /** + * Get the content of the current Node. + * @return {Node} content + * @override + **/ + + + ParenthesisNode.prototype.getContent = function () { + return this.content.getContent(); + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + ParenthesisNode.prototype.forEach = function (callback) { + callback(this.content, 'content', this); + }; + /** + * Create a new ParenthesisNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node) : Node} callback + * @returns {ParenthesisNode} Returns a clone of the node + */ + + + ParenthesisNode.prototype.map = function (callback) { + var content = callback(this.content, 'content', this); + return new ParenthesisNode(content); + }; + /** + * Create a clone of this node, a shallow copy + * @return {ParenthesisNode} + */ + + + ParenthesisNode.prototype.clone = function () { + return new ParenthesisNode(this.content); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ParenthesisNode.prototype._toString = function (options) { + if (!options || options && !options.parenthesis || options && options.parenthesis === 'keep') { + return '(' + this.content.toString(options) + ')'; + } + + return this.content.toString(options); + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + ParenthesisNode.prototype.toJSON = function () { + return { + mathjs: 'ParenthesisNode', + content: this.content + }; + }; + /** + * Instantiate an ParenthesisNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "ParenthesisNode", "content": ...}`, + * where mathjs is optional + * @returns {ParenthesisNode} + */ + + + ParenthesisNode.fromJSON = function (json) { + return new ParenthesisNode(json.content); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ParenthesisNode.prototype.toHTML = function (options) { + if (!options || options && !options.parenthesis || options && options.parenthesis === 'keep') { + return '(' + this.content.toHTML(options) + ')'; + } + + return this.content.toHTML(options); + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + * @override + */ + + + ParenthesisNode.prototype._toTex = function (options) { + if (!options || options && !options.parenthesis || options && options.parenthesis === 'keep') { + return "\\left(".concat(this.content.toTex(options), "\\right)"); + } + + return this.content.toTex(options); + }; + + return ParenthesisNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/RangeNode.js + + + +var RangeNode_name = 'RangeNode'; +var RangeNode_dependencies = ['Node']; +var createRangeNode = /* #__PURE__ */Object(factory["a" /* factory */])(RangeNode_name, RangeNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * @constructor RangeNode + * @extends {Node} + * create a range + * @param {Node} start included lower-bound + * @param {Node} end included upper-bound + * @param {Node} [step] optional step + */ + function RangeNode(start, end, step) { + if (!(this instanceof RangeNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // validate inputs + + + if (!Object(is["w" /* isNode */])(start)) throw new TypeError('Node expected'); + if (!Object(is["w" /* isNode */])(end)) throw new TypeError('Node expected'); + if (step && !Object(is["w" /* isNode */])(step)) throw new TypeError('Node expected'); + if (arguments.length > 3) throw new Error('Too many arguments'); + this.start = start; // included lower-bound + + this.end = end; // included upper-bound + + this.step = step || null; // optional step + } + + RangeNode.prototype = new Node(); + RangeNode.prototype.type = 'RangeNode'; + RangeNode.prototype.isRangeNode = true; + /** + * Check whether the RangeNode needs the `end` symbol to be defined. + * This end is the size of the Matrix in current dimension. + * @return {boolean} + */ + + RangeNode.prototype.needsEnd = function () { + // find all `end` symbols in this RangeNode + var endSymbols = this.filter(function (node) { + return Object(is["J" /* isSymbolNode */])(node) && node.name === 'end'; + }); + return endSymbols.length > 0; + }; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + + RangeNode.prototype._compile = function (math, argNames) { + var range = math.range; + + var evalStart = this.start._compile(math, argNames); + + var evalEnd = this.end._compile(math, argNames); + + if (this.step) { + var evalStep = this.step._compile(math, argNames); + + return function evalRangeNode(scope, args, context) { + return range(evalStart(scope, args, context), evalEnd(scope, args, context), evalStep(scope, args, context)); + }; + } else { + return function evalRangeNode(scope, args, context) { + return range(evalStart(scope, args, context), evalEnd(scope, args, context)); + }; + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + RangeNode.prototype.forEach = function (callback) { + callback(this.start, 'start', this); + callback(this.end, 'end', this); + + if (this.step) { + callback(this.step, 'step', this); + } + }; + /** + * Create a new RangeNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {RangeNode} Returns a transformed copy of the node + */ + + + RangeNode.prototype.map = function (callback) { + return new RangeNode(this._ifNode(callback(this.start, 'start', this)), this._ifNode(callback(this.end, 'end', this)), this.step && this._ifNode(callback(this.step, 'step', this))); + }; + /** + * Create a clone of this node, a shallow copy + * @return {RangeNode} + */ + + + RangeNode.prototype.clone = function () { + return new RangeNode(this.start, this.end, this.step && this.step); + }; + /** + * Calculate the necessary parentheses + * @param {Node} node + * @param {string} parenthesis + * @return {Object} parentheses + * @private + */ + + + function calculateNecessaryParentheses(node, parenthesis) { + var precedence = getPrecedence(node, parenthesis); + var parens = {}; + var startPrecedence = getPrecedence(node.start, parenthesis); + parens.start = startPrecedence !== null && startPrecedence <= precedence || parenthesis === 'all'; + + if (node.step) { + var stepPrecedence = getPrecedence(node.step, parenthesis); + parens.step = stepPrecedence !== null && stepPrecedence <= precedence || parenthesis === 'all'; + } + + var endPrecedence = getPrecedence(node.end, parenthesis); + parens.end = endPrecedence !== null && endPrecedence <= precedence || parenthesis === 'all'; + return parens; + } + /** + * Get string representation + * @param {Object} options + * @return {string} str + */ + + + RangeNode.prototype._toString = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var parens = calculateNecessaryParentheses(this, parenthesis); // format string as start:step:stop + + var str; + var start = this.start.toString(options); + + if (parens.start) { + start = '(' + start + ')'; + } + + str = start; + + if (this.step) { + var step = this.step.toString(options); + + if (parens.step) { + step = '(' + step + ')'; + } + + str += ':' + step; + } + + var end = this.end.toString(options); + + if (parens.end) { + end = '(' + end + ')'; + } + + str += ':' + end; + return str; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + RangeNode.prototype.toJSON = function () { + return { + mathjs: 'RangeNode', + start: this.start, + end: this.end, + step: this.step + }; + }; + /** + * Instantiate an RangeNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "RangeNode", "start": ..., "end": ..., "step": ...}`, + * where mathjs is optional + * @returns {RangeNode} + */ + + + RangeNode.fromJSON = function (json) { + return new RangeNode(json.start, json.end, json.step); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + */ + + + RangeNode.prototype.toHTML = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var parens = calculateNecessaryParentheses(this, parenthesis); // format string as start:step:stop + + var str; + var start = this.start.toHTML(options); + + if (parens.start) { + start = '(' + start + ')'; + } + + str = start; + + if (this.step) { + var step = this.step.toHTML(options); + + if (parens.step) { + step = '(' + step + ')'; + } + + str += ':' + step; + } + + var end = this.end.toHTML(options); + + if (parens.end) { + end = '(' + end + ')'; + } + + str += ':' + end; + return str; + }; + /** + * Get LaTeX representation + * @params {Object} options + * @return {string} str + */ + + + RangeNode.prototype._toTex = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var parens = calculateNecessaryParentheses(this, parenthesis); + var str = this.start.toTex(options); + + if (parens.start) { + str = "\\left(".concat(str, "\\right)"); + } + + if (this.step) { + var step = this.step.toTex(options); + + if (parens.step) { + step = "\\left(".concat(step, "\\right)"); + } + + str += ':' + step; + } + + var end = this.end.toTex(options); + + if (parens.end) { + end = "\\left(".concat(end, "\\right)"); + } + + str += ':' + end; + return str; + }; + + return RangeNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/RelationalNode.js + + + + + +var RelationalNode_name = 'RelationalNode'; +var RelationalNode_dependencies = ['Node']; +var createRelationalNode = /* #__PURE__ */Object(factory["a" /* factory */])(RelationalNode_name, RelationalNode_dependencies, function (_ref) { + var Node = _ref.Node; + + /** + * A node representing a chained conditional expression, such as 'x > y > z' + * + * @param {String[]} conditionals An array of conditional operators used to compare the parameters + * @param {Node[]} params The parameters that will be compared + * + * @constructor RelationalNode + * @extends {Node} + */ + function RelationalNode(conditionals, params) { + if (!(this instanceof RelationalNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (!Array.isArray(conditionals)) throw new TypeError('Parameter conditionals must be an array'); + if (!Array.isArray(params)) throw new TypeError('Parameter params must be an array'); + if (conditionals.length !== params.length - 1) throw new TypeError('Parameter params must contain exactly one more element than parameter conditionals'); + this.conditionals = conditionals; + this.params = params; + } + + RelationalNode.prototype = new Node(); + RelationalNode.prototype.type = 'RelationalNode'; + RelationalNode.prototype.isRelationalNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + RelationalNode.prototype._compile = function (math, argNames) { + var self = this; + var compiled = this.params.map(function (p) { + return p._compile(math, argNames); + }); + return function evalRelationalNode(scope, args, context) { + var evalLhs; + var evalRhs = compiled[0](scope, args, context); + + for (var i = 0; i < self.conditionals.length; i++) { + evalLhs = evalRhs; + evalRhs = compiled[i + 1](scope, args, context); + var condFn = getSafeProperty(math, self.conditionals[i]); + + if (!condFn(evalLhs, evalRhs)) { + return false; + } + } + + return true; + }; + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + RelationalNode.prototype.forEach = function (callback) { + var _this = this; + + this.params.forEach(function (n, i) { + return callback(n, 'params[' + i + ']', _this); + }, this); + }; + /** + * Create a new RelationalNode having its childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {RelationalNode} Returns a transformed copy of the node + */ + + + RelationalNode.prototype.map = function (callback) { + var _this2 = this; + + return new RelationalNode(this.conditionals.slice(), this.params.map(function (n, i) { + return _this2._ifNode(callback(n, 'params[' + i + ']', _this2)); + }, this)); + }; + /** + * Create a clone of this node, a shallow copy + * @return {RelationalNode} + */ + + + RelationalNode.prototype.clone = function () { + return new RelationalNode(this.conditionals, this.params); + }; + /** + * Get string representation. + * @param {Object} options + * @return {string} str + */ + + + RelationalNode.prototype._toString = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var precedence = getPrecedence(this, parenthesis); + var paramStrings = this.params.map(function (p, index) { + var paramPrecedence = getPrecedence(p, parenthesis); + return parenthesis === 'all' || paramPrecedence !== null && paramPrecedence <= precedence ? '(' + p.toString(options) + ')' : p.toString(options); + }); + var operatorMap = { + equal: '==', + unequal: '!=', + smaller: '<', + larger: '>', + smallerEq: '<=', + largerEq: '>=' + }; + var ret = paramStrings[0]; + + for (var i = 0; i < this.conditionals.length; i++) { + ret += ' ' + operatorMap[this.conditionals[i]] + ' ' + paramStrings[i + 1]; + } + + return ret; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + RelationalNode.prototype.toJSON = function () { + return { + mathjs: 'RelationalNode', + conditionals: this.conditionals, + params: this.params + }; + }; + /** + * Instantiate a RelationalNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "RelationalNode", "condition": ..., "trueExpr": ..., "falseExpr": ...}`, + * where mathjs is optional + * @returns {RelationalNode} + */ + + + RelationalNode.fromJSON = function (json) { + return new RelationalNode(json.conditionals, json.params); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + */ + + + RelationalNode.prototype.toHTML = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var precedence = getPrecedence(this, parenthesis); + var paramStrings = this.params.map(function (p, index) { + var paramPrecedence = getPrecedence(p, parenthesis); + return parenthesis === 'all' || paramPrecedence !== null && paramPrecedence <= precedence ? '(' + p.toHTML(options) + ')' : p.toHTML(options); + }); + var operatorMap = { + equal: '==', + unequal: '!=', + smaller: '<', + larger: '>', + smallerEq: '<=', + largerEq: '>=' + }; + var ret = paramStrings[0]; + + for (var i = 0; i < this.conditionals.length; i++) { + ret += '' + Object(utils_string["c" /* escape */])(operatorMap[this.conditionals[i]]) + '' + paramStrings[i + 1]; + } + + return ret; + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + RelationalNode.prototype._toTex = function (options) { + var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep'; + var precedence = getPrecedence(this, parenthesis); + var paramStrings = this.params.map(function (p, index) { + var paramPrecedence = getPrecedence(p, parenthesis); + return parenthesis === 'all' || paramPrecedence !== null && paramPrecedence <= precedence ? '\\left(' + p.toTex(options) + '\right)' : p.toTex(options); + }); + var ret = paramStrings[0]; + + for (var i = 0; i < this.conditionals.length; i++) { + ret += latexOperators[this.conditionals[i]] + paramStrings[i + 1]; + } + + return ret; + }; + + return RelationalNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/SymbolNode.js + + + + +var SymbolNode_name = 'SymbolNode'; +var SymbolNode_dependencies = ['math', '?Unit', 'Node']; +var createSymbolNode = /* #__PURE__ */Object(factory["a" /* factory */])(SymbolNode_name, SymbolNode_dependencies, function (_ref) { + var math = _ref.math, + Unit = _ref.Unit, + Node = _ref.Node; + + /** + * Check whether some name is a valueless unit like "inch". + * @param {string} name + * @return {boolean} + */ + function isValuelessUnit(name) { + return Unit ? Unit.isValuelessUnit(name) : false; + } + /** + * @constructor SymbolNode + * @extends {Node} + * A symbol node can hold and resolve a symbol + * @param {string} name + * @extends {Node} + */ + + + function SymbolNode(name) { + if (!(this instanceof SymbolNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } // validate input + + + if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"'); + this.name = name; + } + + SymbolNode.prototype = new Node(); + SymbolNode.prototype.type = 'SymbolNode'; + SymbolNode.prototype.isSymbolNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + SymbolNode.prototype._compile = function (math, argNames) { + var name = this.name; + + if (argNames[name] === true) { + // this is a FunctionAssignment argument + // (like an x when inside the expression of a function assignment `f(x) = ...`) + return function (scope, args, context) { + return args[name]; + }; + } else if (name in math) { + return function (scope, args, context) { + return name in scope ? getSafeProperty(scope, name) : getSafeProperty(math, name); + }; + } else { + var isUnit = isValuelessUnit(name); + return function (scope, args, context) { + return name in scope ? getSafeProperty(scope, name) : isUnit ? new Unit(null, name) : undef(name); + }; + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + SymbolNode.prototype.forEach = function (callback) {} // nothing to do, we don't have childs + + /** + * Create a new SymbolNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node) : Node} callback + * @returns {SymbolNode} Returns a clone of the node + */ + ; + + SymbolNode.prototype.map = function (callback) { + return this.clone(); + }; + /** + * Throws an error 'Undefined symbol {name}' + * @param {string} name + */ + + + function undef(name) { + throw new Error('Undefined symbol ' + name); + } + /** + * Create a clone of this node, a shallow copy + * @return {SymbolNode} + */ + + + SymbolNode.prototype.clone = function () { + return new SymbolNode(this.name); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + * @override + */ + + + SymbolNode.prototype._toString = function (options) { + return this.name; + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + * @override + */ + + + SymbolNode.prototype.toHTML = function (options) { + var name = Object(utils_string["c" /* escape */])(this.name); + + if (name === 'true' || name === 'false') { + return '' + name + ''; + } else if (name === 'i') { + return '' + name + ''; + } else if (name === 'Infinity') { + return '' + name + ''; + } else if (name === 'NaN') { + return '' + name + ''; + } else if (name === 'null') { + return '' + name + ''; + } else if (name === 'undefined') { + return '' + name + ''; + } + + return '' + name + ''; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + SymbolNode.prototype.toJSON = function () { + return { + mathjs: 'SymbolNode', + name: this.name + }; + }; + /** + * Instantiate a SymbolNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "SymbolNode", name: "x"}`, + * where mathjs is optional + * @returns {SymbolNode} + */ + + + SymbolNode.fromJSON = function (json) { + return new SymbolNode(json.name); + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + * @override + */ + + + SymbolNode.prototype._toTex = function (options) { + var isUnit = false; + + if (typeof math[this.name] === 'undefined' && isValuelessUnit(this.name)) { + isUnit = true; + } + + var symbol = toSymbol(this.name, isUnit); + + if (symbol[0] === '\\') { + // no space needed if the symbol starts with '\' + return symbol; + } // the space prevents symbols from breaking stuff like '\cdot' if it's written right before the symbol + + + return ' ' + symbol; + }; + + return SymbolNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/node/FunctionNode.js +function FunctionNode_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { FunctionNode_typeof = function _typeof(obj) { return typeof obj; }; } else { FunctionNode_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return FunctionNode_typeof(obj); } + +function FunctionNode_extends() { FunctionNode_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return FunctionNode_extends.apply(this, arguments); } + + + + + + + + +var FunctionNode_name = 'FunctionNode'; +var FunctionNode_dependencies = ['math', 'Node', 'SymbolNode']; +var createFunctionNode = /* #__PURE__ */Object(factory["a" /* factory */])(FunctionNode_name, FunctionNode_dependencies, function (_ref) { + var math = _ref.math, + Node = _ref.Node, + SymbolNode = _ref.SymbolNode; + + /** + * @constructor FunctionNode + * @extends {./Node} + * invoke a list with arguments on a node + * @param {./Node | string} fn Node resolving with a function on which to invoke + * the arguments, typically a SymboNode or AccessorNode + * @param {./Node[]} args + */ + function FunctionNode(fn, args) { + if (!(this instanceof FunctionNode)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (typeof fn === 'string') { + fn = new SymbolNode(fn); + } // validate input + + + if (!Object(is["w" /* isNode */])(fn)) throw new TypeError('Node expected as parameter "fn"'); + + if (!Array.isArray(args) || !args.every(is["w" /* isNode */])) { + throw new TypeError('Array containing Nodes expected for parameter "args"'); + } + + this.fn = fn; + this.args = args || []; // readonly property name + + Object.defineProperty(this, 'name', { + get: function () { + return this.fn.name || ''; + }.bind(this), + set: function set() { + throw new Error('Cannot assign a new name, name is read-only'); + } + }); // TODO: deprecated since v3, remove some day + + var deprecated = function deprecated() { + throw new Error('Property `FunctionNode.object` is deprecated, use `FunctionNode.fn` instead'); + }; + + Object.defineProperty(this, 'object', { + get: deprecated, + set: deprecated + }); + } + + FunctionNode.prototype = new Node(); + FunctionNode.prototype.type = 'FunctionNode'; + FunctionNode.prototype.isFunctionNode = true; + /** + * Compile a node into a JavaScript function. + * This basically pre-calculates as much as possible and only leaves open + * calculations which depend on a dynamic scope with variables. + * @param {Object} math Math.js namespace with functions and constants. + * @param {Object} argNames An object with argument names as key and `true` + * as value. Used in the SymbolNode to optimize + * for arguments from user assigned functions + * (see FunctionAssignmentNode) or special symbols + * like `end` (see IndexNode). + * @return {function} Returns a function which can be called like: + * evalNode(scope: Object, args: Object, context: *) + */ + + FunctionNode.prototype._compile = function (math, argNames) { + if (!(this instanceof FunctionNode)) { + throw new TypeError('No valid FunctionNode'); + } // compile arguments + + + var evalArgs = Object(utils_array["m" /* map */])(this.args, function (arg) { + return arg._compile(math, argNames); + }); + + if (Object(is["J" /* isSymbolNode */])(this.fn)) { + // we can statically determine whether the function has an rawArgs property + var _name = this.fn.name; + var fn = _name in math ? getSafeProperty(math, _name) : undefined; + var isRaw = typeof fn === 'function' && fn.rawArgs === true; + + if (isRaw) { + // pass unevaluated parameters (nodes) to the function + // "raw" evaluation + var rawArgs = this.args; + return function evalFunctionNode(scope, args, context) { + return (_name in scope ? getSafeProperty(scope, _name) : fn)(rawArgs, math, FunctionNode_extends({}, scope, args)); + }; + } else { + // "regular" evaluation + if (evalArgs.length === 1) { + var evalArg0 = evalArgs[0]; + return function evalFunctionNode(scope, args, context) { + return (_name in scope ? getSafeProperty(scope, _name) : fn)(evalArg0(scope, args, context)); + }; + } else if (evalArgs.length === 2) { + var _evalArg = evalArgs[0]; + var evalArg1 = evalArgs[1]; + return function evalFunctionNode(scope, args, context) { + return (_name in scope ? getSafeProperty(scope, _name) : fn)(_evalArg(scope, args, context), evalArg1(scope, args, context)); + }; + } else { + return function evalFunctionNode(scope, args, context) { + return (_name in scope ? getSafeProperty(scope, _name) : fn).apply(null, Object(utils_array["m" /* map */])(evalArgs, function (evalArg) { + return evalArg(scope, args, context); + })); + }; + } + } + } else if (Object(is["a" /* isAccessorNode */])(this.fn) && Object(is["u" /* isIndexNode */])(this.fn.index) && this.fn.index.isObjectProperty()) { + // execute the function with the right context: the object of the AccessorNode + var evalObject = this.fn.object._compile(math, argNames); + + var prop = this.fn.index.getObjectProperty(); + var _rawArgs = this.args; + return function evalFunctionNode(scope, args, context) { + var object = evalObject(scope, args, context); + validateSafeMethod(object, prop); + var isRaw = object[prop] && object[prop].rawArgs; + return isRaw ? object[prop](_rawArgs, math, FunctionNode_extends({}, scope, args)) // "raw" evaluation + : object[prop].apply(object, Object(utils_array["m" /* map */])(evalArgs, function (evalArg) { + // "regular" evaluation + return evalArg(scope, args, context); + })); + }; + } else { + // node.fn.isAccessorNode && !node.fn.index.isObjectProperty() + // we have to dynamically determine whether the function has a rawArgs property + var evalFn = this.fn._compile(math, argNames); + + var _rawArgs2 = this.args; + return function evalFunctionNode(scope, args, context) { + var fn = evalFn(scope, args, context); + var isRaw = fn && fn.rawArgs; + return isRaw ? fn(_rawArgs2, math, FunctionNode_extends({}, scope, args)) // "raw" evaluation + : fn.apply(fn, Object(utils_array["m" /* map */])(evalArgs, function (evalArg) { + // "regular" evaluation + return evalArg(scope, args, context); + })); + }; + } + }; + /** + * Execute a callback for each of the child nodes of this node + * @param {function(child: Node, path: string, parent: Node)} callback + */ + + + FunctionNode.prototype.forEach = function (callback) { + callback(this.fn, 'fn', this); + + for (var i = 0; i < this.args.length; i++) { + callback(this.args[i], 'args[' + i + ']', this); + } + }; + /** + * Create a new FunctionNode having it's childs be the results of calling + * the provided callback function for each of the childs of the original node. + * @param {function(child: Node, path: string, parent: Node): Node} callback + * @returns {FunctionNode} Returns a transformed copy of the node + */ + + + FunctionNode.prototype.map = function (callback) { + var fn = this._ifNode(callback(this.fn, 'fn', this)); + + var args = []; + + for (var i = 0; i < this.args.length; i++) { + args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this)); + } + + return new FunctionNode(fn, args); + }; + /** + * Create a clone of this node, a shallow copy + * @return {FunctionNode} + */ + + + FunctionNode.prototype.clone = function () { + return new FunctionNode(this.fn, this.args.slice(0)); + }; // backup Node's toString function + // @private + + + var nodeToString = FunctionNode.prototype.toString; + /** + * Get string representation. (wrapper function) + * This overrides parts of Node's toString function. + * If callback is an object containing callbacks, it + * calls the correct callback for the current node, + * otherwise it falls back to calling Node's toString + * function. + * + * @param {Object} options + * @return {string} str + * @override + */ + + FunctionNode.prototype.toString = function (options) { + var customString; + var name = this.fn.toString(options); + + if (options && FunctionNode_typeof(options.handler) === 'object' && Object(utils_object["f" /* hasOwnProperty */])(options.handler, name)) { + // callback is a map of callback functions + customString = options.handler[name](this, options); + } + + if (typeof customString !== 'undefined') { + return customString; + } // fall back to Node's toString + + + return nodeToString.call(this, options); + }; + /** + * Get string representation + * @param {Object} options + * @return {string} str + */ + + + FunctionNode.prototype._toString = function (options) { + var args = this.args.map(function (arg) { + return arg.toString(options); + }); + var fn = Object(is["q" /* isFunctionAssignmentNode */])(this.fn) ? '(' + this.fn.toString(options) + ')' : this.fn.toString(options); // format the arguments like "add(2, 4.2)" + + return fn + '(' + args.join(', ') + ')'; + }; + /** + * Get a JSON representation of the node + * @returns {Object} + */ + + + FunctionNode.prototype.toJSON = function () { + return { + mathjs: 'FunctionNode', + fn: this.fn, + args: this.args + }; + }; + /** + * Instantiate an AssignmentNode from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "FunctionNode", fn: ..., args: ...}`, + * where mathjs is optional + * @returns {FunctionNode} + */ + + + FunctionNode.fromJSON = function (json) { + return new FunctionNode(json.fn, json.args); + }; + /** + * Get HTML representation + * @param {Object} options + * @return {string} str + */ + + + FunctionNode.prototype.toHTML = function (options) { + var args = this.args.map(function (arg) { + return arg.toHTML(options); + }); // format the arguments like "add(2, 4.2)" + + return '' + Object(utils_string["c" /* escape */])(this.fn) + '(' + args.join(',') + ')'; + }; + /* + * Expand a LaTeX template + * + * @param {string} template + * @param {Node} node + * @param {Object} options + * @private + **/ + + + function expandTemplate(template, node, options) { + var latex = ''; // Match everything of the form ${identifier} or ${identifier[2]} or $$ + // while submatching identifier and 2 (in the second case) + + var regex = new RegExp('\\$(?:\\{([a-z_][a-z_0-9]*)(?:\\[([0-9]+)\\])?\\}|\\$)', 'ig'); + var inputPos = 0; // position in the input string + + var match; + + while ((match = regex.exec(template)) !== null) { + // go through all matches + // add everything in front of the match to the LaTeX string + latex += template.substring(inputPos, match.index); + inputPos = match.index; + + if (match[0] === '$$') { + // escaped dollar sign + latex += '$'; + inputPos++; + } else { + // template parameter + inputPos += match[0].length; + var property = node[match[1]]; + + if (!property) { + throw new ReferenceError('Template: Property ' + match[1] + ' does not exist.'); + } + + if (match[2] === undefined) { + // no square brackets + switch (FunctionNode_typeof(property)) { + case 'string': + latex += property; + break; + + case 'object': + if (Object(is["w" /* isNode */])(property)) { + latex += property.toTex(options); + } else if (Array.isArray(property)) { + // make array of Nodes into comma separated list + latex += property.map(function (arg, index) { + if (Object(is["w" /* isNode */])(arg)) { + return arg.toTex(options); + } + + throw new TypeError('Template: ' + match[1] + '[' + index + '] is not a Node.'); + }).join(','); + } else { + throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes'); + } + + break; + + default: + throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes'); + } + } else { + // with square brackets + if (Object(is["w" /* isNode */])(property[match[2]] && property[match[2]])) { + latex += property[match[2]].toTex(options); + } else { + throw new TypeError('Template: ' + match[1] + '[' + match[2] + '] is not a Node.'); + } + } + } + } + + latex += template.slice(inputPos); // append rest of the template + + return latex; + } // backup Node's toTex function + // @private + + + var nodeToTex = FunctionNode.prototype.toTex; + /** + * Get LaTeX representation. (wrapper function) + * This overrides parts of Node's toTex function. + * If callback is an object containing callbacks, it + * calls the correct callback for the current node, + * otherwise it falls back to calling Node's toTex + * function. + * + * @param {Object} options + * @return {string} + */ + + FunctionNode.prototype.toTex = function (options) { + var customTex; + + if (options && FunctionNode_typeof(options.handler) === 'object' && Object(utils_object["f" /* hasOwnProperty */])(options.handler, this.name)) { + // callback is a map of callback functions + customTex = options.handler[this.name](this, options); + } + + if (typeof customTex !== 'undefined') { + return customTex; + } // fall back to Node's toTex + + + return nodeToTex.call(this, options); + }; + /** + * Get LaTeX representation + * @param {Object} options + * @return {string} str + */ + + + FunctionNode.prototype._toTex = function (options) { + var args = this.args.map(function (arg) { + // get LaTeX of the arguments + return arg.toTex(options); + }); + var latexConverter; + + if (latexFunctions[this.name]) { + latexConverter = latexFunctions[this.name]; + } // toTex property on the function itself + + + if (math[this.name] && (typeof math[this.name].toTex === 'function' || FunctionNode_typeof(math[this.name].toTex) === 'object' || typeof math[this.name].toTex === 'string')) { + // .toTex is a callback function + latexConverter = math[this.name].toTex; + } + + var customToTex; + + switch (FunctionNode_typeof(latexConverter)) { + case 'function': + // a callback function + customToTex = latexConverter(this, options); + break; + + case 'string': + // a template string + customToTex = expandTemplate(latexConverter, this, options); + break; + + case 'object': + // an object with different "converters" for different numbers of arguments + switch (FunctionNode_typeof(latexConverter[args.length])) { + case 'function': + customToTex = latexConverter[args.length](this, options); + break; + + case 'string': + customToTex = expandTemplate(latexConverter[args.length], this, options); + break; + } + + } + + if (typeof customToTex !== 'undefined') { + return customToTex; + } + + return expandTemplate(defaultTemplate, this, options); + }; + /** + * Get identifier. + * @return {string} + */ + + + FunctionNode.prototype.getIdentifier = function () { + return this.type + ':' + this.name; + }; + + return FunctionNode; +}, { + isClass: true, + isNode: true +}); +// CONCATENATED MODULE: ./src/expression/parse.js +function parse_extends() { parse_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return parse_extends.apply(this, arguments); } + + + + + +var parse_name = 'parse'; +var parse_dependencies = ['typed', 'numeric', 'config', 'AccessorNode', 'ArrayNode', 'AssignmentNode', 'BlockNode', 'ConditionalNode', 'ConstantNode', 'FunctionAssignmentNode', 'FunctionNode', 'IndexNode', 'ObjectNode', 'OperatorNode', 'ParenthesisNode', 'RangeNode', 'RelationalNode', 'SymbolNode']; +var createParse = /* #__PURE__ */Object(factory["a" /* factory */])(parse_name, parse_dependencies, function (_ref) { + var typed = _ref.typed, + numeric = _ref.numeric, + config = _ref.config, + AccessorNode = _ref.AccessorNode, + ArrayNode = _ref.ArrayNode, + AssignmentNode = _ref.AssignmentNode, + BlockNode = _ref.BlockNode, + ConditionalNode = _ref.ConditionalNode, + ConstantNode = _ref.ConstantNode, + FunctionAssignmentNode = _ref.FunctionAssignmentNode, + FunctionNode = _ref.FunctionNode, + IndexNode = _ref.IndexNode, + ObjectNode = _ref.ObjectNode, + OperatorNode = _ref.OperatorNode, + ParenthesisNode = _ref.ParenthesisNode, + RangeNode = _ref.RangeNode, + RelationalNode = _ref.RelationalNode, + SymbolNode = _ref.SymbolNode; + + /** + * Parse an expression. Returns a node tree, which can be evaluated by + * invoking node.evaluate(). + * + * Note the evaluating arbitrary expressions may involve security risks, + * see [https://mathjs.org/docs/expressions/security.html](https://mathjs.org/docs/expressions/security.html) for more information. + * + * Syntax: + * + * math.parse(expr) + * math.parse(expr, options) + * math.parse([expr1, expr2, expr3, ...]) + * math.parse([expr1, expr2, expr3, ...], options) + * + * Example: + * + * const node1 = math.parse('sqrt(3^2 + 4^2)') + * node1.compile().evaluate() // 5 + * + * let scope = {a:3, b:4} + * const node2 = math.parse('a * b') // 12 + * const code2 = node2.compile() + * code2.evaluate(scope) // 12 + * scope.a = 5 + * code2.evaluate(scope) // 20 + * + * const nodes = math.parse(['a = 3', 'b = 4', 'a * b']) + * nodes[2].compile().evaluate() // 12 + * + * See also: + * + * evaluate, compile + * + * @param {string | string[] | Matrix} expr Expression to be parsed + * @param {{nodes: Object}} [options] Available options: + * - `nodes` a set of custom nodes + * @return {Node | Node[]} node + * @throws {Error} + */ + var parse = typed(parse_name, { + string: function string(expression) { + return parseStart(expression, {}); + }, + 'Array | Matrix': function ArrayMatrix(expressions) { + return parseMultiple(expressions, {}); + }, + 'string, Object': function stringObject(expression, options) { + var extraNodes = options.nodes !== undefined ? options.nodes : {}; + return parseStart(expression, extraNodes); + }, + 'Array | Matrix, Object': parseMultiple + }); + + function parseMultiple(expressions) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var extraNodes = options.nodes !== undefined ? options.nodes : {}; // parse an array or matrix with expressions + + return deepMap(expressions, function (elem) { + if (typeof elem !== 'string') throw new TypeError('String expected'); + return parseStart(elem, extraNodes); + }); + } // token types enumeration + + + var TOKENTYPE = { + NULL: 0, + DELIMITER: 1, + NUMBER: 2, + SYMBOL: 3, + UNKNOWN: 4 + }; // map with all delimiters + + var DELIMITERS = { + ',': true, + '(': true, + ')': true, + '[': true, + ']': true, + '{': true, + '}': true, + '"': true, + '\'': true, + ';': true, + '+': true, + '-': true, + '*': true, + '.*': true, + '/': true, + './': true, + '%': true, + '^': true, + '.^': true, + '~': true, + '!': true, + '&': true, + '|': true, + '^|': true, + '=': true, + ':': true, + '?': true, + '==': true, + '!=': true, + '<': true, + '>': true, + '<=': true, + '>=': true, + '<<': true, + '>>': true, + '>>>': true + }; // map with all named delimiters + + var NAMED_DELIMITERS = { + mod: true, + to: true, + "in": true, + and: true, + xor: true, + or: true, + not: true + }; + var CONSTANTS = { + "true": true, + "false": false, + "null": null, + undefined: undefined + }; + var NUMERIC_CONSTANTS = ['NaN', 'Infinity']; + + function initialState() { + return { + extraNodes: {}, + // current extra nodes, must be careful not to mutate + expression: '', + // current expression + comment: '', + // last parsed comment + index: 0, + // current index in expr + token: '', + // current token + tokenType: TOKENTYPE.NULL, + // type of the token + nestingLevel: 0, + // level of nesting inside parameters, used to ignore newline characters + conditionalLevel: null // when a conditional is being parsed, the level of the conditional is stored here + + }; + } + /** + * View upto `length` characters of the expression starting at the current character. + * + * @param {Object} state + * @param {number} [length=1] Number of characters to view + * @returns {string} + * @private + */ + + + function currentString(state, length) { + return state.expression.substr(state.index, length); + } + /** + * View the current character. Returns '' if end of expression is reached. + * + * @param {Object} state + * @returns {string} + * @private + */ + + + function currentCharacter(state) { + return currentString(state, 1); + } + /** + * Get the next character from the expression. + * The character is stored into the char c. If the end of the expression is + * reached, the function puts an empty string in c. + * @private + */ + + + function next(state) { + state.index++; + } + /** + * Preview the previous character from the expression. + * @return {string} cNext + * @private + */ + + + function prevCharacter(state) { + return state.expression.charAt(state.index - 1); + } + /** + * Preview the next character from the expression. + * @return {string} cNext + * @private + */ + + + function nextCharacter(state) { + return state.expression.charAt(state.index + 1); + } + /** + * Get next token in the current string expr. + * The token and token type are available as token and tokenType + * @private + */ + + + function getToken(state) { + state.tokenType = TOKENTYPE.NULL; + state.token = ''; + state.comment = ''; // skip over whitespaces + // space, tab, and newline when inside parameters + + while (parse.isWhitespace(currentCharacter(state), state.nestingLevel)) { + next(state); + } // skip comment + + + if (currentCharacter(state) === '#') { + while (currentCharacter(state) !== '\n' && currentCharacter(state) !== '') { + state.comment += currentCharacter(state); + next(state); + } + } // check for end of expression + + + if (currentCharacter(state) === '') { + // token is still empty + state.tokenType = TOKENTYPE.DELIMITER; + return; + } // check for new line character + + + if (currentCharacter(state) === '\n' && !state.nestingLevel) { + state.tokenType = TOKENTYPE.DELIMITER; + state.token = currentCharacter(state); + next(state); + return; + } + + var c1 = currentCharacter(state); + var c2 = currentString(state, 2); + var c3 = currentString(state, 3); + + if (c3.length === 3 && DELIMITERS[c3]) { + state.tokenType = TOKENTYPE.DELIMITER; + state.token = c3; + next(state); + next(state); + next(state); + return; + } // check for delimiters consisting of 2 characters + + + if (c2.length === 2 && DELIMITERS[c2]) { + state.tokenType = TOKENTYPE.DELIMITER; + state.token = c2; + next(state); + next(state); + return; + } // check for delimiters consisting of 1 character + + + if (DELIMITERS[c1]) { + state.tokenType = TOKENTYPE.DELIMITER; + state.token = c1; + next(state); + return; + } // check for a number + + + if (parse.isDigitDot(c1)) { + state.tokenType = TOKENTYPE.NUMBER; // get number, can have a single dot + + if (currentCharacter(state) === '.') { + state.token += currentCharacter(state); + next(state); + + if (!parse.isDigit(currentCharacter(state))) { + // this is no number, it is just a dot (can be dot notation) + state.tokenType = TOKENTYPE.DELIMITER; + } + } else { + while (parse.isDigit(currentCharacter(state))) { + state.token += currentCharacter(state); + next(state); + } + + if (parse.isDecimalMark(currentCharacter(state), nextCharacter(state))) { + state.token += currentCharacter(state); + next(state); + } + } + + while (parse.isDigit(currentCharacter(state))) { + state.token += currentCharacter(state); + next(state); + } // check for exponential notation like "2.3e-4", "1.23e50" or "2e+4" + + + if (currentCharacter(state) === 'E' || currentCharacter(state) === 'e') { + if (parse.isDigit(nextCharacter(state)) || nextCharacter(state) === '-' || nextCharacter(state) === '+') { + state.token += currentCharacter(state); + next(state); + + if (currentCharacter(state) === '+' || currentCharacter(state) === '-') { + state.token += currentCharacter(state); + next(state); + } // Scientific notation MUST be followed by an exponent + + + if (!parse.isDigit(currentCharacter(state))) { + throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"'); + } + + while (parse.isDigit(currentCharacter(state))) { + state.token += currentCharacter(state); + next(state); + } + + if (parse.isDecimalMark(currentCharacter(state), nextCharacter(state))) { + throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"'); + } + } else if (nextCharacter(state) === '.') { + next(state); + throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"'); + } + } + + return; + } // check for variables, functions, named operators + + + if (parse.isAlpha(currentCharacter(state), prevCharacter(state), nextCharacter(state))) { + while (parse.isAlpha(currentCharacter(state), prevCharacter(state), nextCharacter(state)) || parse.isDigit(currentCharacter(state))) { + state.token += currentCharacter(state); + next(state); + } + + if (Object(utils_object["f" /* hasOwnProperty */])(NAMED_DELIMITERS, state.token)) { + state.tokenType = TOKENTYPE.DELIMITER; + } else { + state.tokenType = TOKENTYPE.SYMBOL; + } + + return; + } // something unknown is found, wrong characters -> a syntax error + + + state.tokenType = TOKENTYPE.UNKNOWN; + + while (currentCharacter(state) !== '') { + state.token += currentCharacter(state); + next(state); + } + + throw createSyntaxError(state, 'Syntax error in part "' + state.token + '"'); + } + /** + * Get next token and skip newline tokens + */ + + + function getTokenSkipNewline(state) { + do { + getToken(state); + } while (state.token === '\n'); // eslint-disable-line no-unmodified-loop-condition + + } + /** + * Open parameters. + * New line characters will be ignored until closeParams(state) is called + */ + + + function openParams(state) { + state.nestingLevel++; + } + /** + * Close parameters. + * New line characters will no longer be ignored + */ + + + function closeParams(state) { + state.nestingLevel--; + } + /** + * Checks whether the current character `c` is a valid alpha character: + * + * - A latin letter (upper or lower case) Ascii: a-z, A-Z + * - An underscore Ascii: _ + * - A dollar sign Ascii: $ + * - A latin letter with accents Unicode: \u00C0 - \u02AF + * - A greek letter Unicode: \u0370 - \u03FF + * - A mathematical alphanumeric symbol Unicode: \u{1D400} - \u{1D7FF} excluding invalid code points + * + * The previous and next characters are needed to determine whether + * this character is part of a unicode surrogate pair. + * + * @param {string} c Current character in the expression + * @param {string} cPrev Previous character + * @param {string} cNext Next character + * @return {boolean} + */ + + + parse.isAlpha = function isAlpha(c, cPrev, cNext) { + return parse.isValidLatinOrGreek(c) || parse.isValidMathSymbol(c, cNext) || parse.isValidMathSymbol(cPrev, c); + }; + /** + * Test whether a character is a valid latin, greek, or letter-like character + * @param {string} c + * @return {boolean} + */ + + + parse.isValidLatinOrGreek = function isValidLatinOrGreek(c) { + return /^[a-zA-Z_$\u00C0-\u02AF\u0370-\u03FF\u2100-\u214F]$/.test(c); + }; + /** + * Test whether two given 16 bit characters form a surrogate pair of a + * unicode math symbol. + * + * https://unicode-table.com/en/ + * https://www.wikiwand.com/en/Mathematical_operators_and_symbols_in_Unicode + * + * Note: In ES6 will be unicode aware: + * https://stackoverflow.com/questions/280712/javascript-unicode-regexes + * https://mathiasbynens.be/notes/es6-unicode-regex + * + * @param {string} high + * @param {string} low + * @return {boolean} + */ + + + parse.isValidMathSymbol = function isValidMathSymbol(high, low) { + return /^[\uD835]$/.test(high) && /^[\uDC00-\uDFFF]$/.test(low) && /^[^\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDFCC\uDFCD]$/.test(low); + }; + /** + * Check whether given character c is a white space character: space, tab, or enter + * @param {string} c + * @param {number} nestingLevel + * @return {boolean} + */ + + + parse.isWhitespace = function isWhitespace(c, nestingLevel) { + // TODO: also take '\r' carriage return as newline? Or does that give problems on mac? + return c === ' ' || c === '\t' || c === '\n' && nestingLevel > 0; + }; + /** + * Test whether the character c is a decimal mark (dot). + * This is the case when it's not the start of a delimiter '.*', './', or '.^' + * @param {string} c + * @param {string} cNext + * @return {boolean} + */ + + + parse.isDecimalMark = function isDecimalMark(c, cNext) { + return c === '.' && cNext !== '/' && cNext !== '*' && cNext !== '^'; + }; + /** + * checks if the given char c is a digit or dot + * @param {string} c a string with one character + * @return {boolean} + */ + + + parse.isDigitDot = function isDigitDot(c) { + return c >= '0' && c <= '9' || c === '.'; + }; + /** + * checks if the given char c is a digit + * @param {string} c a string with one character + * @return {boolean} + */ + + + parse.isDigit = function isDigit(c) { + return c >= '0' && c <= '9'; + }; + /** + * Start of the parse levels below, in order of precedence + * @return {Node} node + * @private + */ + + + function parseStart(expression, extraNodes) { + var state = initialState(); + + parse_extends(state, { + expression: expression, + extraNodes: extraNodes + }); + + getToken(state); + var node = parseBlock(state); // check for garbage at the end of the expression + // an expression ends with a empty character '' and tokenType DELIMITER + + if (state.token !== '') { + if (state.tokenType === TOKENTYPE.DELIMITER) { + // user entered a not existing operator like "//" + // TODO: give hints for aliases, for example with "<>" give as hint " did you mean !== ?" + throw createError(state, 'Unexpected operator ' + state.token); + } else { + throw createSyntaxError(state, 'Unexpected part "' + state.token + '"'); + } + } + + return node; + } + /** + * Parse a block with expressions. Expressions can be separated by a newline + * character '\n', or by a semicolon ';'. In case of a semicolon, no output + * of the preceding line is returned. + * @return {Node} node + * @private + */ + + + function parseBlock(state) { + var node; + var blocks = []; + var visible; + + if (state.token !== '' && state.token !== '\n' && state.token !== ';') { + node = parseAssignment(state); + node.comment = state.comment; + } // TODO: simplify this loop + + + while (state.token === '\n' || state.token === ';') { + // eslint-disable-line no-unmodified-loop-condition + if (blocks.length === 0 && node) { + visible = state.token !== ';'; + blocks.push({ + node: node, + visible: visible + }); + } + + getToken(state); + + if (state.token !== '\n' && state.token !== ';' && state.token !== '') { + node = parseAssignment(state); + node.comment = state.comment; + visible = state.token !== ';'; + blocks.push({ + node: node, + visible: visible + }); + } + } + + if (blocks.length > 0) { + return new BlockNode(blocks); + } else { + if (!node) { + node = new ConstantNode(undefined); + node.comment = state.comment; + } + + return node; + } + } + /** + * Assignment of a function or variable, + * - can be a variable like 'a=2.3' + * - or a updating an existing variable like 'matrix(2,3:5)=[6,7,8]' + * - defining a function like 'f(x) = x^2' + * @return {Node} node + * @private + */ + + + function parseAssignment(state) { + var name, args, value, valid; + var node = parseConditional(state); + + if (state.token === '=') { + if (Object(is["J" /* isSymbolNode */])(node)) { + // parse a variable assignment like 'a = 2/3' + name = node.name; + getTokenSkipNewline(state); + value = parseAssignment(state); + return new AssignmentNode(new SymbolNode(name), value); + } else if (Object(is["a" /* isAccessorNode */])(node)) { + // parse a matrix subset assignment like 'A[1,2] = 4' + getTokenSkipNewline(state); + value = parseAssignment(state); + return new AssignmentNode(node.object, node.index, value); + } else if (Object(is["r" /* isFunctionNode */])(node) && Object(is["J" /* isSymbolNode */])(node.fn)) { + // parse function assignment like 'f(x) = x^2' + valid = true; + args = []; + name = node.name; + node.args.forEach(function (arg, index) { + if (Object(is["J" /* isSymbolNode */])(arg)) { + args[index] = arg.name; + } else { + valid = false; + } + }); + + if (valid) { + getTokenSkipNewline(state); + value = parseAssignment(state); + return new FunctionAssignmentNode(name, args, value); + } + } + + throw createSyntaxError(state, 'Invalid left hand side of assignment operator ='); + } + + return node; + } + /** + * conditional operation + * + * condition ? truePart : falsePart + * + * Note: conditional operator is right-associative + * + * @return {Node} node + * @private + */ + + + function parseConditional(state) { + var node = parseLogicalOr(state); + + while (state.token === '?') { + // eslint-disable-line no-unmodified-loop-condition + // set a conditional level, the range operator will be ignored as long + // as conditionalLevel === state.nestingLevel. + var prev = state.conditionalLevel; + state.conditionalLevel = state.nestingLevel; + getTokenSkipNewline(state); + var condition = node; + var trueExpr = parseAssignment(state); + if (state.token !== ':') throw createSyntaxError(state, 'False part of conditional expression expected'); + state.conditionalLevel = null; + getTokenSkipNewline(state); + var falseExpr = parseAssignment(state); // Note: check for conditional operator again, right associativity + + node = new ConditionalNode(condition, trueExpr, falseExpr); // restore the previous conditional level + + state.conditionalLevel = prev; + } + + return node; + } + /** + * logical or, 'x or y' + * @return {Node} node + * @private + */ + + + function parseLogicalOr(state) { + var node = parseLogicalXor(state); + + while (state.token === 'or') { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + node = new OperatorNode('or', 'or', [node, parseLogicalXor(state)]); + } + + return node; + } + /** + * logical exclusive or, 'x xor y' + * @return {Node} node + * @private + */ + + + function parseLogicalXor(state) { + var node = parseLogicalAnd(state); + + while (state.token === 'xor') { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + node = new OperatorNode('xor', 'xor', [node, parseLogicalAnd(state)]); + } + + return node; + } + /** + * logical and, 'x and y' + * @return {Node} node + * @private + */ + + + function parseLogicalAnd(state) { + var node = parseBitwiseOr(state); + + while (state.token === 'and') { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + node = new OperatorNode('and', 'and', [node, parseBitwiseOr(state)]); + } + + return node; + } + /** + * bitwise or, 'x | y' + * @return {Node} node + * @private + */ + + + function parseBitwiseOr(state) { + var node = parseBitwiseXor(state); + + while (state.token === '|') { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + node = new OperatorNode('|', 'bitOr', [node, parseBitwiseXor(state)]); + } + + return node; + } + /** + * bitwise exclusive or (xor), 'x ^| y' + * @return {Node} node + * @private + */ + + + function parseBitwiseXor(state) { + var node = parseBitwiseAnd(state); + + while (state.token === '^|') { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + node = new OperatorNode('^|', 'bitXor', [node, parseBitwiseAnd(state)]); + } + + return node; + } + /** + * bitwise and, 'x & y' + * @return {Node} node + * @private + */ + + + function parseBitwiseAnd(state) { + var node = parseRelational(state); + + while (state.token === '&') { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + node = new OperatorNode('&', 'bitAnd', [node, parseRelational(state)]); + } + + return node; + } + /** + * Parse a chained conditional, like 'a > b >= c' + * @return {Node} node + */ + + + function parseRelational(state) { + var params = [parseShift(state)]; + var conditionals = []; + var operators = { + '==': 'equal', + '!=': 'unequal', + '<': 'smaller', + '>': 'larger', + '<=': 'smallerEq', + '>=': 'largerEq' + }; + + while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + // eslint-disable-line no-unmodified-loop-condition + var cond = { + name: state.token, + fn: operators[state.token] + }; + conditionals.push(cond); + getTokenSkipNewline(state); + params.push(parseShift(state)); + } + + if (params.length === 1) { + return params[0]; + } else if (params.length === 2) { + return new OperatorNode(conditionals[0].name, conditionals[0].fn, params); + } else { + return new RelationalNode(conditionals.map(function (c) { + return c.fn; + }), params); + } + } + /** + * Bitwise left shift, bitwise right arithmetic shift, bitwise right logical shift + * @return {Node} node + * @private + */ + + + function parseShift(state) { + var node, name, fn, params; + node = parseConversion(state); + var operators = { + '<<': 'leftShift', + '>>': 'rightArithShift', + '>>>': 'rightLogShift' + }; + + while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + name = state.token; + fn = operators[name]; + getTokenSkipNewline(state); + params = [node, parseConversion(state)]; + node = new OperatorNode(name, fn, params); + } + + return node; + } + /** + * conversion operators 'to' and 'in' + * @return {Node} node + * @private + */ + + + function parseConversion(state) { + var node, name, fn, params; + node = parseRange(state); + var operators = { + to: 'to', + "in": 'to' // alias of 'to' + + }; + + while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + name = state.token; + fn = operators[name]; + getTokenSkipNewline(state); + + if (name === 'in' && state.token === '') { + // end of expression -> this is the unit 'in' ('inch') + node = new OperatorNode('*', 'multiply', [node, new SymbolNode('in')], true); + } else { + // operator 'a to b' or 'a in b' + params = [node, parseRange(state)]; + node = new OperatorNode(name, fn, params); + } + } + + return node; + } + /** + * parse range, "start:end", "start:step:end", ":", "start:", ":end", etc + * @return {Node} node + * @private + */ + + + function parseRange(state) { + var node; + var params = []; + + if (state.token === ':') { + // implicit start=1 (one-based) + node = new ConstantNode(1); + } else { + // explicit start + node = parseAddSubtract(state); + } + + if (state.token === ':' && state.conditionalLevel !== state.nestingLevel) { + // we ignore the range operator when a conditional operator is being processed on the same level + params.push(node); // parse step and end + + while (state.token === ':' && params.length < 3) { + // eslint-disable-line no-unmodified-loop-condition + getTokenSkipNewline(state); + + if (state.token === ')' || state.token === ']' || state.token === ',' || state.token === '') { + // implicit end + params.push(new SymbolNode('end')); + } else { + // explicit end + params.push(parseAddSubtract(state)); + } + } + + if (params.length === 3) { + // params = [start, step, end] + node = new RangeNode(params[0], params[2], params[1]); // start, end, step + } else { + // length === 2 + // params = [start, end] + node = new RangeNode(params[0], params[1]); // start, end + } + } + + return node; + } + /** + * add or subtract + * @return {Node} node + * @private + */ + + + function parseAddSubtract(state) { + var node, name, fn, params; + node = parseMultiplyDivide(state); + var operators = { + '+': 'add', + '-': 'subtract' + }; + + while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + name = state.token; + fn = operators[name]; + getTokenSkipNewline(state); + params = [node, parseMultiplyDivide(state)]; + node = new OperatorNode(name, fn, params); + } + + return node; + } + /** + * multiply, divide, modulus + * @return {Node} node + * @private + */ + + + function parseMultiplyDivide(state) { + var node, last, name, fn; + node = parseImplicitMultiplication(state); + last = node; + var operators = { + '*': 'multiply', + '.*': 'dotMultiply', + '/': 'divide', + './': 'dotDivide', + '%': 'mod', + mod: 'mod' + }; + + while (true) { + if (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + // explicit operators + name = state.token; + fn = operators[name]; + getTokenSkipNewline(state); + last = parseImplicitMultiplication(state); + node = new OperatorNode(name, fn, [node, last]); + } else { + break; + } + } + + return node; + } + /** + * implicit multiplication + * @return {Node} node + * @private + */ + + + function parseImplicitMultiplication(state) { + var node, last; + node = parseRule2(state); + last = node; + + while (true) { + if (state.tokenType === TOKENTYPE.SYMBOL || state.token === 'in' && Object(is["l" /* isConstantNode */])(node) || state.tokenType === TOKENTYPE.NUMBER && !Object(is["l" /* isConstantNode */])(last) && (!Object(is["B" /* isOperatorNode */])(last) || last.op === '!') || state.token === '(') { + // parse implicit multiplication + // + // symbol: implicit multiplication like '2a', '(2+3)a', 'a b' + // number: implicit multiplication like '(2+3)2' + // parenthesis: implicit multiplication like '2(3+4)', '(3+4)(1+2)' + last = parseRule2(state); + node = new OperatorNode('*', 'multiply', [node, last], true + /* implicit */ + ); + } else { + break; + } + } + + return node; + } + /** + * Infamous "rule 2" as described in https://github.com/josdejong/mathjs/issues/792#issuecomment-361065370 + * Explicit division gets higher precedence than implicit multiplication + * when the division matches this pattern: [number] / [number] [symbol] + * @return {Node} node + * @private + */ + + + function parseRule2(state) { + var node = parseUnary(state); + var last = node; + var tokenStates = []; + + while (true) { + // Match the "number /" part of the pattern "number / number symbol" + if (state.token === '/' && Object(is["l" /* isConstantNode */])(last)) { + // Look ahead to see if the next token is a number + tokenStates.push(parse_extends({}, state)); + getTokenSkipNewline(state); // Match the "number / number" part of the pattern + + if (state.tokenType === TOKENTYPE.NUMBER) { + // Look ahead again + tokenStates.push(parse_extends({}, state)); + getTokenSkipNewline(state); // Match the "symbol" part of the pattern, or a left parenthesis + + if (state.tokenType === TOKENTYPE.SYMBOL || state.token === '(') { + // We've matched the pattern "number / number symbol". + // Rewind once and build the "number / number" node; the symbol will be consumed later + parse_extends(state, tokenStates.pop()); + + tokenStates.pop(); + last = parseUnary(state); + node = new OperatorNode('/', 'divide', [node, last]); + } else { + // Not a match, so rewind + tokenStates.pop(); + + parse_extends(state, tokenStates.pop()); + + break; + } + } else { + // Not a match, so rewind + parse_extends(state, tokenStates.pop()); + + break; + } + } else { + break; + } + } + + return node; + } + /** + * Unary plus and minus, and logical and bitwise not + * @return {Node} node + * @private + */ + + + function parseUnary(state) { + var name, params, fn; + var operators = { + '-': 'unaryMinus', + '+': 'unaryPlus', + '~': 'bitNot', + not: 'not' + }; + + if (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + fn = operators[state.token]; + name = state.token; + getTokenSkipNewline(state); + params = [parseUnary(state)]; + return new OperatorNode(name, fn, params); + } + + return parsePow(state); + } + /** + * power + * Note: power operator is right associative + * @return {Node} node + * @private + */ + + + function parsePow(state) { + var node, name, fn, params; + node = parseLeftHandOperators(state); + + if (state.token === '^' || state.token === '.^') { + name = state.token; + fn = name === '^' ? 'pow' : 'dotPow'; + getTokenSkipNewline(state); + params = [node, parseUnary(state)]; // Go back to unary, we can have '2^-3' + + node = new OperatorNode(name, fn, params); + } + + return node; + } + /** + * Left hand operators: factorial x!, ctranspose x' + * @return {Node} node + * @private + */ + + + function parseLeftHandOperators(state) { + var node, name, fn, params; + node = parseCustomNodes(state); + var operators = { + '!': 'factorial', + '\'': 'ctranspose' + }; + + while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) { + name = state.token; + fn = operators[name]; + getToken(state); + params = [node]; + node = new OperatorNode(name, fn, params); + node = parseAccessors(state, node); + } + + return node; + } + /** + * Parse a custom node handler. A node handler can be used to process + * nodes in a custom way, for example for handling a plot. + * + * A handler must be passed as second argument of the parse function. + * - must extend math.expression.node.Node + * - must contain a function _compile(defs: Object) : string + * - must contain a function find(filter: Object) : Node[] + * - must contain a function toString() : string + * - the constructor is called with a single argument containing all parameters + * + * For example: + * + * nodes = { + * 'plot': PlotHandler + * } + * + * The constructor of the handler is called as: + * + * node = new PlotHandler(params) + * + * The handler will be invoked when evaluating an expression like: + * + * node = math.parse('plot(sin(x), x)', nodes) + * + * @return {Node} node + * @private + */ + + + function parseCustomNodes(state) { + var params = []; + + if (state.tokenType === TOKENTYPE.SYMBOL && Object(utils_object["f" /* hasOwnProperty */])(state.extraNodes, state.token)) { + var CustomNode = state.extraNodes[state.token]; + getToken(state); // parse parameters + + if (state.token === '(') { + params = []; + openParams(state); + getToken(state); + + if (state.token !== ')') { + params.push(parseAssignment(state)); // parse a list with parameters + + while (state.token === ',') { + // eslint-disable-line no-unmodified-loop-condition + getToken(state); + params.push(parseAssignment(state)); + } + } + + if (state.token !== ')') { + throw createSyntaxError(state, 'Parenthesis ) expected'); + } + + closeParams(state); + getToken(state); + } // create a new custom node + // noinspection JSValidateTypes + + + return new CustomNode(params); + } + + return parseSymbol(state); + } + /** + * parse symbols: functions, variables, constants, units + * @return {Node} node + * @private + */ + + + function parseSymbol(state) { + var node, name; + + if (state.tokenType === TOKENTYPE.SYMBOL || state.tokenType === TOKENTYPE.DELIMITER && state.token in NAMED_DELIMITERS) { + name = state.token; + getToken(state); + + if (Object(utils_object["f" /* hasOwnProperty */])(CONSTANTS, name)) { + // true, false, null, ... + node = new ConstantNode(CONSTANTS[name]); + } else if (NUMERIC_CONSTANTS.indexOf(name) !== -1) { + // NaN, Infinity + node = new ConstantNode(numeric(name, 'number')); + } else { + node = new SymbolNode(name); + } // parse function parameters and matrix index + + + node = parseAccessors(state, node); + return node; + } + + return parseDoubleQuotesString(state); + } + /** + * parse accessors: + * - function invocation in round brackets (...), for example sqrt(2) + * - index enclosed in square brackets [...], for example A[2,3] + * - dot notation for properties, like foo.bar + * @param {Object} state + * @param {Node} node Node on which to apply the parameters. If there + * are no parameters in the expression, the node + * itself is returned + * @param {string[]} [types] Filter the types of notations + * can be ['(', '[', '.'] + * @return {Node} node + * @private + */ + + + function parseAccessors(state, node, types) { + var params; + + while ((state.token === '(' || state.token === '[' || state.token === '.') && (!types || types.indexOf(state.token) !== -1)) { + // eslint-disable-line no-unmodified-loop-condition + params = []; + + if (state.token === '(') { + if (Object(is["J" /* isSymbolNode */])(node) || Object(is["a" /* isAccessorNode */])(node)) { + // function invocation like fn(2, 3) or obj.fn(2, 3) + openParams(state); + getToken(state); + + if (state.token !== ')') { + params.push(parseAssignment(state)); // parse a list with parameters + + while (state.token === ',') { + // eslint-disable-line no-unmodified-loop-condition + getToken(state); + params.push(parseAssignment(state)); + } + } + + if (state.token !== ')') { + throw createSyntaxError(state, 'Parenthesis ) expected'); + } + + closeParams(state); + getToken(state); + node = new FunctionNode(node, params); + } else { + // implicit multiplication like (2+3)(4+5) or sqrt(2)(1+2) + // don't parse it here but let it be handled by parseImplicitMultiplication + // with correct precedence + return node; + } + } else if (state.token === '[') { + // index notation like variable[2, 3] + openParams(state); + getToken(state); + + if (state.token !== ']') { + params.push(parseAssignment(state)); // parse a list with parameters + + while (state.token === ',') { + // eslint-disable-line no-unmodified-loop-condition + getToken(state); + params.push(parseAssignment(state)); + } + } + + if (state.token !== ']') { + throw createSyntaxError(state, 'Parenthesis ] expected'); + } + + closeParams(state); + getToken(state); + node = new AccessorNode(node, new IndexNode(params)); + } else { + // dot notation like variable.prop + getToken(state); + + if (state.tokenType !== TOKENTYPE.SYMBOL) { + throw createSyntaxError(state, 'Property name expected after dot'); + } + + params.push(new ConstantNode(state.token)); + getToken(state); + var dotNotation = true; + node = new AccessorNode(node, new IndexNode(params, dotNotation)); + } + } + + return node; + } + /** + * Parse a double quotes string. + * @return {Node} node + * @private + */ + + + function parseDoubleQuotesString(state) { + var node, str; + + if (state.token === '"') { + str = parseDoubleQuotesStringToken(state); // create constant + + node = new ConstantNode(str); // parse index parameters + + node = parseAccessors(state, node); + return node; + } + + return parseSingleQuotesString(state); + } + /** + * Parse a string surrounded by double quotes "..." + * @return {string} + */ + + + function parseDoubleQuotesStringToken(state) { + var str = ''; + + while (currentCharacter(state) !== '' && currentCharacter(state) !== '"') { + if (currentCharacter(state) === '\\') { + // escape character, immediately process the next + // character to prevent stopping at a next '\"' + str += currentCharacter(state); + next(state); + } + + str += currentCharacter(state); + next(state); + } + + getToken(state); + + if (state.token !== '"') { + throw createSyntaxError(state, 'End of string " expected'); + } + + getToken(state); + return JSON.parse('"' + str + '"'); // unescape escaped characters + } + /** + * Parse a single quotes string. + * @return {Node} node + * @private + */ + + + function parseSingleQuotesString(state) { + var node, str; + + if (state.token === '\'') { + str = parseSingleQuotesStringToken(state); // create constant + + node = new ConstantNode(str); // parse index parameters + + node = parseAccessors(state, node); + return node; + } + + return parseMatrix(state); + } + /** + * Parse a string surrounded by single quotes '...' + * @return {string} + */ + + + function parseSingleQuotesStringToken(state) { + var str = ''; + + while (currentCharacter(state) !== '' && currentCharacter(state) !== '\'') { + if (currentCharacter(state) === '\\') { + // escape character, immediately process the next + // character to prevent stopping at a next '\'' + str += currentCharacter(state); + next(state); + } + + str += currentCharacter(state); + next(state); + } + + getToken(state); + + if (state.token !== '\'') { + throw createSyntaxError(state, 'End of string \' expected'); + } + + getToken(state); + return JSON.parse('"' + str + '"'); // unescape escaped characters + } + /** + * parse the matrix + * @return {Node} node + * @private + */ + + + function parseMatrix(state) { + var array, params, rows, cols; + + if (state.token === '[') { + // matrix [...] + openParams(state); + getToken(state); + + if (state.token !== ']') { + // this is a non-empty matrix + var row = parseRow(state); + + if (state.token === ';') { + // 2 dimensional array + rows = 1; + params = [row]; // the rows of the matrix are separated by dot-comma's + + while (state.token === ';') { + // eslint-disable-line no-unmodified-loop-condition + getToken(state); + params[rows] = parseRow(state); + rows++; + } + + if (state.token !== ']') { + throw createSyntaxError(state, 'End of matrix ] expected'); + } + + closeParams(state); + getToken(state); // check if the number of columns matches in all rows + + cols = params[0].items.length; + + for (var r = 1; r < rows; r++) { + if (params[r].items.length !== cols) { + throw createError(state, 'Column dimensions mismatch ' + '(' + params[r].items.length + ' !== ' + cols + ')'); + } + } + + array = new ArrayNode(params); + } else { + // 1 dimensional vector + if (state.token !== ']') { + throw createSyntaxError(state, 'End of matrix ] expected'); + } + + closeParams(state); + getToken(state); + array = row; + } + } else { + // this is an empty matrix "[ ]" + closeParams(state); + getToken(state); + array = new ArrayNode([]); + } + + return parseAccessors(state, array); + } + + return parseObject(state); + } + /** + * Parse a single comma-separated row from a matrix, like 'a, b, c' + * @return {ArrayNode} node + */ + + + function parseRow(state) { + var params = [parseAssignment(state)]; + var len = 1; + + while (state.token === ',') { + // eslint-disable-line no-unmodified-loop-condition + getToken(state); // parse expression + + params[len] = parseAssignment(state); + len++; + } + + return new ArrayNode(params); + } + /** + * parse an object, enclosed in angle brackets{...}, for example {value: 2} + * @return {Node} node + * @private + */ + + + function parseObject(state) { + if (state.token === '{') { + openParams(state); + var key; + var properties = {}; + + do { + getToken(state); + + if (state.token !== '}') { + // parse key + if (state.token === '"') { + key = parseDoubleQuotesStringToken(state); + } else if (state.token === '\'') { + key = parseSingleQuotesStringToken(state); + } else if (state.tokenType === TOKENTYPE.SYMBOL || state.tokenType === TOKENTYPE.DELIMITER && state.token in NAMED_DELIMITERS) { + key = state.token; + getToken(state); + } else { + throw createSyntaxError(state, 'Symbol or string expected as object key'); + } // parse key/value separator + + + if (state.token !== ':') { + throw createSyntaxError(state, 'Colon : expected after object key'); + } + + getToken(state); // parse key + + properties[key] = parseAssignment(state); + } + } while (state.token === ','); // eslint-disable-line no-unmodified-loop-condition + + + if (state.token !== '}') { + throw createSyntaxError(state, 'Comma , or bracket } expected after object value'); + } + + closeParams(state); + getToken(state); + var node = new ObjectNode(properties); // parse index parameters + + node = parseAccessors(state, node); + return node; + } + + return parseNumber(state); + } + /** + * parse a number + * @return {Node} node + * @private + */ + + + function parseNumber(state) { + var numberStr; + + if (state.tokenType === TOKENTYPE.NUMBER) { + // this is a number + numberStr = state.token; + getToken(state); + return new ConstantNode(numeric(numberStr, config.number)); + } + + return parseParentheses(state); + } + /** + * parentheses + * @return {Node} node + * @private + */ + + + function parseParentheses(state) { + var node; // check if it is a parenthesized expression + + if (state.token === '(') { + // parentheses (...) + openParams(state); + getToken(state); + node = parseAssignment(state); // start again + + if (state.token !== ')') { + throw createSyntaxError(state, 'Parenthesis ) expected'); + } + + closeParams(state); + getToken(state); + node = new ParenthesisNode(node); + node = parseAccessors(state, node); + return node; + } + + return parseEnd(state); + } + /** + * Evaluated when the expression is not yet ended but expected to end + * @return {Node} res + * @private + */ + + + function parseEnd(state) { + if (state.token === '') { + // syntax error or unexpected end of expression + throw createSyntaxError(state, 'Unexpected end of expression'); + } else { + throw createSyntaxError(state, 'Value expected'); + } + } + /** + * Shortcut for getting the current row value (one based) + * Returns the line of the currently handled expression + * @private + */ + + /* TODO: implement keeping track on the row number + function row () { + return null + } + */ + + /** + * Shortcut for getting the current col value (one based) + * Returns the column (position) where the last state.token starts + * @private + */ + + + function col(state) { + return state.index - state.token.length + 1; + } + /** + * Create an error + * @param {Object} state + * @param {string} message + * @return {SyntaxError} instantiated error + * @private + */ + + + function createSyntaxError(state, message) { + var c = col(state); + var error = new SyntaxError(message + ' (char ' + c + ')'); + error["char"] = c; + return error; + } + /** + * Create an error + * @param {Object} state + * @param {string} message + * @return {Error} instantiated error + * @private + */ + + + function createError(state, message) { + var c = col(state); + var error = new SyntaxError(message + ' (char ' + c + ')'); + error["char"] = c; + return error; + } + + return parse; +}); +// CONCATENATED MODULE: ./src/expression/function/compile.js + + +var compile_name = 'compile'; +var compile_dependencies = ['typed', 'parse']; +var createCompile = /* #__PURE__ */Object(factory["a" /* factory */])(compile_name, compile_dependencies, function (_ref) { + var typed = _ref.typed, + parse = _ref.parse; + + /** + * Parse and compile an expression. + * Returns a an object with a function `evaluate([scope])` to evaluate the + * compiled expression. + * + * Syntax: + * + * math.compile(expr) // returns one node + * math.compile([expr1, expr2, expr3, ...]) // returns an array with nodes + * + * Examples: + * + * const code1 = math.compile('sqrt(3^2 + 4^2)') + * code1.evaluate() // 5 + * + * let scope = {a: 3, b: 4} + * const code2 = math.compile('a * b') // 12 + * code2.evaluate(scope) // 12 + * scope.a = 5 + * code2.evaluate(scope) // 20 + * + * const nodes = math.compile(['a = 3', 'b = 4', 'a * b']) + * nodes[2].evaluate() // 12 + * + * See also: + * + * parse, evaluate + * + * @param {string | string[] | Array | Matrix} expr + * The expression to be compiled + * @return {{evaluate: Function} | Array.<{evaluate: Function}>} code + * An object with the compiled expression + * @throws {Error} + */ + return typed(compile_name, { + string: function string(expr) { + return parse(expr).compile(); + }, + 'Array | Matrix': function ArrayMatrix(expr) { + return deepMap(expr, function (entry) { + return parse(entry).compile(); + }); + } + }); +}); +// CONCATENATED MODULE: ./src/expression/function/evaluate.js + + +var evaluate_name = 'evaluate'; +var evaluate_dependencies = ['typed', 'parse']; +var createEvaluate = /* #__PURE__ */Object(factory["a" /* factory */])(evaluate_name, evaluate_dependencies, function (_ref) { + var typed = _ref.typed, + parse = _ref.parse; + + /** + * Evaluate an expression. + * + * Note the evaluating arbitrary expressions may involve security risks, + * see [https://mathjs.org/docs/expressions/security.html](https://mathjs.org/docs/expressions/security.html) for more information. + * + * Syntax: + * + * math.evaluate(expr) + * math.evaluate(expr, scope) + * math.evaluate([expr1, expr2, expr3, ...]) + * math.evaluate([expr1, expr2, expr3, ...], scope) + * + * Example: + * + * math.evaluate('(2+3)/4') // 1.25 + * math.evaluate('sqrt(3^2 + 4^2)') // 5 + * math.evaluate('sqrt(-4)') // 2i + * math.evaluate(['a=3', 'b=4', 'a*b']) // [3, 4, 12] + * + * let scope = {a:3, b:4} + * math.evaluate('a * b', scope) // 12 + * + * See also: + * + * parse, compile + * + * @param {string | string[] | Matrix} expr The expression to be evaluated + * @param {Object} [scope] Scope to read/write variables + * @return {*} The result of the expression + * @throws {Error} + */ + return typed(evaluate_name, { + string: function string(expr) { + var scope = {}; + return parse(expr).compile().evaluate(scope); + }, + 'string, Object': function stringObject(expr, scope) { + return parse(expr).compile().evaluate(scope); + }, + 'Array | Matrix': function ArrayMatrix(expr) { + var scope = {}; + return deepMap(expr, function (entry) { + return parse(entry).compile().evaluate(scope); + }); + }, + 'Array | Matrix, Object': function ArrayMatrixObject(expr, scope) { + return deepMap(expr, function (entry) { + return parse(entry).compile().evaluate(scope); + }); + } + }); +}); +// CONCATENATED MODULE: ./src/expression/function/eval.js +// For backward compatibility, deprecated since version 6.0.0. Date: 2018-12-05 + + +var createDeprecatedEval = /* #__PURE__ */Object(factory["a" /* factory */])('eval', ['evaluate'], function (_ref) { + var evaluate = _ref.evaluate; + return function () { + Object(utils_log["a" /* warnOnce */])('Function "eval" has been renamed to "evaluate" in v6.0.0, please use the new function instead.'); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return evaluate.apply(evaluate, args); + }; +}); +// CONCATENATED MODULE: ./src/expression/Parser.js + + + + +var Parser_name = 'Parser'; +var Parser_dependencies = ['parse']; +var createParserClass = /* #__PURE__ */Object(factory["a" /* factory */])(Parser_name, Parser_dependencies, function (_ref) { + var parse = _ref.parse; + + /** + * @constructor Parser + * Parser contains methods to evaluate or parse expressions, and has a number + * of convenience methods to get, set, and remove variables from memory. Parser + * keeps a scope containing variables in memory, which is used for all + * evaluations. + * + * Methods: + * const result = parser.evaluate(expr) // evaluate an expression + * const value = parser.get(name) // retrieve a variable from the parser + * const values = parser.getAll() // retrieve all defined variables + * parser.set(name, value) // set a variable in the parser + * parser.remove(name) // clear a variable from the + * // parsers scope + * parser.clear() // clear the parsers scope + * + * Example usage: + * const parser = new Parser() + * // Note: there is a convenience method which can be used instead: + * // const parser = new math.parser() + * + * // evaluate expressions + * parser.evaluate('sqrt(3^2 + 4^2)') // 5 + * parser.evaluate('sqrt(-4)') // 2i + * parser.evaluate('2 inch in cm') // 5.08 cm + * parser.evaluate('cos(45 deg)') // 0.7071067811865476 + * + * // define variables and functions + * parser.evaluate('x = 7 / 2') // 3.5 + * parser.evaluate('x + 3') // 6.5 + * parser.evaluate('function f(x, y) = x^y') // f(x, y) + * parser.evaluate('f(2, 3)') // 8 + * + * // get and set variables and functions + * const x = parser.get('x') // 7 + * const f = parser.get('f') // function + * const g = f(3, 2) // 9 + * parser.set('h', 500) + * const i = parser.evaluate('h / 2') // 250 + * parser.set('hello', function (name) { + * return 'hello, ' + name + '!' + * }) + * parser.evaluate('hello("user")') // "hello, user!" + * + * // clear defined functions and variables + * parser.clear() + * + */ + function Parser() { + if (!(this instanceof Parser)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + this.scope = {}; + } + /** + * Attach type information + */ + + + Parser.prototype.type = 'Parser'; + Parser.prototype.isParser = true; + /** + * Parse an expression and return the parsed function node. + * The node tree can be compiled via `code = node.compile(math)`, + * and the compiled code can be executed as `code.evaluate([scope])` + * @param {string} expr + * @return {Node} node + * @throws {Error} + */ + + Parser.prototype.parse = function (expr) { + throw new Error('Parser.parse is deprecated. Use math.parse instead.'); + }; + /** + * Parse and compile an expression, return the compiled javascript code. + * The node can be evaluated via code.evaluate([scope]) + * @param {string} expr + * @return {{evaluate: function}} code + * @throws {Error} + */ + + + Parser.prototype.compile = function (expr) { + throw new Error('Parser.compile is deprecated. Use math.compile instead.'); + }; + /** + * Parse and evaluate the given expression + * @param {string} expr A string containing an expression, for example "2+3" + * @return {*} result The result, or undefined when the expression was empty + * @throws {Error} + */ + + + Parser.prototype.evaluate = function (expr) { + // TODO: validate arguments + return parse(expr).compile().evaluate(this.scope); + }; + /** + * Parse and evaluate the given expression + * @param {string} expr A string containing an expression, for example "2+3" + * @return {*} result The result, or undefined when the expression was empty + * @throws {Error} + */ + // TODO: Deprecated since v6.0.0. Clean up some day + + + Parser.prototype.eval = function (expr) { + Object(utils_log["a" /* warnOnce */])('Method Parser.eval is renamed to Parser.evaluate. Please use the new method name.'); + return this.evaluate(expr); + }; + /** + * Get a variable (a function or variable) by name from the parsers scope. + * Returns undefined when not found + * @param {string} name + * @return {* | undefined} value + */ + + + Parser.prototype.get = function (name) { + // TODO: validate arguments + return name in this.scope ? getSafeProperty(this.scope, name) : undefined; + }; + /** + * Get a map with all defined variables + * @return {Object} values + */ + + + Parser.prototype.getAll = function () { + return Object(utils_object["e" /* extend */])({}, this.scope); + }; + /** + * Set a symbol (a function or variable) by name from the parsers scope. + * @param {string} name + * @param {* | undefined} value + */ + + + Parser.prototype.set = function (name, value) { + // TODO: validate arguments + return setSafeProperty(this.scope, name, value); + }; + /** + * Remove a variable from the parsers scope + * @param {string} name + */ + + + Parser.prototype.remove = function (name) { + // TODO: validate arguments + delete this.scope[name]; + }; + /** + * Clear the scope with variables and functions + */ + + + Parser.prototype.clear = function () { + for (var _name in this.scope) { + if (Object(utils_object["f" /* hasOwnProperty */])(this.scope, _name)) { + delete this.scope[_name]; + } + } + }; + + return Parser; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/expression/function/parser.js + +var parser_name = 'parser'; +var parser_dependencies = ['typed', 'Parser']; +var createParser = /* #__PURE__ */Object(factory["a" /* factory */])(parser_name, parser_dependencies, function (_ref) { + var typed = _ref.typed, + Parser = _ref.Parser; + + /** + * Create a parser. The function creates a new `math.Parser` object. + * + * Syntax: + * + * math.parser() + * + * Examples: + * + * const parser = new math.parser() + * + * // evaluate expressions + * const a = parser.evaluate('sqrt(3^2 + 4^2)') // 5 + * const b = parser.evaluate('sqrt(-4)') // 2i + * const c = parser.evaluate('2 inch in cm') // 5.08 cm + * const d = parser.evaluate('cos(45 deg)') // 0.7071067811865476 + * + * // define variables and functions + * parser.evaluate('x = 7 / 2') // 3.5 + * parser.evaluate('x + 3') // 6.5 + * parser.evaluate('function f(x, y) = x^y') // f(x, y) + * parser.evaluate('f(2, 3)') // 8 + * + * // get and set variables and functions + * const x = parser.get('x') // 7 + * const f = parser.get('f') // function + * const g = f(3, 2) // 9 + * parser.set('h', 500) + * const i = parser.evaluate('h / 2') // 250 + * parser.set('hello', function (name) { + * return 'hello, ' + name + '!' + * }) + * parser.evaluate('hello("user")') // "hello, user!" + * + * // clear defined functions and variables + * parser.clear() + * + * See also: + * + * evaluate, compile, parse + * + * @return {Parser} Parser + */ + return typed(parser_name, { + '': function _() { + return new Parser(); + } + }); +}); +// CONCATENATED MODULE: ./src/function/algebra/decomposition/lup.js + + +var lup_name = 'lup'; +var lup_dependencies = ['typed', 'matrix', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtract', 'larger', 'equalScalar', 'unaryMinus', 'DenseMatrix', 'SparseMatrix', 'Spa']; +var createLup = /* #__PURE__ */Object(factory["a" /* factory */])(lup_name, lup_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + abs = _ref.abs, + addScalar = _ref.addScalar, + divideScalar = _ref.divideScalar, + multiplyScalar = _ref.multiplyScalar, + subtract = _ref.subtract, + larger = _ref.larger, + equalScalar = _ref.equalScalar, + unaryMinus = _ref.unaryMinus, + DenseMatrix = _ref.DenseMatrix, + SparseMatrix = _ref.SparseMatrix, + Spa = _ref.Spa; + + /** + * Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a + * row permutation vector `p` where `A[p,:] = L * U` + * + * Syntax: + * + * math.lup(A) + * + * Example: + * + * const m = [[2, 1], [1, 4]] + * const r = math.lup(m) + * // r = { + * // L: [[1, 0], [0.5, 1]], + * // U: [[2, 1], [0, 3.5]], + * // P: [0, 1] + * // } + * + * See also: + * + * slu, lsolve, lusolve, usolve + * + * @param {Matrix | Array} A A two dimensional matrix or array for which to get the LUP decomposition. + * + * @return {{L: Array | Matrix, U: Array | Matrix, P: Array.}} The lower triangular matrix, the upper triangular matrix and the permutation matrix. + */ + return typed(lup_name, { + DenseMatrix: function DenseMatrix(m) { + return _denseLUP(m); + }, + SparseMatrix: function SparseMatrix(m) { + return _sparseLUP(m); + }, + Array: function Array(a) { + // create dense matrix from array + var m = matrix(a); // lup, use matrix implementation + + var r = _denseLUP(m); // result + + + return { + L: r.L.valueOf(), + U: r.U.valueOf(), + p: r.p + }; + } + }); + + function _denseLUP(m) { + // rows & columns + var rows = m._size[0]; + var columns = m._size[1]; // minimum rows and columns + + var n = Math.min(rows, columns); // matrix array, clone original data + + var data = Object(utils_object["a" /* clone */])(m._data); // l matrix arrays + + var ldata = []; + var lsize = [rows, n]; // u matrix arrays + + var udata = []; + var usize = [n, columns]; // vars + + var i, j, k; // permutation vector + + var p = []; + + for (i = 0; i < rows; i++) { + p[i] = i; + } // loop columns + + + for (j = 0; j < columns; j++) { + // skip first column in upper triangular matrix + if (j > 0) { + // loop rows + for (i = 0; i < rows; i++) { + // min i,j + var min = Math.min(i, j); // v[i, j] + + var s = 0; // loop up to min + + for (k = 0; k < min; k++) { + // s = l[i, k] - data[k, j] + s = addScalar(s, multiplyScalar(data[i][k], data[k][j])); + } + + data[i][j] = subtract(data[i][j], s); + } + } // row with larger value in cvector, row >= j + + + var pi = j; + var pabsv = 0; + var vjj = 0; // loop rows + + for (i = j; i < rows; i++) { + // data @ i, j + var v = data[i][j]; // absolute value + + var absv = abs(v); // value is greater than pivote value + + if (larger(absv, pabsv)) { + // store row + pi = i; // update max value + + pabsv = absv; // value @ [j, j] + + vjj = v; + } + } // swap rows (j <-> pi) + + + if (j !== pi) { + // swap values j <-> pi in p + p[j] = [p[pi], p[pi] = p[j]][0]; // swap j <-> pi in data + + DenseMatrix._swapRows(j, pi, data); + } // check column is in lower triangular matrix + + + if (j < rows) { + // loop rows (lower triangular matrix) + for (i = j + 1; i < rows; i++) { + // value @ i, j + var vij = data[i][j]; + + if (!equalScalar(vij, 0)) { + // update data + data[i][j] = divideScalar(data[i][j], vjj); + } + } + } + } // loop columns + + + for (j = 0; j < columns; j++) { + // loop rows + for (i = 0; i < rows; i++) { + // initialize row in arrays + if (j === 0) { + // check row exists in upper triangular matrix + if (i < columns) { + // U + udata[i] = []; + } // L + + + ldata[i] = []; + } // check we are in the upper triangular matrix + + + if (i < j) { + // check row exists in upper triangular matrix + if (i < columns) { + // U + udata[i][j] = data[i][j]; + } // check column exists in lower triangular matrix + + + if (j < rows) { + // L + ldata[i][j] = 0; + } + + continue; + } // diagonal value + + + if (i === j) { + // check row exists in upper triangular matrix + if (i < columns) { + // U + udata[i][j] = data[i][j]; + } // check column exists in lower triangular matrix + + + if (j < rows) { + // L + ldata[i][j] = 1; + } + + continue; + } // check row exists in upper triangular matrix + + + if (i < columns) { + // U + udata[i][j] = 0; + } // check column exists in lower triangular matrix + + + if (j < rows) { + // L + ldata[i][j] = data[i][j]; + } + } + } // l matrix + + + var l = new DenseMatrix({ + data: ldata, + size: lsize + }); // u matrix + + var u = new DenseMatrix({ + data: udata, + size: usize + }); // p vector + + var pv = []; + + for (i = 0, n = p.length; i < n; i++) { + pv[p[i]] = i; + } // return matrices + + + return { + L: l, + U: u, + p: pv, + toString: function toString() { + return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p; + } + }; + } + + function _sparseLUP(m) { + // rows & columns + var rows = m._size[0]; + var columns = m._size[1]; // minimum rows and columns + + var n = Math.min(rows, columns); // matrix arrays (will not be modified, thanks to permutation vector) + + var values = m._values; + var index = m._index; + var ptr = m._ptr; // l matrix arrays + + var lvalues = []; + var lindex = []; + var lptr = []; + var lsize = [rows, n]; // u matrix arrays + + var uvalues = []; + var uindex = []; + var uptr = []; + var usize = [n, columns]; // vars + + var i, j, k; // permutation vectors, (current index -> original index) and (original index -> current index) + + var pvCo = []; + var pvOc = []; + + for (i = 0; i < rows; i++) { + pvCo[i] = i; + pvOc[i] = i; + } // swap indices in permutation vectors (condition x < y)! + + + var swapIndeces = function swapIndeces(x, y) { + // find pv indeces getting data from x and y + var kx = pvOc[x]; + var ky = pvOc[y]; // update permutation vector current -> original + + pvCo[kx] = y; + pvCo[ky] = x; // update permutation vector original -> current + + pvOc[x] = ky; + pvOc[y] = kx; + }; // loop columns + + + var _loop = function _loop() { + // sparse accumulator + var spa = new Spa(); // check lower triangular matrix has a value @ column j + + if (j < rows) { + // update ptr + lptr.push(lvalues.length); // first value in j column for lower triangular matrix + + lvalues.push(1); + lindex.push(j); + } // update ptr + + + uptr.push(uvalues.length); // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] + + var k0 = ptr[j]; + var k1 = ptr[j + 1]; // copy column j into sparse accumulator + + for (k = k0; k < k1; k++) { + // row + i = index[k]; // copy column values into sparse accumulator (use permutation vector) + + spa.set(pvCo[i], values[k]); + } // skip first column in upper triangular matrix + + + if (j > 0) { + // loop rows in column j (above diagonal) + spa.forEach(0, j - 1, function (k, vkj) { + // loop rows in column k (L) + SparseMatrix._forEachRow(k, lvalues, lindex, lptr, function (i, vik) { + // check row is below k + if (i > k) { + // update spa value + spa.accumulate(i, unaryMinus(multiplyScalar(vik, vkj))); + } + }); + }); + } // row with larger value in spa, row >= j + + + var pi = j; + var vjj = spa.get(j); + var pabsv = abs(vjj); // loop values in spa (order by row, below diagonal) + + spa.forEach(j + 1, rows - 1, function (x, v) { + // absolute value + var absv = abs(v); // value is greater than pivote value + + if (larger(absv, pabsv)) { + // store row + pi = x; // update max value + + pabsv = absv; // value @ [j, j] + + vjj = v; + } + }); // swap rows (j <-> pi) + + if (j !== pi) { + // swap values j <-> pi in L + SparseMatrix._swapRows(j, pi, lsize[1], lvalues, lindex, lptr); // swap values j <-> pi in U + + + SparseMatrix._swapRows(j, pi, usize[1], uvalues, uindex, uptr); // swap values in spa + + + spa.swap(j, pi); // update permutation vector (swap values @ j, pi) + + swapIndeces(j, pi); + } // loop values in spa (order by row) + + + spa.forEach(0, rows - 1, function (x, v) { + // check we are above diagonal + if (x <= j) { + // update upper triangular matrix + uvalues.push(v); + uindex.push(x); + } else { + // update value + v = divideScalar(v, vjj); // check value is non zero + + if (!equalScalar(v, 0)) { + // update lower triangular matrix + lvalues.push(v); + lindex.push(x); + } + } + }); + }; + + for (j = 0; j < columns; j++) { + _loop(); + } // update ptrs + + + uptr.push(uvalues.length); + lptr.push(lvalues.length); // return matrices + + return { + L: new SparseMatrix({ + values: lvalues, + index: lindex, + ptr: lptr, + size: lsize + }), + U: new SparseMatrix({ + values: uvalues, + index: uindex, + ptr: uptr, + size: usize + }), + p: pvCo, + toString: function toString() { + return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p; + } + }; + } +}); +// CONCATENATED MODULE: ./src/function/algebra/decomposition/qr.js +function qr_extends() { qr_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return qr_extends.apply(this, arguments); } + + +var qr_name = 'qr'; +var qr_dependencies = ['typed', 'matrix', 'zeros', 'identity', 'isZero', 'equal', 'sign', 'sqrt', 'conj', 'unaryMinus', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtract', 'complex']; +var createQr = /* #__PURE__ */Object(factory["a" /* factory */])(qr_name, qr_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + zeros = _ref.zeros, + identity = _ref.identity, + isZero = _ref.isZero, + equal = _ref.equal, + sign = _ref.sign, + sqrt = _ref.sqrt, + conj = _ref.conj, + unaryMinus = _ref.unaryMinus, + addScalar = _ref.addScalar, + divideScalar = _ref.divideScalar, + multiplyScalar = _ref.multiplyScalar, + subtract = _ref.subtract, + complex = _ref.complex; + + /** + * Calculate the Matrix QR decomposition. Matrix `A` is decomposed in + * two matrices (`Q`, `R`) where `Q` is an + * orthogonal matrix and `R` is an upper triangular matrix. + * + * Syntax: + * + * math.qr(A) + * + * Example: + * + * const m = [ + * [1, -1, 4], + * [1, 4, -2], + * [1, 4, 2], + * [1, -1, 0] + * ] + * const result = math.qr(m) + * // r = { + * // Q: [ + * // [0.5, -0.5, 0.5], + * // [0.5, 0.5, -0.5], + * // [0.5, 0.5, 0.5], + * // [0.5, -0.5, -0.5], + * // ], + * // R: [ + * // [2, 3, 2], + * // [0, 5, -2], + * // [0, 0, 4], + * // [0, 0, 0] + * // ] + * // } + * + * See also: + * + * lup, lusolve + * + * @param {Matrix | Array} A A two dimensional matrix or array + * for which to get the QR decomposition. + * + * @return {{Q: Array | Matrix, R: Array | Matrix}} Q: the orthogonal + * matrix and R: the upper triangular matrix + */ + return qr_extends(typed(qr_name, { + DenseMatrix: function DenseMatrix(m) { + return _denseQR(m); + }, + SparseMatrix: function SparseMatrix(m) { + return _sparseQR(m); + }, + Array: function Array(a) { + // create dense matrix from array + var m = matrix(a); // lup, use matrix implementation + + var r = _denseQR(m); // result + + + return { + Q: r.Q.valueOf(), + R: r.R.valueOf() + }; + } + }), { + _denseQRimpl: _denseQRimpl + }); + + function _denseQRimpl(m) { + // rows & columns (m x n) + var rows = m._size[0]; // m + + var cols = m._size[1]; // n + + var Q = identity([rows], 'dense'); + var Qdata = Q._data; + var R = m.clone(); + var Rdata = R._data; // vars + + var i, j, k; + var w = zeros([rows], ''); + + for (k = 0; k < Math.min(cols, rows); ++k) { + /* + * **k-th Household matrix** + * + * The matrix I - 2*v*transpose(v) + * x = first column of A + * x1 = first element of x + * alpha = x1 / |x1| * |x| + * e1 = tranpose([1, 0, 0, ...]) + * u = x - alpha * e1 + * v = u / |u| + * + * Household matrix = I - 2 * v * tranpose(v) + * + * * Initially Q = I and R = A. + * * Household matrix is a reflection in a plane normal to v which + * will zero out all but the top right element in R. + * * Appplying reflection to both Q and R will not change product. + * * Repeat this process on the (1,1) minor to get R as an upper + * triangular matrix. + * * Reflections leave the magnitude of the columns of Q unchanged + * so Q remains othoganal. + * + */ + var pivot = Rdata[k][k]; + var sgn = unaryMinus(equal(pivot, 0) ? 1 : sign(pivot)); + var conjSgn = conj(sgn); + var alphaSquared = 0; + + for (i = k; i < rows; i++) { + alphaSquared = addScalar(alphaSquared, multiplyScalar(Rdata[i][k], conj(Rdata[i][k]))); + } + + var alpha = multiplyScalar(sgn, sqrt(alphaSquared)); + + if (!isZero(alpha)) { + // first element in vector u + var u1 = subtract(pivot, alpha); // w = v * u1 / |u| (only elements k to (rows-1) are used) + + w[k] = 1; + + for (i = k + 1; i < rows; i++) { + w[i] = divideScalar(Rdata[i][k], u1); + } // tau = - conj(u1 / alpha) + + + var tau = unaryMinus(conj(divideScalar(u1, alpha))); + var s = void 0; + /* + * tau and w have been choosen so that + * + * 2 * v * tranpose(v) = tau * w * tranpose(w) + */ + + /* + * -- calculate R = R - tau * w * tranpose(w) * R -- + * Only do calculation with rows k to (rows-1) + * Additionally columns 0 to (k-1) will not be changed by this + * multiplication so do not bother recalculating them + */ + + for (j = k; j < cols; j++) { + s = 0.0; // calculate jth element of [tranpose(w) * R] + + for (i = k; i < rows; i++) { + s = addScalar(s, multiplyScalar(conj(w[i]), Rdata[i][j])); + } // calculate the jth element of [tau * transpose(w) * R] + + + s = multiplyScalar(s, tau); + + for (i = k; i < rows; i++) { + Rdata[i][j] = multiplyScalar(subtract(Rdata[i][j], multiplyScalar(w[i], s)), conjSgn); + } + } + /* + * -- calculate Q = Q - tau * Q * w * transpose(w) -- + * Q is a square matrix (rows x rows) + * Only do calculation with columns k to (rows-1) + * Additionally rows 0 to (k-1) will not be changed by this + * multiplication so do not bother recalculating them + */ + + + for (i = 0; i < rows; i++) { + s = 0.0; // calculate ith element of [Q * w] + + for (j = k; j < rows; j++) { + s = addScalar(s, multiplyScalar(Qdata[i][j], w[j])); + } // calculate the ith element of [tau * Q * w] + + + s = multiplyScalar(s, tau); + + for (j = k; j < rows; ++j) { + Qdata[i][j] = divideScalar(subtract(Qdata[i][j], multiplyScalar(s, conj(w[j]))), conjSgn); + } + } + } + } // return matrices + + + return { + Q: Q, + R: R, + toString: function toString() { + return 'Q: ' + this.Q.toString() + '\nR: ' + this.R.toString(); + } + }; + } + + function _denseQR(m) { + var ret = _denseQRimpl(m); + + var Rdata = ret.R._data; + + if (m._data.length > 0) { + var zero = Rdata[0][0].type === 'Complex' ? complex(0) : 0; + + for (var i = 0; i < Rdata.length; ++i) { + for (var j = 0; j < i && j < (Rdata[0] || []).length; ++j) { + Rdata[i][j] = zero; + } + } + } + + return ret; + } + + function _sparseQR(m) { + throw new Error('qr not implemented for sparse matrices yet'); + } +}); +// CONCATENATED MODULE: ./src/function/algebra/sparse/csPermute.js +/** + * Permutes a sparse matrix C = P * A * Q + * + * @param {SparseMatrix} a The Matrix A + * @param {Array} pinv The row permutation vector + * @param {Array} q The column permutation vector + * @param {boolean} values Create a pattern matrix (false), values and pattern otherwise + * + * @return {Matrix} C = P * A * Q, null on error + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csPermute(a, pinv, q, values) { + // a arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; + var adt = a._datatype; // rows & columns + + var m = asize[0]; + var n = asize[1]; // c arrays + + var cvalues = values && a._values ? [] : null; + var cindex = []; // (aptr[n]) + + var cptr = []; // (n + 1) + // initialize vars + + var nz = 0; // loop columns + + for (var k = 0; k < n; k++) { + // column k of C is column q[k] of A + cptr[k] = nz; // apply column permutation + + var j = q ? q[k] : k; // loop values in column j of A + + for (var t0 = aptr[j], t1 = aptr[j + 1], t = t0; t < t1; t++) { + // row i of A is row pinv[i] of C + var r = pinv ? pinv[aindex[t]] : aindex[t]; // index + + cindex[nz] = r; // check we need to populate values + + if (cvalues) { + cvalues[nz] = avalues[t]; + } // increment number of nonzero elements + + + nz++; + } + } // finalize the last column of C + + + cptr[n] = nz; // return C matrix + + return a.createSparseMatrix({ + values: cvalues, + index: cindex, + ptr: cptr, + size: [m, n], + datatype: adt + }); +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csTdfs.js +/** + * Depth-first search and postorder of a tree rooted at node j + * + * @param {Number} j The tree node + * @param {Number} k + * @param {Array} w The workspace array + * @param {Number} head The index offset within the workspace for the head array + * @param {Number} next The index offset within the workspace for the next array + * @param {Array} post The post ordering array + * @param {Number} stack The index offset within the workspace for the stack array + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csTdfs(j, k, w, head, next, post, stack) { + // variables + var top = 0; // place j on the stack + + w[stack] = j; // while (stack is not empty) + + while (top >= 0) { + // p = top of stack + var p = w[stack + top]; // i = youngest child of p + + var i = w[head + p]; + + if (i === -1) { + // p has no unordered children left + top--; // node p is the kth postordered node + + post[k++] = p; + } else { + // remove i from children of p + w[head + p] = w[next + i]; // increment top + + ++top; // start dfs on child node i + + w[stack + top] = i; + } + } + + return k; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csPost.js + +/** + * Post order a tree of forest + * + * @param {Array} parent The tree or forest + * @param {Number} n Number of columns + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + +function csPost(parent, n) { + // check inputs + if (!parent) { + return null; + } // vars + + + var k = 0; + var j; // allocate result + + var post = []; // (n) + // workspace, head: first n entries, next: next n entries, stack: last n entries + + var w = []; // (3 * n) + + var head = 0; + var next = n; + var stack = 2 * n; // initialize workspace + + for (j = 0; j < n; j++) { + // empty linked lists + w[head + j] = -1; + } // traverse nodes in reverse order + + + for (j = n - 1; j >= 0; j--) { + // check j is a root + if (parent[j] === -1) { + continue; + } // add j to list of its parent + + + w[next + j] = w[head + parent[j]]; + w[head + parent[j]] = j; + } // loop nodes + + + for (j = 0; j < n; j++) { + // skip j if it is not a root + if (parent[j] !== -1) { + continue; + } // depth-first search + + + k = csTdfs(j, k, w, head, next, post, stack); + } + + return post; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csEtree.js +/** + * Computes the elimination tree of Matrix A (using triu(A)) or the + * elimination tree of A'A without forming A'A. + * + * @param {Matrix} a The A Matrix + * @param {boolean} ata A value of true the function computes the etree of A'A + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csEtree(a, ata) { + // check inputs + if (!a) { + return null; + } // a arrays + + + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; // rows & columns + + var m = asize[0]; + var n = asize[1]; // allocate result + + var parent = []; // (n) + // allocate workspace + + var w = []; // (n + (ata ? m : 0)) + + var ancestor = 0; // first n entries in w + + var prev = n; // last m entries (ata = true) + + var i, inext; // check we are calculating A'A + + if (ata) { + // initialize workspace + for (i = 0; i < m; i++) { + w[prev + i] = -1; + } + } // loop columns + + + for (var k = 0; k < n; k++) { + // node k has no parent yet + parent[k] = -1; // nor does k have an ancestor + + w[ancestor + k] = -1; // values in column k + + for (var p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) { + // row + var r = aindex[p]; // node + + i = ata ? w[prev + r] : r; // traverse from i to k + + for (; i !== -1 && i < k; i = inext) { + // inext = ancestor of i + inext = w[ancestor + i]; // path compression + + w[ancestor + i] = k; // check no anc., parent is k + + if (inext === -1) { + parent[i] = k; + } + } + + if (ata) { + w[prev + r] = k; + } + } + } + + return parent; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csFkeep.js +/** + * Keeps entries in the matrix when the callback function returns true, removes the entry otherwise + * + * @param {Matrix} a The sparse matrix + * @param {function} callback The callback function, function will be invoked with the following args: + * - The entry row + * - The entry column + * - The entry value + * - The state parameter + * @param {any} other The state + * + * @return The number of nonzero elements in the matrix + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csFkeep(a, callback, other) { + // a arrays + var avalues = a._values; + var aindex = a._index; + var aptr = a._ptr; + var asize = a._size; // columns + + var n = asize[1]; // nonzero items + + var nz = 0; // loop columns + + for (var j = 0; j < n; j++) { + // get current location of col j + var p = aptr[j]; // record new location of col j + + aptr[j] = nz; + + for (; p < aptr[j + 1]; p++) { + // check we need to keep this item + if (callback(aindex[p], j, avalues ? avalues[p] : 1, other)) { + // keep A(i,j) + aindex[nz] = aindex[p]; // check we need to process values (pattern only) + + if (avalues) { + avalues[nz] = avalues[p]; + } // increment nonzero items + + + nz++; + } + } + } // finalize A + + + aptr[n] = nz; // trim arrays + + aindex.splice(nz, aindex.length - nz); // check we need to process values (pattern only) + + if (avalues) { + avalues.splice(nz, avalues.length - nz); + } // return number of nonzero items + + + return nz; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csFlip.js +/** + * This function "flips" its input about the integer -1. + * + * @param {Number} i The value to flip + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csFlip(i) { + // flip the value + return -i - 2; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csAmd.js + + + + +var csAmd_name = 'csAmd'; +var csAmd_dependencies = ['add', 'multiply', 'transpose']; +var createCsAmd = /* #__PURE__ */Object(factory["a" /* factory */])(csAmd_name, csAmd_dependencies, function (_ref) { + var add = _ref.add, + multiply = _ref.multiply, + transpose = _ref.transpose; + + /** + * Approximate minimum degree ordering. The minimum degree algorithm is a widely used + * heuristic for finding a permutation P so that P*A*P' has fewer nonzeros in its factorization + * than A. It is a gready method that selects the sparsest pivot row and column during the course + * of a right looking sparse Cholesky factorization. + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + * + * @param {Number} order 0: Natural, 1: Cholesky, 2: LU, 3: QR + * @param {Matrix} m Sparse Matrix + */ + return function csAmd(order, a) { + // check input parameters + if (!a || order <= 0 || order > 3) { + return null; + } // a matrix arrays + + + var asize = a._size; // rows and columns + + var m = asize[0]; + var n = asize[1]; // initialize vars + + var lemax = 0; // dense threshold + + var dense = Math.max(16, 10 * Math.sqrt(n)); + dense = Math.min(n - 2, dense); // create target matrix C + + var cm = _createTargetMatrix(order, a, m, n, dense); // drop diagonal entries + + + csFkeep(cm, _diag, null); // C matrix arrays + + var cindex = cm._index; + var cptr = cm._ptr; // number of nonzero elements in C + + var cnz = cptr[n]; // allocate result (n+1) + + var P = []; // create workspace (8 * (n + 1)) + + var W = []; + var len = 0; // first n + 1 entries + + var nv = n + 1; // next n + 1 entries + + var next = 2 * (n + 1); // next n + 1 entries + + var head = 3 * (n + 1); // next n + 1 entries + + var elen = 4 * (n + 1); // next n + 1 entries + + var degree = 5 * (n + 1); // next n + 1 entries + + var w = 6 * (n + 1); // next n + 1 entries + + var hhead = 7 * (n + 1); // last n + 1 entries + // use P as workspace for last + + var last = P; // initialize quotient graph + + var mark = _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree); // initialize degree lists + + + var nel = _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next); // minimum degree node + + + var mindeg = 0; // vars + + var i, j, k, k1, k2, e, pj, ln, nvi, pk, eln, p1, p2, pn, h, d; // while (selecting pivots) do + + while (nel < n) { + // select node of minimum approximate degree. amd() is now ready to start eliminating the graph. It first + // finds a node k of minimum degree and removes it from its degree list. The variable nel keeps track of thow + // many nodes have been eliminated. + for (k = -1; mindeg < n && (k = W[head + mindeg]) === -1; mindeg++) { + ; + } + + if (W[next + k] !== -1) { + last[W[next + k]] = -1; + } // remove k from degree list + + + W[head + mindeg] = W[next + k]; // elenk = |Ek| + + var elenk = W[elen + k]; // # of nodes k represents + + var nvk = W[nv + k]; // W[nv + k] nodes of A eliminated + + nel += nvk; // Construct a new element. The new element Lk is constructed in place if |Ek| = 0. nv[i] is + // negated for all nodes i in Lk to flag them as members of this set. Each node i is removed from the + // degree lists. All elements e in Ek are absorved into element k. + + var dk = 0; // flag k as in Lk + + W[nv + k] = -nvk; + var p = cptr[k]; // do in place if W[elen + k] === 0 + + var pk1 = elenk === 0 ? p : cnz; + var pk2 = pk1; + + for (k1 = 1; k1 <= elenk + 1; k1++) { + if (k1 > elenk) { + // search the nodes in k + e = k; // list of nodes starts at cindex[pj] + + pj = p; // length of list of nodes in k + + ln = W[len + k] - elenk; + } else { + // search the nodes in e + e = cindex[p++]; + pj = cptr[e]; // length of list of nodes in e + + ln = W[len + e]; + } + + for (k2 = 1; k2 <= ln; k2++) { + i = cindex[pj++]; // check node i dead, or seen + + if ((nvi = W[nv + i]) <= 0) { + continue; + } // W[degree + Lk] += size of node i + + + dk += nvi; // negate W[nv + i] to denote i in Lk + + W[nv + i] = -nvi; // place i in Lk + + cindex[pk2++] = i; + + if (W[next + i] !== -1) { + last[W[next + i]] = last[i]; + } // check we need to remove i from degree list + + + if (last[i] !== -1) { + W[next + last[i]] = W[next + i]; + } else { + W[head + W[degree + i]] = W[next + i]; + } + } + + if (e !== k) { + // absorb e into k + cptr[e] = csFlip(k); // e is now a dead element + + W[w + e] = 0; + } + } // cindex[cnz...nzmax] is free + + + if (elenk !== 0) { + cnz = pk2; + } // external degree of k - |Lk\i| + + + W[degree + k] = dk; // element k is in cindex[pk1..pk2-1] + + cptr[k] = pk1; + W[len + k] = pk2 - pk1; // k is now an element + + W[elen + k] = -2; // Find set differences. The scan1 function now computes the set differences |Le \ Lk| for all elements e. At the start of the + // scan, no entry in the w array is greater than or equal to mark. + // clear w if necessary + + mark = _wclear(mark, lemax, W, w, n); // scan 1: find |Le\Lk| + + for (pk = pk1; pk < pk2; pk++) { + i = cindex[pk]; // check if W[elen + i] empty, skip it + + if ((eln = W[elen + i]) <= 0) { + continue; + } // W[nv + i] was negated + + + nvi = -W[nv + i]; + var wnvi = mark - nvi; // scan Ei + + for (p = cptr[i], p1 = cptr[i] + eln - 1; p <= p1; p++) { + e = cindex[p]; + + if (W[w + e] >= mark) { + // decrement |Le\Lk| + W[w + e] -= nvi; + } else if (W[w + e] !== 0) { + // ensure e is a live element, 1st time e seen in scan 1 + W[w + e] = W[degree + e] + wnvi; + } + } + } // degree update + // The second pass computes the approximate degree di, prunes the sets Ei and Ai, and computes a hash + // function h(i) for all nodes in Lk. + // scan2: degree update + + + for (pk = pk1; pk < pk2; pk++) { + // consider node i in Lk + i = cindex[pk]; + p1 = cptr[i]; + p2 = p1 + W[elen + i] - 1; + pn = p1; // scan Ei + + for (h = 0, d = 0, p = p1; p <= p2; p++) { + e = cindex[p]; // check e is an unabsorbed element + + if (W[w + e] !== 0) { + // dext = |Le\Lk| + var dext = W[w + e] - mark; + + if (dext > 0) { + // sum up the set differences + d += dext; // keep e in Ei + + cindex[pn++] = e; // compute the hash of node i + + h += e; + } else { + // aggressive absorb. e->k + cptr[e] = csFlip(k); // e is a dead element + + W[w + e] = 0; + } + } + } // W[elen + i] = |Ei| + + + W[elen + i] = pn - p1 + 1; + var p3 = pn; + var p4 = p1 + W[len + i]; // prune edges in Ai + + for (p = p2 + 1; p < p4; p++) { + j = cindex[p]; // check node j dead or in Lk + + var nvj = W[nv + j]; + + if (nvj <= 0) { + continue; + } // degree(i) += |j| + + + d += nvj; // place j in node list of i + + cindex[pn++] = j; // compute hash for node i + + h += j; + } // check for mass elimination + + + if (d === 0) { + // absorb i into k + cptr[i] = csFlip(k); + nvi = -W[nv + i]; // |Lk| -= |i| + + dk -= nvi; // |k| += W[nv + i] + + nvk += nvi; + nel += nvi; + W[nv + i] = 0; // node i is dead + + W[elen + i] = -1; + } else { + // update degree(i) + W[degree + i] = Math.min(W[degree + i], d); // move first node to end + + cindex[pn] = cindex[p3]; // move 1st el. to end of Ei + + cindex[p3] = cindex[p1]; // add k as 1st element in of Ei + + cindex[p1] = k; // new len of adj. list of node i + + W[len + i] = pn - p1 + 1; // finalize hash of i + + h = (h < 0 ? -h : h) % n; // place i in hash bucket + + W[next + i] = W[hhead + h]; + W[hhead + h] = i; // save hash of i in last[i] + + last[i] = h; + } + } // finalize |Lk| + + + W[degree + k] = dk; + lemax = Math.max(lemax, dk); // clear w + + mark = _wclear(mark + lemax, lemax, W, w, n); // Supernode detection. Supernode detection relies on the hash function h(i) computed for each node i. + // If two nodes have identical adjacency lists, their hash functions wil be identical. + + for (pk = pk1; pk < pk2; pk++) { + i = cindex[pk]; // check i is dead, skip it + + if (W[nv + i] >= 0) { + continue; + } // scan hash bucket of node i + + + h = last[i]; + i = W[hhead + h]; // hash bucket will be empty + + W[hhead + h] = -1; + + for (; i !== -1 && W[next + i] !== -1; i = W[next + i], mark++) { + ln = W[len + i]; + eln = W[elen + i]; + + for (p = cptr[i] + 1; p <= cptr[i] + ln - 1; p++) { + W[w + cindex[p]] = mark; + } + + var jlast = i; // compare i with all j + + for (j = W[next + i]; j !== -1;) { + var ok = W[len + j] === ln && W[elen + j] === eln; + + for (p = cptr[j] + 1; ok && p <= cptr[j] + ln - 1; p++) { + // compare i and j + if (W[w + cindex[p]] !== mark) { + ok = 0; + } + } // check i and j are identical + + + if (ok) { + // absorb j into i + cptr[j] = csFlip(i); + W[nv + i] += W[nv + j]; + W[nv + j] = 0; // node j is dead + + W[elen + j] = -1; // delete j from hash bucket + + j = W[next + j]; + W[next + jlast] = j; + } else { + // j and i are different + jlast = j; + j = W[next + j]; + } + } + } + } // Finalize new element. The elimination of node k is nearly complete. All nodes i in Lk are scanned one last time. + // Node i is removed from Lk if it is dead. The flagged status of nv[i] is cleared. + + + for (p = pk1, pk = pk1; pk < pk2; pk++) { + i = cindex[pk]; // check i is dead, skip it + + if ((nvi = -W[nv + i]) <= 0) { + continue; + } // restore W[nv + i] + + + W[nv + i] = nvi; // compute external degree(i) + + d = W[degree + i] + dk - nvi; + d = Math.min(d, n - nel - nvi); + + if (W[head + d] !== -1) { + last[W[head + d]] = i; + } // put i back in degree list + + + W[next + i] = W[head + d]; + last[i] = -1; + W[head + d] = i; // find new minimum degree + + mindeg = Math.min(mindeg, d); + W[degree + i] = d; // place i in Lk + + cindex[p++] = i; + } // # nodes absorbed into k + + + W[nv + k] = nvk; // length of adj list of element k + + if ((W[len + k] = p - pk1) === 0) { + // k is a root of the tree + cptr[k] = -1; // k is now a dead element + + W[w + k] = 0; + } + + if (elenk !== 0) { + // free unused space in Lk + cnz = p; + } + } // Postordering. The elimination is complete, but no permutation has been computed. All that is left + // of the graph is the assembly tree (ptr) and a set of dead nodes and elements (i is a dead node if + // nv[i] is zero and a dead element if nv[i] > 0). It is from this information only that the final permutation + // is computed. The tree is restored by unflipping all of ptr. + // fix assembly tree + + + for (i = 0; i < n; i++) { + cptr[i] = csFlip(cptr[i]); + } + + for (j = 0; j <= n; j++) { + W[head + j] = -1; + } // place unordered nodes in lists + + + for (j = n; j >= 0; j--) { + // skip if j is an element + if (W[nv + j] > 0) { + continue; + } // place j in list of its parent + + + W[next + j] = W[head + cptr[j]]; + W[head + cptr[j]] = j; + } // place elements in lists + + + for (e = n; e >= 0; e--) { + // skip unless e is an element + if (W[nv + e] <= 0) { + continue; + } + + if (cptr[e] !== -1) { + // place e in list of its parent + W[next + e] = W[head + cptr[e]]; + W[head + cptr[e]] = e; + } + } // postorder the assembly tree + + + for (k = 0, i = 0; i <= n; i++) { + if (cptr[i] === -1) { + k = csTdfs(i, k, W, head, next, P, w); + } + } // remove last item in array + + + P.splice(P.length - 1, 1); // return P + + return P; + }; + /** + * Creates the matrix that will be used by the approximate minimum degree ordering algorithm. The function accepts the matrix M as input and returns a permutation + * vector P. The amd algorithm operates on a symmetrix matrix, so one of three symmetric matrices is formed. + * + * Order: 0 + * A natural ordering P=null matrix is returned. + * + * Order: 1 + * Matrix must be square. This is appropriate for a Cholesky or LU factorization. + * P = M + M' + * + * Order: 2 + * Dense columns from M' are dropped, M recreated from M'. This is appropriatefor LU factorization of unsymmetric matrices. + * P = M' * M + * + * Order: 3 + * This is best used for QR factorization or LU factorization is matrix M has no dense rows. A dense row is a row with more than 10*sqr(columns) entries. + * P = M' * M + */ + + function _createTargetMatrix(order, a, m, n, dense) { + // compute A' + var at = transpose(a); // check order = 1, matrix must be square + + if (order === 1 && n === m) { + // C = A + A' + return add(a, at); + } // check order = 2, drop dense columns from M' + + + if (order === 2) { + // transpose arrays + var tindex = at._index; + var tptr = at._ptr; // new column index + + var p2 = 0; // loop A' columns (rows) + + for (var j = 0; j < m; j++) { + // column j of AT starts here + var p = tptr[j]; // new column j starts here + + tptr[j] = p2; // skip dense col j + + if (tptr[j + 1] - p > dense) { + continue; + } // map rows in column j of A + + + for (var p1 = tptr[j + 1]; p < p1; p++) { + tindex[p2++] = tindex[p]; + } + } // finalize AT + + + tptr[m] = p2; // recreate A from new transpose matrix + + a = transpose(at); // use A' * A + + return multiply(at, a); + } // use A' * A, square or rectangular matrix + + + return multiply(at, a); + } + /** + * Initialize quotient graph. There are four kind of nodes and elements that must be represented: + * + * - A live node is a node i (or a supernode) that has not been selected as a pivot nad has not been merged into another supernode. + * - A dead node i is one that has been removed from the graph, having been absorved into r = flip(ptr[i]). + * - A live element e is one that is in the graph, having been formed when node e was selected as the pivot. + * - A dead element e is one that has benn absorved into a subsequent element s = flip(ptr[e]). + */ + + + function _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree) { + // Initialize quotient graph + for (var k = 0; k < n; k++) { + W[len + k] = cptr[k + 1] - cptr[k]; + } + + W[len + n] = 0; // initialize workspace + + for (var i = 0; i <= n; i++) { + // degree list i is empty + W[head + i] = -1; + last[i] = -1; + W[next + i] = -1; // hash list i is empty + + W[hhead + i] = -1; // node i is just one node + + W[nv + i] = 1; // node i is alive + + W[w + i] = 1; // Ek of node i is empty + + W[elen + i] = 0; // degree of node i + + W[degree + i] = W[len + i]; + } // clear w + + + var mark = _wclear(0, 0, W, w, n); // n is a dead element + + + W[elen + n] = -2; // n is a root of assembly tree + + cptr[n] = -1; // n is a dead element + + W[w + n] = 0; // return mark + + return mark; + } + /** + * Initialize degree lists. Each node is placed in its degree lists. Nodes of zero degree are eliminated immediately. Nodes with + * degree >= dense are alsol eliminated and merged into a placeholder node n, a dead element. Thes nodes will appera last in the + * output permutation p. + */ + + + function _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next) { + // result + var nel = 0; // loop columns + + for (var i = 0; i < n; i++) { + // degree @ i + var d = W[degree + i]; // check node i is empty + + if (d === 0) { + // element i is dead + W[elen + i] = -2; + nel++; // i is a root of assembly tree + + cptr[i] = -1; + W[w + i] = 0; + } else if (d > dense) { + // absorb i into element n + W[nv + i] = 0; // node i is dead + + W[elen + i] = -1; + nel++; + cptr[i] = csFlip(n); + W[nv + n]++; + } else { + var h = W[head + d]; + + if (h !== -1) { + last[h] = i; + } // put node i in degree list d + + + W[next + i] = W[head + d]; + W[head + d] = i; + } + } + + return nel; + } + + function _wclear(mark, lemax, W, w, n) { + if (mark < 2 || mark + lemax < 0) { + for (var k = 0; k < n; k++) { + if (W[w + k] !== 0) { + W[w + k] = 1; + } + } + + mark = 2; + } // at this point, W [0..n-1] < mark holds + + + return mark; + } + + function _diag(i, j) { + return i !== j; + } +}); +// CONCATENATED MODULE: ./src/function/algebra/sparse/csLeaf.js +/** + * This function determines if j is a leaf of the ith row subtree. + * Consider A(i,j), node j in ith row subtree and return lca(jprev,j) + * + * @param {Number} i The ith row subtree + * @param {Number} j The node to test + * @param {Array} w The workspace array + * @param {Number} first The index offset within the workspace for the first array + * @param {Number} maxfirst The index offset within the workspace for the maxfirst array + * @param {Number} prevleaf The index offset within the workspace for the prevleaf array + * @param {Number} ancestor The index offset within the workspace for the ancestor array + * + * @return {Object} + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor) { + var s, sparent; // our result + + var jleaf = 0; + var q; // check j is a leaf + + if (i <= j || w[first + j] <= w[maxfirst + i]) { + return -1; + } // update max first[j] seen so far + + + w[maxfirst + i] = w[first + j]; // jprev = previous leaf of ith subtree + + var jprev = w[prevleaf + i]; + w[prevleaf + i] = j; // check j is first or subsequent leaf + + if (jprev === -1) { + // 1st leaf, q = root of ith subtree + jleaf = 1; + q = i; + } else { + // update jleaf + jleaf = 2; // q = least common ancester (jprev,j) + + for (q = jprev; q !== w[ancestor + q]; q = w[ancestor + q]) { + ; + } + + for (s = jprev; s !== q; s = sparent) { + // path compression + sparent = w[ancestor + s]; + w[ancestor + s] = q; + } + } + + return { + jleaf: jleaf, + q: q + }; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csCounts.js + + +var csCounts_name = 'csCounts'; +var csCounts_dependencies = ['transpose']; +var createCsCounts = /* #__PURE__ */Object(factory["a" /* factory */])(csCounts_name, csCounts_dependencies, function (_ref) { + var transpose = _ref.transpose; + + /** + * Computes the column counts using the upper triangular part of A. + * It transposes A internally, none of the input parameters are modified. + * + * @param {Matrix} a The sparse matrix A + * + * @param {Matrix} ata Count the columns of A'A instead + * + * @return An array of size n of the column counts or null on error + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + return function (a, parent, post, ata) { + // check inputs + if (!a || !parent || !post) { + return null; + } // a matrix arrays + + + var asize = a._size; // rows and columns + + var m = asize[0]; + var n = asize[1]; // variables + + var i, j, k, J, p, p0, p1; // workspace size + + var s = 4 * n + (ata ? n + m + 1 : 0); // allocate workspace + + var w = []; // (s) + + var ancestor = 0; // first n entries + + var maxfirst = n; // next n entries + + var prevleaf = 2 * n; // next n entries + + var first = 3 * n; // next n entries + + var head = 4 * n; // next n + 1 entries (used when ata is true) + + var next = 5 * n + 1; // last entries in workspace + // clear workspace w[0..s-1] + + for (k = 0; k < s; k++) { + w[k] = -1; + } // allocate result + + + var colcount = []; // (n) + // AT = A' + + var at = transpose(a); // at arrays + + var tindex = at._index; + var tptr = at._ptr; // find w[first + j] + + for (k = 0; k < n; k++) { + j = post[k]; // colcount[j]=1 if j is a leaf + + colcount[j] = w[first + j] === -1 ? 1 : 0; + + for (; j !== -1 && w[first + j] === -1; j = parent[j]) { + w[first + j] = k; + } + } // initialize ata if needed + + + if (ata) { + // invert post + for (k = 0; k < n; k++) { + w[post[k]] = k; + } // loop rows (columns in AT) + + + for (i = 0; i < m; i++) { + // values in column i of AT + for (k = n, p0 = tptr[i], p1 = tptr[i + 1], p = p0; p < p1; p++) { + k = Math.min(k, w[tindex[p]]); + } // place row i in linked list k + + + w[next + i] = w[head + k]; + w[head + k] = i; + } + } // each node in its own set + + + for (i = 0; i < n; i++) { + w[ancestor + i] = i; + } + + for (k = 0; k < n; k++) { + // j is the kth node in postordered etree + j = post[k]; // check j is not a root + + if (parent[j] !== -1) { + colcount[parent[j]]--; + } // J=j for LL'=A case + + + for (J = ata ? w[head + k] : j; J !== -1; J = ata ? w[next + J] : -1) { + for (p = tptr[J]; p < tptr[J + 1]; p++) { + i = tindex[p]; + var r = csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor); // check A(i,j) is in skeleton + + if (r.jleaf >= 1) { + colcount[j]++; + } // check account for overlap in q + + + if (r.jleaf === 2) { + colcount[r.q]--; + } + } + } + + if (parent[j] !== -1) { + w[ancestor + j] = parent[j]; + } + } // sum up colcount's of each child + + + for (j = 0; j < n; j++) { + if (parent[j] !== -1) { + colcount[parent[j]] += colcount[j]; + } + } + + return colcount; + }; +}); +// CONCATENATED MODULE: ./src/function/algebra/sparse/csSqr.js + + + + + + +var csSqr_name = 'csSqr'; +var csSqr_dependencies = ['add', 'multiply', 'transpose']; +var createCsSqr = /* #__PURE__ */Object(factory["a" /* factory */])(csSqr_name, csSqr_dependencies, function (_ref) { + var add = _ref.add, + multiply = _ref.multiply, + transpose = _ref.transpose; + var csAmd = createCsAmd({ + add: add, + multiply: multiply, + transpose: transpose + }); + var csCounts = createCsCounts({ + transpose: transpose + }); + /** + * Symbolic ordering and analysis for QR and LU decompositions. + * + * @param {Number} order The ordering strategy (see csAmd for more details) + * @param {Matrix} a The A matrix + * @param {boolean} qr Symbolic ordering and analysis for QR decomposition (true) or + * symbolic ordering and analysis for LU decomposition (false) + * + * @return {Object} The Symbolic ordering and analysis for matrix A + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + + return function csSqr(order, a, qr) { + // a arrays + var aptr = a._ptr; + var asize = a._size; // columns + + var n = asize[1]; // vars + + var k; // symbolic analysis result + + var s = {}; // fill-reducing ordering + + s.q = csAmd(order, a); // validate results + + if (order && !s.q) { + return null; + } // QR symbolic analysis + + + if (qr) { + // apply permutations if needed + var c = order ? csPermute(a, null, s.q, 0) : a; // etree of C'*C, where C=A(:,q) + + s.parent = csEtree(c, 1); // post order elimination tree + + var post = csPost(s.parent, n); // col counts chol(C'*C) + + s.cp = csCounts(c, s.parent, post, 1); // check we have everything needed to calculate number of nonzero elements + + if (c && s.parent && s.cp && _vcount(c, s)) { + // calculate number of nonzero elements + for (s.unz = 0, k = 0; k < n; k++) { + s.unz += s.cp[k]; + } + } + } else { + // for LU factorization only, guess nnz(L) and nnz(U) + s.unz = 4 * aptr[n] + n; + s.lnz = s.unz; + } // return result S + + + return s; + }; + /** + * Compute nnz(V) = s.lnz, s.pinv, s.leftmost, s.m2 from A and s.parent + */ + + function _vcount(a, s) { + // a arrays + var aptr = a._ptr; + var aindex = a._index; + var asize = a._size; // rows & columns + + var m = asize[0]; + var n = asize[1]; // initialize s arrays + + s.pinv = []; // (m + n) + + s.leftmost = []; // (m) + // vars + + var parent = s.parent; + var pinv = s.pinv; + var leftmost = s.leftmost; // workspace, next: first m entries, head: next n entries, tail: next n entries, nque: next n entries + + var w = []; // (m + 3 * n) + + var next = 0; + var head = m; + var tail = m + n; + var nque = m + 2 * n; // vars + + var i, k, p, p0, p1; // initialize w + + for (k = 0; k < n; k++) { + // queue k is empty + w[head + k] = -1; + w[tail + k] = -1; + w[nque + k] = 0; + } // initialize row arrays + + + for (i = 0; i < m; i++) { + leftmost[i] = -1; + } // loop columns backwards + + + for (k = n - 1; k >= 0; k--) { + // values & index for column k + for (p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) { + // leftmost[i] = min(find(A(i,:))) + leftmost[aindex[p]] = k; + } + } // scan rows in reverse order + + + for (i = m - 1; i >= 0; i--) { + // row i is not yet ordered + pinv[i] = -1; + k = leftmost[i]; // check row i is empty + + if (k === -1) { + continue; + } // first row in queue k + + + if (w[nque + k]++ === 0) { + w[tail + k] = i; + } // put i at head of queue k + + + w[next + i] = w[head + k]; + w[head + k] = i; + } + + s.lnz = 0; + s.m2 = m; // find row permutation and nnz(V) + + for (k = 0; k < n; k++) { + // remove row i from queue k + i = w[head + k]; // count V(k,k) as nonzero + + s.lnz++; // add a fictitious row + + if (i < 0) { + i = s.m2++; + } // associate row i with V(:,k) + + + pinv[i] = k; // skip if V(k+1:m,k) is empty + + if (--nque[k] <= 0) { + continue; + } // nque[k] is nnz (V(k+1:m,k)) + + + s.lnz += w[nque + k]; // move all rows to parent of k + + var pa = parent[k]; + + if (pa !== -1) { + if (w[nque + pa] === 0) { + w[tail + pa] = w[tail + k]; + } + + w[next + w[tail + k]] = w[head + pa]; + w[head + pa] = w[next + i]; + w[nque + pa] += w[nque + k]; + } + } + + for (i = 0; i < m; i++) { + if (pinv[i] < 0) { + pinv[i] = k++; + } + } + + return true; + } +}); +// CONCATENATED MODULE: ./src/function/algebra/sparse/csMarked.js +/** + * Checks if the node at w[j] is marked + * + * @param {Array} w The array + * @param {Number} j The array index + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ +function csMarked(w, j) { + // check node is marked + return w[j] < 0; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csMark.js + +/** + * Marks the node at w[j] + * + * @param {Array} w The array + * @param {Number} j The array index + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + +function csMark(w, j) { + // mark w[j] + w[j] = csFlip(w[j]); +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csUnflip.js + +/** + * Flips the value if it is negative of returns the same value otherwise. + * + * @param {Number} i The value to flip + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + +function csUnflip(i) { + // flip the value if it is negative + return i < 0 ? csFlip(i) : i; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csDfs.js + + + +/** + * Depth-first search computes the nonzero pattern xi of the directed graph G (Matrix) starting + * at nodes in B (see csReach()). + * + * @param {Number} j The starting node for the DFS algorithm + * @param {Matrix} g The G matrix to search, ptr array modified, then restored + * @param {Number} top Start index in stack xi[top..n-1] + * @param {Number} k The kth column in B + * @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n + * The first n entries is the nonzero pattern, the last n entries is the stack + * @param {Array} pinv The inverse row permutation vector, must be null for L * x = b + * + * @return {Number} New value of top + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + +function csDfs(j, g, top, xi, pinv) { + // g arrays + var index = g._index; + var ptr = g._ptr; + var size = g._size; // columns + + var n = size[1]; // vars + + var i, p, p2; // initialize head + + var head = 0; // initialize the recursion stack + + xi[0] = j; // loop + + while (head >= 0) { + // get j from the top of the recursion stack + j = xi[head]; // apply permutation vector + + var jnew = pinv ? pinv[j] : j; // check node j is marked + + if (!csMarked(ptr, j)) { + // mark node j as visited + csMark(ptr, j); // update stack (last n entries in xi) + + xi[n + head] = jnew < 0 ? 0 : csUnflip(ptr[jnew]); + } // node j done if no unvisited neighbors + + + var done = 1; // examine all neighbors of j, stack (last n entries in xi) + + for (p = xi[n + head], p2 = jnew < 0 ? 0 : csUnflip(ptr[jnew + 1]); p < p2; p++) { + // consider neighbor node i + i = index[p]; // check we have visited node i, skip it + + if (csMarked(ptr, i)) { + continue; + } // pause depth-first search of node j, update stack (last n entries in xi) + + + xi[n + head] = p; // start dfs at node i + + xi[++head] = i; // node j is not done + + done = 0; // break, to start dfs(i) + + break; + } // check depth-first search at node j is done + + + if (done) { + // remove j from the recursion stack + head--; // and place in the output stack + + xi[--top] = j; + } + } + + return top; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csReach.js + + + +/** + * The csReach function computes X = Reach(B), where B is the nonzero pattern of the n-by-1 + * sparse column of vector b. The function returns the set of nodes reachable from any node in B. The + * nonzero pattern xi of the solution x to the sparse linear system Lx=b is given by X=Reach(B). + * + * @param {Matrix} g The G matrix + * @param {Matrix} b The B matrix + * @param {Number} k The kth column in B + * @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n + * The first n entries is the nonzero pattern, the last n entries is the stack + * @param {Array} pinv The inverse row permutation vector + * + * @return {Number} The index for the nonzero pattern + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + +function csReach(g, b, k, xi, pinv) { + // g arrays + var gptr = g._ptr; + var gsize = g._size; // b arrays + + var bindex = b._index; + var bptr = b._ptr; // columns + + var n = gsize[1]; // vars + + var p, p0, p1; // initialize top + + var top = n; // loop column indeces in B + + for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) { + // node i + var i = bindex[p]; // check node i is marked + + if (!csMarked(gptr, i)) { + // start a dfs at unmarked node i + top = csDfs(i, g, top, xi, pinv); + } + } // loop columns from top -> n - 1 + + + for (p = top; p < n; p++) { + // restore G + csMark(gptr, xi[p]); + } + + return top; +} +// CONCATENATED MODULE: ./src/function/algebra/sparse/csSpsolve.js + + +var csSpsolve_name = 'csSpsolve'; +var csSpsolve_dependencies = ['divideScalar', 'multiply', 'subtract']; +var createCsSpsolve = /* #__PURE__ */Object(factory["a" /* factory */])(csSpsolve_name, csSpsolve_dependencies, function (_ref) { + var divideScalar = _ref.divideScalar, + multiply = _ref.multiply, + subtract = _ref.subtract; + + /** + * The function csSpsolve() computes the solution to G * x = bk, where bk is the + * kth column of B. When lo is true, the function assumes G = L is lower triangular with the + * diagonal entry as the first entry in each column. When lo is true, the function assumes G = U + * is upper triangular with the diagonal entry as the last entry in each column. + * + * @param {Matrix} g The G matrix + * @param {Matrix} b The B matrix + * @param {Number} k The kth column in B + * @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n + * The first n entries is the nonzero pattern, the last n entries is the stack + * @param {Array} x The soluton to the linear system G * x = b + * @param {Array} pinv The inverse row permutation vector, must be null for L * x = b + * @param {boolean} lo The lower (true) upper triangular (false) flag + * + * @return {Number} The index for the nonzero pattern + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + return function csSpsolve(g, b, k, xi, x, pinv, lo) { + // g arrays + var gvalues = g._values; + var gindex = g._index; + var gptr = g._ptr; + var gsize = g._size; // columns + + var n = gsize[1]; // b arrays + + var bvalues = b._values; + var bindex = b._index; + var bptr = b._ptr; // vars + + var p, p0, p1, q; // xi[top..n-1] = csReach(B(:,k)) + + var top = csReach(g, b, k, xi, pinv); // clear x + + for (p = top; p < n; p++) { + x[xi[p]] = 0; + } // scatter b + + + for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) { + x[bindex[p]] = bvalues[p]; + } // loop columns + + + for (var px = top; px < n; px++) { + // x array index for px + var j = xi[px]; // apply permutation vector (U x = b), j maps to column J of G + + var J = pinv ? pinv[j] : j; // check column J is empty + + if (J < 0) { + continue; + } // column value indeces in G, p0 <= p < p1 + + + p0 = gptr[J]; + p1 = gptr[J + 1]; // x(j) /= G(j,j) + + x[j] = divideScalar(x[j], gvalues[lo ? p0 : p1 - 1]); // first entry L(j,j) + + p = lo ? p0 + 1 : p0; + q = lo ? p1 : p1 - 1; // loop + + for (; p < q; p++) { + // row + var i = gindex[p]; // x(i) -= G(i,j) * x(j) + + x[i] = subtract(x[i], multiply(gvalues[p], x[j])); + } + } // return top of stack + + + return top; + }; +}); +// CONCATENATED MODULE: ./src/function/algebra/sparse/csLu.js + + +var csLu_name = 'csLu'; +var csLu_dependencies = ['abs', 'divideScalar', 'multiply', 'subtract', 'larger', 'largerEq', 'SparseMatrix']; +var createCsLu = /* #__PURE__ */Object(factory["a" /* factory */])(csLu_name, csLu_dependencies, function (_ref) { + var abs = _ref.abs, + divideScalar = _ref.divideScalar, + multiply = _ref.multiply, + subtract = _ref.subtract, + larger = _ref.larger, + largerEq = _ref.largerEq, + SparseMatrix = _ref.SparseMatrix; + var csSpsolve = createCsSpsolve({ + divideScalar: divideScalar, + multiply: multiply, + subtract: subtract + }); + /** + * Computes the numeric LU factorization of the sparse matrix A. Implements a Left-looking LU factorization + * algorithm that computes L and U one column at a tume. At the kth step, it access columns 1 to k-1 of L + * and column k of A. Given the fill-reducing column ordering q (see parameter s) computes L, U and pinv so + * L * U = A(p, q), where p is the inverse of pinv. + * + * @param {Matrix} m The A Matrix to factorize + * @param {Object} s The symbolic analysis from csSqr(). Provides the fill-reducing + * column ordering q + * @param {Number} tol Partial pivoting threshold (1 for partial pivoting) + * + * @return {Number} The numeric LU factorization of A or null + * + * Reference: http://faculty.cse.tamu.edu/davis/publications.html + */ + + return function csLu(m, s, tol) { + // validate input + if (!m) { + return null; + } // m arrays + + + var size = m._size; // columns + + var n = size[1]; // symbolic analysis result + + var q; + var lnz = 100; + var unz = 100; // update symbolic analysis parameters + + if (s) { + q = s.q; + lnz = s.lnz || lnz; + unz = s.unz || unz; + } // L arrays + + + var lvalues = []; // (lnz) + + var lindex = []; // (lnz) + + var lptr = []; // (n + 1) + // L + + var L = new SparseMatrix({ + values: lvalues, + index: lindex, + ptr: lptr, + size: [n, n] + }); // U arrays + + var uvalues = []; // (unz) + + var uindex = []; // (unz) + + var uptr = []; // (n + 1) + // U + + var U = new SparseMatrix({ + values: uvalues, + index: uindex, + ptr: uptr, + size: [n, n] + }); // inverse of permutation vector + + var pinv = []; // (n) + // vars + + var i, p; // allocate arrays + + var x = []; // (n) + + var xi = []; // (2 * n) + // initialize variables + + for (i = 0; i < n; i++) { + // clear workspace + x[i] = 0; // no rows pivotal yet + + pinv[i] = -1; // no cols of L yet + + lptr[i + 1] = 0; + } // reset number of nonzero elements in L and U + + + lnz = 0; + unz = 0; // compute L(:,k) and U(:,k) + + for (var k = 0; k < n; k++) { + // update ptr + lptr[k] = lnz; + uptr[k] = unz; // apply column permutations if needed + + var col = q ? q[k] : k; // solve triangular system, x = L\A(:,col) + + var top = csSpsolve(L, m, col, xi, x, pinv, 1); // find pivot + + var ipiv = -1; + var a = -1; // loop xi[] from top -> n + + for (p = top; p < n; p++) { + // x[i] is nonzero + i = xi[p]; // check row i is not yet pivotal + + if (pinv[i] < 0) { + // absolute value of x[i] + var xabs = abs(x[i]); // check absoulte value is greater than pivot value + + if (larger(xabs, a)) { + // largest pivot candidate so far + a = xabs; + ipiv = i; + } + } else { + // x(i) is the entry U(pinv[i],k) + uindex[unz] = pinv[i]; + uvalues[unz++] = x[i]; + } + } // validate we found a valid pivot + + + if (ipiv === -1 || a <= 0) { + return null; + } // update actual pivot column, give preference to diagonal value + + + if (pinv[col] < 0 && largerEq(abs(x[col]), multiply(a, tol))) { + ipiv = col; + } // the chosen pivot + + + var pivot = x[ipiv]; // last entry in U(:,k) is U(k,k) + + uindex[unz] = k; + uvalues[unz++] = pivot; // ipiv is the kth pivot row + + pinv[ipiv] = k; // first entry in L(:,k) is L(k,k) = 1 + + lindex[lnz] = ipiv; + lvalues[lnz++] = 1; // L(k+1:n,k) = x / pivot + + for (p = top; p < n; p++) { + // row + i = xi[p]; // check x(i) is an entry in L(:,k) + + if (pinv[i] < 0) { + // save unpermuted row in L + lindex[lnz] = i; // scale pivot column + + lvalues[lnz++] = divideScalar(x[i], pivot); + } // x[0..n-1] = 0 for next k + + + x[i] = 0; + } + } // update ptr + + + lptr[n] = lnz; + uptr[n] = unz; // fix row indices of L for final pinv + + for (p = 0; p < lnz; p++) { + lindex[p] = pinv[lindex[p]]; + } // trim arrays + + + lvalues.splice(lnz, lvalues.length - lnz); + lindex.splice(lnz, lindex.length - lnz); + uvalues.splice(unz, uvalues.length - unz); + uindex.splice(unz, uindex.length - unz); // return LU factor + + return { + L: L, + U: U, + pinv: pinv + }; + }; +}); +// CONCATENATED MODULE: ./src/function/algebra/decomposition/slu.js + + + + +var slu_name = 'slu'; +var slu_dependencies = ['typed', 'abs', 'add', 'multiply', 'transpose', 'divideScalar', 'subtract', 'larger', 'largerEq', 'SparseMatrix']; +var createSlu = /* #__PURE__ */Object(factory["a" /* factory */])(slu_name, slu_dependencies, function (_ref) { + var typed = _ref.typed, + abs = _ref.abs, + add = _ref.add, + multiply = _ref.multiply, + transpose = _ref.transpose, + divideScalar = _ref.divideScalar, + subtract = _ref.subtract, + larger = _ref.larger, + largerEq = _ref.largerEq, + SparseMatrix = _ref.SparseMatrix; + var csSqr = createCsSqr({ + add: add, + multiply: multiply, + transpose: transpose + }); + var csLu = createCsLu({ + abs: abs, + divideScalar: divideScalar, + multiply: multiply, + subtract: subtract, + larger: larger, + largerEq: largerEq, + SparseMatrix: SparseMatrix + }); + /** + * Calculate the Sparse Matrix LU decomposition with full pivoting. Sparse Matrix `A` is decomposed in two matrices (`L`, `U`) and two permutation vectors (`pinv`, `q`) where + * + * `P * A * Q = L * U` + * + * Syntax: + * + * math.slu(A, order, threshold) + * + * Examples: + * + * const A = math.sparse([[4,3], [6, 3]]) + * math.slu(A, 1, 0.001) + * // returns: + * // { + * // L: [[1, 0], [1.5, 1]] + * // U: [[4, 3], [0, -1.5]] + * // p: [0, 1] + * // q: [0, 1] + * // } + * + * See also: + * + * lup, lsolve, usolve, lusolve + * + * @param {SparseMatrix} A A two dimensional sparse matrix for which to get the LU decomposition. + * @param {Number} order The Symbolic Ordering and Analysis order: + * 0 - Natural ordering, no permutation vector q is returned + * 1 - Matrix must be square, symbolic ordering and analisis is performed on M = A + A' + * 2 - Symbolic ordering and analisis is performed on M = A' * A. Dense columns from A' are dropped, A recreated from A'. + * This is appropriatefor LU factorization of unsymmetric matrices. + * 3 - Symbolic ordering and analisis is performed on M = A' * A. This is best used for LU factorization is matrix M has no dense rows. + * A dense row is a row with more than 10*sqr(columns) entries. + * @param {Number} threshold Partial pivoting threshold (1 for partial pivoting) + * + * @return {Object} The lower triangular matrix, the upper triangular matrix and the permutation vectors. + */ + + return typed(slu_name, { + 'SparseMatrix, number, number': function SparseMatrixNumberNumber(a, order, threshold) { + // verify order + if (!Object(utils_number["i" /* isInteger */])(order) || order < 0 || order > 3) { + throw new Error('Symbolic Ordering and Analysis order must be an integer number in the interval [0, 3]'); + } // verify threshold + + + if (threshold < 0 || threshold > 1) { + throw new Error('Partial pivoting threshold must be a number from 0 to 1'); + } // perform symbolic ordering and analysis + + + var s = csSqr(order, a, false); // perform lu decomposition + + var f = csLu(a, s, threshold); // return decomposition + + return { + L: f.L, + U: f.U, + p: f.pinv, + q: s.q, + toString: function toString() { + return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\np: ' + this.p.toString() + (this.q ? '\nq: ' + this.q.toString() : '') + '\n'; + } + }; + } + }); +}); +// CONCATENATED MODULE: ./src/function/algebra/sparse/csIpvec.js +/** + * Permutes a vector; x = P'b. In MATLAB notation, x(p)=b. + * + * @param {Array} p The permutation vector of length n. null value denotes identity + * @param {Array} b The input vector + * + * @return {Array} The output vector x = P'b + */ +function csIpvec(p, b) { + // vars + var k; + var n = b.length; + var x = []; // check permutation vector was provided, p = null denotes identity + + if (p) { + // loop vector + for (k = 0; k < n; k++) { + // apply permutation + x[p[k]] = b[k]; + } + } else { + // loop vector + for (k = 0; k < n; k++) { + // x[i] = b[i] + x[k] = b[k]; + } + } + + return x; +} +// CONCATENATED MODULE: ./src/function/algebra/solver/lusolve.js + + + + +var lusolve_name = 'lusolve'; +var lusolve_dependencies = ['typed', 'matrix', 'lup', 'slu', 'usolve', 'lsolve', 'DenseMatrix']; +var createLusolve = /* #__PURE__ */Object(factory["a" /* factory */])(lusolve_name, lusolve_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + lup = _ref.lup, + slu = _ref.slu, + usolve = _ref.usolve, + lsolve = _ref.lsolve, + DenseMatrix = _ref.DenseMatrix; + var solveValidation = createSolveValidation({ + DenseMatrix: DenseMatrix + }); + /** + * Solves the linear system `A * x = b` where `A` is an [n x n] matrix and `b` is a [n] column vector. + * + * Syntax: + * + * math.lusolve(A, b) // returns column vector with the solution to the linear system A * x = b + * math.lusolve(lup, b) // returns column vector with the solution to the linear system A * x = b, lup = math.lup(A) + * + * Examples: + * + * const m = [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]] + * + * const x = math.lusolve(m, [-1, -1, -1, -1]) // x = [[-1], [-0.5], [-1/3], [-0.25]] + * + * const f = math.lup(m) + * const x1 = math.lusolve(f, [-1, -1, -1, -1]) // x1 = [[-1], [-0.5], [-1/3], [-0.25]] + * const x2 = math.lusolve(f, [1, 2, 1, -1]) // x2 = [[1], [1], [1/3], [-0.25]] + * + * const a = [[-2, 3], [2, 1]] + * const b = [11, 9] + * const x = math.lusolve(a, b) // [[2], [5]] + * + * See also: + * + * lup, slu, lsolve, usolve + * + * @param {Matrix | Array | Object} A Invertible Matrix or the Matrix LU decomposition + * @param {Matrix | Array} b Column Vector + * @param {number} [order] The Symbolic Ordering and Analysis order, see slu for details. Matrix must be a SparseMatrix + * @param {Number} [threshold] Partial pivoting threshold (1 for partial pivoting), see slu for details. Matrix must be a SparseMatrix. + * + * @return {DenseMatrix | Array} Column vector with the solution to the linear system A * x = b + */ + + return typed(lusolve_name, { + 'Array, Array | Matrix': function ArrayArrayMatrix(a, b) { + // convert a to matrix + a = matrix(a); // matrix lup decomposition + + var d = lup(a); // solve + + var x = _lusolve(d.L, d.U, d.p, null, b); // convert result to array + + + return x.valueOf(); + }, + 'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(a, b) { + // matrix lup decomposition + var d = lup(a); // solve + + return _lusolve(d.L, d.U, d.p, null, b); + }, + 'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(a, b) { + // matrix lup decomposition + var d = lup(a); // solve + + return _lusolve(d.L, d.U, d.p, null, b); + }, + 'SparseMatrix, Array | Matrix, number, number': function SparseMatrixArrayMatrixNumberNumber(a, b, order, threshold) { + // matrix lu decomposition + var d = slu(a, order, threshold); // solve + + return _lusolve(d.L, d.U, d.p, d.q, b); + }, + 'Object, Array | Matrix': function ObjectArrayMatrix(d, b) { + // solve + return _lusolve(d.L, d.U, d.p, d.q, b); + } + }); + + function _toMatrix(a) { + // check it is a matrix + if (Object(is["v" /* isMatrix */])(a)) { + return a; + } // check array + + + if (Object(is["b" /* isArray */])(a)) { + return matrix(a); + } // throw + + + throw new TypeError('Invalid Matrix LU decomposition'); + } + + function _lusolve(l, u, p, q, b) { + // verify L, U, P + l = _toMatrix(l); + u = _toMatrix(u); // validate matrix and vector + + b = solveValidation(l, b, false); // apply row permutations if needed (b is a DenseMatrix) + + if (p) { + b._data = csIpvec(p, b._data); + } // use forward substitution to resolve L * y = b + + + var y = lsolve(l, b); // use backward substitution to resolve U * x = y + + var x = usolve(u, y); // apply column permutations if needed (x is a DenseMatrix) + + if (q) { + x._data = csIpvec(q, x._data); + } // return solution + + + return x; + } +}); +// CONCATENATED MODULE: ./src/expression/Help.js + + + + +var Help_name = 'Help'; +var Help_dependencies = ['parse']; +var createHelpClass = /* #__PURE__ */Object(factory["a" /* factory */])(Help_name, Help_dependencies, function (_ref) { + var parse = _ref.parse; + + /** + * Documentation object + * @param {Object} doc Object containing properties: + * {string} name + * {string} category + * {string} description + * {string[]} syntax + * {string[]} examples + * {string[]} seealso + * @constructor + */ + function Help(doc) { + if (!(this instanceof Help)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (!doc) throw new Error('Argument "doc" missing'); + this.doc = doc; + } + /** + * Attach type information + */ + + + Help.prototype.type = 'Help'; + Help.prototype.isHelp = true; + /** + * Generate a string representation of the Help object + * @return {string} Returns a string + * @private + */ + + Help.prototype.toString = function () { + var doc = this.doc || {}; + var desc = '\n'; + + if (doc.name) { + desc += 'Name: ' + doc.name + '\n\n'; + } + + if (doc.category) { + desc += 'Category: ' + doc.category + '\n\n'; + } + + if (doc.description) { + desc += 'Description:\n ' + doc.description + '\n\n'; + } + + if (doc.syntax) { + desc += 'Syntax:\n ' + doc.syntax.join('\n ') + '\n\n'; + } + + if (doc.examples) { + desc += 'Examples:\n'; + var scope = {}; + + for (var i = 0; i < doc.examples.length; i++) { + var expr = doc.examples[i]; + desc += ' ' + expr + '\n'; + var res = void 0; + + try { + // note: res can be undefined when `expr` is an empty string + res = parse(expr).compile().evaluate(scope); + } catch (e) { + res = e; + } + + if (res !== undefined && !Object(is["s" /* isHelp */])(res)) { + desc += ' ' + Object(utils_string["d" /* format */])(res, { + precision: 14 + }) + '\n'; + } + } + + desc += '\n'; + } + + if (doc.seealso && doc.seealso.length) { + desc += 'See also: ' + doc.seealso.join(', ') + '\n'; + } + + return desc; + }; + /** + * Export the help object to JSON + */ + + + Help.prototype.toJSON = function () { + var obj = Object(utils_object["a" /* clone */])(this.doc); + obj.mathjs = 'Help'; + return obj; + }; + /** + * Instantiate a Help object from a JSON object + * @param {Object} json + * @returns {Help} Returns a new Help object + */ + + + Help.fromJSON = function (json) { + var doc = {}; + + for (var prop in json) { + if (prop !== 'mathjs') { + // ignore mathjs field + doc[prop] = json[prop]; + } + } + + return new Help(doc); + }; + /** + * Returns a string representation of the Help object + */ + + + Help.prototype.valueOf = Help.prototype.toString; + return Help; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/type/chain/Chain.js + + + + +var Chain_name = 'Chain'; +var Chain_dependencies = ['?on', 'math']; +var createChainClass = /* #__PURE__ */Object(factory["a" /* factory */])(Chain_name, Chain_dependencies, function (_ref) { + var on = _ref.on, + math = _ref.math; + + /** + * @constructor Chain + * Wrap any value in a chain, allowing to perform chained operations on + * the value. + * + * All methods available in the math.js library can be called upon the chain, + * and then will be evaluated with the value itself as first argument. + * The chain can be closed by executing chain.done(), which will return + * the final value. + * + * The Chain has a number of special functions: + * - done() Finalize the chained operation and return the + * chain's value. + * - valueOf() The same as done() + * - toString() Returns a string representation of the chain's value. + * + * @param {*} [value] + */ + function Chain(value) { + if (!(this instanceof Chain)) { + throw new SyntaxError('Constructor must be called with the new operator'); + } + + if (Object(is["h" /* isChain */])(value)) { + this.value = value.value; + } else { + this.value = value; + } + } + /** + * Attach type information + */ + + + Chain.prototype.type = 'Chain'; + Chain.prototype.isChain = true; + /** + * Close the chain. Returns the final value. + * Does the same as method valueOf() + * @returns {*} value + */ + + Chain.prototype.done = function () { + return this.value; + }; + /** + * Close the chain. Returns the final value. + * Does the same as method done() + * @returns {*} value + */ + + + Chain.prototype.valueOf = function () { + return this.value; + }; + /** + * Get a string representation of the value in the chain + * @returns {string} + */ + + + Chain.prototype.toString = function () { + return Object(utils_string["d" /* format */])(this.value); + }; + /** + * Get a JSON representation of the chain + * @returns {Object} + */ + + + Chain.prototype.toJSON = function () { + return { + mathjs: 'Chain', + value: this.value + }; + }; + /** + * Instantiate a Chain from its JSON representation + * @param {Object} json An object structured like + * `{"mathjs": "Chain", value: ...}`, + * where mathjs is optional + * @returns {Chain} + */ + + + Chain.fromJSON = function (json) { + return new Chain(json.value); + }; + /** + * Create a proxy method for the chain + * @param {string} name + * @param {Function} fn The function to be proxied + * If fn is no function, it is silently ignored. + * @private + */ + + + function createProxy(name, fn) { + if (typeof fn === 'function') { + Chain.prototype[name] = chainify(fn); + } + } + /** + * Create a proxy method for the chain + * @param {string} name + * @param {function} resolver The function resolving with the + * function to be proxied + * @private + */ + + + function createLazyProxy(name, resolver) { + Object(utils_object["h" /* lazy */])(Chain.prototype, name, function outerResolver() { + var fn = resolver(); + + if (typeof fn === 'function') { + return chainify(fn); + } + + return undefined; // if not a function, ignore + }); + } + /** + * Make a function chainable + * @param {function} fn + * @return {Function} chain function + * @private + */ + + + function chainify(fn) { + return function () { + var args = [this.value]; // `this` will be the context of a Chain instance + + for (var i = 0; i < arguments.length; i++) { + args[i + 1] = arguments[i]; + } + + return new Chain(fn.apply(fn, args)); + }; + } + /** + * Create a proxy for a single method, or an object with multiple methods. + * Example usage: + * + * Chain.createProxy('add', function add (x, y) {...}) + * Chain.createProxy({ + * add: function add (x, y) {...}, + * subtract: function subtract (x, y) {...} + * } + * + * @param {string | Object} arg0 A name (string), or an object with + * functions + * @param {*} [arg1] A function, when arg0 is a name + */ + + + Chain.createProxy = function (arg0, arg1) { + if (typeof arg0 === 'string') { + // createProxy(name, value) + createProxy(arg0, arg1); + } else { + var _loop = function _loop(_name) { + if (Object(utils_object["f" /* hasOwnProperty */])(arg0, _name) && excludedNames[_name] === undefined) { + createLazyProxy(_name, function () { + return arg0[_name]; + }); + } + }; + + // createProxy(values) + for (var _name in arg0) { + _loop(_name); + } + } + }; + + var excludedNames = { + expression: true, + docs: true, + type: true, + classes: true, + json: true, + error: true, + isChain: true // conflicts with the property isChain of a Chain instance + + }; // create proxy for everything that is in math.js + + Chain.createProxy(math); // register on the import event, automatically add a proxy for every imported function. + + if (on) { + on('import', function (name, resolver, path) { + if (!path) { + // an imported function (not a data type or something special) + createLazyProxy(name, resolver); + } + }); + } + + return Chain; +}, { + isClass: true +}); +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/bignumber.js +var bignumberDocs = { + name: 'bignumber', + category: 'Construction', + syntax: ['bignumber(x)'], + description: 'Create a big number from a number or string.', + examples: ['0.1 + 0.2', 'bignumber(0.1) + bignumber(0.2)', 'bignumber("7.2")', 'bignumber("7.2e500")', 'bignumber([0.1, 0.2, 0.3])'], + seealso: ['boolean', 'complex', 'fraction', 'index', 'matrix', 'string', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/typeOf.js +var typeOfDocs = { + name: 'typeOf', + category: 'Utils', + syntax: ['typeOf(x)'], + description: 'Get the type of a variable.', + examples: ['typeOf(3.5)', 'typeOf(2 - 4i)', 'typeOf(45 deg)', 'typeOf("hello world")'], + seealso: ['getMatrixDataType'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isZero.js +var isZeroDocs = { + name: 'isZero', + category: 'Utils', + syntax: ['isZero(x)'], + description: 'Test whether a value is zero.', + examples: ['isZero(2)', 'isZero(0)', 'isZero(-4)', 'isZero([3, 0, -2, 0])'], + seealso: ['isInteger', 'isNumeric', 'isNegative', 'isPositive'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isPrime.js +var isPrimeDocs = { + name: 'isPrime', + category: 'Utils', + syntax: ['isPrime(x)'], + description: 'Test whether a value is prime: has no divisors other than itself and one.', + examples: ['isPrime(3)', 'isPrime(-2)', 'isPrime([2, 17, 100])'], + seealso: ['isInteger', 'isNumeric', 'isNegative', 'isZero'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isPositive.js +var isPositiveDocs = { + name: 'isPositive', + category: 'Utils', + syntax: ['isPositive(x)'], + description: 'Test whether a value is positive: larger than zero.', + examples: ['isPositive(2)', 'isPositive(0)', 'isPositive(-4)', 'isPositive([3, 0.5, -2])'], + seealso: ['isInteger', 'isNumeric', 'isNegative', 'isZero'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isNumeric.js +var isNumericDocs = { + name: 'isNumeric', + category: 'Utils', + syntax: ['isNumeric(x)'], + description: 'Test whether a value is a numeric value. ' + 'Returns true when the input is a number, BigNumber, Fraction, or boolean.', + examples: ['isNumeric(2)', 'isNumeric("2")', 'hasNumericValue("2")', 'isNumeric(0)', 'isNumeric(bignumber(500))', 'isNumeric(fraction(0.125))', 'isNumeric(2 + 3i)', 'isNumeric([2.3, "foo", false])'], + seealso: ['isInteger', 'isZero', 'isNegative', 'isPositive', 'isNaN', 'hasNumericValue'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/hasNumericValue.js +var hasNumericValueDocs = { + name: 'hasNumericValue', + category: 'Utils', + syntax: ['hasNumericValue(x)'], + description: 'Test whether a value is an numeric value. ' + 'In case of a string, true is returned if the string contains a numeric value.', + examples: ['hasNumericValue(2)', 'hasNumericValue("2")', 'isNumeric("2")', 'hasNumericValue(0)', 'hasNumericValue(bignumber(500))', 'hasNumericValue(fraction(0.125))', 'hasNumericValue(2 + 3i)', 'hasNumericValue([2.3, "foo", false])'], + seealso: ['isInteger', 'isZero', 'isNegative', 'isPositive', 'isNaN', 'isNumeric'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isNegative.js +var isNegativeDocs = { + name: 'isNegative', + category: 'Utils', + syntax: ['isNegative(x)'], + description: 'Test whether a value is negative: smaller than zero.', + examples: ['isNegative(2)', 'isNegative(0)', 'isNegative(-4)', 'isNegative([3, 0.5, -2])'], + seealso: ['isInteger', 'isNumeric', 'isPositive', 'isZero'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isInteger.js +var isIntegerDocs = { + name: 'isInteger', + category: 'Utils', + syntax: ['isInteger(x)'], + description: 'Test whether a value is an integer number.', + examples: ['isInteger(2)', 'isInteger(3.5)', 'isInteger([3, 0.5, -2])'], + seealso: ['isNegative', 'isNumeric', 'isPositive', 'isZero'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isNaN.js +var isNaNDocs = { + name: 'isNaN', + category: 'Utils', + syntax: ['isNaN(x)'], + description: 'Test whether a value is NaN (not a number)', + examples: ['isNaN(2)', 'isNaN(0 / 0)', 'isNaN(NaN)', 'isNaN(Infinity)'], + seealso: ['isNegative', 'isNumeric', 'isPositive', 'isZero'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/format.js +var formatDocs = { + name: 'format', + category: 'Utils', + syntax: ['format(value)', 'format(value, precision)'], + description: 'Format a value of any type as string.', + examples: ['format(2.3)', 'format(3 - 4i)', 'format([])', 'format(pi, 3)'], + seealso: ['print'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/clone.js +var cloneDocs = { + name: 'clone', + category: 'Utils', + syntax: ['clone(x)'], + description: 'Clone a variable. Creates a copy of primitive variables,and a deep copy of matrices', + examples: ['clone(3.5)', 'clone(2 - 4i)', 'clone(45 deg)', 'clone([1, 2; 3, 4])', 'clone("hello world")'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/units/to.js +var toDocs = { + name: 'to', + category: 'Units', + syntax: ['x to unit', 'to(x, unit)'], + description: 'Change the unit of a value.', + examples: ['5 inch to cm', '3.2kg to g', '16 bytes in bits'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/tanh.js +var tanhDocs = { + name: 'tanh', + category: 'Trigonometry', + syntax: ['tanh(x)'], + description: 'Compute the hyperbolic tangent of x in radians.', + examples: ['tanh(0.5)', 'sinh(0.5) / cosh(0.5)'], + seealso: ['sinh', 'cosh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/tan.js +var tanDocs = { + name: 'tan', + category: 'Trigonometry', + syntax: ['tan(x)'], + description: 'Compute the tangent of x in radians.', + examples: ['tan(0.5)', 'sin(0.5) / cos(0.5)', 'tan(pi / 4)', 'tan(45 deg)'], + seealso: ['atan', 'sin', 'cos'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/sinh.js +var sinhDocs = { + name: 'sinh', + category: 'Trigonometry', + syntax: ['sinh(x)'], + description: 'Compute the hyperbolic sine of x in radians.', + examples: ['sinh(0.5)'], + seealso: ['cosh', 'tanh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/sech.js +var sechDocs = { + name: 'sech', + category: 'Trigonometry', + syntax: ['sech(x)'], + description: 'Compute the hyperbolic secant of x in radians. Defined as 1/cosh(x)', + examples: ['sech(2)', '1 / cosh(2)'], + seealso: ['coth', 'csch', 'cosh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/sec.js +var secDocs = { + name: 'sec', + category: 'Trigonometry', + syntax: ['sec(x)'], + description: 'Compute the secant of x in radians. Defined as 1/cos(x)', + examples: ['sec(2)', '1 / cos(2)'], + seealso: ['cot', 'csc', 'cos'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/csch.js +var cschDocs = { + name: 'csch', + category: 'Trigonometry', + syntax: ['csch(x)'], + description: 'Compute the hyperbolic cosecant of x in radians. Defined as 1/sinh(x)', + examples: ['csch(2)', '1 / sinh(2)'], + seealso: ['sech', 'coth', 'sinh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/csc.js +var cscDocs = { + name: 'csc', + category: 'Trigonometry', + syntax: ['csc(x)'], + description: 'Compute the cosecant of x in radians. Defined as 1/sin(x)', + examples: ['csc(2)', '1 / sin(2)'], + seealso: ['sec', 'cot', 'sin'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/coth.js +var cothDocs = { + name: 'coth', + category: 'Trigonometry', + syntax: ['coth(x)'], + description: 'Compute the hyperbolic cotangent of x in radians.', + examples: ['coth(2)', '1 / tanh(2)'], + seealso: ['sech', 'csch', 'tanh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/cot.js +var cotDocs = { + name: 'cot', + category: 'Trigonometry', + syntax: ['cot(x)'], + description: 'Compute the cotangent of x in radians. Defined as 1/tan(x)', + examples: ['cot(2)', '1 / tan(2)'], + seealso: ['sec', 'csc', 'tan'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/cosh.js +var coshDocs = { + name: 'cosh', + category: 'Trigonometry', + syntax: ['cosh(x)'], + description: 'Compute the hyperbolic cosine of x in radians.', + examples: ['cosh(0.5)'], + seealso: ['sinh', 'tanh', 'coth'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/cos.js +var cosDocs = { + name: 'cos', + category: 'Trigonometry', + syntax: ['cos(x)'], + description: 'Compute the cosine of x in radians.', + examples: ['cos(2)', 'cos(pi / 4) ^ 2', 'cos(180 deg)', 'cos(60 deg)', 'sin(0.2)^2 + cos(0.2)^2'], + seealso: ['acos', 'sin', 'tan'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/atan2.js +var atan2Docs = { + name: 'atan2', + category: 'Trigonometry', + syntax: ['atan2(y, x)'], + description: 'Computes the principal value of the arc tangent of y/x in radians.', + examples: ['atan2(2, 2) / pi', 'angle = 60 deg in rad', 'x = cos(angle)', 'y = sin(angle)', 'atan2(y, x)'], + seealso: ['sin', 'cos', 'tan'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/atanh.js +var atanhDocs = { + name: 'atanh', + category: 'Trigonometry', + syntax: ['atanh(x)'], + description: 'Calculate the hyperbolic arctangent of a value, defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.', + examples: ['atanh(0.5)'], + seealso: ['acosh', 'asinh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/atan.js +var atanDocs = { + name: 'atan', + category: 'Trigonometry', + syntax: ['atan(x)'], + description: 'Compute the inverse tangent of a value in radians.', + examples: ['atan(0.5)', 'atan(tan(0.5))'], + seealso: ['tan', 'acos', 'asin'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/asinh.js +var asinhDocs = { + name: 'asinh', + category: 'Trigonometry', + syntax: ['asinh(x)'], + description: 'Calculate the hyperbolic arcsine of a value, defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.', + examples: ['asinh(0.5)'], + seealso: ['acosh', 'atanh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/asin.js +var asinDocs = { + name: 'asin', + category: 'Trigonometry', + syntax: ['asin(x)'], + description: 'Compute the inverse sine of a value in radians.', + examples: ['asin(0.5)', 'asin(sin(0.5))'], + seealso: ['sin', 'acos', 'atan'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/asech.js +var asechDocs = { + name: 'asech', + category: 'Trigonometry', + syntax: ['asech(x)'], + description: 'Calculate the inverse secant of a value.', + examples: ['asech(0.5)'], + seealso: ['acsch', 'acoth'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/asec.js +var asecDocs = { + name: 'asec', + category: 'Trigonometry', + syntax: ['asec(x)'], + description: 'Calculate the inverse secant of a value.', + examples: ['asec(0.5)', 'asec(sec(0.5))', 'asec(2)'], + seealso: ['acos', 'acot', 'acsc'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acsch.js +var acschDocs = { + name: 'acsch', + category: 'Trigonometry', + syntax: ['acsch(x)'], + description: 'Calculate the hyperbolic arccosecant of a value, defined as `acsch(x) = ln(1/x + sqrt(1/x^2 + 1))`.', + examples: ['acsch(0.5)'], + seealso: ['asech', 'acoth'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acsc.js +var acscDocs = { + name: 'acsc', + category: 'Trigonometry', + syntax: ['acsc(x)'], + description: 'Calculate the inverse cotangent of a value.', + examples: ['acsc(2)', 'acsc(csc(0.5))', 'acsc(0.5)'], + seealso: ['csc', 'asin', 'asec'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acoth.js +var acothDocs = { + name: 'acoth', + category: 'Trigonometry', + syntax: ['acoth(x)'], + description: 'Calculate the hyperbolic arccotangent of a value, defined as `acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.', + examples: ['acoth(2)', 'acoth(0.5)'], + seealso: ['acsch', 'asech'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acot.js +var acotDocs = { + name: 'acot', + category: 'Trigonometry', + syntax: ['acot(x)'], + description: 'Calculate the inverse cotangent of a value.', + examples: ['acot(0.5)', 'acot(cot(0.5))', 'acot(2)'], + seealso: ['cot', 'atan'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acosh.js +var acoshDocs = { + name: 'acosh', + category: 'Trigonometry', + syntax: ['acosh(x)'], + description: 'Calculate the hyperbolic arccos of a value, defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.', + examples: ['acosh(1.5)'], + seealso: ['cosh', 'asinh', 'atanh'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acos.js +var acosDocs = { + name: 'acos', + category: 'Trigonometry', + syntax: ['acos(x)'], + description: 'Compute the inverse cosine of a value in radians.', + examples: ['acos(0.5)', 'acos(cos(2.3))'], + seealso: ['cos', 'atan', 'asin'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/sum.js +var sumDocs = { + name: 'sum', + category: 'Statistics', + syntax: ['sum(a, b, c, ...)', 'sum(A)'], + description: 'Compute the sum of all values.', + examples: ['sum(2, 3, 4, 1)', 'sum([2, 3, 4, 1])', 'sum([2, 5; 4, 3])'], + seealso: ['max', 'mean', 'median', 'min', 'prod', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/std.js +var stdDocs = { + name: 'std', + category: 'Statistics', + syntax: ['std(a, b, c, ...)', 'std(A)', 'std(A, normalization)'], + description: 'Compute the standard deviation of all values, defined as std(A) = sqrt(variance(A)). Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".', + examples: ['std(2, 4, 6)', 'std([2, 4, 6, 8])', 'std([2, 4, 6, 8], "uncorrected")', 'std([2, 4, 6, 8], "biased")', 'std([1, 2, 3; 4, 5, 6])'], + seealso: ['max', 'mean', 'min', 'median', 'prod', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/quantileSeq.js +var quantileSeqDocs = { + name: 'quantileSeq', + category: 'Statistics', + syntax: ['quantileSeq(A, prob[, sorted])', 'quantileSeq(A, [prob1, prob2, ...][, sorted])', 'quantileSeq(A, N[, sorted])'], + description: 'Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. Supported types of sequence values are: Number, BigNumber, Unit Supported types of probablity are: Number, BigNumber. \n\nIn case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated.', + examples: ['quantileSeq([3, -1, 5, 7], 0.5)', 'quantileSeq([3, -1, 5, 7], [1/3, 2/3])', 'quantileSeq([3, -1, 5, 7], 2)', 'quantileSeq([-1, 3, 5, 7], 0.5, true)'], + seealso: ['mean', 'median', 'min', 'max', 'prod', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/prod.js +var prodDocs = { + name: 'prod', + category: 'Statistics', + syntax: ['prod(a, b, c, ...)', 'prod(A)'], + description: 'Compute the product of all values.', + examples: ['prod(2, 3, 4)', 'prod([2, 3, 4])', 'prod([2, 5; 4, 3])'], + seealso: ['max', 'mean', 'min', 'median', 'min', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/mode.js +var modeDocs = { + name: 'mode', + category: 'Statistics', + syntax: ['mode(a, b, c, ...)', 'mode(A)', 'mode(A, a, b, B, c, ...)'], + description: 'Computes the mode of all values as an array. In case mode being more than one, multiple values are returned in an array.', + examples: ['mode(2, 1, 4, 3, 1)', 'mode([1, 2.7, 3.2, 4, 2.7])', 'mode(1, 4, 6, 1, 6)'], + seealso: ['max', 'mean', 'min', 'median', 'prod', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/min.js +var minDocs = { + name: 'min', + category: 'Statistics', + syntax: ['min(a, b, c, ...)', 'min(A)', 'min(A, dim)'], + description: 'Compute the minimum value of a list of values.', + examples: ['min(2, 3, 4, 1)', 'min([2, 3, 4, 1])', 'min([2, 5; 4, 3])', 'min([2, 5; 4, 3], 1)', 'min([2, 5; 4, 3], 2)', 'min(2.7, 7.1, -4.5, 2.0, 4.1)', 'max(2.7, 7.1, -4.5, 2.0, 4.1)'], + seealso: ['max', 'mean', 'median', 'prod', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/median.js +var medianDocs = { + name: 'median', + category: 'Statistics', + syntax: ['median(a, b, c, ...)', 'median(A)'], + description: 'Compute the median of all values. The values are sorted and the middle value is returned. In case of an even number of values, the average of the two middle values is returned.', + examples: ['median(5, 2, 7)', 'median([3, -1, 5, 7])'], + seealso: ['max', 'mean', 'min', 'prod', 'std', 'sum', 'variance', 'quantileSeq'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/mean.js +var meanDocs = { + name: 'mean', + category: 'Statistics', + syntax: ['mean(a, b, c, ...)', 'mean(A)', 'mean(A, dim)'], + description: 'Compute the arithmetic mean of a list of values.', + examples: ['mean(2, 3, 4, 1)', 'mean([2, 3, 4, 1])', 'mean([2, 5; 4, 3])', 'mean([2, 5; 4, 3], 1)', 'mean([2, 5; 4, 3], 2)', 'mean([1.0, 2.7, 3.2, 4.0])'], + seealso: ['max', 'median', 'min', 'prod', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/max.js +var maxDocs = { + name: 'max', + category: 'Statistics', + syntax: ['max(a, b, c, ...)', 'max(A)', 'max(A, dim)'], + description: 'Compute the maximum value of a list of values.', + examples: ['max(2, 3, 4, 1)', 'max([2, 3, 4, 1])', 'max([2, 5; 4, 3])', 'max([2, 5; 4, 3], 1)', 'max([2, 5; 4, 3], 2)', 'max(2.7, 7.1, -4.5, 2.0, 4.1)', 'min(2.7, 7.1, -4.5, 2.0, 4.1)'], + seealso: ['mean', 'median', 'min', 'prod', 'std', 'sum', 'variance'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/mad.js +var madDocs = { + name: 'mad', + category: 'Statistics', + syntax: ['mad(a, b, c, ...)', 'mad(A)'], + description: 'Compute the median absolute deviation of a matrix or a list with values. The median absolute deviation is defined as the median of the absolute deviations from the median.', + examples: ['mad(10, 20, 30)', 'mad([1, 2, 3])'], + seealso: ['mean', 'median', 'std', 'abs'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/special/erf.js +var erfDocs = { + name: 'erf', + category: 'Special', + syntax: ['erf(x)'], + description: 'Compute the erf function of a value using a rational Chebyshev approximations for different intervals of x', + examples: ['erf(0.2)', 'erf(-0.5)', 'erf(4)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setUnion.js +var setUnionDocs = { + name: 'setUnion', + category: 'Set', + syntax: ['setUnion(set1, set2)'], + description: 'Create the union of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.', + examples: ['setUnion([1, 2, 3, 4], [3, 4, 5, 6])', 'setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]])'], + seealso: ['setIntersect', 'setDifference'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setSymDifference.js +var setSymDifferenceDocs = { + name: 'setSymDifference', + category: 'Set', + syntax: ['setSymDifference(set1, set2)'], + description: 'Create the symmetric difference of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.', + examples: ['setSymDifference([1, 2, 3, 4], [3, 4, 5, 6])', 'setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])'], + seealso: ['setUnion', 'setIntersect', 'setDifference'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setSize.js +var setSizeDocs = { + name: 'setSize', + category: 'Set', + syntax: ['setSize(set)', 'setSize(set, unique)'], + description: 'Count the number of elements of a (multi)set. When the second parameter "unique" is true, count only the unique values. A multi-dimension array will be converted to a single-dimension array before the operation.', + examples: ['setSize([1, 2, 2, 4])', 'setSize([1, 2, 2, 4], true)'], + seealso: ['setUnion', 'setIntersect', 'setDifference'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setPowerset.js +var setPowersetDocs = { + name: 'setPowerset', + category: 'Set', + syntax: ['setPowerset(set)'], + description: 'Create the powerset of a (multi)set: the powerset contains very possible subsets of a (multi)set. A multi-dimension array will be converted to a single-dimension array before the operation.', + examples: ['setPowerset([1, 2, 3])'], + seealso: ['setCartesian'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setMultiplicity.js +var setMultiplicityDocs = { + name: 'setMultiplicity', + category: 'Set', + syntax: ['setMultiplicity(element, set)'], + description: 'Count the multiplicity of an element in a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.', + examples: ['setMultiplicity(1, [1, 2, 2, 4])', 'setMultiplicity(2, [1, 2, 2, 4])'], + seealso: ['setDistinct', 'setSize'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setIsSubset.js +var setIsSubsetDocs = { + name: 'setIsSubset', + category: 'Set', + syntax: ['setIsSubset(set1, set2)'], + description: 'Check whether a (multi)set is a subset of another (multi)set: every element of set1 is the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.', + examples: ['setIsSubset([1, 2], [3, 4, 5, 6])', 'setIsSubset([3, 4], [3, 4, 5, 6])'], + seealso: ['setUnion', 'setIntersect', 'setDifference'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setIntersect.js +var setIntersectDocs = { + name: 'setIntersect', + category: 'Set', + syntax: ['setIntersect(set1, set2)'], + description: 'Create the intersection of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.', + examples: ['setIntersect([1, 2, 3, 4], [3, 4, 5, 6])', 'setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]])'], + seealso: ['setUnion', 'setDifference'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setDistinct.js +var setDistinctDocs = { + name: 'setDistinct', + category: 'Set', + syntax: ['setDistinct(set)'], + description: 'Collect the distinct elements of a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.', + examples: ['setDistinct([1, 1, 1, 2, 2, 3])'], + seealso: ['setMultiplicity'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setDifference.js +var setDifferenceDocs = { + name: 'setDifference', + category: 'Set', + syntax: ['setDifference(set1, set2)'], + description: 'Create the difference of two (multi)sets: every element of set1, that is not the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.', + examples: ['setDifference([1, 2, 3, 4], [3, 4, 5, 6])', 'setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])'], + seealso: ['setUnion', 'setIntersect', 'setSymDifference'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setCartesian.js +var setCartesianDocs = { + name: 'setCartesian', + category: 'Set', + syntax: ['setCartesian(set1, set2)'], + description: 'Create the cartesian product of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.', + examples: ['setCartesian([1, 2], [3, 4])'], + seealso: ['setUnion', 'setIntersect', 'setDifference', 'setPowerset'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/unequal.js +var unequalDocs = { + name: 'unequal', + category: 'Relational', + syntax: ['x != y', 'unequal(x, y)'], + description: 'Check unequality of two values. Returns true if the values are unequal, and false if they are equal.', + examples: ['2+2 != 3', '2+2 != 4', 'a = 3.2', 'b = 6-2.8', 'a != b', '50cm != 0.5m', '5 cm != 2 inch'], + seealso: ['equal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare', 'deepEqual'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/smallerEq.js +var smallerEqDocs = { + name: 'smallerEq', + category: 'Relational', + syntax: ['x <= y', 'smallerEq(x, y)'], + description: 'Check if value x is smaller or equal to value y. Returns true if x is smaller than y, and false if not.', + examples: ['2 <= 1+1', '2 < 1+1', 'a = 3.2', 'b = 6-2.8', '(a <= b)'], + seealso: ['equal', 'unequal', 'larger', 'smaller', 'largerEq', 'compare'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/smaller.js +var smallerDocs = { + name: 'smaller', + category: 'Relational', + syntax: ['x < y', 'smaller(x, y)'], + description: 'Check if value x is smaller than value y. Returns true if x is smaller than y, and false if not.', + examples: ['2 < 3', '5 < 2*2', 'a = 3.3', 'b = 6-2.8', '(a < b)', '5 cm < 2 inch'], + seealso: ['equal', 'unequal', 'larger', 'smallerEq', 'largerEq', 'compare'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/largerEq.js +var largerEqDocs = { + name: 'largerEq', + category: 'Relational', + syntax: ['x >= y', 'largerEq(x, y)'], + description: 'Check if value x is larger or equal to y. Returns true if x is larger or equal to y, and false if not.', + examples: ['2 >= 1+1', '2 > 1+1', 'a = 3.2', 'b = 6-2.8', '(a >= b)'], + seealso: ['equal', 'unequal', 'smallerEq', 'smaller', 'compare'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/larger.js +var largerDocs = { + name: 'larger', + category: 'Relational', + syntax: ['x > y', 'larger(x, y)'], + description: 'Check if value x is larger than y. Returns true if x is larger than y, and false if not.', + examples: ['2 > 3', '5 > 2*2', 'a = 3.3', 'b = 6-2.8', '(a > b)', '(b < a)', '5 cm > 2 inch'], + seealso: ['equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compare'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/equalText.js +var equalTextDocs = { + name: 'equalText', + category: 'Relational', + syntax: ['equalText(x, y)'], + description: 'Check equality of two strings. Comparison is case sensitive. Returns true if the values are equal, and false if not.', + examples: ['equalText("Hello", "Hello")', 'equalText("a", "A")', 'equal("2e3", "2000")', 'equalText("2e3", "2000")', 'equalText("B", ["A", "B", "C"])'], + seealso: ['compare', 'compareNatural', 'compareText', 'equal'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/equal.js +var equalDocs = { + name: 'equal', + category: 'Relational', + syntax: ['x == y', 'equal(x, y)'], + description: 'Check equality of two values. Returns true if the values are equal, and false if not.', + examples: ['2+2 == 3', '2+2 == 4', 'a = 3.2', 'b = 6-2.8', 'a == b', '50cm == 0.5m'], + seealso: ['unequal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare', 'deepEqual', 'equalText'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/deepEqual.js +var deepEqualDocs = { + name: 'deepEqual', + category: 'Relational', + syntax: ['deepEqual(x, y)'], + description: 'Check equality of two matrices element wise. Returns true if the size of both matrices is equal and when and each of the elements are equal.', + examples: ['deepEqual([1,3,4], [1,3,4])', 'deepEqual([1,3,4], [1,3])'], + seealso: ['equal', 'unequal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/compareText.js +var compareTextDocs = { + name: 'compareText', + category: 'Relational', + syntax: ['compareText(x, y)'], + description: 'Compare two strings lexically. Comparison is case sensitive. ' + 'Returns 1 when x > y, -1 when x < y, and 0 when x == y.', + examples: ['compareText("B", "A")', 'compareText("A", "B")', 'compareText("A", "A")', 'compareText("2", "10")', 'compare("2", "10")', 'compare(2, 10)', 'compareNatural("2", "10")', 'compareText("B", ["A", "B", "C"])'], + seealso: ['compare', 'compareNatural'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/compareNatural.js +var compareNaturalDocs = { + name: 'compareNatural', + category: 'Relational', + syntax: ['compareNatural(x, y)'], + description: 'Compare two values of any type in a deterministic, natural way. ' + 'Returns 1 when x > y, -1 when x < y, and 0 when x == y.', + examples: ['compareNatural(2, 3)', 'compareNatural(3, 2)', 'compareNatural(2, 2)', 'compareNatural(5cm, 40mm)', 'compareNatural("2", "10")', 'compareNatural(2 + 3i, 2 + 4i)', 'compareNatural([1, 2, 4], [1, 2, 3])', 'compareNatural([1, 5], [1, 2, 3])', 'compareNatural([1, 2], [1, 2])', 'compareNatural({a: 2}, {a: 4})'], + seealso: ['equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compare', 'compareText'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/compare.js +var compareDocs = { + name: 'compare', + category: 'Relational', + syntax: ['compare(x, y)'], + description: 'Compare two values. ' + 'Returns 1 when x > y, -1 when x < y, and 0 when x == y.', + examples: ['compare(2, 3)', 'compare(3, 2)', 'compare(2, 2)', 'compare(5cm, 40mm)', 'compare(2, [1, 2, 3])'], + seealso: ['equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compareNatural', 'compareText'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/randomInt.js +var randomIntDocs = { + name: 'randomInt', + category: 'Probability', + syntax: ['randomInt(max)', 'randomInt(min, max)', 'randomInt(size)', 'randomInt(size, max)', 'randomInt(size, min, max)'], + description: 'Return a random integer number', + examples: ['randomInt(10, 20)', 'randomInt([2, 3], 10)'], + seealso: ['pickRandom', 'random'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/random.js +var randomDocs = { + name: 'random', + category: 'Probability', + syntax: ['random()', 'random(max)', 'random(min, max)', 'random(size)', 'random(size, max)', 'random(size, min, max)'], + description: 'Return a random number.', + examples: ['random()', 'random(10, 20)', 'random([2, 3])'], + seealso: ['pickRandom', 'randomInt'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/pickRandom.js +var pickRandomDocs = { + name: 'pickRandom', + category: 'Probability', + syntax: ['pickRandom(array)', 'pickRandom(array, number)', 'pickRandom(array, weights)', 'pickRandom(array, number, weights)', 'pickRandom(array, weights, number)'], + description: 'Pick a random entry from a given array.', + examples: ['pickRandom(0:10)', 'pickRandom([1, 3, 1, 6])', 'pickRandom([1, 3, 1, 6], 2)', 'pickRandom([1, 3, 1, 6], [2, 3, 2, 1])', 'pickRandom([1, 3, 1, 6], 2, [2, 3, 2, 1])', 'pickRandom([1, 3, 1, 6], [2, 3, 2, 1], 2)'], + seealso: ['random', 'randomInt'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/permutations.js +var permutationsDocs = { + name: 'permutations', + category: 'Probability', + syntax: ['permutations(n)', 'permutations(n, k)'], + description: 'Compute the number of permutations of n items taken k at a time', + examples: ['permutations(5)', 'permutations(5, 3)'], + seealso: ['combinations', 'combinationsWithRep', 'factorial'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/multinomial.js +var multinomialDocs = { + name: 'multinomial', + category: 'Probability', + syntax: ['multinomial(A)'], + description: 'Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities. multinomial takes one array of integers as an argument. The following condition must be enforced: every ai > 0.', + examples: ['multinomial([1, 2, 1])'], + seealso: ['combinations', 'factorial'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/kldivergence.js +var kldivergenceDocs = { + name: 'kldivergence', + category: 'Probability', + syntax: ['kldivergence(x, y)'], + description: 'Calculate the Kullback-Leibler (KL) divergence between two distributions.', + examples: ['kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5])'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/gamma.js +var gammaDocs = { + name: 'gamma', + category: 'Probability', + syntax: ['gamma(n)'], + description: 'Compute the gamma function. For small values, the Lanczos approximation is used, and for large values the extended Stirling approximation.', + examples: ['gamma(4)', '3!', 'gamma(1/2)', 'sqrt(pi)'], + seealso: ['factorial'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/factorial.js +var factorialDocs = { + name: 'factorial', + category: 'Probability', + syntax: ['n!', 'factorial(n)'], + description: 'Compute the factorial of a value', + examples: ['5!', '5 * 4 * 3 * 2 * 1', '3!'], + seealso: ['combinations', 'combinationsWithRep', 'permutations', 'gamma'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/combinations.js +var combinationsDocs = { + name: 'combinations', + category: 'Probability', + syntax: ['combinations(n, k)'], + description: 'Compute the number of combinations of n items taken k at a time', + examples: ['combinations(7, 5)'], + seealso: ['combinationsWithRep', 'permutations', 'factorial'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/combinationsWithRep.js +var combinationsWithRepDocs = { + name: 'combinationsWithRep', + category: 'Probability', + syntax: ['combinationsWithRep(n, k)'], + description: 'Compute the number of combinations of n items taken k at a time with replacements.', + examples: ['combinationsWithRep(7, 5)'], + seealso: ['combinations', 'permutations', 'factorial'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/zeros.js +var zerosDocs = { + name: 'zeros', + category: 'Matrix', + syntax: ['zeros(m)', 'zeros(m, n)', 'zeros(m, n, p, ...)', 'zeros([m])', 'zeros([m, n])', 'zeros([m, n, p, ...])'], + description: 'Create a matrix containing zeros.', + examples: ['zeros(3)', 'zeros(3, 5)', 'a = [1, 2, 3; 4, 5, 6]', 'zeros(size(a))'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/transpose.js +var transposeDocs = { + name: 'transpose', + category: 'Matrix', + syntax: ['x\'', 'transpose(x)'], + description: 'Transpose a matrix', + examples: ['a = [1, 2, 3; 4, 5, 6]', 'a\'', 'transpose(a)'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/trace.js +var traceDocs = { + name: 'trace', + category: 'Matrix', + syntax: ['trace(A)'], + description: 'Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.', + examples: ['A = [1, 2, 3; -1, 2, 3; 2, 0, 3]', 'trace(A)'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/subset.js +var subsetDocs = { + name: 'subset', + category: 'Matrix', + syntax: ['value(index)', 'value(index) = replacement', 'subset(value, [index])', 'subset(value, [index], replacement)'], + description: 'Get or set a subset of a matrix or string. ' + 'Indexes are one-based. ' + 'Both the ranges lower-bound and upper-bound are included.', + examples: ['d = [1, 2; 3, 4]', 'e = []', 'e[1, 1:2] = [5, 6]', 'e[2, :] = [7, 8]', 'f = d * e', 'f[2, 1]', 'f[:, 1]'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/squeeze.js +var squeezeDocs = { + name: 'squeeze', + category: 'Matrix', + syntax: ['squeeze(x)'], + description: 'Remove inner and outer singleton dimensions from a matrix.', + examples: ['a = zeros(3,2,1)', 'size(squeeze(a))', 'b = zeros(1,1,3)', 'size(squeeze(b))'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/sort.js +var sortDocs = { + name: 'sort', + category: 'Matrix', + syntax: ['sort(x)', 'sort(x, compare)'], + description: 'Sort the items in a matrix. Compare can be a string "asc", "desc", "natural", or a custom sort function.', + examples: ['sort([5, 10, 1])', 'sort(["C", "B", "A", "D"])', 'sortByLength(a, b) = size(a)[1] - size(b)[1]', 'sort(["Langdon", "Tom", "Sara"], sortByLength)', 'sort(["10", "1", "2"], "natural")'], + seealso: ['map', 'filter', 'forEach'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/size.js +var sizeDocs = { + name: 'size', + category: 'Matrix', + syntax: ['size(x)'], + description: 'Calculate the size of a matrix.', + examples: ['size(2.3)', 'size("hello world")', 'a = [1, 2; 3, 4; 5, 6]', 'size(a)', 'size(1:6)'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/reshape.js +var reshapeDocs = { + name: 'reshape', + category: 'Matrix', + syntax: ['reshape(x, sizes)'], + description: 'Reshape a multi dimensional array to fit the specified dimensions.', + examples: ['reshape([1, 2, 3, 4, 5, 6], [2, 3])', 'reshape([[1, 2], [3, 4]], [1, 4])', 'reshape([[1, 2], [3, 4]], [4])'], + seealso: ['size', 'squeeze', 'resize'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/resize.js +var resizeDocs = { + name: 'resize', + category: 'Matrix', + syntax: ['resize(x, size)', 'resize(x, size, defaultValue)'], + description: 'Resize a matrix.', + examples: ['resize([1,2,3,4,5], [3])', 'resize([1,2,3], [5])', 'resize([1,2,3], [5], -1)', 'resize(2, [2, 3])', 'resize("hello", [8], "!")'], + seealso: ['size', 'subset', 'squeeze', 'reshape'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/range.js +var rangeDocs = { + name: 'range', + category: 'Type', + syntax: ['start:end', 'start:step:end', 'range(start, end)', 'range(start, end, step)', 'range(string)'], + description: 'Create a range. Lower bound of the range is included, upper bound is excluded.', + examples: ['1:5', '3:-1:-3', 'range(3, 7)', 'range(0, 12, 2)', 'range("4:10")', 'a = [1, 2, 3, 4; 5, 6, 7, 8]', 'a[1:2, 1:2]'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/partitionSelect.js +var partitionSelectDocs = { + name: 'partitionSelect', + category: 'Matrix', + syntax: ['partitionSelect(x, k)', 'partitionSelect(x, k, compare)'], + description: 'Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect.', + examples: ['partitionSelect([5, 10, 1], 2)', 'partitionSelect(["C", "B", "A", "D"], 1)'], + seealso: ['sort'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/ones.js +var onesDocs = { + name: 'ones', + category: 'Matrix', + syntax: ['ones(m)', 'ones(m, n)', 'ones(m, n, p, ...)', 'ones([m])', 'ones([m, n])', 'ones([m, n, p, ...])'], + description: 'Create a matrix containing ones.', + examples: ['ones(3)', 'ones(3, 5)', 'ones([2,3]) * 4.5', 'a = [1, 2, 3; 4, 5, 6]', 'ones(size(a))'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/map.js +var mapDocs = { + name: 'map', + category: 'Matrix', + syntax: ['map(x, callback)'], + description: 'Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.', + examples: ['map([1, 2, 3], square)'], + seealso: ['filter', 'forEach'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/kron.js +var kronDocs = { + name: 'kron', + category: 'Matrix', + syntax: ['kron(x, y)'], + description: 'Calculates the kronecker product of 2 matrices or vectors.', + examples: ['kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])', 'kron([1,1], [2,3,4])'], + seealso: ['multiply', 'dot', 'cross'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/inv.js +var invDocs = { + name: 'inv', + category: 'Matrix', + syntax: ['inv(x)'], + description: 'Calculate the inverse of a matrix', + examples: ['inv([1, 2; 3, 4])', 'inv(4)', '1 / 4'], + seealso: ['concat', 'det', 'diag', 'identity', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/forEach.js +var forEachDocs = { + name: 'forEach', + category: 'Matrix', + syntax: ['forEach(x, callback)'], + description: 'Iterates over all elements of a matrix/array, and executes the given callback function.', + examples: ['forEach([1, 2, 3], function(val) { console.log(val) })'], + seealso: ['map', 'sort', 'filter'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/flatten.js +var flattenDocs = { + name: 'flatten', + category: 'Matrix', + syntax: ['flatten(x)'], + description: 'Flatten a multi dimensional matrix into a single dimensional matrix.', + examples: ['a = [1, 2, 3; 4, 5, 6]', 'size(a)', 'b = flatten(a)', 'size(b)'], + seealso: ['concat', 'resize', 'size', 'squeeze'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/filter.js +var filterDocs = { + name: 'filter', + category: 'Matrix', + syntax: ['filter(x, test)'], + description: 'Filter items in a matrix.', + examples: ['isPositive(x) = x > 0', 'filter([6, -2, -1, 4, 3], isPositive)', 'filter([6, -2, 0, 1, 0], x != 0)'], + seealso: ['sort', 'map', 'forEach'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/identity.js +var identityDocs = { + name: 'identity', + category: 'Matrix', + syntax: ['identity(n)', 'identity(m, n)', 'identity([m, n])'], + description: 'Returns the identity matrix with size m-by-n. The matrix has ones on the diagonal and zeros elsewhere.', + examples: ['identity(3)', 'identity(3, 5)', 'a = [1, 2, 3; 4, 5, 6]', 'identity(size(a))'], + seealso: ['concat', 'det', 'diag', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/getMatrixDataType.js +var getMatrixDataTypeDocs = { + name: 'getMatrixDataType', + category: 'Matrix', + syntax: ['getMatrixDataType(x)'], + description: 'Find the data type of all elements in a matrix or array, ' + 'for example "number" if all items are a number ' + 'and "Complex" if all values are complex numbers. ' + 'If a matrix contains more than one data type, it will return "mixed".', + examples: ['getMatrixDataType([1, 2, 3])', 'getMatrixDataType([[5 cm], [2 inch]])', 'getMatrixDataType([1, "text"])', 'getMatrixDataType([1, bignumber(4)])'], + seealso: ['matrix', 'sparse', 'typeOf'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/dot.js +var dotDocs = { + name: 'dot', + category: 'Matrix', + syntax: ['dot(A, B)', 'A * B'], + description: 'Calculate the dot product of two vectors. ' + 'The dot product of A = [a1, a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] ' + 'is defined as dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn', + examples: ['dot([2, 4, 1], [2, 2, 3])', '[2, 4, 1] * [2, 2, 3]'], + seealso: ['multiply', 'cross'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/diag.js +var diagDocs = { + name: 'diag', + category: 'Matrix', + syntax: ['diag(x)', 'diag(x, k)'], + description: 'Create a diagonal matrix or retrieve the diagonal of a matrix. When x is a vector, a matrix with the vector values on the diagonal will be returned. When x is a matrix, a vector with the diagonal values of the matrix is returned. When k is provided, the k-th diagonal will be filled in or retrieved, if k is positive, the values are placed on the super diagonal. When k is negative, the values are placed on the sub diagonal.', + examples: ['diag(1:3)', 'diag(1:3, 1)', 'a = [1, 2, 3; 4, 5, 6; 7, 8, 9]', 'diag(a)'], + seealso: ['concat', 'det', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/det.js +var detDocs = { + name: 'det', + category: 'Matrix', + syntax: ['det(x)'], + description: 'Calculate the determinant of a matrix', + examples: ['det([1, 2; 3, 4])', 'det([-2, 2, 3; -1, 1, 3; 2, 0, -1])'], + seealso: ['concat', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/ctranspose.js +var ctransposeDocs = { + name: 'ctranspose', + category: 'Matrix', + syntax: ['x\'', 'ctranspose(x)'], + description: 'Complex Conjugate and Transpose a matrix', + examples: ['a = [1, 2, 3; 4, 5, 6]', 'a\'', 'ctranspose(a)'], + seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/cross.js +var crossDocs = { + name: 'cross', + category: 'Matrix', + syntax: ['cross(A, B)'], + description: 'Calculate the cross product for two vectors in three dimensional space.', + examples: ['cross([1, 1, 0], [0, 1, 1])', 'cross([3, -3, 1], [4, 9, 2])', 'cross([2, 3, 4], [5, 6, 7])'], + seealso: ['multiply', 'dot'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/concat.js +var concatDocs = { + name: 'concat', + category: 'Matrix', + syntax: ['concat(A, B, C, ...)', 'concat(A, B, C, ..., dim)'], + description: 'Concatenate matrices. By default, the matrices are concatenated by the last dimension. The dimension on which to concatenate can be provided as last argument.', + examples: ['A = [1, 2; 5, 6]', 'B = [3, 4; 7, 8]', 'concat(A, B)', 'concat(A, B, 1)', 'concat(A, B, 2)'], + seealso: ['det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/logical/xor.js +var xorDocs = { + name: 'xor', + category: 'Logical', + syntax: ['x xor y', 'xor(x, y)'], + description: 'Logical exclusive or, xor. Test whether one and only one value is defined with a nonzero/nonempty value.', + examples: ['true xor false', 'false xor false', 'true xor true', '0 xor 4'], + seealso: ['not', 'and', 'or'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/logical/or.js +var orDocs = { + name: 'or', + category: 'Logical', + syntax: ['x or y', 'or(x, y)'], + description: 'Logical or. Test if at least one value is defined with a nonzero/nonempty value.', + examples: ['true or false', 'false or false', '0 or 4'], + seealso: ['not', 'and', 'xor'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/logical/not.js +var notDocs = { + name: 'not', + category: 'Logical', + syntax: ['not x', 'not(x)'], + description: 'Logical not. Flips the boolean value of given argument.', + examples: ['not true', 'not false', 'not 2', 'not 0'], + seealso: ['and', 'or', 'xor'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/logical/and.js +var andDocs = { + name: 'and', + category: 'Logical', + syntax: ['x and y', 'and(x, y)'], + description: 'Logical and. Test whether two values are both defined with a nonzero/nonempty value.', + examples: ['true and false', 'true and true', '2 and 4'], + seealso: ['not', 'or', 'xor'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/geometry/intersect.js +var intersectDocs = { + name: 'intersect', + category: 'Geometry', + syntax: ['intersect(expr1, expr2, expr3, expr4)', 'intersect(expr1, expr2, expr3)'], + description: 'Computes the intersection point of lines and/or planes.', + examples: ['intersect([0, 0], [10, 10], [10, 0], [0, 10])', 'intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6])'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/geometry/distance.js +var distanceDocs = { + name: 'distance', + category: 'Geometry', + syntax: ['distance([x1, y1], [x2, y2])', 'distance([[x1, y1], [x2, y2]])'], + description: 'Calculates the Euclidean distance between two points.', + examples: ['distance([0,0], [4,4])', 'distance([[0,0], [4,4]])'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/expression/help.js +var helpDocs = { + name: 'help', + category: 'Expression', + syntax: ['help(object)', 'help(string)'], + description: 'Display documentation on a function or data type.', + examples: ['help(sqrt)', 'help("complex")'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/expression/evaluate.js +var evaluateDocs = { + name: 'evaluate', + category: 'Expression', + syntax: ['evaluate(expression)', 'evaluate([expr1, expr2, expr3, ...])'], + description: 'Evaluate an expression or an array with expressions.', + examples: ['evaluate("2 + 3")', 'evaluate("sqrt(" + 4 + ")")'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/complex/im.js +var imDocs = { + name: 'im', + category: 'Complex', + syntax: ['im(x)'], + description: 'Get the imaginary part of a complex number.', + examples: ['im(2 + 3i)', 're(2 + 3i)', 'im(-5.2i)', 'im(2.4)'], + seealso: ['re', 'conj', 'abs', 'arg'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/complex/re.js +var reDocs = { + name: 're', + category: 'Complex', + syntax: ['re(x)'], + description: 'Get the real part of a complex number.', + examples: ['re(2 + 3i)', 'im(2 + 3i)', 're(-5.2i)', 're(2.4)'], + seealso: ['im', 'conj', 'abs', 'arg'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/complex/conj.js +var conjDocs = { + name: 'conj', + category: 'Complex', + syntax: ['conj(x)'], + description: 'Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate is a-bi.', + examples: ['conj(2 + 3i)', 'conj(2 - 3i)', 'conj(-5.2i)'], + seealso: ['re', 'im', 'abs', 'arg'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/complex/arg.js +var argDocs = { + name: 'arg', + category: 'Complex', + syntax: ['arg(x)'], + description: 'Compute the argument of a complex value. If x = a+bi, the argument is computed as atan2(b, a).', + examples: ['arg(2 + 2i)', 'atan2(3, 2)', 'arg(2 + 3i)'], + seealso: ['re', 'im', 'conj', 'abs'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/core/typed.js +var typedDocs = { + name: 'typed', + category: 'Core', + syntax: ['typed(signatures)', 'typed(name, signatures)'], + description: 'Create a typed function.', + examples: ['double = typed({ "number, number": f(x)=x+x })', 'double(2)', 'double("hello")'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/core/import.js +var importDocs = { + name: 'import', + category: 'Core', + syntax: ['import(functions)', 'import(functions, options)'], + description: 'Import functions or constants from an object.', + examples: ['import({myFn: f(x)=x^2, myConstant: 32 })', 'myFn(2)', 'myConstant'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/core/config.js +var configDocs = { + name: 'config', + category: 'Core', + syntax: ['config()', 'config(options)'], + description: 'Get configuration or change configuration.', + examples: ['config()', '1/3 + 1/4', 'config({number: "Fraction"})', '1/3 + 1/4'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/combinatorics/stirlingS2.js +var stirlingS2Docs = { + name: 'stirlingS2', + category: 'Combinatorics', + syntax: ['stirlingS2(n, k)'], + description: 'he Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. `stirlingS2` only takes integer arguments. The following condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = 1.', + examples: ['stirlingS2(5, 3)'], + seealso: ['bellNumbers'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/combinatorics/composition.js +var compositionDocs = { + name: 'composition', + category: 'Combinatorics', + syntax: ['composition(n, k)'], + description: 'The composition counts of n into k parts. composition only takes integer arguments. The following condition must be enforced: k <= n.', + examples: ['composition(5, 3)'], + seealso: ['combinations'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/combinatorics/catalan.js +var catalanDocs = { + name: 'catalan', + category: 'Combinatorics', + syntax: ['catalan(n)'], + description: 'The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0.', + examples: ['catalan(3)', 'catalan(8)'], + seealso: ['bellNumbers'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/combinatorics/bellNumbers.js +var bellNumbersDocs = { + name: 'bellNumbers', + category: 'Combinatorics', + syntax: ['bellNumbers(n)'], + description: 'The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S. `bellNumbers` only takes integer arguments. The following condition must be enforced: n >= 0.', + examples: ['bellNumbers(3)', 'bellNumbers(8)'], + seealso: ['stirlingS2'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/rightLogShift.js +var rightLogShiftDocs = { + name: 'rightLogShift', + category: 'Bitwise', + syntax: ['x >>> y', 'rightLogShift(x, y)'], + description: 'Bitwise right logical shift of a value x by y number of bits.', + examples: ['8 >>> 1', '4 << 1', '-12 >>> 2'], + seealso: ['bitAnd', 'bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/rightArithShift.js +var rightArithShiftDocs = { + name: 'rightArithShift', + category: 'Bitwise', + syntax: ['x >> y', 'rightArithShift(x, y)'], + description: 'Bitwise right arithmetic shift of a value x by y number of bits.', + examples: ['8 >> 1', '4 << 1', '-12 >> 2'], + seealso: ['bitAnd', 'bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightLogShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/leftShift.js +var leftShiftDocs = { + name: 'leftShift', + category: 'Bitwise', + syntax: ['x << y', 'leftShift(x, y)'], + description: 'Bitwise left logical shift of a value x by y number of bits.', + examples: ['4 << 1', '8 >> 1'], + seealso: ['bitAnd', 'bitNot', 'bitOr', 'bitXor', 'rightArithShift', 'rightLogShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/bitXor.js +var bitXorDocs = { + name: 'bitXor', + category: 'Bitwise', + syntax: ['bitXor(x, y)'], + description: 'Bitwise XOR operation, exclusive OR. Performs the logical exclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1.', + examples: ['bitOr(1, 2)', 'bitXor([2, 3, 4], 4)'], + seealso: ['bitAnd', 'bitNot', 'bitOr', 'leftShift', 'rightArithShift', 'rightLogShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/bitOr.js +var bitOrDocs = { + name: 'bitOr', + category: 'Bitwise', + syntax: ['x | y', 'bitOr(x, y)'], + description: 'Bitwise OR operation. Performs the logical inclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if the first bit is 1 or the second bit is 1 or both bits are 1, otherwise, the result is 0.', + examples: ['5 | 3', 'bitOr([1, 2, 3], 4)'], + seealso: ['bitAnd', 'bitNot', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/bitNot.js +var bitNotDocs = { + name: 'bitNot', + category: 'Bitwise', + syntax: ['~x', 'bitNot(x)'], + description: 'Bitwise NOT operation. Performs a logical negation on each bit of the given value. Bits that are 0 become 1, and those that are 1 become 0.', + examples: ['~1', '~2', 'bitNot([2, -3, 4])'], + seealso: ['bitAnd', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/bitAnd.js +var bitAndDocs = { + name: 'bitAnd', + category: 'Bitwise', + syntax: ['x & y', 'bitAnd(x, y)'], + description: 'Bitwise AND operation. Performs the logical AND operation on each pair of the corresponding bits of the two given values by multiplying them. If both bits in the compared position are 1, the bit in the resulting binary representation is 1, otherwise, the result is 0', + examples: ['5 & 3', 'bitAnd(53, 131)', '[1, 12, 31] & 42'], + seealso: ['bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/xgcd.js +var xgcdDocs = { + name: 'xgcd', + category: 'Arithmetic', + syntax: ['xgcd(a, b)'], + description: 'Calculate the extended greatest common divisor for two values. The result is an array [d, x, y] with 3 entries, where d is the greatest common divisor, and d = x * a + y * b.', + examples: ['xgcd(8, 12)', 'gcd(8, 12)', 'xgcd(36163, 21199)'], + seealso: ['gcd', 'lcm'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/unaryPlus.js +var unaryPlusDocs = { + name: 'unaryPlus', + category: 'Operators', + syntax: ['+x', 'unaryPlus(x)'], + description: 'Converts booleans and strings to numbers.', + examples: ['+true', '+"2"'], + seealso: ['add', 'subtract', 'unaryMinus'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/unaryMinus.js +var unaryMinusDocs = { + name: 'unaryMinus', + category: 'Operators', + syntax: ['-x', 'unaryMinus(x)'], + description: 'Inverse the sign of a value. Converts booleans and strings to numbers.', + examples: ['-4.5', '-(-5.6)', '-"22"'], + seealso: ['add', 'subtract', 'unaryPlus'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/square.js +var squareDocs = { + name: 'square', + category: 'Arithmetic', + syntax: ['square(x)'], + description: 'Compute the square of a value. The square of x is x * x.', + examples: ['square(3)', 'sqrt(9)', '3^2', '3 * 3'], + seealso: ['multiply', 'pow', 'sqrt', 'cube'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/sqrtm.js +var sqrtmDocs = { + name: 'sqrtm', + category: 'Arithmetic', + syntax: ['sqrtm(x)'], + description: 'Calculate the principal square root of a square matrix. The principal square root matrix `X` of another matrix `A` is such that `X * X = A`.', + examples: ['sqrtm([[1, 2], [3, 4]])'], + seealso: ['sqrt', 'abs', 'square', 'multiply'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/sqrt.js +var sqrtDocs = { + name: 'sqrt', + category: 'Arithmetic', + syntax: ['sqrt(x)'], + description: 'Compute the square root value. If x = y * y, then y is the square root of x.', + examples: ['sqrt(25)', '5 * 5', 'sqrt(-1)'], + seealso: ['square', 'sqrtm', 'multiply', 'nthRoot', 'nthRoots', 'pow'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/sign.js +var signDocs = { + name: 'sign', + category: 'Arithmetic', + syntax: ['sign(x)'], + description: 'Compute the sign of a value. The sign of a value x is 1 when x>1, -1 when x<0, and 0 when x=0.', + examples: ['sign(3.5)', 'sign(-4.2)', 'sign(0)'], + seealso: ['abs'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/round.js +var roundDocs = { + name: 'round', + category: 'Arithmetic', + syntax: ['round(x)', 'round(x, n)'], + description: 'round a value towards the nearest integer.If x is complex, both real and imaginary part are rounded towards the nearest integer. When n is specified, the value is rounded to n decimals.', + examples: ['round(3.2)', 'round(3.8)', 'round(-4.2)', 'round(-4.8)', 'round(pi, 3)', 'round(123.45678, 2)'], + seealso: ['ceil', 'floor', 'fix'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/pow.js +var powDocs = { + name: 'pow', + category: 'Operators', + syntax: ['x ^ y', 'pow(x, y)'], + description: 'Calculates the power of x to y, x^y.', + examples: ['2^3', '2*2*2', '1 + e ^ (pi * i)'], + seealso: ['multiply', 'nthRoot', 'nthRoots', 'sqrt'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/nthRoots.js +var nthRootsDocs = { + name: 'nthRoots', + category: 'Arithmetic', + syntax: ['nthRoots(A)', 'nthRoots(A, root)'], + description: '' + 'Calculate the nth roots of a value. ' + 'An nth root of a positive real number A, ' + 'is a positive real solution of the equation "x^root = A". ' + 'This function returns an array of complex values.', + examples: ['nthRoots(1)', 'nthRoots(1, 3)'], + seealso: ['sqrt', 'pow', 'nthRoot'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/nthRoot.js +var nthRootDocs = { + name: 'nthRoot', + category: 'Arithmetic', + syntax: ['nthRoot(a)', 'nthRoot(a, root)'], + description: 'Calculate the nth root of a value. ' + 'The principal nth root of a positive real number A, ' + 'is the positive real solution of the equation "x^root = A".', + examples: ['4 ^ 3', 'nthRoot(64, 3)', 'nthRoot(9, 2)', 'sqrt(9)'], + seealso: ['nthRoots', 'pow', 'sqrt'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/norm.js +var normDocs = { + name: 'norm', + category: 'Arithmetic', + syntax: ['norm(x)', 'norm(x, p)'], + description: 'Calculate the norm of a number, vector or matrix.', + examples: ['abs(-3.5)', 'norm(-3.5)', 'norm(3 - 4i)', 'norm([1, 2, -3], Infinity)', 'norm([1, 2, -3], -Infinity)', 'norm([3, 4], 2)', 'norm([[1, 2], [3, 4]], 1)', 'norm([[1, 2], [3, 4]], "inf")', 'norm([[1, 2], [3, 4]], "fro")'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/multiply.js +var multiplyDocs = { + name: 'multiply', + category: 'Operators', + syntax: ['x * y', 'multiply(x, y)'], + description: 'multiply two values.', + examples: ['a = 2.1 * 3.4', 'a / 3.4', '2 * 3 + 4', '2 * (3 + 4)', '3 * 2.1 km'], + seealso: ['divide'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/mod.js +var modDocs = { + name: 'mod', + category: 'Operators', + syntax: ['x % y', 'x mod y', 'mod(x, y)'], + description: 'Calculates the modulus, the remainder of an integer division.', + examples: ['7 % 3', '11 % 2', '10 mod 4', 'isOdd(x) = x % 2', 'isOdd(2)', 'isOdd(3)'], + seealso: ['divide'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/log10.js +var log10Docs = { + name: 'log10', + category: 'Arithmetic', + syntax: ['log10(x)'], + description: 'Compute the 10-base logarithm of a value.', + examples: ['log10(0.00001)', 'log10(10000)', '10 ^ 4', 'log(10000) / log(10)', 'log(10000, 10)'], + seealso: ['exp', 'log'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/log1p.js +var log1pDocs = { + name: 'log1p', + category: 'Arithmetic', + syntax: ['log1p(x)', 'log1p(x, base)'], + description: 'Calculate the logarithm of a `value+1`', + examples: ['log1p(2.5)', 'exp(log1p(1.4))', 'pow(10, 4)', 'log1p(9999, 10)', 'log1p(9999) / log(10)'], + seealso: ['exp', 'log', 'log2', 'log10'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/log2.js +var log2Docs = { + name: 'log2', + category: 'Arithmetic', + syntax: ['log2(x)'], + description: 'Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.', + examples: ['log2(0.03125)', 'log2(16)', 'log2(16) / log2(2)', 'pow(2, 4)'], + seealso: ['exp', 'log1p', 'log', 'log10'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/log.js +var logDocs = { + name: 'log', + category: 'Arithmetic', + syntax: ['log(x)', 'log(x, base)'], + description: 'Compute the logarithm of a value. If no base is provided, the natural logarithm of x is calculated. If base if provided, the logarithm is calculated for the specified base. log(x, base) is defined as log(x) / log(base).', + examples: ['log(3.5)', 'a = log(2.4)', 'exp(a)', '10 ^ 4', 'log(10000, 10)', 'log(10000) / log(10)', 'b = log(1024, 2)', '2 ^ b'], + seealso: ['exp', 'log1p', 'log2', 'log10'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/lcm.js +var lcmDocs = { + name: 'lcm', + category: 'Arithmetic', + syntax: ['lcm(x, y)'], + description: 'Compute the least common multiple.', + examples: ['lcm(4, 6)', 'lcm(6, 21)', 'lcm(6, 21, 5)'], + seealso: ['gcd'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/hypot.js +var hypotDocs = { + name: 'hypot', + category: 'Arithmetic', + syntax: ['hypot(a, b, c, ...)', 'hypot([a, b, c, ...])'], + description: 'Calculate the hypotenusa of a list with values. ', + examples: ['hypot(3, 4)', 'sqrt(3^2 + 4^2)', 'hypot(-2)', 'hypot([3, 4, 5])'], + seealso: ['abs', 'norm'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/gcd.js +var gcdDocs = { + name: 'gcd', + category: 'Arithmetic', + syntax: ['gcd(a, b)', 'gcd(a, b, c, ...)'], + description: 'Compute the greatest common divisor.', + examples: ['gcd(8, 12)', 'gcd(-4, 6)', 'gcd(25, 15, -10)'], + seealso: ['lcm', 'xgcd'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/floor.js +var floorDocs = { + name: 'floor', + category: 'Arithmetic', + syntax: ['floor(x)'], + description: 'Round a value towards minus infinity.If x is complex, both real and imaginary part are rounded towards minus infinity.', + examples: ['floor(3.2)', 'floor(3.8)', 'floor(-4.2)'], + seealso: ['ceil', 'fix', 'round'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/fix.js +var fixDocs = { + name: 'fix', + category: 'Arithmetic', + syntax: ['fix(x)'], + description: 'Round a value towards zero. If x is complex, both real and imaginary part are rounded towards zero.', + examples: ['fix(3.2)', 'fix(3.8)', 'fix(-4.2)', 'fix(-4.8)'], + seealso: ['ceil', 'floor', 'round'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/expm1.js +var expm1Docs = { + name: 'expm1', + category: 'Arithmetic', + syntax: ['expm1(x)'], + description: 'Calculate the value of subtracting 1 from the exponential value.', + examples: ['expm1(2)', 'pow(e, 2) - 1', 'log(expm1(2) + 1)'], + seealso: ['exp', 'pow', 'log'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/expm.js +var expmDocs = { + name: 'expm', + category: 'Arithmetic', + syntax: ['exp(x)'], + description: 'Compute the matrix exponential, expm(A) = e^A. ' + 'The matrix must be square. ' + 'Not to be confused with exp(a), which performs element-wise exponentiation.', + examples: ['expm([[0,2],[0,0]])'], + seealso: ['exp'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/eigs.js +var eigsDocs = { + name: 'eigs', + category: 'Matrix', + syntax: ['eigs(x)'], + description: 'Calculate the eigenvalues and eigenvectors of a real symmetric matrix', + examples: ['eigs([[5, 2.3], [2.3, 1]])'], + seealso: ['inv'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/exp.js +var expDocs = { + name: 'exp', + category: 'Arithmetic', + syntax: ['exp(x)'], + description: 'Calculate the exponent of a value.', + examples: ['exp(1.3)', 'e ^ 1.3', 'log(exp(1.3))', 'x = 2.4', '(exp(i*x) == cos(x) + i*sin(x)) # Euler\'s formula'], + seealso: ['expm', 'expm1', 'pow', 'log'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/dotMultiply.js +var dotMultiplyDocs = { + name: 'dotMultiply', + category: 'Operators', + syntax: ['x .* y', 'dotMultiply(x, y)'], + description: 'Multiply two values element wise.', + examples: ['a = [1, 2, 3; 4, 5, 6]', 'b = [2, 1, 1; 3, 2, 5]', 'a .* b'], + seealso: ['multiply', 'divide', 'dotDivide'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/dotDivide.js +var dotDivideDocs = { + name: 'dotDivide', + category: 'Operators', + syntax: ['x ./ y', 'dotDivide(x, y)'], + description: 'Divide two values element wise.', + examples: ['a = [1, 2, 3; 4, 5, 6]', 'b = [2, 1, 1; 3, 2, 5]', 'a ./ b'], + seealso: ['multiply', 'dotMultiply', 'divide'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/divide.js +var divideDocs = { + name: 'divide', + category: 'Operators', + syntax: ['x / y', 'divide(x, y)'], + description: 'Divide two values.', + examples: ['a = 2 / 3', 'a * 3', '4.5 / 2', '3 + 4 / 2', '(3 + 4) / 2', '18 km / 4.5'], + seealso: ['multiply'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/cube.js +var cubeDocs = { + name: 'cube', + category: 'Arithmetic', + syntax: ['cube(x)'], + description: 'Compute the cube of a value. The cube of x is x * x * x.', + examples: ['cube(2)', '2^3', '2 * 2 * 2'], + seealso: ['multiply', 'square', 'pow'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/ceil.js +var ceilDocs = { + name: 'ceil', + category: 'Arithmetic', + syntax: ['ceil(x)'], + description: 'Round a value towards plus infinity. If x is complex, both real and imaginary part are rounded towards plus infinity.', + examples: ['ceil(3.2)', 'ceil(3.8)', 'ceil(-4.2)'], + seealso: ['floor', 'fix', 'round'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/cbrt.js +var cbrtDocs = { + name: 'cbrt', + category: 'Arithmetic', + syntax: ['cbrt(x)', 'cbrt(x, allRoots)'], + description: 'Compute the cubic root value. If x = y * y * y, then y is the cubic root of x. When `x` is a number or complex number, an optional second argument `allRoots` can be provided to return all three cubic roots. If not provided, the principal root is returned', + examples: ['cbrt(64)', 'cube(4)', 'cbrt(-8)', 'cbrt(2 + 3i)', 'cbrt(8i)', 'cbrt(8i, true)', 'cbrt(27 m^3)'], + seealso: ['square', 'sqrt', 'cube', 'multiply'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/add.js +var addDocs = { + name: 'add', + category: 'Operators', + syntax: ['x + y', 'add(x, y)'], + description: 'Add two values.', + examples: ['a = 2.1 + 3.6', 'a - 3.6', '3 + 2i', '3 cm + 2 inch', '"2.3" + "4"'], + seealso: ['subtract'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/abs.js +var absDocs = { + name: 'abs', + category: 'Arithmetic', + syntax: ['abs(x)'], + description: 'Compute the absolute value.', + examples: ['abs(3.5)', 'abs(-4.2)'], + seealso: ['sign'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/qr.js +var qrDocs = { + name: 'qr', + category: 'Algebra', + syntax: ['qr(A)'], + description: 'Calculates the Matrix QR decomposition. Matrix `A` is decomposed in two matrices (`Q`, `R`) where `Q` is an orthogonal matrix and `R` is an upper triangular matrix.', + examples: ['qr([[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]])'], + seealso: ['lup', 'slu', 'matrix'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/usolve.js +var usolveDocs = { + name: 'usolve', + category: 'Algebra', + syntax: ['x=usolve(U, b)'], + description: 'Solves the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.', + examples: ['x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])'], + seealso: ['lup', 'lusolve', 'lsolve', 'matrix', 'sparse'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/slu.js +var sluDocs = { + name: 'slu', + category: 'Algebra', + syntax: ['slu(A, order, threshold)'], + description: 'Calculate the Matrix LU decomposition with full pivoting. Matrix A is decomposed in two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U', + examples: ['slu(sparse([4.5, 0, 3.2, 0; 3.1, 2.9, 0, 0.9; 0, 1.7, 3, 0; 3.5, 0.4, 0, 1]), 1, 0.001)'], + seealso: ['lusolve', 'lsolve', 'usolve', 'matrix', 'sparse', 'lup', 'qr'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/rationalize.js +var rationalizeDocs = { + name: 'rationalize', + category: 'Algebra', + syntax: ['rationalize(expr)', 'rationalize(expr, scope)', 'rationalize(expr, scope, detailed)'], + description: 'Transform a rationalizable expression in a rational fraction. If rational fraction is one variable polynomial then converts the numerator and denominator in canonical form, with decreasing exponents, returning the coefficients of numerator.', + examples: ['rationalize("2x/y - y/(x+1)")', 'rationalize("2x/y - y/(x+1)", true)'], + seealso: ['simplify'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/simplify.js +var simplifyDocs = { + name: 'simplify', + category: 'Algebra', + syntax: ['simplify(expr)', 'simplify(expr, rules)'], + description: 'Simplify an expression tree.', + examples: ['simplify("3 + 2 / 4")', 'simplify("2x + x")', 'f = parse("x * (x + 2 + x)")', 'simplified = simplify(f)', 'simplified.evaluate({x: 2})'], + seealso: ['derivative', 'parse', 'evaluate'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/lup.js +var lupDocs = { + name: 'lup', + category: 'Algebra', + syntax: ['lup(m)'], + description: 'Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in three matrices (L, U, P) where P * A = L * U', + examples: ['lup([[2, 1], [1, 4]])', 'lup(matrix([[2, 1], [1, 4]]))', 'lup(sparse([[2, 1], [1, 4]]))'], + seealso: ['lusolve', 'lsolve', 'usolve', 'matrix', 'sparse', 'slu', 'qr'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/lsolve.js +var lsolveDocs = { + name: 'lsolve', + category: 'Algebra', + syntax: ['x=lsolve(L, b)'], + description: 'Solves the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.', + examples: ['a = [-2, 3; 2, 1]', 'b = [11, 9]', 'x = lsolve(a, b)'], + seealso: ['lup', 'lusolve', 'usolve', 'matrix', 'sparse'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/derivative.js +var derivativeDocs = { + name: 'derivative', + category: 'Algebra', + syntax: ['derivative(expr, variable)', 'derivative(expr, variable, {simplify: boolean})'], + description: 'Takes the derivative of an expression expressed in parser Nodes. The derivative will be taken over the supplied variable in the second parameter. If there are multiple variables in the expression, it will return a partial derivative.', + examples: ['derivative("2x^3", "x")', 'derivative("2x^3", "x", {simplify: false})', 'derivative("2x^2 + 3x + 4", "x")', 'derivative("sin(2x)", "x")', 'f = parse("x^2 + x")', 'x = parse("x")', 'df = derivative(f, x)', 'df.evaluate({x: 3})'], + seealso: ['simplify', 'parse', 'evaluate'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/version.js +var versionDocs = { + name: 'version', + category: 'Constants', + syntax: ['version'], + description: 'A string with the version number of math.js', + examples: ['version'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/true.js +var trueDocs = { + name: 'true', + category: 'Constants', + syntax: ['true'], + description: 'Boolean value true', + examples: ['true'], + seealso: ['false'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/tau.js +var tauDocs = { + name: 'tau', + category: 'Constants', + syntax: ['tau'], + description: 'Tau is the ratio constant of a circle\'s circumference to radius, equal to 2 * pi, approximately 6.2832.', + examples: ['tau', '2 * pi'], + seealso: ['pi'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/SQRT2.js +var SQRT2Docs = { + name: 'SQRT2', + category: 'Constants', + syntax: ['SQRT2'], + description: 'Returns the square root of 2, approximately equal to 1.414', + examples: ['SQRT2', 'sqrt(2)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/SQRT1_2.js +var SQRT12Docs = { + name: 'SQRT1_2', + category: 'Constants', + syntax: ['SQRT1_2'], + description: 'Returns the square root of 1/2, approximately equal to 0.707', + examples: ['SQRT1_2', 'sqrt(1/2)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/phi.js +var phiDocs = { + name: 'phi', + category: 'Constants', + syntax: ['phi'], + description: 'Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as `(1 + sqrt(5)) / 2` and is approximately 1.618034...', + examples: ['phi'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/pi.js +var piDocs = { + name: 'pi', + category: 'Constants', + syntax: ['pi'], + description: 'The number pi is a mathematical constant that is the ratio of a circle\'s circumference to its diameter, and is approximately equal to 3.14159', + examples: ['pi', 'sin(pi/2)'], + seealso: ['tau'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/null.js +var nullDocs = { + name: 'null', + category: 'Constants', + syntax: ['null'], + description: 'Value null', + examples: ['null'], + seealso: ['true', 'false'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/NaN.js +var NaNDocs = { + name: 'NaN', + category: 'Constants', + syntax: ['NaN'], + description: 'Not a number', + examples: ['NaN', '0 / 0'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/LOG10E.js +var LOG10EDocs = { + name: 'LOG10E', + category: 'Constants', + syntax: ['LOG10E'], + description: 'Returns the base-10 logarithm of E, approximately equal to 0.434', + examples: ['LOG10E', 'log(e, 10)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/LOG2E.js +var LOG2EDocs = { + name: 'LOG2E', + category: 'Constants', + syntax: ['LOG2E'], + description: 'Returns the base-2 logarithm of E, approximately equal to 1.442', + examples: ['LOG2E', 'log(e, 2)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/LN10.js +var LN10Docs = { + name: 'LN10', + category: 'Constants', + syntax: ['LN10'], + description: 'Returns the natural logarithm of 10, approximately equal to 2.302', + examples: ['LN10', 'log(10)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/LN2.js +var LN2Docs = { + name: 'LN2', + category: 'Constants', + syntax: ['LN2'], + description: 'Returns the natural logarithm of 2, approximately equal to 0.693', + examples: ['LN2', 'log(2)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/Infinity.js +var InfinityDocs = { + name: 'Infinity', + category: 'Constants', + syntax: ['Infinity'], + description: 'Infinity, a number which is larger than the maximum number that can be handled by a floating point number.', + examples: ['Infinity', '1 / 0'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/i.js +var iDocs = { + name: 'i', + category: 'Constants', + syntax: ['i'], + description: 'Imaginary unit, defined as i*i=-1. A complex number is described as a + b*i, where a is the real part, and b is the imaginary part.', + examples: ['i', 'i * i', 'sqrt(-1)'], + seealso: [] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/false.js +var falseDocs = { + name: 'false', + category: 'Constants', + syntax: ['false'], + description: 'Boolean value false', + examples: ['false'], + seealso: ['true'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/e.js +var eDocs = { + name: 'e', + category: 'Constants', + syntax: ['e'], + description: 'Euler\'s number, the base of the natural logarithm. Approximately equal to 2.71828', + examples: ['e', 'e ^ 2', 'exp(2)', 'log(e)'], + seealso: ['exp'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/unit.js +var unitDocs = { + name: 'unit', + category: 'Construction', + syntax: ['value unit', 'unit(value, unit)', 'unit(string)'], + description: 'Create a unit.', + examples: ['5.5 mm', '3 inch', 'unit(7.1, "kilogram")', 'unit("23 deg")'], + seealso: ['bignumber', 'boolean', 'complex', 'index', 'matrix', 'number', 'string'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/string.js +var stringDocs = { + name: 'string', + category: 'Construction', + syntax: ['"text"', 'string(x)'], + description: 'Create a string or convert a value to a string', + examples: ['"Hello World!"', 'string(4.2)', 'string(3 + 2i)'], + seealso: ['bignumber', 'boolean', 'complex', 'index', 'matrix', 'number', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/splitUnit.js +var splitUnitDocs = { + name: 'splitUnit', + category: 'Construction', + syntax: ['splitUnit(unit: Unit, parts: Unit[])'], + description: 'Split a unit in an array of units whose sum is equal to the original unit.', + examples: ['splitUnit(1 m, ["feet", "inch"])'], + seealso: ['unit', 'createUnit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/sparse.js +var sparseDocs = { + name: 'sparse', + category: 'Construction', + syntax: ['sparse()', 'sparse([a1, b1, ...; a1, b2, ...])', 'sparse([a1, b1, ...; a1, b2, ...], "number")'], + description: 'Create a sparse matrix.', + examples: ['sparse()', 'sparse([3, 4; 5, 6])', 'sparse([3, 0; 5, 0], "number")'], + seealso: ['bignumber', 'boolean', 'complex', 'index', 'number', 'string', 'unit', 'matrix'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/number.js +var numberDocs = { + name: 'number', + category: 'Construction', + syntax: ['x', 'number(x)', 'number(unit, valuelessUnit)'], + description: 'Create a number or convert a string or boolean into a number.', + examples: ['2', '2e3', '4.05', 'number(2)', 'number("7.2")', 'number(true)', 'number([true, false, true, true])', 'number(unit("52cm"), "m")'], + seealso: ['bignumber', 'boolean', 'complex', 'fraction', 'index', 'matrix', 'string', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/matrix.js +var matrixDocs = { + name: 'matrix', + category: 'Construction', + syntax: ['[]', '[a1, b1, ...; a2, b2, ...]', 'matrix()', 'matrix("dense")', 'matrix([...])'], + description: 'Create a matrix.', + examples: ['[]', '[1, 2, 3]', '[1, 2, 3; 4, 5, 6]', 'matrix()', 'matrix([3, 4])', 'matrix([3, 4; 5, 6], "sparse")', 'matrix([3, 4; 5, 6], "sparse", "number")'], + seealso: ['bignumber', 'boolean', 'complex', 'index', 'number', 'string', 'unit', 'sparse'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/index.js +var indexDocs = { + name: 'index', + category: 'Construction', + syntax: ['[start]', '[start:end]', '[start:step:end]', '[start1, start 2, ...]', '[start1:end1, start2:end2, ...]', '[start1:step1:end1, start2:step2:end2, ...]'], + description: 'Create an index to get or replace a subset of a matrix', + examples: ['[]', '[1, 2, 3]', 'A = [1, 2, 3; 4, 5, 6]', 'A[1, :]', 'A[1, 2] = 50', 'A[0:2, 0:2] = ones(2, 2)'], + seealso: ['bignumber', 'boolean', 'complex', 'matrix,', 'number', 'range', 'string', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/fraction.js +var fractionDocs = { + name: 'fraction', + category: 'Construction', + syntax: ['fraction(num)', 'fraction(num,den)'], + description: 'Create a fraction from a number or from a numerator and denominator.', + examples: ['fraction(0.125)', 'fraction(1, 3) + fraction(2, 5)'], + seealso: ['bignumber', 'boolean', 'complex', 'index', 'matrix', 'string', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/createUnit.js +var createUnitDocs = { + name: 'createUnit', + category: 'Construction', + syntax: ['createUnit(definitions)', 'createUnit(name, definition)'], + description: 'Create a user-defined unit and register it with the Unit type.', + examples: ['createUnit("foo")', 'createUnit("knot", {definition: "0.514444444 m/s", aliases: ["knots", "kt", "kts"]})', 'createUnit("mph", "1 mile/hour")'], + seealso: ['unit', 'splitUnit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/complex.js +var complexDocs = { + name: 'complex', + category: 'Construction', + syntax: ['complex()', 'complex(re, im)', 'complex(string)'], + description: 'Create a complex number.', + examples: ['complex()', 'complex(2, 3)', 'complex("7 - 2i")'], + seealso: ['bignumber', 'boolean', 'index', 'matrix', 'number', 'string', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/boolean.js +var booleanDocs = { + name: 'boolean', + category: 'Construction', + syntax: ['x', 'boolean(x)'], + description: 'Convert a string or number into a boolean.', + examples: ['boolean(0)', 'boolean(1)', 'boolean(3)', 'boolean("true")', 'boolean("false")', 'boolean([1, 0, 1, 1])'], + seealso: ['bignumber', 'complex', 'index', 'matrix', 'number', 'string', 'unit'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/dotPow.js +var dotPowDocs = { + name: 'dotPow', + category: 'Operators', + syntax: ['x .^ y', 'dotPow(x, y)'], + description: 'Calculates the power of x to y element wise.', + examples: ['a = [1, 2, 3; 4, 5, 6]', 'a .^ 2'], + seealso: ['pow'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/lusolve.js +var lusolveDocs = { + name: 'lusolve', + category: 'Algebra', + syntax: ['x=lusolve(A, b)', 'x=lusolve(lu, b)'], + description: 'Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector.', + examples: ['a = [-2, 3; 2, 1]', 'b = [11, 9]', 'x = lusolve(a, b)'], + seealso: ['lup', 'slu', 'lsolve', 'usolve', 'matrix', 'sparse'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/subtract.js +var subtractDocs = { + name: 'subtract', + category: 'Operators', + syntax: ['x - y', 'subtract(x, y)'], + description: 'subtract two values.', + examples: ['a = 5.3 - 2', 'a + 2', '2/3 - 1/6', '2 * 3 - 3', '2.1 km - 500m'], + seealso: ['add'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/variance.js +var varianceDocs = { + name: 'variance', + category: 'Statistics', + syntax: ['variance(a, b, c, ...)', 'variance(A)', 'variance(A, normalization)'], + description: 'Compute the variance of all values. Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".', + examples: ['variance(2, 4, 6)', 'variance([2, 4, 6, 8])', 'variance([2, 4, 6, 8], "uncorrected")', 'variance([2, 4, 6, 8], "biased")', 'variance([1, 2, 3; 4, 5, 6])'], + seealso: ['max', 'mean', 'min', 'median', 'min', 'prod', 'std', 'sum'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/sin.js +var sinDocs = { + name: 'sin', + category: 'Trigonometry', + syntax: ['sin(x)'], + description: 'Compute the sine of x in radians.', + examples: ['sin(2)', 'sin(pi / 4) ^ 2', 'sin(90 deg)', 'sin(30 deg)', 'sin(0.2)^2 + cos(0.2)^2'], + seealso: ['asin', 'cos', 'tan'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/numeric.js +var numericDocs = { + name: 'numeric', + category: 'Utils', + syntax: ['numeric(x)'], + description: 'Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction.', + examples: ['numeric("4")', 'numeric("4", "number")', 'numeric("4", "BigNumber")', 'numeric("4", "Fraction)', 'numeric(4, "Fraction")', 'numeric(fraction(2, 5), "number)'], + seealso: ['number', 'fraction', 'bignumber', 'string', 'format'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/column.js +var columnDocs = { + name: 'column', + category: 'Matrix', + syntax: ['column(x, index)'], + description: 'Return a column from a matrix or array.', + examples: ['A = [[1, 2], [3, 4]]', 'column(A, 1)', 'column(A, 2)'], + seealso: ['row'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/row.js +var rowDocs = { + name: 'row', + category: 'Matrix', + syntax: ['row(x, index)'], + description: 'Return a row from a matrix or array.', + examples: ['A = [[1, 2], [3, 4]]', 'row(A, 1)', 'row(A, 2)'], + seealso: ['column'] +}; +// CONCATENATED MODULE: ./src/expression/embeddedDocs/embeddedDocs.js + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +var embeddedDocs = { + // construction functions + bignumber: bignumberDocs, + "boolean": booleanDocs, + complex: complexDocs, + createUnit: createUnitDocs, + fraction: fractionDocs, + index: indexDocs, + matrix: matrixDocs, + number: numberDocs, + sparse: sparseDocs, + splitUnit: splitUnitDocs, + string: stringDocs, + unit: unitDocs, + // constants + e: eDocs, + E: eDocs, + "false": falseDocs, + i: iDocs, + Infinity: InfinityDocs, + LN2: LN2Docs, + LN10: LN10Docs, + LOG2E: LOG2EDocs, + LOG10E: LOG10EDocs, + NaN: NaNDocs, + "null": nullDocs, + pi: piDocs, + PI: piDocs, + phi: phiDocs, + SQRT1_2: SQRT12Docs, + SQRT2: SQRT2Docs, + tau: tauDocs, + "true": trueDocs, + version: versionDocs, + // physical constants + // TODO: more detailed docs for physical constants + speedOfLight: { + description: 'Speed of light in vacuum', + examples: ['speedOfLight'] + }, + gravitationConstant: { + description: 'Newtonian constant of gravitation', + examples: ['gravitationConstant'] + }, + planckConstant: { + description: 'Planck constant', + examples: ['planckConstant'] + }, + reducedPlanckConstant: { + description: 'Reduced Planck constant', + examples: ['reducedPlanckConstant'] + }, + magneticConstant: { + description: 'Magnetic constant (vacuum permeability)', + examples: ['magneticConstant'] + }, + electricConstant: { + description: 'Electric constant (vacuum permeability)', + examples: ['electricConstant'] + }, + vacuumImpedance: { + description: 'Characteristic impedance of vacuum', + examples: ['vacuumImpedance'] + }, + coulomb: { + description: 'Coulomb\'s constant', + examples: ['coulomb'] + }, + elementaryCharge: { + description: 'Elementary charge', + examples: ['elementaryCharge'] + }, + bohrMagneton: { + description: 'Borh magneton', + examples: ['bohrMagneton'] + }, + conductanceQuantum: { + description: 'Conductance quantum', + examples: ['conductanceQuantum'] + }, + inverseConductanceQuantum: { + description: 'Inverse conductance quantum', + examples: ['inverseConductanceQuantum'] + }, + // josephson: {description: 'Josephson constant', examples: ['josephson']}, + magneticFluxQuantum: { + description: 'Magnetic flux quantum', + examples: ['magneticFluxQuantum'] + }, + nuclearMagneton: { + description: 'Nuclear magneton', + examples: ['nuclearMagneton'] + }, + klitzing: { + description: 'Von Klitzing constant', + examples: ['klitzing'] + }, + bohrRadius: { + description: 'Borh radius', + examples: ['bohrRadius'] + }, + classicalElectronRadius: { + description: 'Classical electron radius', + examples: ['classicalElectronRadius'] + }, + electronMass: { + description: 'Electron mass', + examples: ['electronMass'] + }, + fermiCoupling: { + description: 'Fermi coupling constant', + examples: ['fermiCoupling'] + }, + fineStructure: { + description: 'Fine-structure constant', + examples: ['fineStructure'] + }, + hartreeEnergy: { + description: 'Hartree energy', + examples: ['hartreeEnergy'] + }, + protonMass: { + description: 'Proton mass', + examples: ['protonMass'] + }, + deuteronMass: { + description: 'Deuteron Mass', + examples: ['deuteronMass'] + }, + neutronMass: { + description: 'Neutron mass', + examples: ['neutronMass'] + }, + quantumOfCirculation: { + description: 'Quantum of circulation', + examples: ['quantumOfCirculation'] + }, + rydberg: { + description: 'Rydberg constant', + examples: ['rydberg'] + }, + thomsonCrossSection: { + description: 'Thomson cross section', + examples: ['thomsonCrossSection'] + }, + weakMixingAngle: { + description: 'Weak mixing angle', + examples: ['weakMixingAngle'] + }, + efimovFactor: { + description: 'Efimov factor', + examples: ['efimovFactor'] + }, + atomicMass: { + description: 'Atomic mass constant', + examples: ['atomicMass'] + }, + avogadro: { + description: 'Avogadro\'s number', + examples: ['avogadro'] + }, + boltzmann: { + description: 'Boltzmann constant', + examples: ['boltzmann'] + }, + faraday: { + description: 'Faraday constant', + examples: ['faraday'] + }, + firstRadiation: { + description: 'First radiation constant', + examples: ['firstRadiation'] + }, + loschmidt: { + description: 'Loschmidt constant at T=273.15 K and p=101.325 kPa', + examples: ['loschmidt'] + }, + gasConstant: { + description: 'Gas constant', + examples: ['gasConstant'] + }, + molarPlanckConstant: { + description: 'Molar Planck constant', + examples: ['molarPlanckConstant'] + }, + molarVolume: { + description: 'Molar volume of an ideal gas at T=273.15 K and p=101.325 kPa', + examples: ['molarVolume'] + }, + sackurTetrode: { + description: 'Sackur-Tetrode constant at T=1 K and p=101.325 kPa', + examples: ['sackurTetrode'] + }, + secondRadiation: { + description: 'Second radiation constant', + examples: ['secondRadiation'] + }, + stefanBoltzmann: { + description: 'Stefan-Boltzmann constant', + examples: ['stefanBoltzmann'] + }, + wienDisplacement: { + description: 'Wien displacement law constant', + examples: ['wienDisplacement'] + }, + // spectralRadiance: {description: 'First radiation constant for spectral radiance', examples: ['spectralRadiance']}, + molarMass: { + description: 'Molar mass constant', + examples: ['molarMass'] + }, + molarMassC12: { + description: 'Molar mass constant of carbon-12', + examples: ['molarMassC12'] + }, + gravity: { + description: 'Standard acceleration of gravity (standard acceleration of free-fall on Earth)', + examples: ['gravity'] + }, + planckLength: { + description: 'Planck length', + examples: ['planckLength'] + }, + planckMass: { + description: 'Planck mass', + examples: ['planckMass'] + }, + planckTime: { + description: 'Planck time', + examples: ['planckTime'] + }, + planckCharge: { + description: 'Planck charge', + examples: ['planckCharge'] + }, + planckTemperature: { + description: 'Planck temperature', + examples: ['planckTemperature'] + }, + // functions - algebra + derivative: derivativeDocs, + lsolve: lsolveDocs, + lup: lupDocs, + lusolve: lusolveDocs, + simplify: simplifyDocs, + rationalize: rationalizeDocs, + slu: sluDocs, + usolve: usolveDocs, + qr: qrDocs, + // functions - arithmetic + abs: absDocs, + add: addDocs, + cbrt: cbrtDocs, + ceil: ceilDocs, + cube: cubeDocs, + divide: divideDocs, + dotDivide: dotDivideDocs, + dotMultiply: dotMultiplyDocs, + dotPow: dotPowDocs, + exp: expDocs, + expm: expmDocs, + expm1: expm1Docs, + fix: fixDocs, + floor: floorDocs, + gcd: gcdDocs, + hypot: hypotDocs, + lcm: lcmDocs, + log: logDocs, + log2: log2Docs, + log1p: log1pDocs, + log10: log10Docs, + mod: modDocs, + multiply: multiplyDocs, + norm: normDocs, + nthRoot: nthRootDocs, + nthRoots: nthRootsDocs, + pow: powDocs, + round: roundDocs, + sign: signDocs, + sqrt: sqrtDocs, + sqrtm: sqrtmDocs, + square: squareDocs, + subtract: subtractDocs, + unaryMinus: unaryMinusDocs, + unaryPlus: unaryPlusDocs, + xgcd: xgcdDocs, + // functions - bitwise + bitAnd: bitAndDocs, + bitNot: bitNotDocs, + bitOr: bitOrDocs, + bitXor: bitXorDocs, + leftShift: leftShiftDocs, + rightArithShift: rightArithShiftDocs, + rightLogShift: rightLogShiftDocs, + // functions - combinatorics + bellNumbers: bellNumbersDocs, + catalan: catalanDocs, + composition: compositionDocs, + stirlingS2: stirlingS2Docs, + // functions - core + config: configDocs, + "import": importDocs, + typed: typedDocs, + // functions - complex + arg: argDocs, + conj: conjDocs, + re: reDocs, + im: imDocs, + // functions - expression + evaluate: evaluateDocs, + eval: evaluateDocs, + // TODO: deprecated, cleanup in v7 + help: helpDocs, + // functions - geometry + distance: distanceDocs, + intersect: intersectDocs, + // functions - logical + and: andDocs, + not: notDocs, + or: orDocs, + xor: xorDocs, + // functions - matrix + concat: concatDocs, + cross: crossDocs, + column: columnDocs, + ctranspose: ctransposeDocs, + det: detDocs, + diag: diagDocs, + dot: dotDocs, + getMatrixDataType: getMatrixDataTypeDocs, + identity: identityDocs, + filter: filterDocs, + flatten: flattenDocs, + forEach: forEachDocs, + inv: invDocs, + eigs: eigsDocs, + kron: kronDocs, + map: mapDocs, + ones: onesDocs, + partitionSelect: partitionSelectDocs, + range: rangeDocs, + resize: resizeDocs, + reshape: reshapeDocs, + row: rowDocs, + size: sizeDocs, + sort: sortDocs, + squeeze: squeezeDocs, + subset: subsetDocs, + trace: traceDocs, + transpose: transposeDocs, + zeros: zerosDocs, + // functions - probability + combinations: combinationsDocs, + combinationsWithRep: combinationsWithRepDocs, + // distribution: distributionDocs, + factorial: factorialDocs, + gamma: gammaDocs, + kldivergence: kldivergenceDocs, + multinomial: multinomialDocs, + permutations: permutationsDocs, + pickRandom: pickRandomDocs, + random: randomDocs, + randomInt: randomIntDocs, + // functions - relational + compare: compareDocs, + compareNatural: compareNaturalDocs, + compareText: compareTextDocs, + deepEqual: deepEqualDocs, + equal: equalDocs, + equalText: equalTextDocs, + larger: largerDocs, + largerEq: largerEqDocs, + smaller: smallerDocs, + smallerEq: smallerEqDocs, + unequal: unequalDocs, + // functions - set + setCartesian: setCartesianDocs, + setDifference: setDifferenceDocs, + setDistinct: setDistinctDocs, + setIntersect: setIntersectDocs, + setIsSubset: setIsSubsetDocs, + setMultiplicity: setMultiplicityDocs, + setPowerset: setPowersetDocs, + setSize: setSizeDocs, + setSymDifference: setSymDifferenceDocs, + setUnion: setUnionDocs, + // functions - special + erf: erfDocs, + // functions - statistics + mad: madDocs, + max: maxDocs, + mean: meanDocs, + median: medianDocs, + min: minDocs, + mode: modeDocs, + prod: prodDocs, + quantileSeq: quantileSeqDocs, + std: stdDocs, + sum: sumDocs, + variance: varianceDocs, + "var": varianceDocs, + // TODO: deprecated, cleanup in v7 + // functions - trigonometry + acos: acosDocs, + acosh: acoshDocs, + acot: acotDocs, + acoth: acothDocs, + acsc: acscDocs, + acsch: acschDocs, + asec: asecDocs, + asech: asechDocs, + asin: asinDocs, + asinh: asinhDocs, + atan: atanDocs, + atanh: atanhDocs, + atan2: atan2Docs, + cos: cosDocs, + cosh: coshDocs, + cot: cotDocs, + coth: cothDocs, + csc: cscDocs, + csch: cschDocs, + sec: secDocs, + sech: sechDocs, + sin: sinDocs, + sinh: sinhDocs, + tan: tanDocs, + tanh: tanhDocs, + // functions - units + to: toDocs, + // functions - utils + clone: cloneDocs, + format: formatDocs, + isNaN: isNaNDocs, + isInteger: isIntegerDocs, + isNegative: isNegativeDocs, + isNumeric: isNumericDocs, + hasNumericValue: hasNumericValueDocs, + isPositive: isPositiveDocs, + isPrime: isPrimeDocs, + isZero: isZeroDocs, + // print: printDocs // TODO: add documentation for print as soon as the parser supports objects. + typeOf: typeOfDocs, + "typeof": typeOfDocs, + // TODO: deprecated, cleanup in v7 + numeric: numericDocs +}; +// CONCATENATED MODULE: ./src/expression/function/help.js + + + + +var help_name = 'help'; +var help_dependencies = ['typed', 'mathWithTransform', 'Help']; +var createHelp = /* #__PURE__ */Object(factory["a" /* factory */])(help_name, help_dependencies, function (_ref) { + var typed = _ref.typed, + mathWithTransform = _ref.mathWithTransform, + Help = _ref.Help; + + /** + * Retrieve help on a function or data type. + * Help files are retrieved from the embedded documentation in math.docs. + * + * Syntax: + * + * math.help(search) + * + * Examples: + * + * console.log(math.help('sin').toString()) + * console.log(math.help(math.add).toString()) + * console.log(math.help(math.add).toJSON()) + * + * @param {Function | string | Object} search A function or function name + * for which to get help + * @return {Help} A help object + */ + return typed(help_name, { + any: function any(search) { + var prop; + var searchName = search; + + if (typeof search !== 'string') { + for (prop in mathWithTransform) { + // search in functions and constants + if (Object(utils_object["f" /* hasOwnProperty */])(mathWithTransform, prop) && search === mathWithTransform[prop]) { + searchName = prop; + break; + } + } + /* TODO: implement help for data types + if (!text) { + // search data type + for (prop in math.type) { + if (hasOwnProperty(math, prop)) { + if (search === math.type[prop]) { + text = prop + break + } + } + } + } + */ + + } + + var doc = getSafeProperty(embeddedDocs, searchName); + + if (!doc) { + var searchText = typeof searchName === 'function' ? searchName.name : searchName; + throw new Error('No documentation found on "' + searchText + '"'); + } + + return new Help(doc); + } + }); +}); +// CONCATENATED MODULE: ./src/type/chain/function/chain.js + +var chain_name = 'chain'; +var chain_dependencies = ['typed', 'Chain']; +var createChain = /* #__PURE__ */Object(factory["a" /* factory */])(chain_name, chain_dependencies, function (_ref) { + var typed = _ref.typed, + Chain = _ref.Chain; + + /** + * Wrap any value in a chain, allowing to perform chained operations on + * the value. + * + * All methods available in the math.js library can be called upon the chain, + * and then will be evaluated with the value itself as first argument. + * The chain can be closed by executing `chain.done()`, which returns + * the final value. + * + * The chain has a number of special functions: + * + * - `done()` Finalize the chain and return the chain's value. + * - `valueOf()` The same as `done()` + * - `toString()` Executes `math.format()` onto the chain's value, returning + * a string representation of the value. + * + * Syntax: + * + * math.chain(value) + * + * Examples: + * + * math.chain(3) + * .add(4) + * .subtract(2) + * .done() // 5 + * + * math.chain( [[1, 2], [3, 4]] ) + * .subset(math.index(0, 0), 8) + * .multiply(3) + * .done() // [[24, 6], [9, 12]] + * + * @param {*} [value] A value of any type on which to start a chained operation. + * @return {math.Chain} The created chain + */ + return typed(chain_name, { + '': function _() { + return new Chain(); + }, + any: function any(value) { + return new Chain(value); + } + }); +}); +// CONCATENATED MODULE: ./src/function/matrix/det.js + + + + +var det_name = 'det'; +var det_dependencies = ['typed', 'matrix', 'subtract', 'multiply', 'unaryMinus', 'lup']; +var createDet = /* #__PURE__ */Object(factory["a" /* factory */])(det_name, det_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + subtract = _ref.subtract, + multiply = _ref.multiply, + unaryMinus = _ref.unaryMinus, + lup = _ref.lup; + + /** + * Calculate the determinant of a matrix. + * + * Syntax: + * + * math.det(x) + * + * Examples: + * + * math.det([[1, 2], [3, 4]]) // returns -2 + * + * const A = [ + * [-2, 2, 3], + * [-1, 1, 3], + * [2, 0, -1] + * ] + * math.det(A) // returns 6 + * + * See also: + * + * inv + * + * @param {Array | Matrix} x A matrix + * @return {number} The determinant of `x` + */ + return typed(det_name, { + any: function any(x) { + return Object(utils_object["a" /* clone */])(x); + }, + 'Array | Matrix': function det(x) { + var size; + + if (Object(is["v" /* isMatrix */])(x)) { + size = x.size(); + } else if (Array.isArray(x)) { + x = matrix(x); + size = x.size(); + } else { + // a scalar + size = []; + } + + switch (size.length) { + case 0: + // scalar + return Object(utils_object["a" /* clone */])(x); + + case 1: + // vector + if (size[0] === 1) { + return Object(utils_object["a" /* clone */])(x.valueOf()[0]); + } else { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + + case 2: + { + // two dimensional array + var rows = size[0]; + var cols = size[1]; + + if (rows === cols) { + return _det(x.clone().valueOf(), rows, cols); + } else { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + } + + default: + // multi dimensional array + throw new RangeError('Matrix must be two dimensional ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + } + }); + /** + * Calculate the determinant of a matrix + * @param {Array[]} matrix A square, two dimensional matrix + * @param {number} rows Number of rows of the matrix (zero-based) + * @param {number} cols Number of columns of the matrix (zero-based) + * @returns {number} det + * @private + */ + + function _det(matrix, rows, cols) { + if (rows === 1) { + // this is a 1 x 1 matrix + return Object(utils_object["a" /* clone */])(matrix[0][0]); + } else if (rows === 2) { + // this is a 2 x 2 matrix + // the determinant of [a11,a12;a21,a22] is det = a11*a22-a21*a12 + return subtract(multiply(matrix[0][0], matrix[1][1]), multiply(matrix[1][0], matrix[0][1])); + } else { + // Compute the LU decomposition + var decomp = lup(matrix); // The determinant is the product of the diagonal entries of U (and those of L, but they are all 1) + + var det = decomp.U[0][0]; + + for (var _i = 1; _i < rows; _i++) { + det = multiply(det, decomp.U[_i][_i]); + } // The determinant will be multiplied by 1 or -1 depending on the parity of the permutation matrix. + // This can be determined by counting the cycles. This is roughly a linear time algorithm. + + + var evenCycles = 0; + var i = 0; + var visited = []; + + while (true) { + while (visited[i]) { + i++; + } + + if (i >= rows) break; + var j = i; + var cycleLen = 0; + + while (!visited[decomp.p[j]]) { + visited[decomp.p[j]] = true; + j = decomp.p[j]; + cycleLen++; + } + + if (cycleLen % 2 === 0) { + evenCycles++; + } + } + + return evenCycles % 2 === 0 ? det : unaryMinus(det); + } + } +}); +// CONCATENATED MODULE: ./src/function/matrix/inv.js + + + + +var inv_name = 'inv'; +var inv_dependencies = ['typed', 'matrix', 'divideScalar', 'addScalar', 'multiply', 'unaryMinus', 'det', 'identity', 'abs']; +var createInv = /* #__PURE__ */Object(factory["a" /* factory */])(inv_name, inv_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + divideScalar = _ref.divideScalar, + addScalar = _ref.addScalar, + multiply = _ref.multiply, + unaryMinus = _ref.unaryMinus, + det = _ref.det, + identity = _ref.identity, + abs = _ref.abs; + + /** + * Calculate the inverse of a square matrix. + * + * Syntax: + * + * math.inv(x) + * + * Examples: + * + * math.inv([[1, 2], [3, 4]]) // returns [[-2, 1], [1.5, -0.5]] + * math.inv(4) // returns 0.25 + * 1 / 4 // returns 0.25 + * + * See also: + * + * det, transpose + * + * @param {number | Complex | Array | Matrix} x Matrix to be inversed + * @return {number | Complex | Array | Matrix} The inverse of `x`. + */ + return typed(inv_name, { + 'Array | Matrix': function ArrayMatrix(x) { + var size = Object(is["v" /* isMatrix */])(x) ? x.size() : Object(utils_array["a" /* arraySize */])(x); + + switch (size.length) { + case 1: + // vector + if (size[0] === 1) { + if (Object(is["v" /* isMatrix */])(x)) { + return matrix([divideScalar(1, x.valueOf()[0])]); + } else { + return [divideScalar(1, x[0])]; + } + } else { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + + case 2: + // two dimensional array + { + var rows = size[0]; + var cols = size[1]; + + if (rows === cols) { + if (Object(is["v" /* isMatrix */])(x)) { + return matrix(_inv(x.valueOf(), rows, cols), x.storage()); + } else { + // return an Array + return _inv(x, rows, cols); + } + } else { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + } + + default: + // multi dimensional array + throw new RangeError('Matrix must be two dimensional ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + }, + any: function any(x) { + // scalar + return divideScalar(1, x); // FIXME: create a BigNumber one when configured for bignumbers + } + }); + /** + * Calculate the inverse of a square matrix + * @param {Array[]} mat A square matrix + * @param {number} rows Number of rows + * @param {number} cols Number of columns, must equal rows + * @return {Array[]} inv Inverse matrix + * @private + */ + + function _inv(mat, rows, cols) { + var r, s, f, value, temp; + + if (rows === 1) { + // this is a 1 x 1 matrix + value = mat[0][0]; + + if (value === 0) { + throw Error('Cannot calculate inverse, determinant is zero'); + } + + return [[divideScalar(1, value)]]; + } else if (rows === 2) { + // this is a 2 x 2 matrix + var d = det(mat); + + if (d === 0) { + throw Error('Cannot calculate inverse, determinant is zero'); + } + + return [[divideScalar(mat[1][1], d), divideScalar(unaryMinus(mat[0][1]), d)], [divideScalar(unaryMinus(mat[1][0]), d), divideScalar(mat[0][0], d)]]; + } else { + // this is a matrix of 3 x 3 or larger + // calculate inverse using gauss-jordan elimination + // https://en.wikipedia.org/wiki/Gaussian_elimination + // http://mathworld.wolfram.com/MatrixInverse.html + // http://math.uww.edu/~mcfarlat/inverse.htm + // make a copy of the matrix (only the arrays, not of the elements) + var A = mat.concat(); + + for (r = 0; r < rows; r++) { + A[r] = A[r].concat(); + } // create an identity matrix which in the end will contain the + // matrix inverse + + + var B = identity(rows).valueOf(); // loop over all columns, and perform row reductions + + for (var c = 0; c < cols; c++) { + // Pivoting: Swap row c with row r, where row r contains the largest element A[r][c] + var ABig = abs(A[c][c]); + var rBig = c; + r = c + 1; + + while (r < rows) { + if (abs(A[r][c]) > ABig) { + ABig = abs(A[r][c]); + rBig = r; + } + + r++; + } + + if (ABig === 0) { + throw Error('Cannot calculate inverse, determinant is zero'); + } + + r = rBig; + + if (r !== c) { + temp = A[c]; + A[c] = A[r]; + A[r] = temp; + temp = B[c]; + B[c] = B[r]; + B[r] = temp; + } // eliminate non-zero values on the other rows at column c + + + var Ac = A[c]; + var Bc = B[c]; + + for (r = 0; r < rows; r++) { + var Ar = A[r]; + var Br = B[r]; + + if (r !== c) { + // eliminate value at column c and row r + if (Ar[c] !== 0) { + f = divideScalar(unaryMinus(Ar[c]), Ac[c]); // add (f * row c) to row r to eliminate the value + // at column c + + for (s = c; s < cols; s++) { + Ar[s] = addScalar(Ar[s], multiply(f, Ac[s])); + } + + for (s = 0; s < cols; s++) { + Br[s] = addScalar(Br[s], multiply(f, Bc[s])); + } + } + } else { + // normalize value at Acc to 1, + // divide each value on row r with the value at Acc + f = Ac[c]; + + for (s = c; s < cols; s++) { + Ar[s] = divideScalar(Ar[s], f); + } + + for (s = 0; s < cols; s++) { + Br[s] = divideScalar(Br[s], f); + } + } + } + } + + return B; + } + } +}); +// CONCATENATED MODULE: ./src/function/matrix/eigs.js + + + +var eigs_name = 'eigs'; +var eigs_dependencies = ['config', 'typed', 'matrix', 'addScalar', 'equal', 'subtract', 'abs', 'atan', 'cos', 'sin', 'multiplyScalar', 'inv', 'bignumber', 'multiply', 'add']; +var createEigs = /* #__PURE__ */Object(factory["a" /* factory */])(eigs_name, eigs_dependencies, function (_ref) { + var config = _ref.config, + typed = _ref.typed, + matrix = _ref.matrix, + addScalar = _ref.addScalar, + subtract = _ref.subtract, + equal = _ref.equal, + abs = _ref.abs, + atan = _ref.atan, + cos = _ref.cos, + sin = _ref.sin, + multiplyScalar = _ref.multiplyScalar, + inv = _ref.inv, + bignumber = _ref.bignumber, + multiply = _ref.multiply, + add = _ref.add; + + /** + * Compute eigenvalue and eigenvector of a real symmetric matrix. + * Only applicable to two dimensional symmetric matrices. Uses Jacobi + * Algorithm. Matrix containing mixed type ('number', 'bignumber', 'fraction') + * of elements are not supported. Input matrix or 2D array should contain all elements + * of either 'number', 'bignumber' or 'fraction' type. For 'number' and 'fraction', the + * eigenvalues are of 'number' type. For 'bignumber' the eigenvalues are of ''bignumber' type. + * Eigenvectors are always of 'number' type. + * + * Syntax: + * + * math.eigs(x) + * + * Examples: + * + * const H = [[5, 2.3], [2.3, 1]] + * const ans = math.eigs(H) // returns {values: [E1,E2...sorted], vectors: [v1,v2.... corresponding vectors]} + * const E = ans.values + * const U = ans.vectors + * const UTxHxU = math.multiply(math.transpose(U), H, U) // rotates H to the eigen-representation + * E[0] == UTxHxU[0][0] // returns true + * See also: + * + * inv + * + * @param {Array | Matrix} x Matrix to be diagonalized + * @return {{values: Array, vectors: Array} | {values: Matrix, vectors: Matrix}} Object containing eigenvalues (Array or Matrix) and eigenvectors (2D Array/Matrix). + */ + var eigs = typed('eigs', { + Array: function Array(x) { + // check array size + var mat = matrix(x); + var size = mat.size(); + + if (size.length !== 2 || size[0] !== size[1]) { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } // use dense 2D matrix implementation + + + var ans = checkAndSubmit(mat, size[0]); + return { + values: ans[0], + vectors: ans[1] + }; + }, + Matrix: function Matrix(x) { + // use dense 2D array implementation + // dense matrix + var size = x.size(); + + if (size.length !== 2 || size[0] !== size[1]) { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + + var ans = checkAndSubmit(x, size[0]); + return { + values: matrix(ans[0]), + vectors: matrix(ans[1]) + }; + } + }); // Is the matrix + // symmetric ? + + function isSymmetric(x, n) { + for (var i = 0; i < n; i++) { + for (var j = i; j < n; j++) { + // not symmtric + if (!equal(x[i][j], x[j][i])) { + throw new TypeError('Input matrix is not symmetric'); + } + } + } + } // check input for possible problems + // and perform diagonalization efficiently for + // specific type of number + + + function checkAndSubmit(x, n) { + var type = x.datatype(); // type check + + if (type === undefined) { + type = x.getDataType(); + } + + if (type !== 'number' && type !== 'BigNumber' && type !== 'Fraction') { + if (type === 'mixed') { + throw new TypeError('Mixed matrix element type is not supported'); + } else { + throw new TypeError('Matrix element type not supported (' + type + ')'); + } + } else { + isSymmetric(x.toArray(), n); + } // perform efficient calculation for 'numbers' + + + if (type === 'number') { + return diag(x.toArray()); + } else if (type === 'Fraction') { + var xArr = x.toArray(); // convert fraction to numbers + + for (var i = 0; i < n; i++) { + for (var j = i; j < n; j++) { + xArr[i][j] = xArr[i][j].valueOf(); + xArr[j][i] = xArr[i][j]; + } + } + + return diag(x.toArray()); + } else if (type === 'BigNumber') { + return diagBig(x.toArray()); + } + } // diagonalization implementation for number (efficient) + + + function diag(x) { + var N = x.length; + var e0 = Math.abs(config.epsilon / N); + var psi; + var Sij = new Array(N); // Sij is Identity Matrix + + for (var i = 0; i < N; i++) { + Sij[i] = createArray(N, 0); + Sij[i][i] = 1.0; + } // initial error + + + var Vab = getAij(x); + + while (Math.abs(Vab[1]) >= Math.abs(e0)) { + var _i = Vab[0][0]; + var j = Vab[0][1]; + psi = getTheta(x[_i][_i], x[j][j], x[_i][j]); + x = x1(x, psi, _i, j); + Sij = Sij1(Sij, psi, _i, j); + Vab = getAij(x); + } + + var Ei = createArray(N, 0); // eigenvalues + + for (var _i2 = 0; _i2 < N; _i2++) { + Ei[_i2] = x[_i2][_i2]; + } + + return sorting(Object(utils_object["a" /* clone */])(Ei), Object(utils_object["a" /* clone */])(Sij)); + } // diagonalization implementation for bigNumber + + + function diagBig(x) { + var N = x.length; + var e0 = abs(config.epsilon / N); + var psi; + var Sij = new Array(N); // Sij is Identity Matrix + + for (var i = 0; i < N; i++) { + Sij[i] = createArray(N, 0); + Sij[i][i] = 1.0; + } // initial error + + + var Vab = getAijBig(x); + + while (abs(Vab[1]) >= abs(e0)) { + var _i3 = Vab[0][0]; + var j = Vab[0][1]; + psi = getThetaBig(x[_i3][_i3], x[j][j], x[_i3][j]); + x = x1Big(x, psi, _i3, j); + Sij = Sij1Big(Sij, psi, _i3, j); + Vab = getAijBig(x); + } + + var Ei = createArray(N, 0); // eigenvalues + + for (var _i4 = 0; _i4 < N; _i4++) { + Ei[_i4] = x[_i4][_i4]; + } // return [clone(Ei), clone(Sij)] + + + return sorting(Object(utils_object["a" /* clone */])(Ei), Object(utils_object["a" /* clone */])(Sij)); + } // get angle + + + function getTheta(aii, ajj, aij) { + var denom = ajj - aii; + + if (Math.abs(denom) <= config.epsilon) { + return Math.PI / 4; + } else { + return 0.5 * Math.atan(2 * aij / (ajj - aii)); + } + } // get angle + + + function getThetaBig(aii, ajj, aij) { + var denom = subtract(ajj, aii); + + if (abs(denom) <= config.epsilon) { + return bignumber(-1).acos().div(4); + } else { + return multiplyScalar(0.5, atan(multiply(2, aij, inv(denom)))); + } + } // update eigvec + + + function Sij1(Sij, theta, i, j) { + var N = Sij.length; + var c = Math.cos(theta); + var s = Math.sin(theta); + var Ski = createArray(N, 0); + var Skj = createArray(N, 0); + + for (var k = 0; k < N; k++) { + Ski[k] = c * Sij[k][i] - s * Sij[k][j]; + Skj[k] = s * Sij[k][i] + c * Sij[k][j]; + } + + for (var _k = 0; _k < N; _k++) { + Sij[_k][i] = Ski[_k]; + Sij[_k][j] = Skj[_k]; + } + + return Sij; + } // update eigvec for overlap + + + function Sij1Big(Sij, theta, i, j) { + var N = Sij.length; + var c = cos(theta); + var s = sin(theta); + var Ski = createArray(N, bignumber(0)); + var Skj = createArray(N, bignumber(0)); + + for (var k = 0; k < N; k++) { + Ski[k] = subtract(multiplyScalar(c, Sij[k][i]), multiplyScalar(s, Sij[k][j])); + Skj[k] = addScalar(multiplyScalar(s, Sij[k][i]), multiplyScalar(c, Sij[k][j])); + } + + for (var _k2 = 0; _k2 < N; _k2++) { + Sij[_k2][i] = Ski[_k2]; + Sij[_k2][j] = Skj[_k2]; + } + + return Sij; + } // update matrix + + + function x1Big(Hij, theta, i, j) { + var N = Hij.length; + var c = bignumber(cos(theta)); + var s = bignumber(sin(theta)); + var c2 = multiplyScalar(c, c); + var s2 = multiplyScalar(s, s); + var Aki = createArray(N, bignumber(0)); + var Akj = createArray(N, bignumber(0)); // 2cs Hij + + var csHij = multiply(bignumber(2), c, s, Hij[i][j]); // Aii + + var Aii = addScalar(subtract(multiplyScalar(c2, Hij[i][i]), csHij), multiplyScalar(s2, Hij[j][j])); + var Ajj = add(multiplyScalar(s2, Hij[i][i]), csHij, multiplyScalar(c2, Hij[j][j])); // 0 to i + + for (var k = 0; k < N; k++) { + Aki[k] = subtract(multiplyScalar(c, Hij[i][k]), multiplyScalar(s, Hij[j][k])); + Akj[k] = addScalar(multiplyScalar(s, Hij[i][k]), multiplyScalar(c, Hij[j][k])); + } // Modify Hij + + + Hij[i][i] = Aii; + Hij[j][j] = Ajj; + Hij[i][j] = bignumber(0); + Hij[j][i] = bignumber(0); // 0 to i + + for (var _k3 = 0; _k3 < N; _k3++) { + if (_k3 !== i && _k3 !== j) { + Hij[i][_k3] = Aki[_k3]; + Hij[_k3][i] = Aki[_k3]; + Hij[j][_k3] = Akj[_k3]; + Hij[_k3][j] = Akj[_k3]; + } + } + + return Hij; + } // update matrix + + + function x1(Hij, theta, i, j) { + var N = Hij.length; + var c = Math.cos(theta); + var s = Math.sin(theta); + var c2 = c * c; + var s2 = s * s; + var Aki = createArray(N, 0); + var Akj = createArray(N, 0); // Aii + + var Aii = c2 * Hij[i][i] - 2 * c * s * Hij[i][j] + s2 * Hij[j][j]; + var Ajj = s2 * Hij[i][i] + 2 * c * s * Hij[i][j] + c2 * Hij[j][j]; // 0 to i + + for (var k = 0; k < N; k++) { + Aki[k] = c * Hij[i][k] - s * Hij[j][k]; + Akj[k] = s * Hij[i][k] + c * Hij[j][k]; + } // Modify Hij + + + Hij[i][i] = Aii; + Hij[j][j] = Ajj; + Hij[i][j] = 0; + Hij[j][i] = 0; // 0 to i + + for (var _k4 = 0; _k4 < N; _k4++) { + if (_k4 !== i && _k4 !== j) { + Hij[i][_k4] = Aki[_k4]; + Hij[_k4][i] = Aki[_k4]; + Hij[j][_k4] = Akj[_k4]; + Hij[_k4][j] = Akj[_k4]; + } + } + + return Hij; + } // get max off-diagonal value from Upper Diagonal + + + function getAij(Mij) { + var N = Mij.length; + var maxMij = 0; + var maxIJ = [0, 1]; + + for (var i = 0; i < N; i++) { + for (var j = i + 1; j < N; j++) { + if (Math.abs(maxMij) < Math.abs(Mij[i][j])) { + maxMij = Math.abs(Mij[i][j]); + maxIJ = [i, j]; + } + } + } + + return [maxIJ, maxMij]; + } // get max off-diagonal value from Upper Diagonal + + + function getAijBig(Mij) { + var N = Mij.length; + var maxMij = 0; + var maxIJ = [0, 1]; + + for (var i = 0; i < N; i++) { + for (var j = i + 1; j < N; j++) { + if (abs(maxMij) < abs(Mij[i][j])) { + maxMij = abs(Mij[i][j]); + maxIJ = [i, j]; + } + } + } + + return [maxIJ, maxMij]; + } // sort results + + + function sorting(E, S) { + var N = E.length; + var Ef = Array(N); + var Sf = Array(N); + + for (var k = 0; k < N; k++) { + Sf[k] = Array(N); + } + + for (var i = 0; i < N; i++) { + var minID = 0; + var minE = E[0]; + + for (var j = 0; j < E.length; j++) { + if (E[j] < minE) { + minID = j; + minE = E[minID]; + } + } + + Ef[i] = E.splice(minID, 1)[0]; + + for (var _k5 = 0; _k5 < N; _k5++) { + Sf[_k5][i] = S[_k5][minID]; + + S[_k5].splice(minID, 1); + } + } + + return [Object(utils_object["a" /* clone */])(Ef), Object(utils_object["a" /* clone */])(Sf)]; + } + /** + * Create an array of a certain size and fill all items with an initial value + * @param {number} size + * @param {number} value + * @return {number[]} + */ + + + function createArray(size, value) { + // TODO: as soon as all browsers support Array.fill, use that instead (IE doesn't support it) + var array = new Array(size); + + for (var i = 0; i < size; i++) { + array[i] = value; + } + + return array; + } + + return eigs; +}); +// CONCATENATED MODULE: ./src/function/matrix/expm.js + + + +var expm_name = 'expm'; +var expm_dependencies = ['typed', 'abs', 'add', 'identity', 'inv', 'multiply']; +var createExpm = /* #__PURE__ */Object(factory["a" /* factory */])(expm_name, expm_dependencies, function (_ref) { + var typed = _ref.typed, + abs = _ref.abs, + add = _ref.add, + identity = _ref.identity, + inv = _ref.inv, + multiply = _ref.multiply; + + /** + * Compute the matrix exponential, expm(A) = e^A. The matrix must be square. + * Not to be confused with exp(a), which performs element-wise + * exponentiation. + * + * The exponential is calculated using the Padé approximant with scaling and + * squaring; see "Nineteen Dubious Ways to Compute the Exponential of a + * Matrix," by Moler and Van Loan. + * + * Syntax: + * + * math.expm(x) + * + * Examples: + * + * const A = [[0,2],[0,0]] + * math.expm(A) // returns [[1,2],[0,1]] + * + * See also: + * + * exp + * + * @param {Matrix} x A square Matrix + * @return {Matrix} The exponential of x + */ + return typed(expm_name, { + Matrix: function Matrix(A) { + // Check matrix size + var size = A.size(); + + if (size.length !== 2 || size[0] !== size[1]) { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + + var n = size[0]; // Desired accuracy of the approximant (The actual accuracy + // will be affected by round-off error) + + var eps = 1e-15; // The Padé approximant is not so accurate when the values of A + // are "large", so scale A by powers of two. Then compute the + // exponential, and square the result repeatedly according to + // the identity e^A = (e^(A/m))^m + // Compute infinity-norm of A, ||A||, to see how "big" it is + + var infNorm = infinityNorm(A); // Find the optimal scaling factor and number of terms in the + // Padé approximant to reach the desired accuracy + + var params = findParams(infNorm, eps); + var q = params.q; + var j = params.j; // The Pade approximation to e^A is: + // Rqq(A) = Dqq(A) ^ -1 * Nqq(A) + // where + // Nqq(A) = sum(i=0, q, (2q-i)!p! / [ (2q)!i!(q-i)! ] A^i + // Dqq(A) = sum(i=0, q, (2q-i)!q! / [ (2q)!i!(q-i)! ] (-A)^i + // Scale A by 1 / 2^j + + var Apos = multiply(A, Math.pow(2, -j)); // The i=0 term is just the identity matrix + + var N = identity(n); + var D = identity(n); // Initialization (i=0) + + var factor = 1; // Initialization (i=1) + + var AposToI = Apos; // Cloning not necessary + + var alternate = -1; + + for (var i = 1; i <= q; i++) { + if (i > 1) { + AposToI = multiply(AposToI, Apos); + alternate = -alternate; + } + + factor = factor * (q - i + 1) / ((2 * q - i + 1) * i); + N = add(N, multiply(factor, AposToI)); + D = add(D, multiply(factor * alternate, AposToI)); + } + + var R = multiply(inv(D), N); // Square j times + + for (var _i = 0; _i < j; _i++) { + R = multiply(R, R); + } + + return Object(is["H" /* isSparseMatrix */])(A) ? A.createSparseMatrix(R) : R; + } + }); + + function infinityNorm(A) { + var n = A.size()[0]; + var infNorm = 0; + + for (var i = 0; i < n; i++) { + var rowSum = 0; + + for (var j = 0; j < n; j++) { + rowSum += abs(A.get([i, j])); + } + + infNorm = Math.max(rowSum, infNorm); + } + + return infNorm; + } + /** + * Find the best parameters for the Pade approximant given + * the matrix norm and desired accuracy. Returns the first acceptable + * combination in order of increasing computational load. + */ + + + function findParams(infNorm, eps) { + var maxSearchSize = 30; + + for (var k = 0; k < maxSearchSize; k++) { + for (var q = 0; q <= k; q++) { + var j = k - q; + + if (errorEstimate(infNorm, q, j) < eps) { + return { + q: q, + j: j + }; + } + } + } + + throw new Error('Could not find acceptable parameters to compute the matrix exponential (try increasing maxSearchSize in expm.js)'); + } + /** + * Returns the estimated error of the Pade approximant for the given + * parameters. + */ + + + function errorEstimate(infNorm, q, j) { + var qfac = 1; + + for (var i = 2; i <= q; i++) { + qfac *= i; + } + + var twoqfac = qfac; + + for (var _i2 = q + 1; _i2 <= 2 * q; _i2++) { + twoqfac *= _i2; + } + + var twoqp1fac = twoqfac * (2 * q + 1); + return 8.0 * Math.pow(infNorm / Math.pow(2, j), 2 * q) * qfac * qfac / (twoqfac * twoqp1fac); + } +}); +// CONCATENATED MODULE: ./src/function/matrix/sqrtm.js + + + + +var sqrtm_name = 'sqrtm'; +var sqrtm_dependencies = ['typed', 'abs', 'add', 'multiply', 'sqrt', 'subtract', 'inv', 'size', 'max', 'identity']; +var createSqrtm = /* #__PURE__ */Object(factory["a" /* factory */])(sqrtm_name, sqrtm_dependencies, function (_ref) { + var typed = _ref.typed, + abs = _ref.abs, + add = _ref.add, + multiply = _ref.multiply, + sqrt = _ref.sqrt, + subtract = _ref.subtract, + inv = _ref.inv, + size = _ref.size, + max = _ref.max, + identity = _ref.identity; + + /** + * Calculate the principal square root of a square matrix. + * The principal square root matrix `X` of another matrix `A` is such that `X * X = A`. + * + * https://en.wikipedia.org/wiki/Square_root_of_a_matrix + * + * Syntax: + * + * X = math.sqrtm(A) + * + * Examples: + * + * math.sqrtm([[1, 2], [3, 4]]) // returns [[-2, 1], [1.5, -0.5]] + * + * See also: + * + * sqrt, pow + * + * @param {Array | Matrix} A The square matrix `A` + * @return {Array | Matrix} The principal square root of matrix `A` + */ + var sqrtm = typed(sqrtm_name, { + 'Array | Matrix': function ArrayMatrix(A) { + var size = Object(is["v" /* isMatrix */])(A) ? A.size() : Object(utils_array["a" /* arraySize */])(A); + + switch (size.length) { + case 1: + // Single element Array | Matrix + if (size[0] === 1) { + return sqrt(A); + } else { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + + case 2: + { + // Two-dimensional Array | Matrix + var rows = size[0]; + var cols = size[1]; + + if (rows === cols) { + return _denmanBeavers(A); + } else { + throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')'); + } + } + } + } + }); + var _maxIterations = 1e3; + var _tolerance = 1e-6; + /** + * Calculate the principal square root matrix using the Denman–Beavers iterative method + * + * https://en.wikipedia.org/wiki/Square_root_of_a_matrix#By_Denman–Beavers_iteration + * + * @param {Array | Matrix} A The square matrix `A` + * @return {Array | Matrix} The principal square root of matrix `A` + * @private + */ + + function _denmanBeavers(A) { + var error; + var iterations = 0; + var Y = A; + var Z = identity(size(A)); + + do { + var Yk = Y; + Y = multiply(0.5, add(Yk, inv(Z))); + Z = multiply(0.5, add(Z, inv(Yk))); + error = max(abs(subtract(Y, Yk))); + + if (error > _tolerance && ++iterations > _maxIterations) { + throw new Error('computing square root of matrix: iterative method could not converge'); + } + } while (error > _tolerance); + + return Y; + } + + return sqrtm; +}); +// CONCATENATED MODULE: ./src/function/arithmetic/divide.js + + + + +var divide_name = 'divide'; +var divide_dependencies = ['typed', 'matrix', 'multiply', 'equalScalar', 'divideScalar', 'inv']; +var createDivide = /* #__PURE__ */Object(factory["a" /* factory */])(divide_name, divide_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + multiply = _ref.multiply, + equalScalar = _ref.equalScalar, + divideScalar = _ref.divideScalar, + inv = _ref.inv; + var algorithm11 = createAlgorithm11({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm14 = createAlgorithm14({ + typed: typed + }); + /** + * Divide two values, `x / y`. + * To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`. + * + * Syntax: + * + * math.divide(x, y) + * + * Examples: + * + * math.divide(2, 3) // returns number 0.6666666666666666 + * + * const a = math.complex(5, 14) + * const b = math.complex(4, 1) + * math.divide(a, b) // returns Complex 2 + 3i + * + * const c = [[7, -6], [13, -4]] + * const d = [[1, 2], [4, 3]] + * math.divide(c, d) // returns Array [[-9, 4], [-11, 6]] + * + * const e = math.unit('18 km') + * math.divide(e, 4.5) // returns Unit 4 km + * + * See also: + * + * multiply + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator + * @param {number | BigNumber | Fraction | Complex | Array | Matrix} y Denominator + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Quotient, `x / y` + */ + + return typed('divide', Object(utils_object["e" /* extend */])({ + // we extend the signatures of divideScalar with signatures dealing with matrices + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(x, y) { + // TODO: implement matrix right division using pseudo inverse + // https://www.mathworks.nl/help/matlab/ref/mrdivide.html + // https://www.gnu.org/software/octave/doc/interpreter/Arithmetic-Ops.html + // https://stackoverflow.com/questions/12263932/how-does-gnu-octave-matrix-division-work-getting-unexpected-behaviour + return multiply(x, inv(y)); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, divideScalar, false); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, divideScalar, false); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, divideScalar, false).valueOf(); + }, + 'any, Array | Matrix': function anyArrayMatrix(x, y) { + return multiply(x, inv(y)); + } + }, divideScalar.signatures)); +}); +// CONCATENATED MODULE: ./src/function/geometry/distance.js + + +var distance_name = 'distance'; +var distance_dependencies = ['typed', 'addScalar', 'subtract', 'divideScalar', 'multiplyScalar', 'unaryMinus', 'sqrt', 'abs']; +var createDistance = /* #__PURE__ */Object(factory["a" /* factory */])(distance_name, distance_dependencies, function (_ref) { + var typed = _ref.typed, + addScalar = _ref.addScalar, + subtract = _ref.subtract, + multiplyScalar = _ref.multiplyScalar, + divideScalar = _ref.divideScalar, + unaryMinus = _ref.unaryMinus, + sqrt = _ref.sqrt, + abs = _ref.abs; + + /** + * Calculates: + * The eucledian distance between two points in N-dimensional spaces. + * Distance between point and a line in 2 and 3 dimensional spaces. + * Pairwise distance between a set of 2D or 3D points + * NOTE: + * When substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c + * For parametric equation of a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, c) + * + * Syntax: + * math.distance([x1, y1], [x2, y2]) + *- math.distance({pointOneX: 4, pointOneY: 5}, {pointTwoX: 2, pointTwoY: 7}) + * math.distance([x1, y1, z1], [x2, y2, z2]) + * math.distance({pointOneX: 4, pointOneY: 5, pointOneZ: 8}, {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9}) + * math.distance([x1, y1, ... , N1], [x2, y2, ... , N2]) + * math.distance([[A], [B], [C]...]) + * math.distance([x1, y1], [LinePtX1, LinePtY1], [LinePtX2, LinePtY2]) + * math.distance({pointX: 1, pointY: 4}, {lineOnePtX: 6, lineOnePtY: 3}, {lineTwoPtX: 2, lineTwoPtY: 8}) + * math.distance([x1, y1, z1], [LinePtX1, LinePtY1, LinePtZ1], [LinePtX2, LinePtY2, LinePtZ2]) + * math.distance({pointX: 1, pointY: 4, pointZ: 7}, {lineOnePtX: 6, lineOnePtY: 3, lineOnePtZ: 4}, {lineTwoPtX: 2, lineTwoPtY: 8, lineTwoPtZ: 5}) + * math.distance([x1, y1], [xCoeffLine, yCoeffLine, constant]) + * math.distance({pointX: 10, pointY: 10}, {xCoeffLine: 8, yCoeffLine: 1, constant: 3}) + * math.distance([x1, y1, z1], [x0, y0, z0, a-tCoeff, b-tCoeff, c-tCoeff]) point and parametric equation of 3D line + * math.distance([x, y, z], [x0, y0, z0, a, b, c]) + * math.distance({pointX: 2, pointY: 5, pointZ: 9}, {x0: 4, y0: 6, z0: 3, a: 4, b: 2, c: 0}) + * + * Examples: + * math.distance([0,0], [4,4]) // Returns 5.6569 + * math.distance( + * {pointOneX: 0, pointOneY: 0}, + * {pointTwoX: 10, pointTwoY: 10}) // Returns 14.142135623730951 + * math.distance([1, 0, 1], [4, -2, 2]) // Returns 3.74166 + * math.distance( + * {pointOneX: 4, pointOneY: 5, pointOneZ: 8}, + * {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9}) // Returns 3 + * math.distance([1, 0, 1, 0], [0, -1, 0, -1]) // Returns 2 + * math.distance([[1, 2], [1, 2], [1, 3]]) // Returns [0, 1, 1] + * math.distance([[1,2,4], [1,2,6], [8,1,3]]) // Returns [2, 7.14142842854285, 7.681145747868608] + * math.distance([10, 10], [8, 1, 3]) // Returns 11.535230316796387 + * math.distance([10, 10], [2, 3], [-8, 0]) // Returns 8.759953130362847 + * math.distance( + * {pointX: 1, pointY: 4}, + * {lineOnePtX: 6, lineOnePtY: 3}, + * {lineTwoPtX: 2, lineTwoPtY: 8}) // Returns 2.720549372624744 + * math.distance([2, 3, 1], [1, 1, 2, 5, 0, 1]) // Returns 2.3204774044612857 + * math.distance( + * {pointX: 2, pointY: 3, pointZ: 1}, + * {x0: 1, y0: 1, z0: 2, a: 5, b: 0, c: 1} // Returns 2.3204774044612857 + * + * @param {Array | Matrix | Object} x Co-ordinates of first point + * @param {Array | Matrix | Object} y Co-ordinates of second point + * @return {Number | BigNumber} Returns the distance from two/three points + */ + return typed(distance_name, { + 'Array, Array, Array': function ArrayArrayArray(x, y, z) { + // Point to Line 2D (x=Point, y=LinePoint1, z=LinePoint2) + if (x.length === 2 && y.length === 2 && z.length === 2) { + if (!_2d(x)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument'); + } + + if (!_2d(y)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for second argument'); + } + + if (!_2d(z)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for third argument'); + } + + var m = divideScalar(subtract(z[1], z[0]), subtract(y[1], y[0])); + var xCoeff = multiplyScalar(multiplyScalar(m, m), y[0]); + var yCoeff = unaryMinus(multiplyScalar(m, y[0])); + var constant = x[1]; + return _distancePointLine2D(x[0], x[1], xCoeff, yCoeff, constant); + } else { + throw new TypeError('Invalid Arguments: Try again'); + } + }, + 'Object, Object, Object': function ObjectObjectObject(x, y, z) { + if (Object.keys(x).length === 2 && Object.keys(y).length === 2 && Object.keys(z).length === 2) { + if (!_2d(x)) { + throw new TypeError('Values of pointX and pointY should be numbers or BigNumbers'); + } + + if (!_2d(y)) { + throw new TypeError('Values of lineOnePtX and lineOnePtY should be numbers or BigNumbers'); + } + + if (!_2d(z)) { + throw new TypeError('Values of lineTwoPtX and lineTwoPtY should be numbers or BigNumbers'); + } + + if ('pointX' in x && 'pointY' in x && 'lineOnePtX' in y && 'lineOnePtY' in y && 'lineTwoPtX' in z && 'lineTwoPtY' in z) { + var m = divideScalar(subtract(z.lineTwoPtY, z.lineTwoPtX), subtract(y.lineOnePtY, y.lineOnePtX)); + var xCoeff = multiplyScalar(multiplyScalar(m, m), y.lineOnePtX); + var yCoeff = unaryMinus(multiplyScalar(m, y.lineOnePtX)); + var constant = x.pointX; + return _distancePointLine2D(x.pointX, x.pointY, xCoeff, yCoeff, constant); + } else { + throw new TypeError('Key names do not match'); + } + } else { + throw new TypeError('Invalid Arguments: Try again'); + } + }, + 'Array, Array': function ArrayArray(x, y) { + // Point to Line 2D (x=[pointX, pointY], y=[x-coeff, y-coeff, const]) + if (x.length === 2 && y.length === 3) { + if (!_2d(x)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument'); + } + + if (!_3d(y)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument'); + } + + return _distancePointLine2D(x[0], x[1], y[0], y[1], y[2]); + } else if (x.length === 3 && y.length === 6) { + // Point to Line 3D + if (!_3d(x)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument'); + } + + if (!_parametricLine(y)) { + throw new TypeError('Array with 6 numbers or BigNumbers expected for second argument'); + } + + return _distancePointLine3D(x[0], x[1], x[2], y[0], y[1], y[2], y[3], y[4], y[5]); + } else if (x.length === y.length && x.length > 0) { + // Point to Point N-dimensions + if (!_containsOnlyNumbers(x)) { + throw new TypeError('All values of an array should be numbers or BigNumbers'); + } + + if (!_containsOnlyNumbers(y)) { + throw new TypeError('All values of an array should be numbers or BigNumbers'); + } + + return _euclideanDistance(x, y); + } else { + throw new TypeError('Invalid Arguments: Try again'); + } + }, + 'Object, Object': function ObjectObject(x, y) { + if (Object.keys(x).length === 2 && Object.keys(y).length === 3) { + if (!_2d(x)) { + throw new TypeError('Values of pointX and pointY should be numbers or BigNumbers'); + } + + if (!_3d(y)) { + throw new TypeError('Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers'); + } + + if ('pointX' in x && 'pointY' in x && 'xCoeffLine' in y && 'yCoeffLine' in y && 'constant' in y) { + return _distancePointLine2D(x.pointX, x.pointY, y.xCoeffLine, y.yCoeffLine, y.constant); + } else { + throw new TypeError('Key names do not match'); + } + } else if (Object.keys(x).length === 3 && Object.keys(y).length === 6) { + // Point to Line 3D + if (!_3d(x)) { + throw new TypeError('Values of pointX, pointY and pointZ should be numbers or BigNumbers'); + } + + if (!_parametricLine(y)) { + throw new TypeError('Values of x0, y0, z0, a, b and c should be numbers or BigNumbers'); + } + + if ('pointX' in x && 'pointY' in x && 'x0' in y && 'y0' in y && 'z0' in y && 'a' in y && 'b' in y && 'c' in y) { + return _distancePointLine3D(x.pointX, x.pointY, x.pointZ, y.x0, y.y0, y.z0, y.a, y.b, y.c); + } else { + throw new TypeError('Key names do not match'); + } + } else if (Object.keys(x).length === 2 && Object.keys(y).length === 2) { + // Point to Point 2D + if (!_2d(x)) { + throw new TypeError('Values of pointOneX and pointOneY should be numbers or BigNumbers'); + } + + if (!_2d(y)) { + throw new TypeError('Values of pointTwoX and pointTwoY should be numbers or BigNumbers'); + } + + if ('pointOneX' in x && 'pointOneY' in x && 'pointTwoX' in y && 'pointTwoY' in y) { + return _euclideanDistance([x.pointOneX, x.pointOneY], [y.pointTwoX, y.pointTwoY]); + } else { + throw new TypeError('Key names do not match'); + } + } else if (Object.keys(x).length === 3 && Object.keys(y).length === 3) { + // Point to Point 3D + if (!_3d(x)) { + throw new TypeError('Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers'); + } + + if (!_3d(y)) { + throw new TypeError('Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers'); + } + + if ('pointOneX' in x && 'pointOneY' in x && 'pointOneZ' in x && 'pointTwoX' in y && 'pointTwoY' in y && 'pointTwoZ' in y) { + return _euclideanDistance([x.pointOneX, x.pointOneY, x.pointOneZ], [y.pointTwoX, y.pointTwoY, y.pointTwoZ]); + } else { + throw new TypeError('Key names do not match'); + } + } else { + throw new TypeError('Invalid Arguments: Try again'); + } + }, + Array: function Array(arr) { + if (!_pairwise(arr)) { + throw new TypeError('Incorrect array format entered for pairwise distance calculation'); + } + + return _distancePairwise(arr); + } + }); + + function _isNumber(a) { + // distance supports numbers and bignumbers + return typeof a === 'number' || Object(is["e" /* isBigNumber */])(a); + } + + function _2d(a) { + // checks if the number of arguments are correct in count and are valid (should be numbers) + if (a.constructor !== Array) { + a = _objectToArray(a); + } + + return _isNumber(a[0]) && _isNumber(a[1]); + } + + function _3d(a) { + // checks if the number of arguments are correct in count and are valid (should be numbers) + if (a.constructor !== Array) { + a = _objectToArray(a); + } + + return _isNumber(a[0]) && _isNumber(a[1]) && _isNumber(a[2]); + } + + function _containsOnlyNumbers(a) { + // checks if the number of arguments are correct in count and are valid (should be numbers) + if (!Array.isArray(a)) { + a = _objectToArray(a); + } + + return a.every(_isNumber); + } + + function _parametricLine(a) { + if (a.constructor !== Array) { + a = _objectToArray(a); + } + + return _isNumber(a[0]) && _isNumber(a[1]) && _isNumber(a[2]) && _isNumber(a[3]) && _isNumber(a[4]) && _isNumber(a[5]); + } + + function _objectToArray(o) { + var keys = Object.keys(o); + var a = []; + + for (var i = 0; i < keys.length; i++) { + a.push(o[keys[i]]); + } + + return a; + } + + function _pairwise(a) { + // checks for valid arguments passed to _distancePairwise(Array) + if (a[0].length === 2 && _isNumber(a[0][0]) && _isNumber(a[0][1])) { + if (a.some(function (aI) { + return aI.length !== 2 || !_isNumber(aI[0]) || !_isNumber(aI[1]); + })) { + return false; + } + } else if (a[0].length === 3 && _isNumber(a[0][0]) && _isNumber(a[0][1]) && _isNumber(a[0][2])) { + if (a.some(function (aI) { + return aI.length !== 3 || !_isNumber(aI[0]) || !_isNumber(aI[1]) || !_isNumber(aI[2]); + })) { + return false; + } + } else { + return false; + } + + return true; + } + + function _distancePointLine2D(x, y, a, b, c) { + var num = abs(addScalar(addScalar(multiplyScalar(a, x), multiplyScalar(b, y)), c)); + var den = sqrt(addScalar(multiplyScalar(a, a), multiplyScalar(b, b))); + return divideScalar(num, den); + } + + function _distancePointLine3D(x, y, z, x0, y0, z0, a, b, c) { + var num = [subtract(multiplyScalar(subtract(y0, y), c), multiplyScalar(subtract(z0, z), b)), subtract(multiplyScalar(subtract(z0, z), a), multiplyScalar(subtract(x0, x), c)), subtract(multiplyScalar(subtract(x0, x), b), multiplyScalar(subtract(y0, y), a))]; + num = sqrt(addScalar(addScalar(multiplyScalar(num[0], num[0]), multiplyScalar(num[1], num[1])), multiplyScalar(num[2], num[2]))); + var den = sqrt(addScalar(addScalar(multiplyScalar(a, a), multiplyScalar(b, b)), multiplyScalar(c, c))); + return divideScalar(num, den); + } + + function _euclideanDistance(x, y) { + var vectorSize = x.length; + var result = 0; + var diff = 0; + + for (var i = 0; i < vectorSize; i++) { + diff = subtract(x[i], y[i]); + result = addScalar(multiplyScalar(diff, diff), result); + } + + return sqrt(result); + } + + function _distancePairwise(a) { + var result = []; + var pointA = []; + var pointB = []; + + for (var i = 0; i < a.length - 1; i++) { + for (var j = i + 1; j < a.length; j++) { + if (a[0].length === 2) { + pointA = [a[i][0], a[i][1]]; + pointB = [a[j][0], a[j][1]]; + } else if (a[0].length === 3) { + pointA = [a[i][0], a[i][1], a[i][2]]; + pointB = [a[j][0], a[j][1], a[j][2]]; + } + + result.push(_euclideanDistance(pointA, pointB)); + } + } + + return result; + } +}); +// CONCATENATED MODULE: ./src/function/geometry/intersect.js + + +var intersect_name = 'intersect'; +var intersect_dependencies = ['typed', 'config', 'abs', 'add', 'addScalar', 'matrix', 'multiply', 'multiplyScalar', 'divideScalar', 'subtract', 'smaller', 'equalScalar']; +var createIntersect = /* #__PURE__ */Object(factory["a" /* factory */])(intersect_name, intersect_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + abs = _ref.abs, + add = _ref.add, + addScalar = _ref.addScalar, + matrix = _ref.matrix, + multiply = _ref.multiply, + multiplyScalar = _ref.multiplyScalar, + divideScalar = _ref.divideScalar, + subtract = _ref.subtract, + smaller = _ref.smaller, + equalScalar = _ref.equalScalar; + + /** + * Calculates the point of intersection of two lines in two or three dimensions + * and of a line and a plane in three dimensions. The inputs are in the form of + * arrays or 1 dimensional matrices. The line intersection functions return null + * if the lines do not meet. + * + * Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`. + * + * Syntax: + * + * math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2) + * math.intersect(endPoint1, endPoint2, planeCoefficients) + * + * Examples: + * + * math.intersect([0, 0], [10, 10], [10, 0], [0, 10]) // Returns [5, 5] + * math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]) // Returns [5, 5, 0] + * math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]) // Returns [7, -4, 3] + * + * @param {Array | Matrix} w Co-ordinates of first end-point of first line + * @param {Array | Matrix} x Co-ordinates of second end-point of first line + * @param {Array | Matrix} y Co-ordinates of first end-point of second line + * OR Co-efficients of the plane's equation + * @param {Array | Matrix} z Co-ordinates of second end-point of second line + * OR null if the calculation is for line and plane + * @return {Array} Returns the point of intersection of lines/lines-planes + */ + var intersect = typed('intersect', { + 'Array, Array, Array': function ArrayArrayArray(x, y, plane) { + if (!_3d(x)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument'); + } + + if (!_3d(y)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument'); + } + + if (!_4d(plane)) { + throw new TypeError('Array with 4 numbers expected as third argument'); + } + + return _intersectLinePlane(x[0], x[1], x[2], y[0], y[1], y[2], plane[0], plane[1], plane[2], plane[3]); + }, + 'Array, Array, Array, Array': function ArrayArrayArrayArray(w, x, y, z) { + if (w.length === 2) { + if (!_2d(w)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument'); + } + + if (!_2d(x)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for second argument'); + } + + if (!_2d(y)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for third argument'); + } + + if (!_2d(z)) { + throw new TypeError('Array with 2 numbers or BigNumbers expected for fourth argument'); + } + + return _intersect2d(w, x, y, z); + } else if (w.length === 3) { + if (!_3d(w)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument'); + } + + if (!_3d(x)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument'); + } + + if (!_3d(y)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for third argument'); + } + + if (!_3d(z)) { + throw new TypeError('Array with 3 numbers or BigNumbers expected for fourth argument'); + } + + return _intersect3d(w[0], w[1], w[2], x[0], x[1], x[2], y[0], y[1], y[2], z[0], z[1], z[2]); + } else { + throw new TypeError('Arrays with two or thee dimensional points expected'); + } + }, + 'Matrix, Matrix, Matrix': function MatrixMatrixMatrix(x, y, plane) { + return matrix(intersect(x.valueOf(), y.valueOf(), plane.valueOf())); + }, + 'Matrix, Matrix, Matrix, Matrix': function MatrixMatrixMatrixMatrix(w, x, y, z) { + // TODO: output matrix type should match input matrix type + return matrix(intersect(w.valueOf(), x.valueOf(), y.valueOf(), z.valueOf())); + } + }); + + function _isNumeric(a) { + // intersect supports numbers and bignumbers + return typeof a === 'number' || Object(is["e" /* isBigNumber */])(a); + } + + function _2d(x) { + return x.length === 2 && _isNumeric(x[0]) && _isNumeric(x[1]); + } + + function _3d(x) { + return x.length === 3 && _isNumeric(x[0]) && _isNumeric(x[1]) && _isNumeric(x[2]); + } + + function _4d(x) { + return x.length === 4 && _isNumeric(x[0]) && _isNumeric(x[1]) && _isNumeric(x[2]) && _isNumeric(x[3]); + } + + function _intersect2d(p1a, p1b, p2a, p2b) { + var o1 = p1a; + var o2 = p2a; + var d1 = subtract(o1, p1b); + var d2 = subtract(o2, p2b); + var det = subtract(multiplyScalar(d1[0], d2[1]), multiplyScalar(d2[0], d1[1])); + + if (smaller(abs(det), config.epsilon)) { + return null; + } + + var d20o11 = multiplyScalar(d2[0], o1[1]); + var d21o10 = multiplyScalar(d2[1], o1[0]); + var d20o21 = multiplyScalar(d2[0], o2[1]); + var d21o20 = multiplyScalar(d2[1], o2[0]); + var t = divideScalar(addScalar(subtract(subtract(d20o11, d21o10), d20o21), d21o20), det); + return add(multiply(d1, t), o1); + } + + function _intersect3dHelper(a, b, c, d, e, f, g, h, i, j, k, l) { + // (a - b)*(c - d) + (e - f)*(g - h) + (i - j)*(k - l) + var add1 = multiplyScalar(subtract(a, b), subtract(c, d)); + var add2 = multiplyScalar(subtract(e, f), subtract(g, h)); + var add3 = multiplyScalar(subtract(i, j), subtract(k, l)); + return addScalar(addScalar(add1, add2), add3); + } + + function _intersect3d(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) { + var d1343 = _intersect3dHelper(x1, x3, x4, x3, y1, y3, y4, y3, z1, z3, z4, z3); + + var d4321 = _intersect3dHelper(x4, x3, x2, x1, y4, y3, y2, y1, z4, z3, z2, z1); + + var d1321 = _intersect3dHelper(x1, x3, x2, x1, y1, y3, y2, y1, z1, z3, z2, z1); + + var d4343 = _intersect3dHelper(x4, x3, x4, x3, y4, y3, y4, y3, z4, z3, z4, z3); + + var d2121 = _intersect3dHelper(x2, x1, x2, x1, y2, y1, y2, y1, z2, z1, z2, z1); + + var ta = divideScalar(subtract(multiplyScalar(d1343, d4321), multiplyScalar(d1321, d4343)), subtract(multiplyScalar(d2121, d4343), multiplyScalar(d4321, d4321))); + var tb = divideScalar(addScalar(d1343, multiplyScalar(ta, d4321)), d4343); + var pax = addScalar(x1, multiplyScalar(ta, subtract(x2, x1))); + var pay = addScalar(y1, multiplyScalar(ta, subtract(y2, y1))); + var paz = addScalar(z1, multiplyScalar(ta, subtract(z2, z1))); + var pbx = addScalar(x3, multiplyScalar(tb, subtract(x4, x3))); + var pby = addScalar(y3, multiplyScalar(tb, subtract(y4, y3))); + var pbz = addScalar(z3, multiplyScalar(tb, subtract(z4, z3))); + + if (equalScalar(pax, pbx) && equalScalar(pay, pby) && equalScalar(paz, pbz)) { + return [pax, pay, paz]; + } else { + return null; + } + } + + function _intersectLinePlane(x1, y1, z1, x2, y2, z2, x, y, z, c) { + var x1x = multiplyScalar(x1, x); + var x2x = multiplyScalar(x2, x); + var y1y = multiplyScalar(y1, y); + var y2y = multiplyScalar(y2, y); + var z1z = multiplyScalar(z1, z); + var z2z = multiplyScalar(z2, z); + var t = divideScalar(subtract(subtract(subtract(c, x1x), y1y), z1z), subtract(subtract(subtract(addScalar(addScalar(x2x, y2y), z2z), x1x), y1y), z1z)); + var px = addScalar(x1, multiplyScalar(t, subtract(x2, x1))); + var py = addScalar(y1, multiplyScalar(t, subtract(y2, y1))); + var pz = addScalar(z1, multiplyScalar(t, subtract(z2, z1))); + return [px, py, pz]; // TODO: Add cases when line is parallel to the plane: + // (a) no intersection, + // (b) line contained in plane + } + + return intersect; +}); +// CONCATENATED MODULE: ./src/function/statistics/sum.js + + + + +var sum_name = 'sum'; +var sum_dependencies = ['typed', 'config', 'add', '?bignumber', '?fraction']; +var createSum = /* #__PURE__ */Object(factory["a" /* factory */])(sum_name, sum_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + add = _ref.add, + bignumber = _ref.bignumber, + fraction = _ref.fraction; + + /** + * Compute the sum of a matrix or a list with values. + * In case of a (multi dimensional) array or matrix, the sum of all + * elements will be calculated. + * + * Syntax: + * + * math.sum(a, b, c, ...) + * math.sum(A) + * + * Examples: + * + * math.sum(2, 1, 4, 3) // returns 10 + * math.sum([2, 1, 4, 3]) // returns 10 + * math.sum([[2, 5], [4, 3], [1, 7]]) // returns 22 + * + * See also: + * + * mean, median, min, max, prod, std, variance + * + * @param {... *} args A single matrix or or multiple scalar values + * @return {*} The sum of all values + */ + return typed(sum_name, { + // sum([a, b, c, d, ...]) + 'Array | Matrix': _sum, + // sum([a, b, c, d, ...], dim) + 'Array | Matrix, number | BigNumber': _nsumDim, + // sum(a, b, c, d, ...) + '...': function _(args) { + if (containsCollections(args)) { + throw new TypeError('Scalar values expected in function sum'); + } + + return _sum(args); + } + }); + /** + * Recursively calculate the sum of an n-dimensional array + * @param {Array} array + * @return {number} sum + * @private + */ + + function _sum(array) { + var sum; + deepForEach(array, function (value) { + try { + sum = sum === undefined ? value : add(sum, value); + } catch (err) { + throw improveErrorMessage(err, 'sum', value); + } + }); + + if (sum === undefined) { + switch (config.number) { + case 'number': + return 0; + + case 'BigNumber': + return bignumber ? bignumber(0) : noBignumber(); + + case 'Fraction': + return fraction ? fraction(0) : noFraction(); + + default: + return 0; + } + } + + return sum; + } + + function _nsumDim(array, dim) { + try { + var sum = reduce(array, dim, add); + return sum; + } catch (err) { + throw improveErrorMessage(err, 'sum'); + } + } +}); +// CONCATENATED MODULE: ./src/function/statistics/mean.js + + + + +var mean_name = 'mean'; +var mean_dependencies = ['typed', 'add', 'divide']; +var createMean = /* #__PURE__ */Object(factory["a" /* factory */])(mean_name, mean_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + divide = _ref.divide; + + /** + * Compute the mean value of matrix or a list with values. + * In case of a multi dimensional array, the mean of the flattened array + * will be calculated. When `dim` is provided, the maximum over the selected + * dimension will be calculated. Parameter `dim` is zero-based. + * + * Syntax: + * + * math.mean(a, b, c, ...) + * math.mean(A) + * math.mean(A, dim) + * + * Examples: + * + * math.mean(2, 1, 4, 3) // returns 2.5 + * math.mean([1, 2.7, 3.2, 4]) // returns 2.725 + * + * math.mean([[2, 5], [6, 3], [1, 7]], 0) // returns [3, 5] + * math.mean([[2, 5], [6, 3], [1, 7]], 1) // returns [3.5, 4.5, 4] + * + * See also: + * + * median, min, max, sum, prod, std, variance + * + * @param {... *} args A single matrix or or multiple scalar values + * @return {*} The mean of all values + */ + return typed(mean_name, { + // mean([a, b, c, d, ...]) + 'Array | Matrix': _mean, + // mean([a, b, c, d, ...], dim) + 'Array | Matrix, number | BigNumber': _nmeanDim, + // mean(a, b, c, d, ...) + '...': function _(args) { + if (containsCollections(args)) { + throw new TypeError('Scalar values expected in function mean'); + } + + return _mean(args); + } + }); + /** + * Calculate the mean value in an n-dimensional array, returning a + * n-1 dimensional array + * @param {Array} array + * @param {number} dim + * @return {number} mean + * @private + */ + + function _nmeanDim(array, dim) { + try { + var sum = reduce(array, dim, add); + var s = Array.isArray(array) ? Object(utils_array["a" /* arraySize */])(array) : array.size(); + return divide(sum, s[dim]); + } catch (err) { + throw improveErrorMessage(err, 'mean'); + } + } + /** + * Recursively calculate the mean value in an n-dimensional array + * @param {Array} array + * @return {number} mean + * @private + */ + + + function _mean(array) { + var sum; + var num = 0; + deepForEach(array, function (value) { + try { + sum = sum === undefined ? value : add(sum, value); + num++; + } catch (err) { + throw improveErrorMessage(err, 'mean', value); + } + }); + + if (num === 0) { + throw new Error('Cannot calculate the mean of an empty array'); + } + + return divide(sum, num); + } +}); +// CONCATENATED MODULE: ./src/function/statistics/median.js + + + + +var median_name = 'median'; +var median_dependencies = ['typed', 'add', 'divide', 'compare', 'partitionSelect']; +var createMedian = /* #__PURE__ */Object(factory["a" /* factory */])(median_name, median_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + divide = _ref.divide, + compare = _ref.compare, + partitionSelect = _ref.partitionSelect; + + /** + * Compute the median of a matrix or a list with values. The values are + * sorted and the middle value is returned. In case of an even number of + * values, the average of the two middle values is returned. + * Supported types of values are: Number, BigNumber, Unit + * + * In case of a (multi dimensional) array or matrix, the median of all + * elements will be calculated. + * + * Syntax: + * + * math.median(a, b, c, ...) + * math.median(A) + * + * Examples: + * + * math.median(5, 2, 7) // returns 5 + * math.median([3, -1, 5, 7]) // returns 4 + * + * See also: + * + * mean, min, max, sum, prod, std, variance, quantileSeq + * + * @param {... *} args A single matrix or or multiple scalar values + * @return {*} The median + */ + var median = typed(median_name, { + // median([a, b, c, d, ...]) + 'Array | Matrix': _median, + // median([a, b, c, d, ...], dim) + 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) { + // TODO: implement median(A, dim) + throw new Error('median(A, dim) is not yet supported'); // return reduce(arguments[0], arguments[1], ...) + }, + // median(a, b, c, d, ...) + '...': function _(args) { + if (containsCollections(args)) { + throw new TypeError('Scalar values expected in function median'); + } + + return _median(args); + } + }); + /** + * Recursively calculate the median of an n-dimensional array + * @param {Array} array + * @return {Number} median + * @private + */ + + function _median(array) { + try { + array = Object(utils_array["e" /* flatten */])(array.valueOf()); + var num = array.length; + + if (num === 0) { + throw new Error('Cannot calculate median of an empty array'); + } + + if (num % 2 === 0) { + // even: return the average of the two middle values + var mid = num / 2 - 1; + var right = partitionSelect(array, mid + 1); // array now partitioned at mid + 1, take max of left part + + var left = array[mid]; + + for (var i = 0; i < mid; ++i) { + if (compare(array[i], left) > 0) { + left = array[i]; + } + } + + return middle2(left, right); + } else { + // odd: return the middle value + var m = partitionSelect(array, (num - 1) / 2); + return middle(m); + } + } catch (err) { + throw improveErrorMessage(err, 'median'); + } + } // helper function to type check the middle value of the array + + + var middle = typed({ + 'number | BigNumber | Complex | Unit': function numberBigNumberComplexUnit(value) { + return value; + } + }); // helper function to type check the two middle value of the array + + var middle2 = typed({ + 'number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit': function numberBigNumberComplexUnitNumberBigNumberComplexUnit(left, right) { + return divide(add(left, right), 2); + } + }); + return median; +}); +// CONCATENATED MODULE: ./src/function/statistics/mad.js + + + +var mad_name = 'mad'; +var mad_dependencies = ['typed', 'abs', 'map', 'median', 'subtract']; +var createMad = /* #__PURE__ */Object(factory["a" /* factory */])(mad_name, mad_dependencies, function (_ref) { + var typed = _ref.typed, + abs = _ref.abs, + map = _ref.map, + median = _ref.median, + subtract = _ref.subtract; + + /** + * Compute the median absolute deviation of a matrix or a list with values. + * The median absolute deviation is defined as the median of the absolute + * deviations from the median. + * + * Syntax: + * + * math.mad(a, b, c, ...) + * math.mad(A) + * + * Examples: + * + * math.mad(10, 20, 30) // returns 10 + * math.mad([1, 2, 3]) // returns 1 + * math.mad([[1, 2, 3], [4, 5, 6]]) // returns 1.5 + * + * See also: + * + * median, mean, std, abs + * + * @param {Array | Matrix} array + * A single matrix or multiple scalar values. + * @return {*} The median absolute deviation. + */ + return typed(mad_name, { + // mad([a, b, c, d, ...]) + 'Array | Matrix': _mad, + // mad(a, b, c, d, ...) + '...': function _(args) { + return _mad(args); + } + }); + + function _mad(array) { + array = Object(utils_array["e" /* flatten */])(array.valueOf()); + + if (array.length === 0) { + throw new Error('Cannot calculate median absolute deviation (mad) of an empty array'); + } + + try { + var med = median(array); + return median(map(array, function (value) { + return abs(subtract(value, med)); + })); + } catch (err) { + if (err instanceof TypeError && err.message.indexOf('median') !== -1) { + throw new TypeError(err.message.replace('median', 'mad')); + } else { + throw improveErrorMessage(err, 'mad'); + } + } + } +}); +// CONCATENATED MODULE: ./src/function/statistics/variance.js + + + + + +var DEFAULT_NORMALIZATION = 'unbiased'; +var variance_name = 'variance'; +var variance_dependencies = ['typed', 'add', 'subtract', 'multiply', 'divide', 'apply', 'isNaN']; +var createVariance = /* #__PURE__ */Object(factory["a" /* factory */])(variance_name, variance_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + subtract = _ref.subtract, + multiply = _ref.multiply, + divide = _ref.divide, + apply = _ref.apply, + isNaN = _ref.isNaN; + + /** + * Compute the variance of a matrix or a list with values. + * In case of a (multi dimensional) array or matrix, the variance over all + * elements will be calculated. + * + * Additionally, it is possible to compute the variance along the rows + * or columns of a matrix by specifying the dimension as the second argument. + * + * Optionally, the type of normalization can be specified as the final + * parameter. The parameter `normalization` can be one of the following values: + * + * - 'unbiased' (default) The sum of squared errors is divided by (n - 1) + * - 'uncorrected' The sum of squared errors is divided by n + * - 'biased' The sum of squared errors is divided by (n + 1) + * + * + * Note that older browser may not like the variable name `var`. In that + * case, the function can be called as `math['var'](...)` instead of + * `math.var(...)`. + * + * Syntax: + * + * math.variance(a, b, c, ...) + * math.variance(A) + * math.variance(A, normalization) + * math.variance(A, dimension) + * math.variance(A, dimension, normalization) + * + * Examples: + * + * math.variance(2, 4, 6) // returns 4 + * math.variance([2, 4, 6, 8]) // returns 6.666666666666667 + * math.variance([2, 4, 6, 8], 'uncorrected') // returns 5 + * math.variance([2, 4, 6, 8], 'biased') // returns 4 + * + * math.variance([[1, 2, 3], [4, 5, 6]]) // returns 3.5 + * math.variance([[1, 2, 3], [4, 6, 8]], 0) // returns [4.5, 8, 12.5] + * math.variance([[1, 2, 3], [4, 6, 8]], 1) // returns [1, 4] + * math.variance([[1, 2, 3], [4, 6, 8]], 1, 'biased') // returns [0.5, 2] + * + * See also: + * + * mean, median, max, min, prod, std, sum + * + * @param {Array | Matrix} array + * A single matrix or or multiple scalar values + * @param {string} [normalization='unbiased'] + * Determines how to normalize the variance. + * Choose 'unbiased' (default), 'uncorrected', or 'biased'. + * @param dimension {number | BigNumber} + * Determines the axis to compute the variance for a matrix + * @return {*} The variance + */ + return typed(variance_name, { + // variance([a, b, c, d, ...]) + 'Array | Matrix': function ArrayMatrix(array) { + return _var(array, DEFAULT_NORMALIZATION); + }, + // variance([a, b, c, d, ...], normalization) + 'Array | Matrix, string': _var, + // variance([a, b, c, c, ...], dim) + 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) { + return _varDim(array, dim, DEFAULT_NORMALIZATION); + }, + // variance([a, b, c, c, ...], dim, normalization) + 'Array | Matrix, number | BigNumber, string': _varDim, + // variance(a, b, c, d, ...) + '...': function _(args) { + return _var(args, DEFAULT_NORMALIZATION); + } + }); + /** + * Recursively calculate the variance of an n-dimensional array + * @param {Array} array + * @param {string} normalization + * Determines how to normalize the variance: + * - 'unbiased' The sum of squared errors is divided by (n - 1) + * - 'uncorrected' The sum of squared errors is divided by n + * - 'biased' The sum of squared errors is divided by (n + 1) + * @return {number | BigNumber} variance + * @private + */ + + function _var(array, normalization) { + var sum = 0; + var num = 0; + + if (array.length === 0) { + throw new SyntaxError('Function variance requires one or more parameters (0 provided)'); + } // calculate the mean and number of elements + + + deepForEach(array, function (value) { + try { + sum = add(sum, value); + num++; + } catch (err) { + throw improveErrorMessage(err, 'variance', value); + } + }); + if (num === 0) throw new Error('Cannot calculate variance of an empty array'); + var mean = divide(sum, num); // calculate the variance + + sum = 0; + deepForEach(array, function (value) { + var diff = subtract(value, mean); + sum = add(sum, multiply(diff, diff)); + }); + + if (isNaN(sum)) { + return sum; + } + + switch (normalization) { + case 'uncorrected': + return divide(sum, num); + + case 'biased': + return divide(sum, num + 1); + + case 'unbiased': + { + var zero = Object(is["e" /* isBigNumber */])(sum) ? sum.mul(0) : 0; + return num === 1 ? zero : divide(sum, num - 1); + } + + default: + throw new Error('Unknown normalization "' + normalization + '". ' + 'Choose "unbiased" (default), "uncorrected", or "biased".'); + } + } + + function _varDim(array, dim, normalization) { + try { + if (array.length === 0) { + throw new SyntaxError('Function variance requires one or more parameters (0 provided)'); + } + + return apply(array, dim, function (x) { + return _var(x, normalization); + }); + } catch (err) { + throw improveErrorMessage(err, 'variance'); + } + } +}); // For backward compatibility, deprecated since version 6.0.0. Date: 2018-11-09 + +var createDeprecatedVar = /* #__PURE__ */Object(factory["a" /* factory */])('var', ['variance'], function (_ref2) { + var variance = _ref2.variance; + return function () { + Object(utils_log["a" /* warnOnce */])('Function "var" has been renamed to "variance" in v6.0.0, please use the new function instead.'); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return variance.apply(variance, args); + }; +}); +// CONCATENATED MODULE: ./src/function/statistics/quantileSeq.js + + + + +var quantileSeq_name = 'quantileSeq'; +var quantileSeq_dependencies = ['typed', 'add', 'multiply', 'partitionSelect', 'compare']; +var createQuantileSeq = /* #__PURE__ */Object(factory["a" /* factory */])(quantileSeq_name, quantileSeq_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + multiply = _ref.multiply, + partitionSelect = _ref.partitionSelect, + compare = _ref.compare; + + /** + * Compute the prob order quantile of a matrix or a list with values. + * The sequence is sorted and the middle value is returned. + * Supported types of sequence values are: Number, BigNumber, Unit + * Supported types of probability are: Number, BigNumber + * + * In case of a (multi dimensional) array or matrix, the prob order quantile + * of all elements will be calculated. + * + * Syntax: + * + * math.quantileSeq(A, prob[, sorted]) + * math.quantileSeq(A, [prob1, prob2, ...][, sorted]) + * math.quantileSeq(A, N[, sorted]) + * + * Examples: + * + * math.quantileSeq([3, -1, 5, 7], 0.5) // returns 4 + * math.quantileSeq([3, -1, 5, 7], [1/3, 2/3]) // returns [3, 5] + * math.quantileSeq([3, -1, 5, 7], 2) // returns [3, 5] + * math.quantileSeq([-1, 3, 5, 7], 0.5, true) // returns 4 + * + * See also: + * + * median, mean, min, max, sum, prod, std, variance + * + * @param {Array, Matrix} data A single matrix or Array + * @param {Number, BigNumber, Array} probOrN prob is the order of the quantile, while N is + * the amount of evenly distributed steps of + * probabilities; only one of these options can + * be provided + * @param {Boolean} sorted=false is data sorted in ascending order + * @return {Number, BigNumber, Unit, Array} Quantile(s) + */ + function quantileSeq(data, probOrN, sorted) { + var probArr, dataArr, one; + + if (arguments.length < 2 || arguments.length > 3) { + throw new SyntaxError('Function quantileSeq requires two or three parameters'); + } + + if (Object(is["i" /* isCollection */])(data)) { + sorted = sorted || false; + + if (typeof sorted === 'boolean') { + dataArr = data.valueOf(); + + if (Object(is["y" /* isNumber */])(probOrN)) { + if (probOrN < 0) { + throw new Error('N/prob must be non-negative'); + } + + if (probOrN <= 1) { + // quantileSeq([a, b, c, d, ...], prob[,sorted]) + return _quantileSeq(dataArr, probOrN, sorted); + } + + if (probOrN > 1) { + // quantileSeq([a, b, c, d, ...], N[,sorted]) + if (!Object(utils_number["i" /* isInteger */])(probOrN)) { + throw new Error('N must be a positive integer'); + } + + var nPlusOne = probOrN + 1; + probArr = new Array(probOrN); + + for (var i = 0; i < probOrN;) { + probArr[i] = _quantileSeq(dataArr, ++i / nPlusOne, sorted); + } + + return probArr; + } + } + + if (Object(is["e" /* isBigNumber */])(probOrN)) { + var BigNumber = probOrN.constructor; + + if (probOrN.isNegative()) { + throw new Error('N/prob must be non-negative'); + } + + one = new BigNumber(1); + + if (probOrN.lte(one)) { + // quantileSeq([a, b, c, d, ...], prob[,sorted]) + return new BigNumber(_quantileSeq(dataArr, probOrN, sorted)); + } + + if (probOrN.gt(one)) { + // quantileSeq([a, b, c, d, ...], N[,sorted]) + if (!probOrN.isInteger()) { + throw new Error('N must be a positive integer'); + } // largest possible Array length is 2^32-1 + // 2^32 < 10^15, thus safe conversion guaranteed + + + var intN = probOrN.toNumber(); + + if (intN > 4294967295) { + throw new Error('N must be less than or equal to 2^32-1, as that is the maximum length of an Array'); + } + + var _nPlusOne = new BigNumber(intN + 1); + + probArr = new Array(intN); + + for (var _i = 0; _i < intN;) { + probArr[_i] = new BigNumber(_quantileSeq(dataArr, new BigNumber(++_i).div(_nPlusOne), sorted)); + } + + return probArr; + } + } + + if (Array.isArray(probOrN)) { + // quantileSeq([a, b, c, d, ...], [prob1, prob2, ...][,sorted]) + probArr = new Array(probOrN.length); + + for (var _i2 = 0; _i2 < probArr.length; ++_i2) { + var currProb = probOrN[_i2]; + + if (Object(is["y" /* isNumber */])(currProb)) { + if (currProb < 0 || currProb > 1) { + throw new Error('Probability must be between 0 and 1, inclusive'); + } + } else if (Object(is["e" /* isBigNumber */])(currProb)) { + one = new currProb.constructor(1); + + if (currProb.isNegative() || currProb.gt(one)) { + throw new Error('Probability must be between 0 and 1, inclusive'); + } + } else { + throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function + } + + probArr[_i2] = _quantileSeq(dataArr, currProb, sorted); + } + + return probArr; + } + + throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function + } + + throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function + } + + throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function + } + /** + * Calculate the prob order quantile of an n-dimensional array. + * + * @param {Array} array + * @param {Number, BigNumber} prob + * @param {Boolean} sorted + * @return {Number, BigNumber, Unit} prob order quantile + * @private + */ + + + function _quantileSeq(array, prob, sorted) { + var flat = Object(utils_array["e" /* flatten */])(array); + var len = flat.length; + + if (len === 0) { + throw new Error('Cannot calculate quantile of an empty sequence'); + } + + if (Object(is["y" /* isNumber */])(prob)) { + var _index = prob * (len - 1); + + var _fracPart = _index % 1; + + if (_fracPart === 0) { + var value = sorted ? flat[_index] : partitionSelect(flat, _index); + validate(value); + return value; + } + + var _integerPart = Math.floor(_index); + + var _left; + + var _right; + + if (sorted) { + _left = flat[_integerPart]; + _right = flat[_integerPart + 1]; + } else { + _right = partitionSelect(flat, _integerPart + 1); // max of partition is kth largest + + _left = flat[_integerPart]; + + for (var i = 0; i < _integerPart; ++i) { + if (compare(flat[i], _left) > 0) { + _left = flat[i]; + } + } + } + + validate(_left); + validate(_right); // Q(prob) = (1-f)*A[floor(index)] + f*A[floor(index)+1] + + return add(multiply(_left, 1 - _fracPart), multiply(_right, _fracPart)); + } // If prob is a BigNumber + + + var index = prob.times(len - 1); + + if (index.isInteger()) { + index = index.toNumber(); + + var _value = sorted ? flat[index] : partitionSelect(flat, index); + + validate(_value); + return _value; + } + + var integerPart = index.floor(); + var fracPart = index.minus(integerPart); + var integerPartNumber = integerPart.toNumber(); + var left; + var right; + + if (sorted) { + left = flat[integerPartNumber]; + right = flat[integerPartNumber + 1]; + } else { + right = partitionSelect(flat, integerPartNumber + 1); // max of partition is kth largest + + left = flat[integerPartNumber]; + + for (var _i3 = 0; _i3 < integerPartNumber; ++_i3) { + if (compare(flat[_i3], left) > 0) { + left = flat[_i3]; + } + } + } + + validate(left); + validate(right); // Q(prob) = (1-f)*A[floor(index)] + f*A[floor(index)+1] + + var one = new fracPart.constructor(1); + return add(multiply(left, one.minus(fracPart)), multiply(right, fracPart)); + } + /** + * Check if array value types are valid, throw error otherwise. + * @param {number | BigNumber | Unit} x + * @param {number | BigNumber | Unit} x + * @private + */ + + + var validate = typed({ + 'number | BigNumber | Unit': function numberBigNumberUnit(x) { + return x; + } + }); + return quantileSeq; +}); +// CONCATENATED MODULE: ./src/function/statistics/std.js + +var std_name = 'std'; +var std_dependencies = ['typed', 'sqrt', 'variance']; +var createStd = /* #__PURE__ */Object(factory["a" /* factory */])(std_name, std_dependencies, function (_ref) { + var typed = _ref.typed, + sqrt = _ref.sqrt, + variance = _ref.variance; + + /** + * Compute the standard deviation of a matrix or a list with values. + * The standard deviations is defined as the square root of the variance: + * `std(A) = sqrt(variance(A))`. + * In case of a (multi dimensional) array or matrix, the standard deviation + * over all elements will be calculated by default, unless an axis is specified + * in which case the standard deviation will be computed along that axis. + * + * Additionally, it is possible to compute the standard deviation along the rows + * or columns of a matrix by specifying the dimension as the second argument. + * + * Optionally, the type of normalization can be specified as the final + * parameter. The parameter `normalization` can be one of the following values: + * + * - 'unbiased' (default) The sum of squared errors is divided by (n - 1) + * - 'uncorrected' The sum of squared errors is divided by n + * - 'biased' The sum of squared errors is divided by (n + 1) + * + * + * Syntax: + * + * math.std(a, b, c, ...) + * math.std(A) + * math.std(A, normalization) + * math.std(A, dimension) + * math.std(A, dimension, normalization) + * + * Examples: + * + * math.std(2, 4, 6) // returns 2 + * math.std([2, 4, 6, 8]) // returns 2.581988897471611 + * math.std([2, 4, 6, 8], 'uncorrected') // returns 2.23606797749979 + * math.std([2, 4, 6, 8], 'biased') // returns 2 + * + * math.std([[1, 2, 3], [4, 5, 6]]) // returns 1.8708286933869707 + * math.std([[1, 2, 3], [4, 6, 8]], 0) // returns [2.1213203435596424, 2.8284271247461903, 3.5355339059327378] + * math.std([[1, 2, 3], [4, 6, 8]], 1) // returns [1, 2] + * math.std([[1, 2, 3], [4, 6, 8]], 1, 'biased') // returns [0.7071067811865476, 1.4142135623730951] + * + * See also: + * + * mean, median, max, min, prod, sum, variance + * + * @param {Array | Matrix} array + * A single matrix or or multiple scalar values + * @param {string} [normalization='unbiased'] + * Determines how to normalize the variance. + * Choose 'unbiased' (default), 'uncorrected', or 'biased'. + * @param dimension {number | BigNumber} + * Determines the axis to compute the standard deviation for a matrix + * @return {*} The standard deviation + */ + return typed(std_name, { + // std([a, b, c, d, ...]) + 'Array | Matrix': _std, + // std([a, b, c, d, ...], normalization) + 'Array | Matrix, string': _std, + // std([a, b, c, c, ...], dim) + 'Array | Matrix, number | BigNumber': _std, + // std([a, b, c, c, ...], dim, normalization) + 'Array | Matrix, number | BigNumber, string': _std, + // std(a, b, c, d, ...) + '...': function _(args) { + return _std(args); + } + }); + + function _std(array, normalization) { + if (array.length === 0) { + throw new SyntaxError('Function std requires one or more parameters (0 provided)'); + } + + try { + return sqrt(variance.apply(null, arguments)); + } catch (err) { + if (err instanceof TypeError && err.message.indexOf(' variance') !== -1) { + throw new TypeError(err.message.replace(' variance', ' std')); + } else { + throw err; + } + } + } +}); +// CONCATENATED MODULE: ./src/utils/product.js +/** @param {number} i + * @param {number} n + * @returns {number} product of i to n + */ +function product_product(i, n) { + if (n < i) { + return 1; + } + + if (n === i) { + return n; + } + + var half = n + i >> 1; // divide (n + i) by 2 and truncate to integer + + return product_product(i, half) * product_product(half + 1, n); +} +// CONCATENATED MODULE: ./src/plain/number/combinations.js + + +function combinationsNumber(n, k) { + if (!Object(utils_number["i" /* isInteger */])(n) || n < 0) { + throw new TypeError('Positive integer value expected in function combinations'); + } + + if (!Object(utils_number["i" /* isInteger */])(k) || k < 0) { + throw new TypeError('Positive integer value expected in function combinations'); + } + + if (k > n) { + throw new TypeError('k must be less than or equal to n'); + } + + var nMinusk = n - k; + var prodrange; + + if (k < nMinusk) { + prodrange = product_product(nMinusk + 1, n); + return prodrange / product_product(1, k); + } + + prodrange = product_product(k + 1, n); + return prodrange / product_product(1, nMinusk); +} +combinationsNumber.signature = 'number, number'; +// CONCATENATED MODULE: ./src/function/probability/combinations.js + + +var combinations_name = 'combinations'; +var combinations_dependencies = ['typed']; +var createCombinations = /* #__PURE__ */Object(factory["a" /* factory */])(combinations_name, combinations_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the number of ways of picking `k` unordered outcomes from `n` + * possibilities. + * + * Combinations only takes integer arguments. + * The following condition must be enforced: k <= n. + * + * Syntax: + * + * math.combinations(n, k) + * + * Examples: + * + * math.combinations(7, 5) // returns 21 + * + * See also: + * + * combinationsWithRep, permutations, factorial + * + * @param {number | BigNumber} n Total number of objects in the set + * @param {number | BigNumber} k Number of objects in the subset + * @return {number | BigNumber} Number of possible combinations. + */ + return typed(combinations_name, { + 'number, number': combinationsNumber, + 'BigNumber, BigNumber': function BigNumberBigNumber(n, k) { + var BigNumber = n.constructor; + var result, i; + var nMinusk = n.minus(k); + var one = new BigNumber(1); + + if (!isPositiveInteger(n) || !isPositiveInteger(k)) { + throw new TypeError('Positive integer value expected in function combinations'); + } + + if (k.gt(n)) { + throw new TypeError('k must be less than n in function combinations'); + } + + result = one; + + if (k.lt(nMinusk)) { + for (i = one; i.lte(nMinusk); i = i.plus(one)) { + result = result.times(k.plus(i)).dividedBy(i); + } + } else { + for (i = one; i.lte(k); i = i.plus(one)) { + result = result.times(nMinusk.plus(i)).dividedBy(i); + } + } + + return result; + } // TODO: implement support for collection in combinations + + }); +}); +/** + * Test whether BigNumber n is a positive integer + * @param {BigNumber} n + * @returns {boolean} isPositiveInteger + */ + +function isPositiveInteger(n) { + return n.isInteger() && n.gte(0); +} +// CONCATENATED MODULE: ./src/function/probability/combinationsWithRep.js + + + +var combinationsWithRep_name = 'combinationsWithRep'; +var combinationsWithRep_dependencies = ['typed']; +var createCombinationsWithRep = /* #__PURE__ */Object(factory["a" /* factory */])(combinationsWithRep_name, combinationsWithRep_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Compute the number of ways of picking `k` unordered outcomes from `n` + * possibilities, allowing individual outcomes to be repeated more than once. + * + * CombinationsWithRep only takes integer arguments. + * The following condition must be enforced: k <= n + k -1. + * + * Syntax: + * + * math.combinationsWithRep(n, k) + * + * Examples: + * + * math.combinationsWithRep(7, 5) // returns 462 + * + * See also: + * + * combinations, permutations, factorial + * + * @param {number | BigNumber} n Total number of objects in the set + * @param {number | BigNumber} k Number of objects in the subset + * @return {number | BigNumber} Number of possible combinations with replacement. + */ + return typed(combinationsWithRep_name, { + 'number, number': function numberNumber(n, k) { + if (!Object(utils_number["i" /* isInteger */])(n) || n < 0) { + throw new TypeError('Positive integer value expected in function combinationsWithRep'); + } + + if (!Object(utils_number["i" /* isInteger */])(k) || k < 0) { + throw new TypeError('Positive integer value expected in function combinationsWithRep'); + } + + if (n < 1) { + throw new TypeError('k must be less than or equal to n + k - 1'); + } + + if (k < n - 1) { + var _prodrange = product_product(n, n + k - 1); + + return _prodrange / product_product(1, k); + } + + var prodrange = product_product(k + 1, n + k - 1); + return prodrange / product_product(1, n - 1); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(n, k) { + var BigNumber = n.constructor; + var result, i; + var one = new BigNumber(1); + var nMinusOne = n.minus(one); + + if (!combinationsWithRep_isPositiveInteger(n) || !combinationsWithRep_isPositiveInteger(k)) { + throw new TypeError('Positive integer value expected in function combinationsWithRep'); + } + + if (n.lt(one)) { + throw new TypeError('k must be less than or equal to n + k - 1 in function combinationsWithRep'); + } + + result = one; + + if (k.lt(nMinusOne)) { + for (i = one; i.lte(nMinusOne); i = i.plus(one)) { + result = result.times(k.plus(i)).dividedBy(i); + } + } else { + for (i = one; i.lte(k); i = i.plus(one)) { + result = result.times(nMinusOne.plus(i)).dividedBy(i); + } + } + + return result; + } + }); +}); +/** + * Test whether BigNumber n is a positive integer + * @param {BigNumber} n + * @returns {boolean} isPositiveInteger + */ + +function combinationsWithRep_isPositiveInteger(n) { + return n.isInteger() && n.gte(0); +} +// CONCATENATED MODULE: ./src/plain/number/probability.js + + +function gammaNumber(n) { + var x; + + if (Object(utils_number["i" /* isInteger */])(n)) { + if (n <= 0) { + return isFinite(n) ? Infinity : NaN; + } + + if (n > 171) { + return Infinity; // Will overflow + } + + return product_product(1, n - 1); + } + + if (n < 0.5) { + return Math.PI / (Math.sin(Math.PI * n) * gammaNumber(1 - n)); + } + + if (n >= 171.35) { + return Infinity; // will overflow + } + + if (n > 85.0) { + // Extended Stirling Approx + var twoN = n * n; + var threeN = twoN * n; + var fourN = threeN * n; + var fiveN = fourN * n; + return Math.sqrt(2 * Math.PI / n) * Math.pow(n / Math.E, n) * (1 + 1 / (12 * n) + 1 / (288 * twoN) - 139 / (51840 * threeN) - 571 / (2488320 * fourN) + 163879 / (209018880 * fiveN) + 5246819 / (75246796800 * fiveN * n)); + } + + --n; + x = gammaP[0]; + + for (var i = 1; i < gammaP.length; ++i) { + x += gammaP[i] / (n + i); + } + + var t = n + gammaG + 0.5; + return Math.sqrt(2 * Math.PI) * Math.pow(t, n + 0.5) * Math.exp(-t) * x; +} +gammaNumber.signature = 'number'; // TODO: comment on the variables g and p + +var gammaG = 4.7421875; +var gammaP = [0.99999999999999709182, 57.156235665862923517, -59.597960355475491248, 14.136097974741747174, -0.49191381609762019978, 0.33994649984811888699e-4, 0.46523628927048575665e-4, -0.98374475304879564677e-4, 0.15808870322491248884e-3, -0.21026444172410488319e-3, 0.21743961811521264320e-3, -0.16431810653676389022e-3, 0.84418223983852743293e-4, -0.26190838401581408670e-4, 0.36899182659531622704e-5]; +// CONCATENATED MODULE: ./src/function/probability/gamma.js + + + +var gamma_name = 'gamma'; +var gamma_dependencies = ['typed', 'config', 'multiplyScalar', 'pow', 'BigNumber', 'Complex']; +var createGamma = /* #__PURE__ */Object(factory["a" /* factory */])(gamma_name, gamma_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + multiplyScalar = _ref.multiplyScalar, + pow = _ref.pow, + _BigNumber = _ref.BigNumber, + _Complex = _ref.Complex; + + /** + * Compute the gamma function of a value using Lanczos approximation for + * small values, and an extended Stirling approximation for large values. + * + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.gamma(n) + * + * Examples: + * + * math.gamma(5) // returns 24 + * math.gamma(-0.5) // returns -3.5449077018110335 + * math.gamma(math.i) // returns -0.15494982830180973 - 0.49801566811835596i + * + * See also: + * + * combinations, factorial, permutations + * + * @param {number | Array | Matrix} n A real or complex number + * @return {number | Array | Matrix} The gamma of `n` + */ + var gamma = typed(gamma_name, { + number: gammaNumber, + Complex: function Complex(n) { + if (n.im === 0) { + return gamma(n.re); + } + + n = new _Complex(n.re - 1, n.im); + var x = new _Complex(gammaP[0], 0); + + for (var i = 1; i < gammaP.length; ++i) { + var real = n.re + i; // x += p[i]/(n+i) + + var den = real * real + n.im * n.im; + + if (den !== 0) { + x.re += gammaP[i] * real / den; + x.im += -(gammaP[i] * n.im) / den; + } else { + x.re = gammaP[i] < 0 ? -Infinity : Infinity; + } + } + + var t = new _Complex(n.re + gammaG + 0.5, n.im); + var twoPiSqrt = Math.sqrt(2 * Math.PI); + n.re += 0.5; + var result = pow(t, n); + + if (result.im === 0) { + // sqrt(2*PI)*result + result.re *= twoPiSqrt; + } else if (result.re === 0) { + result.im *= twoPiSqrt; + } else { + result.re *= twoPiSqrt; + result.im *= twoPiSqrt; + } + + var r = Math.exp(-t.re); // exp(-t) + + t.re = r * Math.cos(-t.im); + t.im = r * Math.sin(-t.im); + return multiplyScalar(multiplyScalar(result, t), x); + }, + BigNumber: function BigNumber(n) { + if (n.isInteger()) { + return n.isNegative() || n.isZero() ? new _BigNumber(Infinity) : bigFactorial(n.minus(1)); + } + + if (!n.isFinite()) { + return new _BigNumber(n.isNegative() ? NaN : Infinity); + } + + throw new Error('Integer BigNumber expected'); + }, + 'Array | Matrix': function ArrayMatrix(n) { + return deepMap(n, gamma); + } + }); + /** + * Calculate factorial for a BigNumber + * @param {BigNumber} n + * @returns {BigNumber} Returns the factorial of n + */ + + function bigFactorial(n) { + if (n < 8) { + return new _BigNumber([1, 1, 2, 6, 24, 120, 720, 5040][n]); + } + + var precision = config.precision + (Math.log(n.toNumber()) | 0); + + var Big = _BigNumber.clone({ + precision: precision + }); + + if (n % 2 === 1) { + return n.times(bigFactorial(new _BigNumber(n - 1))); + } + + var p = n; + var prod = new Big(n); + var sum = n.toNumber(); + + while (p > 2) { + p -= 2; + sum += p; + prod = prod.times(sum); + } + + return new _BigNumber(prod.toPrecision(_BigNumber.precision)); + } + + return gamma; +}); +// CONCATENATED MODULE: ./src/function/probability/factorial.js + + +var factorial_name = 'factorial'; +var factorial_dependencies = ['typed', 'gamma']; +var createFactorial = /* #__PURE__ */Object(factory["a" /* factory */])(factorial_name, factorial_dependencies, function (_ref) { + var typed = _ref.typed, + gamma = _ref.gamma; + + /** + * Compute the factorial of a value + * + * Factorial only supports an integer value as argument. + * For matrices, the function is evaluated element wise. + * + * Syntax: + * + * math.factorial(n) + * + * Examples: + * + * math.factorial(5) // returns 120 + * math.factorial(3) // returns 6 + * + * See also: + * + * combinations, combinationsWithRep, gamma, permutations + * + * @param {number | BigNumber | Array | Matrix} n An integer number + * @return {number | BigNumber | Array | Matrix} The factorial of `n` + */ + var factorial = typed(factorial_name, { + number: function number(n) { + if (n < 0) { + throw new Error('Value must be non-negative'); + } + + return gamma(n + 1); + }, + BigNumber: function BigNumber(n) { + if (n.isNegative()) { + throw new Error('Value must be non-negative'); + } + + return gamma(n.plus(1)); + }, + 'Array | Matrix': function ArrayMatrix(n) { + return deepMap(n, factorial); + } + }); + return factorial; +}); +// CONCATENATED MODULE: ./src/function/probability/kldivergence.js + +var kldivergence_name = 'kldivergence'; +var kldivergence_dependencies = ['typed', 'matrix', 'divide', 'sum', 'multiply', 'dotDivide', 'log', 'isNumeric']; +var createKldivergence = /* #__PURE__ */Object(factory["a" /* factory */])(kldivergence_name, kldivergence_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + divide = _ref.divide, + sum = _ref.sum, + multiply = _ref.multiply, + dotDivide = _ref.dotDivide, + log = _ref.log, + isNumeric = _ref.isNumeric; + + /** + * Calculate the Kullback-Leibler (KL) divergence between two distributions + * + * Syntax: + * + * math.kldivergence(x, y) + * + * Examples: + * + * math.kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5]) //returns 0.24376698773121153 + * + * + * @param {Array | Matrix} q First vector + * @param {Array | Matrix} p Second vector + * @return {number} Returns distance between q and p + */ + return typed(kldivergence_name, { + 'Array, Array': function ArrayArray(q, p) { + return _kldiv(matrix(q), matrix(p)); + }, + 'Matrix, Array': function MatrixArray(q, p) { + return _kldiv(q, matrix(p)); + }, + 'Array, Matrix': function ArrayMatrix(q, p) { + return _kldiv(matrix(q), p); + }, + 'Matrix, Matrix': function MatrixMatrix(q, p) { + return _kldiv(q, p); + } + }); + + function _kldiv(q, p) { + var plength = p.size().length; + var qlength = q.size().length; + + if (plength > 1) { + throw new Error('first object must be one dimensional'); + } + + if (qlength > 1) { + throw new Error('second object must be one dimensional'); + } + + if (plength !== qlength) { + throw new Error('Length of two vectors must be equal'); + } // Before calculation, apply normalization + + + var sumq = sum(q); + + if (sumq === 0) { + throw new Error('Sum of elements in first object must be non zero'); + } + + var sump = sum(p); + + if (sump === 0) { + throw new Error('Sum of elements in second object must be non zero'); + } + + var qnorm = divide(q, sum(q)); + var pnorm = divide(p, sum(p)); + var result = sum(multiply(qnorm, log(dotDivide(qnorm, pnorm)))); + + if (isNumeric(result)) { + return result; + } else { + return Number.NaN; + } + } +}); +// CONCATENATED MODULE: ./src/function/probability/multinomial.js + + +var multinomial_name = 'multinomial'; +var multinomial_dependencies = ['typed', 'add', 'divide', 'multiply', 'factorial', 'isInteger', 'isPositive']; +var createMultinomial = /* #__PURE__ */Object(factory["a" /* factory */])(multinomial_name, multinomial_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + divide = _ref.divide, + multiply = _ref.multiply, + factorial = _ref.factorial, + isInteger = _ref.isInteger, + isPositive = _ref.isPositive; + + /** + * Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities. + * + * multinomial takes one array of integers as an argument. + * The following condition must be enforced: every ai <= 0 + * + * Syntax: + * + * math.multinomial(a) // a is an array type + * + * Examples: + * + * math.multinomial([1,2,1]) // returns 12 + * + * See also: + * + * combinations, factorial + * + * @param {number[] | BigNumber[]} a Integer numbers of objects in the subset + * @return {Number | BigNumber} Multinomial coefficient. + */ + return typed(multinomial_name, { + 'Array | Matrix': function ArrayMatrix(a) { + var sum = 0; + var denom = 1; + deepForEach(a, function (ai) { + if (!isInteger(ai) || !isPositive(ai)) { + throw new TypeError('Positive integer value expected in function multinomial'); + } + + sum = add(sum, ai); + denom = multiply(denom, factorial(ai)); + }); + return divide(factorial(sum), denom); + } + }); +}); +// CONCATENATED MODULE: ./src/function/probability/permutations.js + + + +var permutations_name = 'permutations'; +var permutations_dependencies = ['typed', 'factorial']; +var createPermutations = /* #__PURE__ */Object(factory["a" /* factory */])(permutations_name, permutations_dependencies, function (_ref) { + var typed = _ref.typed, + factorial = _ref.factorial; + + /** + * Compute the number of ways of obtaining an ordered subset of `k` elements + * from a set of `n` elements. + * + * Permutations only takes integer arguments. + * The following condition must be enforced: k <= n. + * + * Syntax: + * + * math.permutations(n) + * math.permutations(n, k) + * + * Examples: + * + * math.permutations(5) // 120 + * math.permutations(5, 3) // 60 + * + * See also: + * + * combinations, combinationsWithRep, factorial + * + * @param {number | BigNumber} n The number of objects in total + * @param {number | BigNumber} [k] The number of objects in the subset + * @return {number | BigNumber} The number of permutations + */ + return typed(permutations_name, { + 'number | BigNumber': factorial, + 'number, number': function numberNumber(n, k) { + if (!Object(utils_number["i" /* isInteger */])(n) || n < 0) { + throw new TypeError('Positive integer value expected in function permutations'); + } + + if (!Object(utils_number["i" /* isInteger */])(k) || k < 0) { + throw new TypeError('Positive integer value expected in function permutations'); + } + + if (k > n) { + throw new TypeError('second argument k must be less than or equal to first argument n'); + } // Permute n objects, k at a time + + + return product_product(n - k + 1, n); + }, + 'BigNumber, BigNumber': function BigNumberBigNumber(n, k) { + var result, i; + + if (!permutations_isPositiveInteger(n) || !permutations_isPositiveInteger(k)) { + throw new TypeError('Positive integer value expected in function permutations'); + } + + if (k.gt(n)) { + throw new TypeError('second argument k must be less than or equal to first argument n'); + } + + var one = n.mul(0).add(1); + result = one; + + for (i = n.minus(k).plus(1); i.lte(n); i = i.plus(1)) { + result = result.times(i); + } + + return result; + } // TODO: implement support for collection in permutations + + }); +}); +/** + * Test whether BigNumber n is a positive integer + * @param {BigNumber} n + * @returns {boolean} isPositiveInteger + */ + +function permutations_isPositiveInteger(n) { + return n.isInteger() && n.gte(0); +} +// EXTERNAL MODULE: ./node_modules/seed-random/index.js +var seed_random = __webpack_require__(15); +var seed_random_default = /*#__PURE__*/__webpack_require__.n(seed_random); + +// CONCATENATED MODULE: ./src/function/probability/util/seededRNG.js +// create a random seed here to prevent an infinite loop from seed-random +// inside the factory. Reason is that math.random is defined as a getter/setter +// and seed-random generates a seed from the local entropy by reading every +// defined object including `math` itself. That means that whilst getting +// math.random, it tries to get math.random, etc... an infinite loop. +// See https://github.com/ForbesLindesay/seed-random/issues/6 + +var singletonRandom = /* #__PURE__ */seed_random_default()(); +function createRng(randomSeed) { + var random; // create a new random generator with given seed + + function setSeed(seed) { + random = seed === null ? singletonRandom : seed_random_default()(String(seed)); + } // initialize a seeded pseudo random number generator with config's random seed + + + setSeed(randomSeed); // wrapper function so the rng can be updated via generator + + function rng() { + return random(); + } + + return rng; +} +// CONCATENATED MODULE: ./src/function/probability/pickRandom.js + + + + +var pickRandom_name = 'pickRandom'; +var pickRandom_dependencies = ['typed', 'config', '?on']; +var createPickRandom = /* #__PURE__ */Object(factory["a" /* factory */])(pickRandom_name, pickRandom_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + on = _ref.on; + // seeded pseudo random number generator + var rng = createRng(config.randomSeed); + + if (on) { + on('config', function (curr, prev) { + if (curr.randomSeed !== prev.randomSeed) { + rng = createRng(curr.randomSeed); + } + }); + } + /** + * Random pick one or more values from a one dimensional array. + * Array elements are picked using a random function with uniform or weighted distribution. + * + * Syntax: + * + * math.pickRandom(array) + * math.pickRandom(array, number) + * math.pickRandom(array, weights) + * math.pickRandom(array, number, weights) + * math.pickRandom(array, weights, number) + * + * Examples: + * + * math.pickRandom([3, 6, 12, 2]) // returns one of the values in the array + * math.pickRandom([3, 6, 12, 2], 2) // returns an array of two of the values in the array + * math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1]) // returns one of the values in the array with weighted distribution + * math.pickRandom([3, 6, 12, 2], 2, [1, 3, 2, 1]) // returns an array of two of the values in the array with weighted distribution + * math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1], 2) // returns an array of two of the values in the array with weighted distribution + * + * See also: + * + * random, randomInt + * + * @param {Array | Matrix} array A one dimensional array + * @param {Int} number An int or float + * @param {Array | Matrix} weights An array of ints or floats + * @return {number | Array} Returns a single random value from array when number is 1 or undefined. + * Returns an array with the configured number of elements when number is > 1. + */ + + + return typed({ + 'Array | Matrix': function ArrayMatrix(possibles) { + return _pickRandom(possibles); + }, + 'Array | Matrix, number': function ArrayMatrixNumber(possibles, number) { + return _pickRandom(possibles, number, undefined); + }, + 'Array | Matrix, Array': function ArrayMatrixArray(possibles, weights) { + return _pickRandom(possibles, undefined, weights); + }, + 'Array | Matrix, Array | Matrix, number': function ArrayMatrixArrayMatrixNumber(possibles, weights, number) { + return _pickRandom(possibles, number, weights); + }, + 'Array | Matrix, number, Array | Matrix': function ArrayMatrixNumberArrayMatrix(possibles, number, weights) { + return _pickRandom(possibles, number, weights); + } + }); + + function _pickRandom(possibles, number, weights) { + var single = typeof number === 'undefined'; + + if (single) { + number = 1; + } + + possibles = possibles.valueOf(); // get Array + + if (weights) { + weights = weights.valueOf(); // get Array + } + + if (Object(utils_array["a" /* arraySize */])(possibles).length > 1) { + throw new Error('Only one dimensional vectors supported'); + } + + var totalWeights = 0; + + if (typeof weights !== 'undefined') { + if (weights.length !== possibles.length) { + throw new Error('Weights must have the same length as possibles'); + } + + for (var i = 0, len = weights.length; i < len; i++) { + if (!Object(is["y" /* isNumber */])(weights[i]) || weights[i] < 0) { + throw new Error('Weights must be an array of positive numbers'); + } + + totalWeights += weights[i]; + } + } + + var length = possibles.length; + + if (length === 0) { + return []; + } else if (number >= length) { + return number > 1 ? possibles : possibles[0]; + } + + var result = []; + var pick; + + while (result.length < number) { + if (typeof weights === 'undefined') { + pick = possibles[Math.floor(rng() * length)]; + } else { + var randKey = rng() * totalWeights; + + for (var _i = 0, _len = possibles.length; _i < _len; _i++) { + randKey -= weights[_i]; + + if (randKey < 0) { + pick = possibles[_i]; + break; + } + } + } + + if (result.indexOf(pick) === -1) { + result.push(pick); + } + } + + return single ? result[0] : result; // TODO: return matrix when input was a matrix + // TODO: add support for multi dimensional matrices + } +}); +// CONCATENATED MODULE: ./src/function/probability/util/randomMatrix.js +/** + * This is a util function for generating a random matrix recursively. + * @param {number[]} size + * @param {function} random + * @returns {Array} + */ +function randomMatrix(size, random) { + var data = []; + size = size.slice(0); + + if (size.length > 1) { + for (var i = 0, length = size.shift(); i < length; i++) { + data.push(randomMatrix(size, random)); + } + } else { + for (var _i = 0, _length = size.shift(); _i < _length; _i++) { + data.push(random()); + } + } + + return data; +} +// CONCATENATED MODULE: ./src/function/probability/random.js + + + + +var random_name = 'random'; +var random_dependencies = ['typed', 'config', '?on']; +var createRandom = /* #__PURE__ */Object(factory["a" /* factory */])(random_name, random_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + on = _ref.on; + // seeded pseudo random number generator + var rng = createRng(config.randomSeed); + + if (on) { + on('config', function (curr, prev) { + if (curr.randomSeed !== prev.randomSeed) { + rng = createRng(curr.randomSeed); + } + }); + } + /** + * Return a random number larger or equal to `min` and smaller than `max` + * using a uniform distribution. + * + * Syntax: + * + * math.random() // generate a random number between 0 and 1 + * math.random(max) // generate a random number between 0 and max + * math.random(min, max) // generate a random number between min and max + * math.random(size) // generate a matrix with random numbers between 0 and 1 + * math.random(size, max) // generate a matrix with random numbers between 0 and max + * math.random(size, min, max) // generate a matrix with random numbers between min and max + * + * Examples: + * + * math.random() // returns a random number between 0 and 1 + * math.random(100) // returns a random number between 0 and 100 + * math.random(30, 40) // returns a random number between 30 and 40 + * math.random([2, 3]) // returns a 2x3 matrix with random numbers between 0 and 1 + * + * See also: + * + * randomInt, pickRandom + * + * @param {Array | Matrix} [size] If provided, an array or matrix with given + * size and filled with random values is returned + * @param {number} [min] Minimum boundary for the random value, included + * @param {number} [max] Maximum boundary for the random value, excluded + * @return {number | Array | Matrix} A random number + */ + + + return typed(random_name, { + '': function _() { + return _random(0, 1); + }, + number: function number(max) { + return _random(0, max); + }, + 'number, number': function numberNumber(min, max) { + return _random(min, max); + }, + 'Array | Matrix': function ArrayMatrix(size) { + return _randomMatrix(size, 0, 1); + }, + 'Array | Matrix, number': function ArrayMatrixNumber(size, max) { + return _randomMatrix(size, 0, max); + }, + 'Array | Matrix, number, number': function ArrayMatrixNumberNumber(size, min, max) { + return _randomMatrix(size, min, max); + } + }); + + function _randomMatrix(size, min, max) { + var res = randomMatrix(size.valueOf(), function () { + return _random(min, max); + }); + return Object(is["v" /* isMatrix */])(size) ? size.create(res) : res; + } + + function _random(min, max) { + return min + rng() * (max - min); + } +}); // number only implementation of random, no matrix support +// TODO: there is quite some duplicate code in both createRandom and createRandomNumber, can we improve that? + +var createRandomNumber = /* #__PURE__ */Object(factory["a" /* factory */])(random_name, ['typed', 'config', '?on'], function (_ref2) { + var typed = _ref2.typed, + config = _ref2.config, + on = _ref2.on, + matrix = _ref2.matrix; + // seeded pseudo random number generator1 + var rng = createRng(config.randomSeed); + + if (on) { + on('config', function (curr, prev) { + if (curr.randomSeed !== prev.randomSeed) { + rng = createRng(curr.randomSeed); + } + }); + } + + return typed(random_name, { + '': function _() { + return _random(0, 1); + }, + number: function number(max) { + return _random(0, max); + }, + 'number, number': function numberNumber(min, max) { + return _random(min, max); + } + }); + + function _random(min, max) { + return min + rng() * (max - min); + } +}); +// CONCATENATED MODULE: ./src/function/probability/randomInt.js + + + + +var randomInt_name = 'randomInt'; +var randomInt_dependencies = ['typed', 'config', '?on']; +var createRandomInt = /* #__PURE__ */Object(factory["a" /* factory */])(randomInt_name, randomInt_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + on = _ref.on; + // seeded pseudo random number generator + var rng = createRng(config.randomSeed); + + if (on) { + on('config', function (curr, prev) { + if (curr.randomSeed !== prev.randomSeed) { + rng = createRng(curr.randomSeed); + } + }); + } + /** + * Return a random integer number larger or equal to `min` and smaller than `max` + * using a uniform distribution. + * + * Syntax: + * + * math.randomInt() // generate a random integer between 0 and 1 + * math.randomInt(max) // generate a random integer between 0 and max + * math.randomInt(min, max) // generate a random integer between min and max + * math.randomInt(size) // generate a matrix with random integer between 0 and 1 + * math.randomInt(size, max) // generate a matrix with random integer between 0 and max + * math.randomInt(size, min, max) // generate a matrix with random integer between min and max + * + * Examples: + * + * math.randomInt(100) // returns a random integer between 0 and 100 + * math.randomInt(30, 40) // returns a random integer between 30 and 40 + * math.randomInt([2, 3]) // returns a 2x3 matrix with random integers between 0 and 1 + * + * See also: + * + * random, pickRandom + * + * @param {Array | Matrix} [size] If provided, an array or matrix with given + * size and filled with random values is returned + * @param {number} [min] Minimum boundary for the random value, included + * @param {number} [max] Maximum boundary for the random value, excluded + * @return {number | Array | Matrix} A random integer value + */ + + + return typed(randomInt_name, { + '': function _() { + return _randomInt(0, 1); + }, + number: function number(max) { + return _randomInt(0, max); + }, + 'number, number': function numberNumber(min, max) { + return _randomInt(min, max); + }, + 'Array | Matrix': function ArrayMatrix(size) { + return _randomIntMatrix(size, 0, 1); + }, + 'Array | Matrix, number': function ArrayMatrixNumber(size, max) { + return _randomIntMatrix(size, 0, max); + }, + 'Array | Matrix, number, number': function ArrayMatrixNumberNumber(size, min, max) { + return _randomIntMatrix(size, min, max); + } + }); + + function _randomIntMatrix(size, min, max) { + var res = randomMatrix(size.valueOf(), function () { + return _randomInt(min, max); + }); + return Object(is["v" /* isMatrix */])(size) ? size.create(res) : res; + } + + function _randomInt(min, max) { + return Math.floor(min + rng() * (max - min)); + } +}); +// CONCATENATED MODULE: ./src/function/combinatorics/stirlingS2.js + +var stirlingS2_name = 'stirlingS2'; +var stirlingS2_dependencies = ['typed', 'addScalar', 'subtract', 'multiplyScalar', 'divideScalar', 'pow', 'factorial', 'combinations', 'isNegative', 'isInteger', 'larger']; +var createStirlingS2 = /* #__PURE__ */Object(factory["a" /* factory */])(stirlingS2_name, stirlingS2_dependencies, function (_ref) { + var typed = _ref.typed, + addScalar = _ref.addScalar, + subtract = _ref.subtract, + multiplyScalar = _ref.multiplyScalar, + divideScalar = _ref.divideScalar, + pow = _ref.pow, + factorial = _ref.factorial, + combinations = _ref.combinations, + isNegative = _ref.isNegative, + isInteger = _ref.isInteger, + larger = _ref.larger; + + /** + * The Stirling numbers of the second kind, counts the number of ways to partition + * a set of n labelled objects into k nonempty unlabelled subsets. + * stirlingS2 only takes integer arguments. + * The following condition must be enforced: k <= n. + * + * If n = k or k = 1, then s(n,k) = 1 + * + * Syntax: + * + * math.stirlingS2(n, k) + * + * Examples: + * + * math.stirlingS2(5, 3) //returns 25 + * + * See also: + * + * bellNumbers + * + * @param {Number | BigNumber} n Total number of objects in the set + * @param {Number | BigNumber} k Number of objects in the subset + * @return {Number | BigNumber} S(n,k) + */ + return typed(stirlingS2_name, { + 'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(n, k) { + if (!isInteger(n) || isNegative(n) || !isInteger(k) || isNegative(k)) { + throw new TypeError('Non-negative integer value expected in function stirlingS2'); + } else if (larger(k, n)) { + throw new TypeError('k must be less than or equal to n in function stirlingS2'); + } // 1/k! Sum(i=0 -> k) [(-1)^(k-i)*C(k,j)* i^n] + + + var kFactorial = factorial(k); + var result = 0; + + for (var i = 0; i <= k; i++) { + var negativeOne = pow(-1, subtract(k, i)); + var kChooseI = combinations(k, i); + var iPower = pow(i, n); + result = addScalar(result, multiplyScalar(multiplyScalar(kChooseI, iPower), negativeOne)); + } + + return divideScalar(result, kFactorial); + } + }); +}); +// CONCATENATED MODULE: ./src/function/combinatorics/bellNumbers.js + +var bellNumbers_name = 'bellNumbers'; +var bellNumbers_dependencies = ['typed', 'addScalar', 'isNegative', 'isInteger', 'stirlingS2']; +var createBellNumbers = /* #__PURE__ */Object(factory["a" /* factory */])(bellNumbers_name, bellNumbers_dependencies, function (_ref) { + var typed = _ref.typed, + addScalar = _ref.addScalar, + isNegative = _ref.isNegative, + isInteger = _ref.isInteger, + stirlingS2 = _ref.stirlingS2; + + /** + * The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S. + * bellNumbers only takes integer arguments. + * The following condition must be enforced: n >= 0 + * + * Syntax: + * + * math.bellNumbers(n) + * + * Examples: + * + * math.bellNumbers(3) // returns 5 + * math.bellNumbers(8) // returns 4140 + * + * See also: + * + * stirlingS2 + * + * @param {Number | BigNumber} n Total number of objects in the set + * @return {Number | BigNumber} B(n) + */ + return typed(bellNumbers_name, { + 'number | BigNumber': function numberBigNumber(n) { + if (!isInteger(n) || isNegative(n)) { + throw new TypeError('Non-negative integer value expected in function bellNumbers'); + } // Sum (k=0, n) S(n,k). + + + var result = 0; + + for (var i = 0; i <= n; i++) { + result = addScalar(result, stirlingS2(n, i)); + } + + return result; + } + }); +}); +// CONCATENATED MODULE: ./src/function/combinatorics/catalan.js + +var catalan_name = 'catalan'; +var catalan_dependencies = ['typed', 'addScalar', 'divideScalar', 'multiplyScalar', 'combinations', 'isNegative', 'isInteger']; +var createCatalan = /* #__PURE__ */Object(factory["a" /* factory */])(catalan_name, catalan_dependencies, function (_ref) { + var typed = _ref.typed, + addScalar = _ref.addScalar, + divideScalar = _ref.divideScalar, + multiplyScalar = _ref.multiplyScalar, + combinations = _ref.combinations, + isNegative = _ref.isNegative, + isInteger = _ref.isInteger; + + /** + * The Catalan Numbers enumerate combinatorial structures of many different types. + * catalan only takes integer arguments. + * The following condition must be enforced: n >= 0 + * + * Syntax: + * + * math.catalan(n) + * + * Examples: + * + * math.catalan(3) // returns 5 + * math.catalan(8) // returns 1430 + * + * See also: + * + * bellNumbers + * + * @param {Number | BigNumber} n nth Catalan number + * @return {Number | BigNumber} Cn(n) + */ + return typed(catalan_name, { + 'number | BigNumber': function numberBigNumber(n) { + if (!isInteger(n) || isNegative(n)) { + throw new TypeError('Non-negative integer value expected in function catalan'); + } + + return divideScalar(combinations(multiplyScalar(n, 2), n), addScalar(n, 1)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/combinatorics/composition.js + +var composition_name = 'composition'; +var composition_dependencies = ['typed', 'addScalar', 'combinations', 'isNegative', 'isPositive', 'isInteger', 'larger']; +var createComposition = /* #__PURE__ */Object(factory["a" /* factory */])(composition_name, composition_dependencies, function (_ref) { + var typed = _ref.typed, + addScalar = _ref.addScalar, + combinations = _ref.combinations, + isPositive = _ref.isPositive, + isNegative = _ref.isNegative, + isInteger = _ref.isInteger, + larger = _ref.larger; + + /** + * The composition counts of n into k parts. + * + * composition only takes integer arguments. + * The following condition must be enforced: k <= n. + * + * Syntax: + * + * math.composition(n, k) + * + * Examples: + * + * math.composition(5, 3) // returns 6 + * + * See also: + * + * combinations + * + * @param {Number | BigNumber} n Total number of objects in the set + * @param {Number | BigNumber} k Number of objects in the subset + * @return {Number | BigNumber} Returns the composition counts of n into k parts. + */ + return typed(composition_name, { + 'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(n, k) { + if (!isInteger(n) || !isPositive(n) || !isInteger(k) || !isPositive(k)) { + throw new TypeError('Positive integer value expected in function composition'); + } else if (larger(k, n)) { + throw new TypeError('k must be less than or equal to n in function composition'); + } + + return combinations(addScalar(n, -1), addScalar(k, -1)); + } + }); +}); +// CONCATENATED MODULE: ./src/function/algebra/simplify/util.js + + + +var util_name = 'simplifyUtil'; +var util_dependencies = ['FunctionNode', 'OperatorNode', 'SymbolNode']; +var createUtil = /* #__PURE__ */Object(factory["a" /* factory */])(util_name, util_dependencies, function (_ref) { + var FunctionNode = _ref.FunctionNode, + OperatorNode = _ref.OperatorNode, + SymbolNode = _ref.SymbolNode; + // TODO commutative/associative properties rely on the arguments + // e.g. multiply is not commutative for matrices + // The properties should be calculated from an argument to simplify, or possibly something in math.config + // the other option is for typed() to specify a return type so that we can evaluate the type of arguments + var commutative = { + add: true, + multiply: true + }; + var associative = { + add: true, + multiply: true + }; + + function isCommutative(node, context) { + if (!Object(is["B" /* isOperatorNode */])(node)) { + return true; + } + + var name = node.fn.toString(); + + if (context && Object(utils_object["f" /* hasOwnProperty */])(context, name) && Object(utils_object["f" /* hasOwnProperty */])(context[name], 'commutative')) { + return context[name].commutative; + } + + return commutative[name] || false; + } + + function isAssociative(node, context) { + if (!Object(is["B" /* isOperatorNode */])(node)) { + return false; + } + + var name = node.fn.toString(); + + if (context && Object(utils_object["f" /* hasOwnProperty */])(context, name) && Object(utils_object["f" /* hasOwnProperty */])(context[name], 'associative')) { + return context[name].associative; + } + + return associative[name] || false; + } + /** + * Flatten all associative operators in an expression tree. + * Assumes parentheses have already been removed. + */ + + + function flatten(node) { + if (!node.args || node.args.length === 0) { + return node; + } + + node.args = allChildren(node); + + for (var i = 0; i < node.args.length; i++) { + flatten(node.args[i]); + } + } + /** + * Get the children of a node as if it has been flattened. + * TODO implement for FunctionNodes + */ + + + function allChildren(node) { + var op; + var children = []; + + var findChildren = function findChildren(node) { + for (var i = 0; i < node.args.length; i++) { + var child = node.args[i]; + + if (Object(is["B" /* isOperatorNode */])(child) && op === child.op) { + findChildren(child); + } else { + children.push(child); + } + } + }; + + if (isAssociative(node)) { + op = node.op; + findChildren(node); + return children; + } else { + return node.args; + } + } + /** + * Unflatten all flattened operators to a right-heavy binary tree. + */ + + + function unflattenr(node) { + if (!node.args || node.args.length === 0) { + return; + } + + var makeNode = createMakeNodeFunction(node); + var l = node.args.length; + + for (var i = 0; i < l; i++) { + unflattenr(node.args[i]); + } + + if (l > 2 && isAssociative(node)) { + var curnode = node.args.pop(); + + while (node.args.length > 0) { + curnode = makeNode([node.args.pop(), curnode]); + } + + node.args = curnode.args; + } + } + /** + * Unflatten all flattened operators to a left-heavy binary tree. + */ + + + function unflattenl(node) { + if (!node.args || node.args.length === 0) { + return; + } + + var makeNode = createMakeNodeFunction(node); + var l = node.args.length; + + for (var i = 0; i < l; i++) { + unflattenl(node.args[i]); + } + + if (l > 2 && isAssociative(node)) { + var curnode = node.args.shift(); + + while (node.args.length > 0) { + curnode = makeNode([curnode, node.args.shift()]); + } + + node.args = curnode.args; + } + } + + function createMakeNodeFunction(node) { + if (Object(is["B" /* isOperatorNode */])(node)) { + return function (args) { + try { + return new OperatorNode(node.op, node.fn, args, node.implicit); + } catch (err) { + console.error(err); + return []; + } + }; + } else { + return function (args) { + return new FunctionNode(new SymbolNode(node.name), args); + }; + } + } + + return { + createMakeNodeFunction: createMakeNodeFunction, + isCommutative: isCommutative, + isAssociative: isAssociative, + flatten: flatten, + allChildren: allChildren, + unflattenr: unflattenr, + unflattenl: unflattenl + }; +}); +// CONCATENATED MODULE: ./src/function/algebra/simplify/simplifyCore.js + + +var simplifyCore_name = 'simplifyCore'; +var simplifyCore_dependencies = ['equal', 'isZero', 'add', 'subtract', 'multiply', 'divide', 'pow', 'ConstantNode', 'OperatorNode', 'FunctionNode', 'ParenthesisNode']; +var createSimplifyCore = /* #__PURE__ */Object(factory["a" /* factory */])(simplifyCore_name, simplifyCore_dependencies, function (_ref) { + var equal = _ref.equal, + isZero = _ref.isZero, + add = _ref.add, + subtract = _ref.subtract, + multiply = _ref.multiply, + divide = _ref.divide, + pow = _ref.pow, + ConstantNode = _ref.ConstantNode, + OperatorNode = _ref.OperatorNode, + FunctionNode = _ref.FunctionNode, + ParenthesisNode = _ref.ParenthesisNode; + var node0 = new ConstantNode(0); + var node1 = new ConstantNode(1); + /** + * simplifyCore() performs single pass simplification suitable for + * applications requiring ultimate performance. In contrast, simplify() + * extends simplifyCore() with additional passes to provide deeper + * simplification. + * + * Syntax: + * + * simplify.simplifyCore(expr) + * + * Examples: + * + * const f = math.parse('2 * 1 * x ^ (2 - 1)') + * math.simplify.simpifyCore(f) // Node {2 * x} + * math.simplify('2 * 1 * x ^ (2 - 1)', [math.simplify.simpifyCore]) // Node {2 * x} + * + * See also: + * + * derivative + * + * @param {Node} node + * The expression to be simplified + */ + + function simplifyCore(node) { + if (Object(is["B" /* isOperatorNode */])(node) && node.isUnary()) { + var a0 = simplifyCore(node.args[0]); + + if (node.op === '+') { + // unary plus + return a0; + } + + if (node.op === '-') { + // unary minus + if (Object(is["B" /* isOperatorNode */])(a0)) { + if (a0.isUnary() && a0.op === '-') { + return a0.args[0]; + } else if (a0.isBinary() && a0.fn === 'subtract') { + return new OperatorNode('-', 'subtract', [a0.args[1], a0.args[0]]); + } + } + + return new OperatorNode(node.op, node.fn, [a0]); + } + } else if (Object(is["B" /* isOperatorNode */])(node) && node.isBinary()) { + var _a = simplifyCore(node.args[0]); + + var a1 = simplifyCore(node.args[1]); + + if (node.op === '+') { + if (Object(is["l" /* isConstantNode */])(_a)) { + if (isZero(_a.value)) { + return a1; + } else if (Object(is["l" /* isConstantNode */])(a1)) { + return new ConstantNode(add(_a.value, a1.value)); + } + } + + if (Object(is["l" /* isConstantNode */])(a1) && isZero(a1.value)) { + return _a; + } + + if (Object(is["B" /* isOperatorNode */])(a1) && a1.isUnary() && a1.op === '-') { + return new OperatorNode('-', 'subtract', [_a, a1.args[0]]); + } + + return new OperatorNode(node.op, node.fn, a1 ? [_a, a1] : [_a]); + } else if (node.op === '-') { + if (Object(is["l" /* isConstantNode */])(_a) && a1) { + if (Object(is["l" /* isConstantNode */])(a1)) { + return new ConstantNode(subtract(_a.value, a1.value)); + } else if (isZero(_a.value)) { + return new OperatorNode('-', 'unaryMinus', [a1]); + } + } // if (node.fn === "subtract" && node.args.length === 2) { + + + if (node.fn === 'subtract') { + if (Object(is["l" /* isConstantNode */])(a1) && isZero(a1.value)) { + return _a; + } + + if (Object(is["B" /* isOperatorNode */])(a1) && a1.isUnary() && a1.op === '-') { + return simplifyCore(new OperatorNode('+', 'add', [_a, a1.args[0]])); + } + + return new OperatorNode(node.op, node.fn, [_a, a1]); + } + } else if (node.op === '*') { + if (Object(is["l" /* isConstantNode */])(_a)) { + if (isZero(_a.value)) { + return node0; + } else if (equal(_a.value, 1)) { + return a1; + } else if (Object(is["l" /* isConstantNode */])(a1)) { + return new ConstantNode(multiply(_a.value, a1.value)); + } + } + + if (Object(is["l" /* isConstantNode */])(a1)) { + if (isZero(a1.value)) { + return node0; + } else if (equal(a1.value, 1)) { + return _a; + } else if (Object(is["B" /* isOperatorNode */])(_a) && _a.isBinary() && _a.op === node.op) { + var a00 = _a.args[0]; + + if (Object(is["l" /* isConstantNode */])(a00)) { + var a00a1 = new ConstantNode(multiply(a00.value, a1.value)); + return new OperatorNode(node.op, node.fn, [a00a1, _a.args[1]], node.implicit); // constants on left + } + } + + return new OperatorNode(node.op, node.fn, [a1, _a], node.implicit); // constants on left + } + + return new OperatorNode(node.op, node.fn, [_a, a1], node.implicit); + } else if (node.op === '/') { + if (Object(is["l" /* isConstantNode */])(_a)) { + if (isZero(_a.value)) { + return node0; + } else if (Object(is["l" /* isConstantNode */])(a1) && (equal(a1.value, 1) || equal(a1.value, 2) || equal(a1.value, 4))) { + return new ConstantNode(divide(_a.value, a1.value)); + } + } + + return new OperatorNode(node.op, node.fn, [_a, a1]); + } else if (node.op === '^') { + if (Object(is["l" /* isConstantNode */])(a1)) { + if (isZero(a1.value)) { + return node1; + } else if (equal(a1.value, 1)) { + return _a; + } else { + if (Object(is["l" /* isConstantNode */])(_a)) { + // fold constant + return new ConstantNode(pow(_a.value, a1.value)); + } else if (Object(is["B" /* isOperatorNode */])(_a) && _a.isBinary() && _a.op === '^') { + var a01 = _a.args[1]; + + if (Object(is["l" /* isConstantNode */])(a01)) { + return new OperatorNode(node.op, node.fn, [_a.args[0], new ConstantNode(multiply(a01.value, a1.value))]); + } + } + } + } + + return new OperatorNode(node.op, node.fn, [_a, a1]); + } + } else if (Object(is["C" /* isParenthesisNode */])(node)) { + var c = simplifyCore(node.content); + + if (Object(is["C" /* isParenthesisNode */])(c) || Object(is["J" /* isSymbolNode */])(c) || Object(is["l" /* isConstantNode */])(c)) { + return c; + } + + return new ParenthesisNode(c); + } else if (Object(is["r" /* isFunctionNode */])(node)) { + var args = node.args.map(simplifyCore).map(function (arg) { + return Object(is["C" /* isParenthesisNode */])(arg) ? arg.content : arg; + }); + return new FunctionNode(simplifyCore(node.fn), args); + } else {// cannot simplify + } + + return node; + } + + return simplifyCore; +}); +// CONCATENATED MODULE: ./src/function/algebra/simplify/simplifyConstant.js +// TODO this could be improved by simplifying seperated constants under associative and commutative operators + + + + +var simplifyConstant_name = 'simplifyConstant'; +var simplifyConstant_dependencies = ['typed', 'config', 'mathWithTransform', '?fraction', '?bignumber', 'ConstantNode', 'OperatorNode', 'FunctionNode', 'SymbolNode']; +var createSimplifyConstant = /* #__PURE__ */Object(factory["a" /* factory */])(simplifyConstant_name, simplifyConstant_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + mathWithTransform = _ref.mathWithTransform, + fraction = _ref.fraction, + bignumber = _ref.bignumber, + ConstantNode = _ref.ConstantNode, + OperatorNode = _ref.OperatorNode, + FunctionNode = _ref.FunctionNode, + SymbolNode = _ref.SymbolNode; + + var _createUtil = createUtil({ + FunctionNode: FunctionNode, + OperatorNode: OperatorNode, + SymbolNode: SymbolNode + }), + isCommutative = _createUtil.isCommutative, + isAssociative = _createUtil.isAssociative, + allChildren = _createUtil.allChildren, + createMakeNodeFunction = _createUtil.createMakeNodeFunction; + + function simplifyConstant(expr, options) { + var res = foldFraction(expr, options); + return Object(is["w" /* isNode */])(res) ? res : _toNode(res); + } + + function _eval(fnname, args, options) { + try { + return _toNumber(mathWithTransform[fnname].apply(null, args), options); + } catch (ignore) { + // sometimes the implicit type conversion causes the evaluation to fail, so we'll try again after removing Fractions + args = args.map(function (x) { + if (Object(is["o" /* isFraction */])(x)) { + return x.valueOf(); + } + + return x; + }); + return _toNumber(mathWithTransform[fnname].apply(null, args), options); + } + } + + var _toNode = typed({ + Fraction: _fractionToNode, + number: function number(n) { + if (n < 0) { + return unaryMinusNode(new ConstantNode(-n)); + } + + return new ConstantNode(n); + }, + BigNumber: function BigNumber(n) { + if (n < 0) { + return unaryMinusNode(new ConstantNode(-n)); + } + + return new ConstantNode(n); // old parameters: (n.toString(), 'number') + }, + Complex: function Complex(s) { + throw new Error('Cannot convert Complex number to Node'); + } + }); // convert a number to a fraction only if it can be expressed exactly + + + function _exactFraction(n, options) { + var exactFractions = options && options.exactFractions !== false; + + if (exactFractions && isFinite(n) && fraction) { + var f = fraction(n); + + if (f.valueOf() === n) { + return f; + } + } + + return n; + } // Convert numbers to a preferred number type in preference order: Fraction, number, Complex + // BigNumbers are left alone + + + var _toNumber = typed({ + 'string, Object': function stringObject(s, options) { + if (config.number === 'BigNumber') { + if (bignumber === undefined) { + noBignumber(); + } + + return bignumber(s); + } else if (config.number === 'Fraction') { + if (fraction === undefined) { + noFraction(); + } + + return fraction(s); + } else { + var n = parseFloat(s); + return _exactFraction(n, options); + } + }, + 'Fraction, Object': function FractionObject(s, options) { + return s; + }, + // we don't need options here + 'BigNumber, Object': function BigNumberObject(s, options) { + return s; + }, + // we don't need options here + 'number, Object': function numberObject(s, options) { + return _exactFraction(s, options); + }, + 'Complex, Object': function ComplexObject(s, options) { + if (s.im !== 0) { + return s; + } + + return _exactFraction(s.re, options); + } + }); + + function unaryMinusNode(n) { + return new OperatorNode('-', 'unaryMinus', [n]); + } + + function _fractionToNode(f) { + var n; + var vn = f.s * f.n; + + if (vn < 0) { + n = new OperatorNode('-', 'unaryMinus', [new ConstantNode(-vn)]); + } else { + n = new ConstantNode(vn); + } + + if (f.d === 1) { + return n; + } + + return new OperatorNode('/', 'divide', [n, new ConstantNode(f.d)]); + } + /* + * Create a binary tree from a list of Fractions and Nodes. + * Tries to fold Fractions by evaluating them until the first Node in the list is hit, so + * `args` should be sorted to have the Fractions at the start (if the operator is commutative). + * @param args - list of Fractions and Nodes + * @param fn - evaluator for the binary operation evaluator that accepts two Fractions + * @param makeNode - creates a binary OperatorNode/FunctionNode from a list of child Nodes + * if args.length is 1, returns args[0] + * @return - Either a Node representing a binary expression or Fraction + */ + + + function foldOp(fn, args, makeNode, options) { + return args.reduce(function (a, b) { + if (!Object(is["w" /* isNode */])(a) && !Object(is["w" /* isNode */])(b)) { + try { + return _eval(fn, [a, b], options); + } catch (ignoreandcontinue) {} + + a = _toNode(a); + b = _toNode(b); + } else if (!Object(is["w" /* isNode */])(a)) { + a = _toNode(a); + } else if (!Object(is["w" /* isNode */])(b)) { + b = _toNode(b); + } + + return makeNode([a, b]); + }); + } // destroys the original node and returns a folded one + + + function foldFraction(node, options) { + switch (node.type) { + case 'SymbolNode': + return node; + + case 'ConstantNode': + if (typeof node.value === 'number' || !isNaN(node.value)) { + return _toNumber(node.value, options); + } + + return node; + + case 'FunctionNode': + if (mathWithTransform[node.name] && mathWithTransform[node.name].rawArgs) { + return node; + } + + { + // Process operators as OperatorNode + var operatorFunctions = ['add', 'multiply']; + + if (operatorFunctions.indexOf(node.name) === -1) { + var args = node.args.map(function (arg) { + return foldFraction(arg, options); + }); // If all args are numbers + + if (!args.some(is["w" /* isNode */])) { + try { + return _eval(node.name, args, options); + } catch (ignoreandcontine) {} + } // Convert all args to nodes and construct a symbolic function call + + + args = args.map(function (arg) { + return Object(is["w" /* isNode */])(arg) ? arg : _toNode(arg); + }); + return new FunctionNode(node.name, args); + } else {// treat as operator + } + } + + /* falls through */ + + case 'OperatorNode': + { + var fn = node.fn.toString(); + + var _args; + + var res; + var makeNode = createMakeNodeFunction(node); + + if (Object(is["B" /* isOperatorNode */])(node) && node.isUnary()) { + _args = [foldFraction(node.args[0], options)]; + + if (!Object(is["w" /* isNode */])(_args[0])) { + res = _eval(fn, _args, options); + } else { + res = makeNode(_args); + } + } else if (isAssociative(node)) { + _args = allChildren(node); + _args = _args.map(function (arg) { + return foldFraction(arg, options); + }); + + if (isCommutative(fn)) { + // commutative binary operator + var consts = []; + var vars = []; + + for (var i = 0; i < _args.length; i++) { + if (!Object(is["w" /* isNode */])(_args[i])) { + consts.push(_args[i]); + } else { + vars.push(_args[i]); + } + } + + if (consts.length > 1) { + res = foldOp(fn, consts, makeNode, options); + vars.unshift(res); + res = foldOp(fn, vars, makeNode, options); + } else { + // we won't change the children order since it's not neccessary + res = foldOp(fn, _args, makeNode, options); + } + } else { + // non-commutative binary operator + res = foldOp(fn, _args, makeNode, options); + } + } else { + // non-associative binary operator + _args = node.args.map(function (arg) { + return foldFraction(arg, options); + }); + res = foldOp(fn, _args, makeNode, options); + } + + return res; + } + + case 'ParenthesisNode': + // remove the uneccessary parenthesis + return foldFraction(node.content, options); + + case 'AccessorNode': + /* falls through */ + + case 'ArrayNode': + /* falls through */ + + case 'AssignmentNode': + /* falls through */ + + case 'BlockNode': + /* falls through */ + + case 'FunctionAssignmentNode': + /* falls through */ + + case 'IndexNode': + /* falls through */ + + case 'ObjectNode': + /* falls through */ + + case 'RangeNode': + /* falls through */ + + case 'ConditionalNode': + /* falls through */ + + default: + throw new Error("Unimplemented node type in simplifyConstant: ".concat(node.type)); + } + } + + return simplifyConstant; +}); +// CONCATENATED MODULE: ./src/function/algebra/simplify/resolve.js + + +var resolve_name = 'resolve'; +var resolve_dependencies = ['parse', 'FunctionNode', 'OperatorNode', 'ParenthesisNode']; +var createResolve = /* #__PURE__ */Object(factory["a" /* factory */])(resolve_name, resolve_dependencies, function (_ref) { + var parse = _ref.parse, + FunctionNode = _ref.FunctionNode, + OperatorNode = _ref.OperatorNode, + ParenthesisNode = _ref.ParenthesisNode; + + /** + * resolve(expr, scope) replaces variable nodes with their scoped values + * + * Syntax: + * + * simplify.resolve(expr, scope) + * + * Examples: + * + * math.simplify.resolve('x + y', {x:1, y:2}) // Node {1 + 2} + * math.simplify.resolve(math.parse('x+y'), {x:1, y:2}) // Node {1 + 2} + * math.simplify('x+y', {x:2, y:'x+x'}).toString() // "6" + * + * @param {Node} node + * The expression tree to be simplified + * @param {Object} scope with variables to be resolved + */ + function resolve(node, scope) { + if (!scope) { + return node; + } + + if (Object(is["J" /* isSymbolNode */])(node)) { + var value = scope[node.name]; + + if (Object(is["w" /* isNode */])(value)) { + return resolve(value, scope); + } else if (typeof value === 'number') { + return parse(String(value)); + } + } else if (Object(is["B" /* isOperatorNode */])(node)) { + var args = node.args.map(function (arg) { + return resolve(arg, scope); + }); + return new OperatorNode(node.op, node.fn, args, node.implicit); + } else if (Object(is["C" /* isParenthesisNode */])(node)) { + return new ParenthesisNode(resolve(node.content, scope)); + } else if (Object(is["r" /* isFunctionNode */])(node)) { + var _args = node.args.map(function (arg) { + return resolve(arg, scope); + }); + + return new FunctionNode(node.name, _args); + } + + return node; + } + + return resolve; +}); +// CONCATENATED MODULE: ./src/function/algebra/simplify.js +function simplify_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { simplify_typeof = function _typeof(obj) { return typeof obj; }; } else { simplify_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return simplify_typeof(obj); } + + + + + + + + +var simplify_name = 'simplify'; +var simplify_dependencies = ['config', 'typed', 'parse', 'add', 'subtract', 'multiply', 'divide', 'pow', 'isZero', 'equal', '?fraction', '?bignumber', 'mathWithTransform', 'ConstantNode', 'FunctionNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode']; +var createSimplify = /* #__PURE__ */Object(factory["a" /* factory */])(simplify_name, simplify_dependencies, function (_ref) { + var config = _ref.config, + typed = _ref.typed, + parse = _ref.parse, + add = _ref.add, + subtract = _ref.subtract, + multiply = _ref.multiply, + divide = _ref.divide, + pow = _ref.pow, + isZero = _ref.isZero, + equal = _ref.equal, + fraction = _ref.fraction, + bignumber = _ref.bignumber, + mathWithTransform = _ref.mathWithTransform, + ConstantNode = _ref.ConstantNode, + FunctionNode = _ref.FunctionNode, + OperatorNode = _ref.OperatorNode, + ParenthesisNode = _ref.ParenthesisNode, + SymbolNode = _ref.SymbolNode; + var simplifyConstant = createSimplifyConstant({ + typed: typed, + config: config, + mathWithTransform: mathWithTransform, + fraction: fraction, + bignumber: bignumber, + ConstantNode: ConstantNode, + OperatorNode: OperatorNode, + FunctionNode: FunctionNode, + SymbolNode: SymbolNode + }); + var simplifyCore = createSimplifyCore({ + equal: equal, + isZero: isZero, + add: add, + subtract: subtract, + multiply: multiply, + divide: divide, + pow: pow, + ConstantNode: ConstantNode, + OperatorNode: OperatorNode, + FunctionNode: FunctionNode, + ParenthesisNode: ParenthesisNode + }); + var resolve = createResolve({ + parse: parse, + FunctionNode: FunctionNode, + OperatorNode: OperatorNode, + ParenthesisNode: ParenthesisNode + }); + + var _createUtil = createUtil({ + FunctionNode: FunctionNode, + OperatorNode: OperatorNode, + SymbolNode: SymbolNode + }), + isCommutative = _createUtil.isCommutative, + isAssociative = _createUtil.isAssociative, + flatten = _createUtil.flatten, + unflattenr = _createUtil.unflattenr, + unflattenl = _createUtil.unflattenl, + createMakeNodeFunction = _createUtil.createMakeNodeFunction; + /** + * Simplify an expression tree. + * + * A list of rules are applied to an expression, repeating over the list until + * no further changes are made. + * It's possible to pass a custom set of rules to the function as second + * argument. A rule can be specified as an object, string, or function: + * + * const rules = [ + * { l: 'n1*n3 + n2*n3', r: '(n1+n2)*n3' }, + * 'n1*n3 + n2*n3 -> (n1+n2)*n3', + * function (node) { + * // ... return a new node or return the node unchanged + * return node + * } + * ] + * + * String and object rules consist of a left and right pattern. The left is + * used to match against the expression and the right determines what matches + * are replaced with. The main difference between a pattern and a normal + * expression is that variables starting with the following characters are + * interpreted as wildcards: + * + * - 'n' - matches any Node + * - 'c' - matches any ConstantNode + * - 'v' - matches any Node that is not a ConstantNode + * + * The default list of rules is exposed on the function as `simplify.rules` + * and can be used as a basis to built a set of custom rules. + * + * For more details on the theory, see: + * + * - [Strategies for simplifying math expressions (Stackoverflow)](https://stackoverflow.com/questions/7540227/strategies-for-simplifying-math-expressions) + * - [Symbolic computation - Simplification (Wikipedia)](https://en.wikipedia.org/wiki/Symbolic_computation#Simplification) + * + * An optional `options` argument can be passed as last argument of `simplify`. + * There is currently one option available: `exactFractions`, a boolean which + * is `true` by default. + * + * Syntax: + * + * simplify(expr) + * simplify(expr, rules) + * simplify(expr, rules) + * simplify(expr, rules, scope) + * simplify(expr, rules, scope, options) + * simplify(expr, scope) + * simplify(expr, scope, options) + * + * Examples: + * + * math.simplify('2 * 1 * x ^ (2 - 1)') // Node "2 * x" + * math.simplify('2 * 3 * x', {x: 4}) // Node "24" + * const f = math.parse('2 * 1 * x ^ (2 - 1)') + * math.simplify(f) // Node "2 * x" + * math.simplify('0.4 * x', {}, {exactFractions: true}) // Node "x * 2 / 5" + * math.simplify('0.4 * x', {}, {exactFractions: false}) // Node "0.4 * x" + * + * See also: + * + * derivative, parse, evaluate, rationalize + * + * @param {Node | string} expr + * The expression to be simplified + * @param {Array<{l:string, r: string} | string | function>} [rules] + * Optional list with custom rules + * @return {Node} Returns the simplified form of `expr` + */ + + + var simplify = typed('simplify', { + string: function string(expr) { + return simplify(parse(expr), simplify.rules, {}, {}); + }, + 'string, Object': function stringObject(expr, scope) { + return simplify(parse(expr), simplify.rules, scope, {}); + }, + 'string, Object, Object': function stringObjectObject(expr, scope, options) { + return simplify(parse(expr), simplify.rules, scope, options); + }, + 'string, Array': function stringArray(expr, rules) { + return simplify(parse(expr), rules, {}, {}); + }, + 'string, Array, Object': function stringArrayObject(expr, rules, scope) { + return simplify(parse(expr), rules, scope, {}); + }, + 'string, Array, Object, Object': function stringArrayObjectObject(expr, rules, scope, options) { + return simplify(parse(expr), rules, scope, options); + }, + 'Node, Object': function NodeObject(expr, scope) { + return simplify(expr, simplify.rules, scope, {}); + }, + 'Node, Object, Object': function NodeObjectObject(expr, scope, options) { + return simplify(expr, simplify.rules, scope, options); + }, + Node: function Node(expr) { + return simplify(expr, simplify.rules, {}, {}); + }, + 'Node, Array': function NodeArray(expr, rules) { + return simplify(expr, rules, {}, {}); + }, + 'Node, Array, Object': function NodeArrayObject(expr, rules, scope) { + return simplify(expr, rules, scope, {}); + }, + 'Node, Array, Object, Object': function NodeArrayObjectObject(expr, rules, scope, options) { + rules = _buildRules(rules); + var res = resolve(expr, scope); + res = removeParens(res); + var visited = {}; + var str = res.toString({ + parenthesis: 'all' + }); + + while (!visited[str]) { + visited[str] = true; + _lastsym = 0; // counter for placeholder symbols + + for (var i = 0; i < rules.length; i++) { + if (typeof rules[i] === 'function') { + res = rules[i](res, options); + } else { + flatten(res); + res = applyRule(res, rules[i]); + } + + unflattenl(res); // using left-heavy binary tree here since custom rule functions may expect it + } + + str = res.toString({ + parenthesis: 'all' + }); + } + + return res; + } + }); + simplify.simplifyCore = simplifyCore; + simplify.resolve = resolve; + + function removeParens(node) { + return node.transform(function (node, path, parent) { + return Object(is["C" /* isParenthesisNode */])(node) ? removeParens(node.content) : node; + }); + } // All constants that are allowed in rules + + + var SUPPORTED_CONSTANTS = { + "true": true, + "false": true, + e: true, + i: true, + Infinity: true, + LN2: true, + LN10: true, + LOG2E: true, + LOG10E: true, + NaN: true, + phi: true, + pi: true, + SQRT1_2: true, + SQRT2: true, + tau: true // null: false, + // undefined: false, + // version: false, + + }; // Array of strings, used to build the ruleSet. + // Each l (left side) and r (right side) are parsed by + // the expression parser into a node tree. + // Left hand sides are matched to subtrees within the + // expression to be parsed and replaced with the right + // hand side. + // TODO: Add support for constraints on constants (either in the form of a '=' expression or a callback [callback allows things like comparing symbols alphabetically]) + // To evaluate lhs constants for rhs constants, use: { l: 'c1+c2', r: 'c3', evaluate: 'c3 = c1 + c2' }. Multiple assignments are separated by ';' in block format. + // It is possible to get into an infinite loop with conflicting rules + + simplify.rules = [simplifyCore, // { l: 'n+0', r: 'n' }, // simplifyCore + // { l: 'n^0', r: '1' }, // simplifyCore + // { l: '0*n', r: '0' }, // simplifyCore + // { l: 'n/n', r: '1'}, // simplifyCore + // { l: 'n^1', r: 'n' }, // simplifyCore + // { l: '+n1', r:'n1' }, // simplifyCore + // { l: 'n--n1', r:'n+n1' }, // simplifyCore + { + l: 'log(e)', + r: '1' + }, // temporary rules + { + l: 'n-n1', + r: 'n+-n1' + }, // temporarily replace 'subtract' so we can further flatten the 'add' operator + { + l: '-(c*v)', + r: '(-c) * v' + }, // make non-constant terms positive + { + l: '-v', + r: '(-1) * v' + }, { + l: 'n/n1^n2', + r: 'n*n1^-n2' + }, // temporarily replace 'divide' so we can further flatten the 'multiply' operator + { + l: 'n/n1', + r: 'n*n1^-1' + }, // expand nested exponentiation + { + l: '(n ^ n1) ^ n2', + r: 'n ^ (n1 * n2)' + }, // collect like factors + { + l: 'n*n', + r: 'n^2' + }, { + l: 'n * n^n1', + r: 'n^(n1+1)' + }, { + l: 'n^n1 * n^n2', + r: 'n^(n1+n2)' + }, // collect like terms + { + l: 'n+n', + r: '2*n' + }, { + l: 'n+-n', + r: '0' + }, { + l: 'n1*n2 + n2', + r: '(n1+1)*n2' + }, { + l: 'n1*n3 + n2*n3', + r: '(n1+n2)*n3' + }, // remove parenthesis in the case of negating a quantitiy + { + l: 'n1 + -1 * (n2 + n3)', + r: 'n1 + -1 * n2 + -1 * n3' + }, simplifyConstant, { + l: '(-n)*n1', + r: '-(n*n1)' + }, // make factors positive (and undo 'make non-constant terms positive') + // ordering of constants + { + l: 'c+v', + r: 'v+c', + context: { + add: { + commutative: false + } + } + }, { + l: 'v*c', + r: 'c*v', + context: { + multiply: { + commutative: false + } + } + }, // undo temporary rules + // { l: '(-1) * n', r: '-n' }, // #811 added test which proved this is redundant + { + l: 'n+-n1', + r: 'n-n1' + }, // undo replace 'subtract' + { + l: 'n*(n1^-1)', + r: 'n/n1' + }, // undo replace 'divide' + { + l: 'n*n1^-n2', + r: 'n/n1^n2' + }, { + l: 'n1^-1', + r: '1/n1' + }, { + l: 'n*(n1/n2)', + r: '(n*n1)/n2' + }, // '*' before '/' + { + l: 'n-(n1+n2)', + r: 'n-n1-n2' + }, // '-' before '+' + // { l: '(n1/n2)/n3', r: 'n1/(n2*n3)' }, + // { l: '(n*n1)/(n*n2)', r: 'n1/n2' }, + { + l: '1*n', + r: 'n' + }, // this pattern can be produced by simplifyConstant + { + l: 'n1/(n2/n3)', + r: '(n1*n3)/n2' + }]; + /** + * Parse the string array of rules into nodes + * + * Example syntax for rules: + * + * Position constants to the left in a product: + * { l: 'n1 * c1', r: 'c1 * n1' } + * n1 is any Node, and c1 is a ConstantNode. + * + * Apply difference of squares formula: + * { l: '(n1 - n2) * (n1 + n2)', r: 'n1^2 - n2^2' } + * n1, n2 mean any Node. + * + * Short hand notation: + * 'n1 * c1 -> c1 * n1' + */ + + function _buildRules(rules) { + // Array of rules to be used to simplify expressions + var ruleSet = []; + + for (var i = 0; i < rules.length; i++) { + var rule = rules[i]; + var newRule = void 0; + + var ruleType = simplify_typeof(rule); + + switch (ruleType) { + case 'string': + { + var lr = rule.split('->'); + + if (lr.length === 2) { + rule = { + l: lr[0], + r: lr[1] + }; + } else { + throw SyntaxError('Could not parse rule: ' + rule); + } + } + + /* falls through */ + + case 'object': + newRule = { + l: removeParens(parse(rule.l)), + r: removeParens(parse(rule.r)) + }; + + if (rule.context) { + newRule.evaluate = rule.context; + } + + if (rule.evaluate) { + newRule.evaluate = parse(rule.evaluate); + } + + if (isAssociative(newRule.l)) { + var makeNode = createMakeNodeFunction(newRule.l); + + var expandsym = _getExpandPlaceholderSymbol(); + + newRule.expanded = {}; + newRule.expanded.l = makeNode([newRule.l.clone(), expandsym]); // Push the expandsym into the deepest possible branch. + // This helps to match the newRule against nodes returned from getSplits() later on. + + flatten(newRule.expanded.l); + unflattenr(newRule.expanded.l); + newRule.expanded.r = makeNode([newRule.r, expandsym]); + } + + break; + + case 'function': + newRule = rule; + break; + + default: + throw TypeError('Unsupported type of rule: ' + ruleType); + } // console.log('Adding rule: ' + rules[i]) + // console.log(newRule) + + + ruleSet.push(newRule); + } + + return ruleSet; + } + + var _lastsym = 0; + + function _getExpandPlaceholderSymbol() { + return new SymbolNode('_p' + _lastsym++); + } + /** + * Returns a simplfied form of node, or the original node if no simplification was possible. + * + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node + * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The simplified form of `expr`, or the original node if no simplification was possible. + */ + + + var applyRule = typed('applyRule', { + 'Node, Object': function NodeObject(node, rule) { + // console.log('Entering applyRule(' + node.toString() + ')') + // Do not clone node unless we find a match + var res = node; // First replace our child nodes with their simplified versions + // If a child could not be simplified, the assignments will have + // no effect since the node is returned unchanged + + if (res instanceof OperatorNode || res instanceof FunctionNode) { + if (res.args) { + for (var i = 0; i < res.args.length; i++) { + res.args[i] = applyRule(res.args[i], rule); + } + } + } else if (res instanceof ParenthesisNode) { + if (res.content) { + res.content = applyRule(res.content, rule); + } + } // Try to match a rule against this node + + + var repl = rule.r; + + var matches = _ruleMatch(rule.l, res)[0]; // If the rule is associative operator, we can try matching it while allowing additional terms. + // This allows us to match rules like 'n+n' to the expression '(1+x)+x' or even 'x+1+x' if the operator is commutative. + + + if (!matches && rule.expanded) { + repl = rule.expanded.r; + matches = _ruleMatch(rule.expanded.l, res)[0]; + } + + if (matches) { + // const before = res.toString({parenthesis: 'all'}) + // Create a new node by cloning the rhs of the matched rule + // we keep any implicit multiplication state if relevant + var implicit = res.implicit; + res = repl.clone(); + + if (implicit && 'implicit' in repl) { + res.implicit = true; + } // Replace placeholders with their respective nodes without traversing deeper into the replaced nodes + + + res = res.transform(function (node) { + if (node.isSymbolNode && Object(utils_object["f" /* hasOwnProperty */])(matches.placeholders, node.name)) { + return matches.placeholders[node.name].clone(); + } else { + return node; + } + }); // const after = res.toString({parenthesis: 'all'}) + // console.log('Simplified ' + before + ' to ' + after) + } + + return res; + } + }); + /** + * Get (binary) combinations of a flattened binary node + * e.g. +(node1, node2, node3) -> [ + * +(node1, +(node2, node3)), + * +(node2, +(node1, node3)), + * +(node3, +(node1, node2))] + * + */ + + function getSplits(node, context) { + var res = []; + var right, rightArgs; + var makeNode = createMakeNodeFunction(node); + + if (isCommutative(node, context)) { + for (var i = 0; i < node.args.length; i++) { + rightArgs = node.args.slice(0); + rightArgs.splice(i, 1); + right = rightArgs.length === 1 ? rightArgs[0] : makeNode(rightArgs); + res.push(makeNode([node.args[i], right])); + } + } else { + rightArgs = node.args.slice(1); + right = rightArgs.length === 1 ? rightArgs[0] : makeNode(rightArgs); + res.push(makeNode([node.args[0], right])); + } + + return res; + } + /** + * Returns the set union of two match-placeholders or null if there is a conflict. + */ + + + function mergeMatch(match1, match2) { + var res = { + placeholders: {} + }; // Some matches may not have placeholders; this is OK + + if (!match1.placeholders && !match2.placeholders) { + return res; + } else if (!match1.placeholders) { + return match2; + } else if (!match2.placeholders) { + return match1; + } // Placeholders with the same key must match exactly + + + for (var key in match1.placeholders) { + res.placeholders[key] = match1.placeholders[key]; + + if (Object(utils_object["f" /* hasOwnProperty */])(match2.placeholders, key)) { + if (!_exactMatch(match1.placeholders[key], match2.placeholders[key])) { + return null; + } + } + } + + for (var _key in match2.placeholders) { + res.placeholders[_key] = match2.placeholders[_key]; + } + + return res; + } + /** + * Combine two lists of matches by applying mergeMatch to the cartesian product of two lists of matches. + * Each list represents matches found in one child of a node. + */ + + + function combineChildMatches(list1, list2) { + var res = []; + + if (list1.length === 0 || list2.length === 0) { + return res; + } + + var merged; + + for (var i1 = 0; i1 < list1.length; i1++) { + for (var i2 = 0; i2 < list2.length; i2++) { + merged = mergeMatch(list1[i1], list2[i2]); + + if (merged) { + res.push(merged); + } + } + } + + return res; + } + /** + * Combine multiple lists of matches by applying mergeMatch to the cartesian product of two lists of matches. + * Each list represents matches found in one child of a node. + * Returns a list of unique matches. + */ + + + function mergeChildMatches(childMatches) { + if (childMatches.length === 0) { + return childMatches; + } + + var sets = childMatches.reduce(combineChildMatches); + var uniqueSets = []; + var unique = {}; + + for (var i = 0; i < sets.length; i++) { + var s = JSON.stringify(sets[i]); + + if (!unique[s]) { + unique[s] = true; + uniqueSets.push(sets[i]); + } + } + + return uniqueSets; + } + /** + * Determines whether node matches rule. + * + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} rule + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node + * @return {Object} Information about the match, if it exists. + */ + + + function _ruleMatch(rule, node, isSplit) { + // console.log('Entering _ruleMatch(' + JSON.stringify(rule) + ', ' + JSON.stringify(node) + ')') + // console.log('rule = ' + rule) + // console.log('node = ' + node) + // console.log('Entering _ruleMatch(' + rule.toString() + ', ' + node.toString() + ')') + var res = [{ + placeholders: {} + }]; + + if (rule instanceof OperatorNode && node instanceof OperatorNode || rule instanceof FunctionNode && node instanceof FunctionNode) { + // If the rule is an OperatorNode or a FunctionNode, then node must match exactly + if (rule instanceof OperatorNode) { + if (rule.op !== node.op || rule.fn !== node.fn) { + return []; + } + } else if (rule instanceof FunctionNode) { + if (rule.name !== node.name) { + return []; + } + } // rule and node match. Search the children of rule and node. + + + if (node.args.length === 1 && rule.args.length === 1 || !isAssociative(node) || isSplit) { + // Expect non-associative operators to match exactly + var childMatches = []; + + for (var i = 0; i < rule.args.length; i++) { + var childMatch = _ruleMatch(rule.args[i], node.args[i]); + + if (childMatch.length === 0) { + // Child did not match, so stop searching immediately + return []; + } // The child matched, so add the information returned from the child to our result + + + childMatches.push(childMatch); + } + + res = mergeChildMatches(childMatches); + } else if (node.args.length >= 2 && rule.args.length === 2) { + // node is flattened, rule is not + // Associative operators/functions can be split in different ways so we check if the rule matches each + // them and return their union. + var splits = getSplits(node, rule.context); + var splitMatches = []; + + for (var _i = 0; _i < splits.length; _i++) { + var matchSet = _ruleMatch(rule, splits[_i], true); // recursing at the same tree depth here + + + splitMatches = splitMatches.concat(matchSet); + } + + return splitMatches; + } else if (rule.args.length > 2) { + throw Error('Unexpected non-binary associative function: ' + rule.toString()); + } else { + // Incorrect number of arguments in rule and node, so no match + return []; + } + } else if (rule instanceof SymbolNode) { + // If the rule is a SymbolNode, then it carries a special meaning + // according to the first character of the symbol node name. + // c.* matches a ConstantNode + // n.* matches any node + if (rule.name.length === 0) { + throw new Error('Symbol in rule has 0 length...!?'); + } + + if (SUPPORTED_CONSTANTS[rule.name]) { + // built-in constant must match exactly + if (rule.name !== node.name) { + return []; + } + } else if (rule.name[0] === 'n' || rule.name.substring(0, 2) === '_p') { + // rule matches _anything_, so assign this node to the rule.name placeholder + // Assign node to the rule.name placeholder. + // Our parent will check for matches among placeholders. + res[0].placeholders[rule.name] = node; + } else if (rule.name[0] === 'v') { + // rule matches any variable thing (not a ConstantNode) + if (!Object(is["l" /* isConstantNode */])(node)) { + res[0].placeholders[rule.name] = node; + } else { + // Mis-match: rule was expecting something other than a ConstantNode + return []; + } + } else if (rule.name[0] === 'c') { + // rule matches any ConstantNode + if (node instanceof ConstantNode) { + res[0].placeholders[rule.name] = node; + } else { + // Mis-match: rule was expecting a ConstantNode + return []; + } + } else { + throw new Error('Invalid symbol in rule: ' + rule.name); + } + } else if (rule instanceof ConstantNode) { + // Literal constant must match exactly + if (!equal(rule.value, node.value)) { + return []; + } + } else { + // Some other node was encountered which we aren't prepared for, so no match + return []; + } // It's a match! + // console.log('_ruleMatch(' + rule.toString() + ', ' + node.toString() + ') found a match') + + + return res; + } + /** + * Determines whether p and q (and all their children nodes) are identical. + * + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} p + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} q + * @return {Object} Information about the match, if it exists. + */ + + + function _exactMatch(p, q) { + if (p instanceof ConstantNode && q instanceof ConstantNode) { + if (!equal(p.value, q.value)) { + return false; + } + } else if (p instanceof SymbolNode && q instanceof SymbolNode) { + if (p.name !== q.name) { + return false; + } + } else if (p instanceof OperatorNode && q instanceof OperatorNode || p instanceof FunctionNode && q instanceof FunctionNode) { + if (p instanceof OperatorNode) { + if (p.op !== q.op || p.fn !== q.fn) { + return false; + } + } else if (p instanceof FunctionNode) { + if (p.name !== q.name) { + return false; + } + } + + if (p.args.length !== q.args.length) { + return false; + } + + for (var i = 0; i < p.args.length; i++) { + if (!_exactMatch(p.args[i], q.args[i])) { + return false; + } + } + } else { + return false; + } + + return true; + } + + return simplify; +}); +// CONCATENATED MODULE: ./src/function/algebra/derivative.js + + +var derivative_name = 'derivative'; +var derivative_dependencies = ['typed', 'config', 'parse', 'simplify', 'equal', 'isZero', 'numeric', 'ConstantNode', 'FunctionNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode']; +var createDerivative = /* #__PURE__ */Object(factory["a" /* factory */])(derivative_name, derivative_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + parse = _ref.parse, + simplify = _ref.simplify, + equal = _ref.equal, + isZero = _ref.isZero, + numeric = _ref.numeric, + ConstantNode = _ref.ConstantNode, + FunctionNode = _ref.FunctionNode, + OperatorNode = _ref.OperatorNode, + ParenthesisNode = _ref.ParenthesisNode, + SymbolNode = _ref.SymbolNode; + + /** + * Takes the derivative of an expression expressed in parser Nodes. + * The derivative will be taken over the supplied variable in the + * second parameter. If there are multiple variables in the expression, + * it will return a partial derivative. + * + * This uses rules of differentiation which can be found here: + * + * - [Differentiation rules (Wikipedia)](https://en.wikipedia.org/wiki/Differentiation_rules) + * + * Syntax: + * + * derivative(expr, variable) + * derivative(expr, variable, options) + * + * Examples: + * + * math.derivative('x^2', 'x') // Node {2 * x} + * math.derivative('x^2', 'x', {simplify: false}) // Node {2 * 1 * x ^ (2 - 1) + * math.derivative('sin(2x)', 'x')) // Node {2 * cos(2 * x)} + * math.derivative('2*x', 'x').evaluate() // number 2 + * math.derivative('x^2', 'x').evaluate({x: 4}) // number 8 + * const f = math.parse('x^2') + * const x = math.parse('x') + * math.derivative(f, x) // Node {2 * x} + * + * See also: + * + * simplify, parse, evaluate + * + * @param {Node | string} expr The expression to differentiate + * @param {SymbolNode | string} variable The variable over which to differentiate + * @param {{simplify: boolean}} [options] + * There is one option available, `simplify`, which + * is true by default. When false, output will not + * be simplified. + * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The derivative of `expr` + */ + var derivative = typed('derivative', { + 'Node, SymbolNode, Object': function NodeSymbolNodeObject(expr, variable, options) { + var constNodes = {}; + constTag(constNodes, expr, variable.name); + + var res = _derivative(expr, constNodes); + + return options.simplify ? simplify(res) : res; + }, + 'Node, SymbolNode': function NodeSymbolNode(expr, variable) { + return derivative(expr, variable, { + simplify: true + }); + }, + 'string, SymbolNode': function stringSymbolNode(expr, variable) { + return derivative(parse(expr), variable); + }, + 'string, SymbolNode, Object': function stringSymbolNodeObject(expr, variable, options) { + return derivative(parse(expr), variable, options); + }, + 'string, string': function stringString(expr, variable) { + return derivative(parse(expr), parse(variable)); + }, + 'string, string, Object': function stringStringObject(expr, variable, options) { + return derivative(parse(expr), parse(variable), options); + }, + 'Node, string': function NodeString(expr, variable) { + return derivative(expr, parse(variable)); + }, + 'Node, string, Object': function NodeStringObject(expr, variable, options) { + return derivative(expr, parse(variable), options); + } // TODO: replace the 8 signatures above with 4 as soon as typed-function supports optional arguments + + /* TODO: implement and test syntax with order of derivatives -> implement as an option {order: number} + 'Node, SymbolNode, ConstantNode': function (expr, variable, {order}) { + let res = expr + for (let i = 0; i < order; i++) { + let constNodes = {} + constTag(constNodes, expr, variable.name) + res = _derivative(res, constNodes) + } + return res + } + */ + + }); + derivative._simplify = true; + + derivative.toTex = function (deriv) { + return _derivTex.apply(null, deriv.args); + }; // FIXME: move the toTex method of derivative to latex.js. Difficulty is that it relies on parse. + // NOTE: the optional "order" parameter here is currently unused + + + var _derivTex = typed('_derivTex', { + 'Node, SymbolNode': function NodeSymbolNode(expr, x) { + if (Object(is["l" /* isConstantNode */])(expr) && Object(is["M" /* typeOf */])(expr.value) === 'string') { + return _derivTex(parse(expr.value).toString(), x.toString(), 1); + } else { + return _derivTex(expr.toString(), x.toString(), 1); + } + }, + 'Node, ConstantNode': function NodeConstantNode(expr, x) { + if (Object(is["M" /* typeOf */])(x.value) === 'string') { + return _derivTex(expr, parse(x.value)); + } else { + throw new Error("The second parameter to 'derivative' is a non-string constant"); + } + }, + 'Node, SymbolNode, ConstantNode': function NodeSymbolNodeConstantNode(expr, x, order) { + return _derivTex(expr.toString(), x.name, order.value); + }, + 'string, string, number': function stringStringNumber(expr, x, order) { + var d; + + if (order === 1) { + d = '{d\\over d' + x + '}'; + } else { + d = '{d^{' + order + '}\\over d' + x + '^{' + order + '}}'; + } + + return d + "\\left[".concat(expr, "\\right]"); + } + }); + /** + * Does a depth-first search on the expression tree to identify what Nodes + * are constants (e.g. 2 + 2), and stores the ones that are constants in + * constNodes. Classification is done as follows: + * + * 1. ConstantNodes are constants. + * 2. If there exists a SymbolNode, of which we are differentiating over, + * in the subtree it is not constant. + * + * @param {Object} constNodes Holds the nodes that are constant + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node + * @param {string} varName Variable that we are differentiating + * @return {boolean} if node is constant + */ + // TODO: can we rewrite constTag into a pure function? + + + var constTag = typed('constTag', { + 'Object, ConstantNode, string': function ObjectConstantNodeString(constNodes, node) { + constNodes[node] = true; + return true; + }, + 'Object, SymbolNode, string': function ObjectSymbolNodeString(constNodes, node, varName) { + // Treat other variables like constants. For reasoning, see: + // https://en.wikipedia.org/wiki/Partial_derivative + if (node.name !== varName) { + constNodes[node] = true; + return true; + } + + return false; + }, + 'Object, ParenthesisNode, string': function ObjectParenthesisNodeString(constNodes, node, varName) { + return constTag(constNodes, node.content, varName); + }, + 'Object, FunctionAssignmentNode, string': function ObjectFunctionAssignmentNodeString(constNodes, node, varName) { + if (node.params.indexOf(varName) === -1) { + constNodes[node] = true; + return true; + } + + return constTag(constNodes, node.expr, varName); + }, + 'Object, FunctionNode | OperatorNode, string': function ObjectFunctionNodeOperatorNodeString(constNodes, node, varName) { + if (node.args.length > 0) { + var isConst = constTag(constNodes, node.args[0], varName); + + for (var i = 1; i < node.args.length; ++i) { + isConst = constTag(constNodes, node.args[i], varName) && isConst; + } + + if (isConst) { + constNodes[node] = true; + return true; + } + } + + return false; + } + }); + /** + * Applies differentiation rules. + * + * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node + * @param {Object} constNodes Holds the nodes that are constant + * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The derivative of `expr` + */ + + var _derivative = typed('_derivative', { + 'ConstantNode, Object': function ConstantNodeObject(node) { + return createConstantNode(0); + }, + 'SymbolNode, Object': function SymbolNodeObject(node, constNodes) { + if (constNodes[node] !== undefined) { + return createConstantNode(0); + } + + return createConstantNode(1); + }, + 'ParenthesisNode, Object': function ParenthesisNodeObject(node, constNodes) { + return new ParenthesisNode(_derivative(node.content, constNodes)); + }, + 'FunctionAssignmentNode, Object': function FunctionAssignmentNodeObject(node, constNodes) { + if (constNodes[node] !== undefined) { + return createConstantNode(0); + } + + return _derivative(node.expr, constNodes); + }, + 'FunctionNode, Object': function FunctionNodeObject(node, constNodes) { + if (node.args.length !== 1) { + funcArgsCheck(node); + } + + if (constNodes[node] !== undefined) { + return createConstantNode(0); + } + + var arg0 = node.args[0]; + var arg1; + var div = false; // is output a fraction? + + var negative = false; // is output negative? + + var funcDerivative; + + switch (node.name) { + case 'cbrt': + // d/dx(cbrt(x)) = 1 / (3x^(2/3)) + div = true; + funcDerivative = new OperatorNode('*', 'multiply', [createConstantNode(3), new OperatorNode('^', 'pow', [arg0, new OperatorNode('/', 'divide', [createConstantNode(2), createConstantNode(3)])])]); + break; + + case 'sqrt': + case 'nthRoot': + // d/dx(sqrt(x)) = 1 / (2*sqrt(x)) + if (node.args.length === 1) { + div = true; + funcDerivative = new OperatorNode('*', 'multiply', [createConstantNode(2), new FunctionNode('sqrt', [arg0])]); + } else if (node.args.length === 2) { + // Rearrange from nthRoot(x, a) -> x^(1/a) + arg1 = new OperatorNode('/', 'divide', [createConstantNode(1), node.args[1]]); // Is a variable? + + constNodes[arg1] = constNodes[node.args[1]]; + return _derivative(new OperatorNode('^', 'pow', [arg0, arg1]), constNodes); + } + + break; + + case 'log10': + arg1 = createConstantNode(10); + + /* fall through! */ + + case 'log': + if (!arg1 && node.args.length === 1) { + // d/dx(log(x)) = 1 / x + funcDerivative = arg0.clone(); + div = true; + } else if (node.args.length === 1 && arg1 || node.args.length === 2 && constNodes[node.args[1]] !== undefined) { + // d/dx(log(x, c)) = 1 / (x*ln(c)) + funcDerivative = new OperatorNode('*', 'multiply', [arg0.clone(), new FunctionNode('log', [arg1 || node.args[1]])]); + div = true; + } else if (node.args.length === 2) { + // d/dx(log(f(x), g(x))) = d/dx(log(f(x)) / log(g(x))) + return _derivative(new OperatorNode('/', 'divide', [new FunctionNode('log', [arg0]), new FunctionNode('log', [node.args[1]])]), constNodes); + } + + break; + + case 'pow': + constNodes[arg1] = constNodes[node.args[1]]; // Pass to pow operator node parser + + return _derivative(new OperatorNode('^', 'pow', [arg0, node.args[1]]), constNodes); + + case 'exp': + // d/dx(e^x) = e^x + funcDerivative = new FunctionNode('exp', [arg0.clone()]); + break; + + case 'sin': + // d/dx(sin(x)) = cos(x) + funcDerivative = new FunctionNode('cos', [arg0.clone()]); + break; + + case 'cos': + // d/dx(cos(x)) = -sin(x) + funcDerivative = new OperatorNode('-', 'unaryMinus', [new FunctionNode('sin', [arg0.clone()])]); + break; + + case 'tan': + // d/dx(tan(x)) = sec(x)^2 + funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('sec', [arg0.clone()]), createConstantNode(2)]); + break; + + case 'sec': + // d/dx(sec(x)) = sec(x)tan(x) + funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('tan', [arg0.clone()])]); + break; + + case 'csc': + // d/dx(csc(x)) = -csc(x)cot(x) + negative = true; + funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('cot', [arg0.clone()])]); + break; + + case 'cot': + // d/dx(cot(x)) = -csc(x)^2 + negative = true; + funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('csc', [arg0.clone()]), createConstantNode(2)]); + break; + + case 'asin': + // d/dx(asin(x)) = 1 / sqrt(1 - x^2) + div = true; + funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])]); + break; + + case 'acos': + // d/dx(acos(x)) = -1 / sqrt(1 - x^2) + div = true; + negative = true; + funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])]); + break; + + case 'atan': + // d/dx(atan(x)) = 1 / (x^2 + 1) + div = true; + funcDerivative = new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)]); + break; + + case 'asec': + // d/dx(asec(x)) = 1 / (|x|*sqrt(x^2 - 1)) + div = true; + funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]); + break; + + case 'acsc': + // d/dx(acsc(x)) = -1 / (|x|*sqrt(x^2 - 1)) + div = true; + negative = true; + funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]); + break; + + case 'acot': + // d/dx(acot(x)) = -1 / (x^2 + 1) + div = true; + negative = true; + funcDerivative = new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)]); + break; + + case 'sinh': + // d/dx(sinh(x)) = cosh(x) + funcDerivative = new FunctionNode('cosh', [arg0.clone()]); + break; + + case 'cosh': + // d/dx(cosh(x)) = sinh(x) + funcDerivative = new FunctionNode('sinh', [arg0.clone()]); + break; + + case 'tanh': + // d/dx(tanh(x)) = sech(x)^2 + funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('sech', [arg0.clone()]), createConstantNode(2)]); + break; + + case 'sech': + // d/dx(sech(x)) = -sech(x)tanh(x) + negative = true; + funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('tanh', [arg0.clone()])]); + break; + + case 'csch': + // d/dx(csch(x)) = -csch(x)coth(x) + negative = true; + funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('coth', [arg0.clone()])]); + break; + + case 'coth': + // d/dx(coth(x)) = -csch(x)^2 + negative = true; + funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('csch', [arg0.clone()]), createConstantNode(2)]); + break; + + case 'asinh': + // d/dx(asinh(x)) = 1 / sqrt(x^2 + 1) + div = true; + funcDerivative = new FunctionNode('sqrt', [new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])]); + break; + + case 'acosh': + // d/dx(acosh(x)) = 1 / sqrt(x^2 - 1); XXX potentially only for x >= 1 (the real spectrum) + div = true; + funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])]); + break; + + case 'atanh': + // d/dx(atanh(x)) = 1 / (1 - x^2) + div = true; + funcDerivative = new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])]); + break; + + case 'asech': + // d/dx(asech(x)) = -1 / (x*sqrt(1 - x^2)) + div = true; + negative = true; + funcDerivative = new OperatorNode('*', 'multiply', [arg0.clone(), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])])]); + break; + + case 'acsch': + // d/dx(acsch(x)) = -1 / (|x|*sqrt(x^2 + 1)) + div = true; + negative = true; + funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]); + break; + + case 'acoth': + // d/dx(acoth(x)) = -1 / (1 - x^2) + div = true; + negative = true; + funcDerivative = new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])]); + break; + + case 'abs': + // d/dx(abs(x)) = abs(x)/x + funcDerivative = new OperatorNode('/', 'divide', [new FunctionNode(new SymbolNode('abs'), [arg0.clone()]), arg0.clone()]); + break; + + case 'gamma': // Needs digamma function, d/dx(gamma(x)) = gamma(x)digamma(x) + + default: + throw new Error('Function "' + node.name + '" is not supported by derivative, or a wrong number of arguments is passed'); + } + + var op, func; + + if (div) { + op = '/'; + func = 'divide'; + } else { + op = '*'; + func = 'multiply'; + } + /* Apply chain rule to all functions: + F(x) = f(g(x)) + F'(x) = g'(x)*f'(g(x)) */ + + + var chainDerivative = _derivative(arg0, constNodes); + + if (negative) { + chainDerivative = new OperatorNode('-', 'unaryMinus', [chainDerivative]); + } + + return new OperatorNode(op, func, [chainDerivative, funcDerivative]); + }, + 'OperatorNode, Object': function OperatorNodeObject(node, constNodes) { + if (constNodes[node] !== undefined) { + return createConstantNode(0); + } + + if (node.op === '+') { + // d/dx(sum(f(x)) = sum(f'(x)) + return new OperatorNode(node.op, node.fn, node.args.map(function (arg) { + return _derivative(arg, constNodes); + })); + } + + if (node.op === '-') { + // d/dx(+/-f(x)) = +/-f'(x) + if (node.isUnary()) { + return new OperatorNode(node.op, node.fn, [_derivative(node.args[0], constNodes)]); + } // Linearity of differentiation, d/dx(f(x) +/- g(x)) = f'(x) +/- g'(x) + + + if (node.isBinary()) { + return new OperatorNode(node.op, node.fn, [_derivative(node.args[0], constNodes), _derivative(node.args[1], constNodes)]); + } + } + + if (node.op === '*') { + // d/dx(c*f(x)) = c*f'(x) + var constantTerms = node.args.filter(function (arg) { + return constNodes[arg] !== undefined; + }); + + if (constantTerms.length > 0) { + var nonConstantTerms = node.args.filter(function (arg) { + return constNodes[arg] === undefined; + }); + var nonConstantNode = nonConstantTerms.length === 1 ? nonConstantTerms[0] : new OperatorNode('*', 'multiply', nonConstantTerms); + var newArgs = constantTerms.concat(_derivative(nonConstantNode, constNodes)); + return new OperatorNode('*', 'multiply', newArgs); + } // Product Rule, d/dx(f(x)*g(x)) = f'(x)*g(x) + f(x)*g'(x) + + + return new OperatorNode('+', 'add', node.args.map(function (argOuter) { + return new OperatorNode('*', 'multiply', node.args.map(function (argInner) { + return argInner === argOuter ? _derivative(argInner, constNodes) : argInner.clone(); + })); + })); + } + + if (node.op === '/' && node.isBinary()) { + var arg0 = node.args[0]; + var arg1 = node.args[1]; // d/dx(f(x) / c) = f'(x) / c + + if (constNodes[arg1] !== undefined) { + return new OperatorNode('/', 'divide', [_derivative(arg0, constNodes), arg1]); + } // Reciprocal Rule, d/dx(c / f(x)) = -c(f'(x)/f(x)^2) + + + if (constNodes[arg0] !== undefined) { + return new OperatorNode('*', 'multiply', [new OperatorNode('-', 'unaryMinus', [arg0]), new OperatorNode('/', 'divide', [_derivative(arg1, constNodes), new OperatorNode('^', 'pow', [arg1.clone(), createConstantNode(2)])])]); + } // Quotient rule, d/dx(f(x) / g(x)) = (f'(x)g(x) - f(x)g'(x)) / g(x)^2 + + + return new OperatorNode('/', 'divide', [new OperatorNode('-', 'subtract', [new OperatorNode('*', 'multiply', [_derivative(arg0, constNodes), arg1.clone()]), new OperatorNode('*', 'multiply', [arg0.clone(), _derivative(arg1, constNodes)])]), new OperatorNode('^', 'pow', [arg1.clone(), createConstantNode(2)])]); + } + + if (node.op === '^' && node.isBinary()) { + var _arg = node.args[0]; + var _arg2 = node.args[1]; + + if (constNodes[_arg] !== undefined) { + // If is secretly constant; 0^f(x) = 1 (in JS), 1^f(x) = 1 + if (Object(is["l" /* isConstantNode */])(_arg) && (isZero(_arg.value) || equal(_arg.value, 1))) { + return createConstantNode(0); + } // d/dx(c^f(x)) = c^f(x)*ln(c)*f'(x) + + + return new OperatorNode('*', 'multiply', [node, new OperatorNode('*', 'multiply', [new FunctionNode('log', [_arg.clone()]), _derivative(_arg2.clone(), constNodes)])]); + } + + if (constNodes[_arg2] !== undefined) { + if (Object(is["l" /* isConstantNode */])(_arg2)) { + // If is secretly constant; f(x)^0 = 1 -> d/dx(1) = 0 + if (isZero(_arg2.value)) { + return createConstantNode(0); + } // Ignore exponent; f(x)^1 = f(x) + + + if (equal(_arg2.value, 1)) { + return _derivative(_arg, constNodes); + } + } // Elementary Power Rule, d/dx(f(x)^c) = c*f'(x)*f(x)^(c-1) + + + var powMinusOne = new OperatorNode('^', 'pow', [_arg.clone(), new OperatorNode('-', 'subtract', [_arg2, createConstantNode(1)])]); + return new OperatorNode('*', 'multiply', [_arg2.clone(), new OperatorNode('*', 'multiply', [_derivative(_arg, constNodes), powMinusOne])]); + } // Functional Power Rule, d/dx(f^g) = f^g*[f'*(g/f) + g'ln(f)] + + + return new OperatorNode('*', 'multiply', [new OperatorNode('^', 'pow', [_arg.clone(), _arg2.clone()]), new OperatorNode('+', 'add', [new OperatorNode('*', 'multiply', [_derivative(_arg, constNodes), new OperatorNode('/', 'divide', [_arg2.clone(), _arg.clone()])]), new OperatorNode('*', 'multiply', [_derivative(_arg2, constNodes), new FunctionNode('log', [_arg.clone()])])])]); + } + + throw new Error('Operator "' + node.op + '" is not supported by derivative, or a wrong number of arguments is passed'); + } + }); + /** + * Ensures the number of arguments for a function are correct, + * and will throw an error otherwise. + * + * @param {FunctionNode} node + */ + + + function funcArgsCheck(node) { + // TODO add min, max etc + if ((node.name === 'log' || node.name === 'nthRoot' || node.name === 'pow') && node.args.length === 2) { + return; + } // There should be an incorrect number of arguments if we reach here + // Change all args to constants to avoid unidentified + // symbol error when compiling function + + + for (var i = 0; i < node.args.length; ++i) { + node.args[i] = createConstantNode(0); + } + + node.compile().evaluate(); + throw new Error('Expected TypeError, but none found'); + } + /** + * Helper function to create a constant node with a specific type + * (number, BigNumber, Fraction) + * @param {number} value + * @param {string} [valueType] + * @return {ConstantNode} + */ + + + function createConstantNode(value, valueType) { + return new ConstantNode(numeric(value, valueType || config.number)); + } + + return derivative; +}); +// CONCATENATED MODULE: ./src/function/algebra/rationalize.js + + + + +var rationalize_name = 'rationalize'; +var rationalize_dependencies = ['config', 'typed', 'equal', 'isZero', 'add', 'subtract', 'multiply', 'divide', 'pow', 'parse', 'simplify', '?bignumber', '?fraction', 'mathWithTransform', 'ConstantNode', 'OperatorNode', 'FunctionNode', 'SymbolNode', 'ParenthesisNode']; +var createRationalize = /* #__PURE__ */Object(factory["a" /* factory */])(rationalize_name, rationalize_dependencies, function (_ref) { + var config = _ref.config, + typed = _ref.typed, + equal = _ref.equal, + isZero = _ref.isZero, + add = _ref.add, + subtract = _ref.subtract, + multiply = _ref.multiply, + divide = _ref.divide, + pow = _ref.pow, + parse = _ref.parse, + simplify = _ref.simplify, + fraction = _ref.fraction, + bignumber = _ref.bignumber, + mathWithTransform = _ref.mathWithTransform, + ConstantNode = _ref.ConstantNode, + OperatorNode = _ref.OperatorNode, + FunctionNode = _ref.FunctionNode, + SymbolNode = _ref.SymbolNode, + ParenthesisNode = _ref.ParenthesisNode; + var simplifyConstant = createSimplifyConstant({ + typed: typed, + config: config, + mathWithTransform: mathWithTransform, + fraction: fraction, + bignumber: bignumber, + ConstantNode: ConstantNode, + OperatorNode: OperatorNode, + FunctionNode: FunctionNode, + SymbolNode: SymbolNode + }); + var simplifyCore = createSimplifyCore({ + equal: equal, + isZero: isZero, + add: add, + subtract: subtract, + multiply: multiply, + divide: divide, + pow: pow, + ConstantNode: ConstantNode, + OperatorNode: OperatorNode, + FunctionNode: FunctionNode, + ParenthesisNode: ParenthesisNode + }); + /** + * Transform a rationalizable expression in a rational fraction. + * If rational fraction is one variable polynomial then converts + * the numerator and denominator in canonical form, with decreasing + * exponents, returning the coefficients of numerator. + * + * Syntax: + * + * rationalize(expr) + * rationalize(expr, detailed) + * rationalize(expr, scope) + * rationalize(expr, scope, detailed) + * + * Examples: + * + * math.rationalize('sin(x)+y') + * // Error: There is an unsolved function call + * math.rationalize('2x/y - y/(x+1)') + * // (2*x^2-y^2+2*x)/(x*y+y) + * math.rationalize('(2x+1)^6') + * // 64*x^6+192*x^5+240*x^4+160*x^3+60*x^2+12*x+1 + * math.rationalize('2x/( (2x-1) / (3x+2) ) - 5x/ ( (3x+4) / (2x^2-5) ) + 3') + * // -20*x^4+28*x^3+104*x^2+6*x-12)/(6*x^2+5*x-4) + * math.rationalize('x/(1-x)/(x-2)/(x-3)/(x-4) + 2x/ ( (1-2x)/(2-3x) )/ ((3-4x)/(4-5x) )') = + * // (-30*x^7+344*x^6-1506*x^5+3200*x^4-3472*x^3+1846*x^2-381*x)/ + * // (-8*x^6+90*x^5-383*x^4+780*x^3-797*x^2+390*x-72) + * + * math.rationalize('x+x+x+y',{y:1}) // 3*x+1 + * math.rationalize('x+x+x+y',{}) // 3*x+y + * + * const ret = math.rationalize('x+x+x+y',{},true) + * // ret.expression=3*x+y, ret.variables = ["x","y"] + * const ret = math.rationalize('-2+5x^2',{},true) + * // ret.expression=5*x^2-2, ret.variables = ["x"], ret.coefficients=[-2,0,5] + * + * See also: + * + * simplify + * + * @param {Node|string} expr The expression to check if is a polynomial expression + * @param {Object|boolean} optional scope of expression or true for already evaluated rational expression at input + * @param {Boolean} detailed optional True if return an object, false if return expression node (default) + * + * @return {Object | Node} The rational polynomial of `expr` or na object + * {Object} + * {Expression Node} expression: node simplified expression + * {Expression Node} numerator: simplified numerator of expression + * {Expression Node | boolean} denominator: simplified denominator or false (if there is no denominator) + * {Array} variables: variable names + * {Array} coefficients: coefficients of numerator sorted by increased exponent + * {Expression Node} node simplified expression + * + */ + + var rationalize = typed(rationalize_name, { + string: function string(expr) { + return rationalize(parse(expr), {}, false); + }, + 'string, boolean': function stringBoolean(expr, detailed) { + return rationalize(parse(expr), {}, detailed); + }, + 'string, Object': function stringObject(expr, scope) { + return rationalize(parse(expr), scope, false); + }, + 'string, Object, boolean': function stringObjectBoolean(expr, scope, detailed) { + return rationalize(parse(expr), scope, detailed); + }, + Node: function Node(expr) { + return rationalize(expr, {}, false); + }, + 'Node, boolean': function NodeBoolean(expr, detailed) { + return rationalize(expr, {}, detailed); + }, + 'Node, Object': function NodeObject(expr, scope) { + return rationalize(expr, scope, false); + }, + 'Node, Object, boolean': function NodeObjectBoolean(expr, scope, detailed) { + var setRules = rulesRationalize(); // Rules for change polynomial in near canonical form + + var polyRet = polynomial(expr, scope, true, setRules.firstRules); // Check if expression is a rationalizable polynomial + + var nVars = polyRet.variables.length; + expr = polyRet.expression; + + if (nVars >= 1) { + // If expression in not a constant + expr = expandPower(expr); // First expand power of polynomials (cannot be made from rules!) + + var sBefore; // Previous expression + + var rules; + var eDistrDiv = true; + var redoInic = false; + expr = simplify(expr, setRules.firstRules, {}, { + exactFractions: false + }); // Apply the initial rules, including succ div rules + + var s; + + while (true) { + // Apply alternately successive division rules and distr.div.rules + rules = eDistrDiv ? setRules.distrDivRules : setRules.sucDivRules; + expr = simplify(expr, rules); // until no more changes + + eDistrDiv = !eDistrDiv; // Swap between Distr.Div and Succ. Div. Rules + + s = expr.toString(); + + if (s === sBefore) { + break; // No changes : end of the loop + } + + redoInic = true; + sBefore = s; + } + + if (redoInic) { + // Apply first rules again without succ div rules (if there are changes) + expr = simplify(expr, setRules.firstRulesAgain, {}, { + exactFractions: false + }); + } + + expr = simplify(expr, setRules.finalRules, {}, { + exactFractions: false + }); // Apply final rules + } // NVars >= 1 + + + var coefficients = []; + var retRationalize = {}; + + if (expr.type === 'OperatorNode' && expr.isBinary() && expr.op === '/') { + // Separate numerator from denominator + if (nVars === 1) { + expr.args[0] = polyToCanonical(expr.args[0], coefficients); + expr.args[1] = polyToCanonical(expr.args[1]); + } + + if (detailed) { + retRationalize.numerator = expr.args[0]; + retRationalize.denominator = expr.args[1]; + } + } else { + if (nVars === 1) { + expr = polyToCanonical(expr, coefficients); + } + + if (detailed) { + retRationalize.numerator = expr; + retRationalize.denominator = null; + } + } // nVars + + + if (!detailed) return expr; + retRationalize.coefficients = coefficients; + retRationalize.variables = polyRet.variables; + retRationalize.expression = expr; + return retRationalize; + } // ^^^^^^^ end of rationalize ^^^^^^^^ + + }); // end of typed rationalize + + /** + * Function to simplify an expression using an optional scope and + * return it if the expression is a polynomial expression, i.e. + * an expression with one or more variables and the operators + * +, -, *, and ^, where the exponent can only be a positive integer. + * + * Syntax: + * + * polynomial(expr,scope,extended, rules) + * + * @param {Node | string} expr The expression to simplify and check if is polynomial expression + * @param {object} scope Optional scope for expression simplification + * @param {boolean} extended Optional. Default is false. When true allows divide operator. + * @param {array} rules Optional. Default is no rule. + * + * + * @return {Object} + * {Object} node: node simplified expression + * {Array} variables: variable names + */ + + function polynomial(expr, scope, extended, rules) { + var variables = []; + var node = simplify(expr, rules, scope, { + exactFractions: false + }); // Resolves any variables and functions with all defined parameters + + extended = !!extended; + var oper = '+-*' + (extended ? '/' : ''); + recPoly(node); + var retFunc = {}; + retFunc.expression = node; + retFunc.variables = variables; + return retFunc; // ------------------------------------------------------------------------------------------------------- + + /** + * Function to simplify an expression using an optional scope and + * return it if the expression is a polynomial expression, i.e. + * an expression with one or more variables and the operators + * +, -, *, and ^, where the exponent can only be a positive integer. + * + * Syntax: + * + * recPoly(node) + * + * + * @param {Node} node The current sub tree expression in recursion + * + * @return nothing, throw an exception if error + */ + + function recPoly(node) { + var tp = node.type; // node type + + if (tp === 'FunctionNode') { + // No function call in polynomial expression + throw new Error('There is an unsolved function call'); + } else if (tp === 'OperatorNode') { + if (node.op === '^') { + // TODO: handle negative exponents like in '1/x^(-2)' + if (node.args[1].type !== 'ConstantNode' || !Object(utils_number["i" /* isInteger */])(parseFloat(node.args[1].value))) { + throw new Error('There is a non-integer exponent'); + } else { + recPoly(node.args[0]); + } + } else { + if (oper.indexOf(node.op) === -1) { + throw new Error('Operator ' + node.op + ' invalid in polynomial expression'); + } + + for (var i = 0; i < node.args.length; i++) { + recPoly(node.args[i]); + } + } // type of operator + + } else if (tp === 'SymbolNode') { + var _name = node.name; // variable name + + var pos = variables.indexOf(_name); + + if (pos === -1) { + // new variable in expression + variables.push(_name); + } + } else if (tp === 'ParenthesisNode') { + recPoly(node.content); + } else if (tp !== 'ConstantNode') { + throw new Error('type ' + tp + ' is not allowed in polynomial expression'); + } + } // end of recPoly + + } // end of polynomial + // --------------------------------------------------------------------------------------- + + /** + * Return a rule set to rationalize an polynomial expression in rationalize + * + * Syntax: + * + * rulesRationalize() + * + * @return {array} rule set to rationalize an polynomial expression + */ + + + function rulesRationalize() { + var oldRules = [simplifyCore, // sCore + { + l: 'n+n', + r: '2*n' + }, { + l: 'n+-n', + r: '0' + }, simplifyConstant, // sConstant + { + l: 'n*(n1^-1)', + r: 'n/n1' + }, { + l: 'n*n1^-n2', + r: 'n/n1^n2' + }, { + l: 'n1^-1', + r: '1/n1' + }, { + l: 'n*(n1/n2)', + r: '(n*n1)/n2' + }, { + l: '1*n', + r: 'n' + }]; + var rulesFirst = [{ + l: '(-n1)/(-n2)', + r: 'n1/n2' + }, // Unary division + { + l: '(-n1)*(-n2)', + r: 'n1*n2' + }, // Unary multiplication + { + l: 'n1--n2', + r: 'n1+n2' + }, // '--' elimination + { + l: 'n1-n2', + r: 'n1+(-n2)' + }, // Subtraction turn into add with un�ry minus + { + l: '(n1+n2)*n3', + r: '(n1*n3 + n2*n3)' + }, // Distributive 1 + { + l: 'n1*(n2+n3)', + r: '(n1*n2+n1*n3)' + }, // Distributive 2 + { + l: 'c1*n + c2*n', + r: '(c1+c2)*n' + }, // Joining constants + { + l: 'c1*n + n', + r: '(c1+1)*n' + }, // Joining constants + { + l: 'c1*n - c2*n', + r: '(c1-c2)*n' + }, // Joining constants + { + l: 'c1*n - n', + r: '(c1-1)*n' + }, // Joining constants + { + l: 'v/c', + r: '(1/c)*v' + }, // variable/constant (new!) + { + l: 'v/-c', + r: '-(1/c)*v' + }, // variable/constant (new!) + { + l: '-v*-c', + r: 'c*v' + }, // Inversion constant and variable 1 + { + l: '-v*c', + r: '-c*v' + }, // Inversion constant and variable 2 + { + l: 'v*-c', + r: '-c*v' + }, // Inversion constant and variable 3 + { + l: 'v*c', + r: 'c*v' + }, // Inversion constant and variable 4 + { + l: '-(-n1*n2)', + r: '(n1*n2)' + }, // Unary propagation + { + l: '-(n1*n2)', + r: '(-n1*n2)' + }, // Unary propagation + { + l: '-(-n1+n2)', + r: '(n1-n2)' + }, // Unary propagation + { + l: '-(n1+n2)', + r: '(-n1-n2)' + }, // Unary propagation + { + l: '(n1^n2)^n3', + r: '(n1^(n2*n3))' + }, // Power to Power + { + l: '-(-n1/n2)', + r: '(n1/n2)' + }, // Division and Unary + { + l: '-(n1/n2)', + r: '(-n1/n2)' + }]; // Divisao and Unary + + var rulesDistrDiv = [{ + l: '(n1/n2 + n3/n4)', + r: '((n1*n4 + n3*n2)/(n2*n4))' + }, // Sum of fractions + { + l: '(n1/n2 + n3)', + r: '((n1 + n3*n2)/n2)' + }, // Sum fraction with number 1 + { + l: '(n1 + n2/n3)', + r: '((n1*n3 + n2)/n3)' + }]; // Sum fraction with number 1 + + var rulesSucDiv = [{ + l: '(n1/(n2/n3))', + r: '((n1*n3)/n2)' + }, // Division simplification + { + l: '(n1/n2/n3)', + r: '(n1/(n2*n3))' + }]; + var setRules = {}; // rules set in 4 steps. + // All rules => infinite loop + // setRules.allRules =oldRules.concat(rulesFirst,rulesDistrDiv,rulesSucDiv) + + setRules.firstRules = oldRules.concat(rulesFirst, rulesSucDiv); // First rule set + + setRules.distrDivRules = rulesDistrDiv; // Just distr. div. rules + + setRules.sucDivRules = rulesSucDiv; // Jus succ. div. rules + + setRules.firstRulesAgain = oldRules.concat(rulesFirst); // Last rules set without succ. div. + // Division simplification + // Second rule set. + // There is no aggregate expression with parentesis, but the only variable can be scattered. + + setRules.finalRules = [simplifyCore, // simplify.rules[0] + { + l: 'n*-n', + r: '-n^2' + }, // Joining multiply with power 1 + { + l: 'n*n', + r: 'n^2' + }, // Joining multiply with power 2 + simplifyConstant, // simplify.rules[14] old 3rd index in oldRules + { + l: 'n*-n^n1', + r: '-n^(n1+1)' + }, // Joining multiply with power 3 + { + l: 'n*n^n1', + r: 'n^(n1+1)' + }, // Joining multiply with power 4 + { + l: 'n^n1*-n^n2', + r: '-n^(n1+n2)' + }, // Joining multiply with power 5 + { + l: 'n^n1*n^n2', + r: 'n^(n1+n2)' + }, // Joining multiply with power 6 + { + l: 'n^n1*-n', + r: '-n^(n1+1)' + }, // Joining multiply with power 7 + { + l: 'n^n1*n', + r: 'n^(n1+1)' + }, // Joining multiply with power 8 + { + l: 'n^n1/-n', + r: '-n^(n1-1)' + }, // Joining multiply with power 8 + { + l: 'n^n1/n', + r: 'n^(n1-1)' + }, // Joining division with power 1 + { + l: 'n/-n^n1', + r: '-n^(1-n1)' + }, // Joining division with power 2 + { + l: 'n/n^n1', + r: 'n^(1-n1)' + }, // Joining division with power 3 + { + l: 'n^n1/-n^n2', + r: 'n^(n1-n2)' + }, // Joining division with power 4 + { + l: 'n^n1/n^n2', + r: 'n^(n1-n2)' + }, // Joining division with power 5 + { + l: 'n1+(-n2*n3)', + r: 'n1-n2*n3' + }, // Solving useless parenthesis 1 + { + l: 'v*(-c)', + r: '-c*v' + }, // Solving useless unary 2 + { + l: 'n1+-n2', + r: 'n1-n2' + }, // Solving +- together (new!) + { + l: 'v*c', + r: 'c*v' + }, // inversion constant with variable + { + l: '(n1^n2)^n3', + r: '(n1^(n2*n3))' + } // Power to Power + ]; + return setRules; + } // End rulesRationalize + // --------------------------------------------------------------------------------------- + + /** + * Expand recursively a tree node for handling with expressions with exponents + * (it's not for constants, symbols or functions with exponents) + * PS: The other parameters are internal for recursion + * + * Syntax: + * + * expandPower(node) + * + * @param {Node} node Current expression node + * @param {node} parent Parent current node inside the recursion + * @param (int} Parent number of chid inside the rercursion + * + * @return {node} node expression with all powers expanded. + */ + + + function expandPower(node, parent, indParent) { + var tp = node.type; + var internal = arguments.length > 1; // TRUE in internal calls + + if (tp === 'OperatorNode' && node.isBinary()) { + var does = false; + var val; + + if (node.op === '^') { + // First operator: Parenthesis or UnaryMinus + if ((node.args[0].type === 'ParenthesisNode' || node.args[0].type === 'OperatorNode') && node.args[1].type === 'ConstantNode') { + // Second operator: Constant + val = parseFloat(node.args[1].value); + does = val >= 2 && Object(utils_number["i" /* isInteger */])(val); + } + } + + if (does) { + // Exponent >= 2 + // Before: + // operator A --> Subtree + // parent pow + // constant + // + if (val > 2) { + // Exponent > 2, + // AFTER: (exponent > 2) + // operator A --> Subtree + // parent * + // deep clone (operator A --> Subtree + // pow + // constant - 1 + // + var nEsqTopo = node.args[0]; + var nDirTopo = new OperatorNode('^', 'pow', [node.args[0].cloneDeep(), new ConstantNode(val - 1)]); + node = new OperatorNode('*', 'multiply', [nEsqTopo, nDirTopo]); + } else { + // Expo = 2 - no power + // AFTER: (exponent = 2) + // operator A --> Subtree + // parent oper + // deep clone (operator A --> Subtree) + // + node = new OperatorNode('*', 'multiply', [node.args[0], node.args[0].cloneDeep()]); + } + + if (internal) { + // Change parent references in internal recursive calls + if (indParent === 'content') { + parent.content = node; + } else { + parent.args[indParent] = node; + } + } + } // does + + } // binary OperatorNode + + + if (tp === 'ParenthesisNode') { + // Recursion + expandPower(node.content, node, 'content'); + } else if (tp !== 'ConstantNode' && tp !== 'SymbolNode') { + for (var i = 0; i < node.args.length; i++) { + expandPower(node.args[i], node, i); + } + } + + if (!internal) { + // return the root node + return node; + } + } // End expandPower + // --------------------------------------------------------------------------------------- + + /** + * Auxilary function for rationalize + * Convert near canonical polynomial in one variable in a canonical polynomial + * with one term for each exponent in decreasing order + * + * Syntax: + * + * polyToCanonical(node [, coefficients]) + * + * @param {Node | string} expr The near canonical polynomial expression to convert in a a canonical polynomial expression + * + * The string or tree expression needs to be at below syntax, with free spaces: + * ( (^(-)? | [+-]? )cte (*)? var (^expo)? | cte )+ + * Where 'var' is one variable with any valid name + * 'cte' are real numeric constants with any value. It can be omitted if equal than 1 + * 'expo' are integers greater than 0. It can be omitted if equal than 1. + * + * @param {array} coefficients Optional returns coefficients sorted by increased exponent + * + * + * @return {node} new node tree with one variable polynomial or string error. + */ + + + function polyToCanonical(node, coefficients) { + if (coefficients === undefined) { + coefficients = []; + } // coefficients. + + + coefficients[0] = 0; // index is the exponent + + var o = {}; + o.cte = 1; + o.oper = '+'; // fire: mark with * or ^ when finds * or ^ down tree, reset to "" with + and -. + // It is used to deduce the exponent: 1 for *, 0 for "". + + o.fire = ''; + var maxExpo = 0; // maximum exponent + + var varname = ''; // variable name + + recurPol(node, null, o); + maxExpo = coefficients.length - 1; + var first = true; + var no; + + for (var i = maxExpo; i >= 0; i--) { + if (coefficients[i] === 0) continue; + var n1 = new ConstantNode(first ? coefficients[i] : Math.abs(coefficients[i])); + var op = coefficients[i] < 0 ? '-' : '+'; + + if (i > 0) { + // Is not a constant without variable + var n2 = new SymbolNode(varname); + + if (i > 1) { + var n3 = new ConstantNode(i); + n2 = new OperatorNode('^', 'pow', [n2, n3]); + } + + if (coefficients[i] === -1 && first) { + n1 = new OperatorNode('-', 'unaryMinus', [n2]); + } else if (Math.abs(coefficients[i]) === 1) { + n1 = n2; + } else { + n1 = new OperatorNode('*', 'multiply', [n1, n2]); + } + } + + if (first) { + no = n1; + } else if (op === '+') { + no = new OperatorNode('+', 'add', [no, n1]); + } else { + no = new OperatorNode('-', 'subtract', [no, n1]); + } + + first = false; + } // for + + + if (first) { + return new ConstantNode(0); + } else { + return no; + } + /** + * Recursive auxilary function inside polyToCanonical for + * converting expression in canonical form + * + * Syntax: + * + * recurPol(node, noPai, obj) + * + * @param {Node} node The current subpolynomial expression + * @param {Node | Null} noPai The current parent node + * @param {object} obj Object with many internal flags + * + * @return {} No return. If error, throws an exception + */ + + + function recurPol(node, noPai, o) { + var tp = node.type; + + if (tp === 'FunctionNode') { + // ***** FunctionName ***** + // No function call in polynomial expression + throw new Error('There is an unsolved function call'); + } else if (tp === 'OperatorNode') { + // ***** OperatorName ***** + if ('+-*^'.indexOf(node.op) === -1) throw new Error('Operator ' + node.op + ' invalid'); + + if (noPai !== null) { + // -(unary),^ : children of *,+,- + if ((node.fn === 'unaryMinus' || node.fn === 'pow') && noPai.fn !== 'add' && noPai.fn !== 'subtract' && noPai.fn !== 'multiply') { + throw new Error('Invalid ' + node.op + ' placing'); + } // -,+,* : children of +,- + + + if ((node.fn === 'subtract' || node.fn === 'add' || node.fn === 'multiply') && noPai.fn !== 'add' && noPai.fn !== 'subtract') { + throw new Error('Invalid ' + node.op + ' placing'); + } // -,+ : first child + + + if ((node.fn === 'subtract' || node.fn === 'add' || node.fn === 'unaryMinus') && o.noFil !== 0) { + throw new Error('Invalid ' + node.op + ' placing'); + } + } // Has parent + // Firers: ^,* Old: ^,&,-(unary): firers + + + if (node.op === '^' || node.op === '*') { + o.fire = node.op; + } + + for (var _i = 0; _i < node.args.length; _i++) { + // +,-: reset fire + if (node.fn === 'unaryMinus') o.oper = '-'; + + if (node.op === '+' || node.fn === 'subtract') { + o.fire = ''; + o.cte = 1; // default if there is no constant + + o.oper = _i === 0 ? '+' : node.op; + } + + o.noFil = _i; // number of son + + recurPol(node.args[_i], node, o); + } // for in children + + } else if (tp === 'SymbolNode') { + // ***** SymbolName ***** + if (node.name !== varname && varname !== '') { + throw new Error('There is more than one variable'); + } + + varname = node.name; + + if (noPai === null) { + coefficients[1] = 1; + return; + } // ^: Symbol is First child + + + if (noPai.op === '^' && o.noFil !== 0) { + throw new Error('In power the variable should be the first parameter'); + } // *: Symbol is Second child + + + if (noPai.op === '*' && o.noFil !== 1) { + throw new Error('In multiply the variable should be the second parameter'); + } // Symbol: firers '',* => it means there is no exponent above, so it's 1 (cte * var) + + + if (o.fire === '' || o.fire === '*') { + if (maxExpo < 1) coefficients[1] = 0; + coefficients[1] += o.cte * (o.oper === '+' ? 1 : -1); + maxExpo = Math.max(1, maxExpo); + } + } else if (tp === 'ConstantNode') { + var valor = parseFloat(node.value); + + if (noPai === null) { + coefficients[0] = valor; + return; + } + + if (noPai.op === '^') { + // cte: second child of power + if (o.noFil !== 1) throw new Error('Constant cannot be powered'); + + if (!Object(utils_number["i" /* isInteger */])(valor) || valor <= 0) { + throw new Error('Non-integer exponent is not allowed'); + } + + for (var _i2 = maxExpo + 1; _i2 < valor; _i2++) { + coefficients[_i2] = 0; + } + + if (valor > maxExpo) coefficients[valor] = 0; + coefficients[valor] += o.cte * (o.oper === '+' ? 1 : -1); + maxExpo = Math.max(valor, maxExpo); + return; + } + + o.cte = valor; // Cte: firer '' => There is no exponent and no multiplication, so the exponent is 0. + + if (o.fire === '') { + coefficients[0] += o.cte * (o.oper === '+' ? 1 : -1); + } + } else { + throw new Error('Type ' + tp + ' is not allowed'); + } + } // End of recurPol + + } // End of polyToCanonical + + + return rationalize; +}); +// CONCATENATED MODULE: ./src/json/reviver.js + +var reviver_name = 'reviver'; +var reviver_dependencies = ['classes']; +var createReviver = /* #__PURE__ */Object(factory["a" /* factory */])(reviver_name, reviver_dependencies, function (_ref) { + var classes = _ref.classes; + + /** + * Instantiate mathjs data types from their JSON representation + * @param {string} key + * @param {*} value + * @returns {*} Returns the revived object + */ + return function reviver(key, value) { + var constructor = classes[value && value.mathjs]; + + if (constructor && typeof constructor.fromJSON === 'function') { + return constructor.fromJSON(value); + } + + return value; + }; +}); +// CONCATENATED MODULE: ./src/json/replacer.js + +var replacer_name = 'replacer'; +var replacer_dependencies = []; +var createReplacer = /* #__PURE__ */Object(factory["a" /* factory */])(replacer_name, replacer_dependencies, function () { + /** + * Stringify data types into their JSON representation. + * Most data types can be serialized using their `.toJSON` method, + * but not all, for example the number `Infinity`. For these cases you have + * to use the replacer. Example usage: + * + * JSON.stringify([2, Infinity], math.replacer) + * + * @param {string} key + * @param {*} value + * @returns {*} Returns the replaced object + */ + return function replacer(key, value) { + // the numeric values Infinitiy, -Infinity, and NaN cannot be serialized to JSON + if (typeof value === 'number' && (!isFinite(value) || isNaN(value))) { + return { + mathjs: 'number', + value: String(value) + }; + } + + return value; + }; +}); +// CONCATENATED MODULE: ./src/version.js +var version = '6.6.5'; // Note: This file is automatically generated when building math.js. +// Changes made in this file will be overwritten. +// CONCATENATED MODULE: ./src/plain/number/constants.js +var constants_pi = Math.PI; +var tau = 2 * Math.PI; +var constants_e = Math.E; +var constants_phi = 1.61803398874989484820458683436563811772030917980576286213545; +// CONCATENATED MODULE: ./src/constants.js + + + + +var createTrue = /* #__PURE__ */Object(factory["a" /* factory */])('true', [], function () { + return true; +}); +var createFalse = /* #__PURE__ */Object(factory["a" /* factory */])('false', [], function () { + return false; +}); +var createNull = /* #__PURE__ */Object(factory["a" /* factory */])('null', [], function () { + return null; +}); +var createInfinity = /* #__PURE__ */recreateFactory('Infinity', ['config', '?BigNumber'], function (_ref) { + var config = _ref.config, + BigNumber = _ref.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(Infinity) : Infinity; +}); +var createNaN = /* #__PURE__ */recreateFactory('NaN', ['config', '?BigNumber'], function (_ref2) { + var config = _ref2.config, + BigNumber = _ref2.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(NaN) : NaN; +}); +var createPi = /* #__PURE__ */recreateFactory('pi', ['config', '?BigNumber'], function (_ref3) { + var config = _ref3.config, + BigNumber = _ref3.BigNumber; + return config.number === 'BigNumber' ? createBigNumberPi(BigNumber) : constants_pi; +}); +var createTau = /* #__PURE__ */recreateFactory('tau', ['config', '?BigNumber'], function (_ref4) { + var config = _ref4.config, + BigNumber = _ref4.BigNumber; + return config.number === 'BigNumber' ? createBigNumberTau(BigNumber) : tau; +}); +var createE = /* #__PURE__ */recreateFactory('e', ['config', '?BigNumber'], function (_ref5) { + var config = _ref5.config, + BigNumber = _ref5.BigNumber; + return config.number === 'BigNumber' ? createBigNumberE(BigNumber) : constants_e; +}); // golden ratio, (1+sqrt(5))/2 + +var createPhi = /* #__PURE__ */recreateFactory('phi', ['config', '?BigNumber'], function (_ref6) { + var config = _ref6.config, + BigNumber = _ref6.BigNumber; + return config.number === 'BigNumber' ? createBigNumberPhi(BigNumber) : constants_phi; +}); +var createLN2 = /* #__PURE__ */recreateFactory('LN2', ['config', '?BigNumber'], function (_ref7) { + var config = _ref7.config, + BigNumber = _ref7.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(2).ln() : Math.LN2; +}); +var createLN10 = /* #__PURE__ */recreateFactory('LN10', ['config', '?BigNumber'], function (_ref8) { + var config = _ref8.config, + BigNumber = _ref8.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(10).ln() : Math.LN10; +}); +var createLOG2E = /* #__PURE__ */recreateFactory('LOG2E', ['config', '?BigNumber'], function (_ref9) { + var config = _ref9.config, + BigNumber = _ref9.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(1).div(new BigNumber(2).ln()) : Math.LOG2E; +}); +var createLOG10E = /* #__PURE__ */recreateFactory('LOG10E', ['config', '?BigNumber'], function (_ref10) { + var config = _ref10.config, + BigNumber = _ref10.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(1).div(new BigNumber(10).ln()) : Math.LOG10E; +}); +var createSQRT1_2 = /* #__PURE__ */recreateFactory( // eslint-disable-line camelcase +'SQRT1_2', ['config', '?BigNumber'], function (_ref11) { + var config = _ref11.config, + BigNumber = _ref11.BigNumber; + return config.number === 'BigNumber' ? new BigNumber('0.5').sqrt() : Math.SQRT1_2; +}); +var createSQRT2 = /* #__PURE__ */recreateFactory('SQRT2', ['config', '?BigNumber'], function (_ref12) { + var config = _ref12.config, + BigNumber = _ref12.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(2).sqrt() : Math.SQRT2; +}); +var createI = /* #__PURE__ */recreateFactory('i', ['Complex'], function (_ref13) { + var Complex = _ref13.Complex; + return Complex.I; +}); // for backward compatibility with v5 + +var createUppercasePi = /* #__PURE__ */Object(factory["a" /* factory */])('PI', ['pi'], function (_ref14) { + var pi = _ref14.pi; + return pi; +}); +var createUppercaseE = /* #__PURE__ */Object(factory["a" /* factory */])('E', ['e'], function (_ref15) { + var e = _ref15.e; + return e; +}); +var createVersion = /* #__PURE__ */Object(factory["a" /* factory */])('version', [], function () { + return version; +}); // helper function to create a factory with a flag recreateOnConfigChange +// idea: allow passing optional properties to be attached to the factory function as 4th argument? + +function recreateFactory(name, dependencies, create) { + return Object(factory["a" /* factory */])(name, dependencies, create, { + recreateOnConfigChange: true + }); +} +// CONCATENATED MODULE: ./src/type/unit/physicalConstants.js + // Source: https://en.wikipedia.org/wiki/Physical_constant +// Universal constants + +var createSpeedOfLight = /* #__PURE__ */unitFactory('speedOfLight', '299792458', 'm s^-1'); +var createGravitationConstant = /* #__PURE__ */unitFactory('gravitationConstant', '6.67430e-11', 'm^3 kg^-1 s^-2'); +var createPlanckConstant = /* #__PURE__ */unitFactory('planckConstant', '6.62607015e-34', 'J s'); +var createReducedPlanckConstant = /* #__PURE__ */unitFactory('reducedPlanckConstant', '1.0545718176461565e-34', 'J s'); // Electromagnetic constants + +var createMagneticConstant = /* #__PURE__ */unitFactory('magneticConstant', '1.25663706212e-6', 'N A^-2'); +var createElectricConstant = /* #__PURE__ */unitFactory('electricConstant', '8.8541878128e-12', 'F m^-1'); +var createVacuumImpedance = /* #__PURE__ */unitFactory('vacuumImpedance', '376.730313667', 'ohm'); +var createCoulomb = /* #__PURE__ */unitFactory('coulomb', '8.987551792261171e9', 'N m^2 C^-2'); +var createElementaryCharge = /* #__PURE__ */unitFactory('elementaryCharge', '1.602176634e-19', 'C'); +var createBohrMagneton = /* #__PURE__ */unitFactory('bohrMagneton', '9.2740100783e-24', 'J T^-1'); +var createConductanceQuantum = /* #__PURE__ */unitFactory('conductanceQuantum', '7.748091729863649e-5', 'S'); +var createInverseConductanceQuantum = /* #__PURE__ */unitFactory('inverseConductanceQuantum', '12906.403729652257', 'ohm'); +var createMagneticFluxQuantum = /* #__PURE__ */unitFactory('magneticFluxQuantum', '2.0678338484619295e-15', 'Wb'); +var createNuclearMagneton = /* #__PURE__ */unitFactory('nuclearMagneton', '5.0507837461e-27', 'J T^-1'); +var createKlitzing = /* #__PURE__ */unitFactory('klitzing', '25812.807459304513', 'ohm'); +var createJosephson = /* #__PURE__ */unitFactory('josephson', '4.835978484169836e14 Hz V', 'Hz V^-1'); // TODO: support for Hz needed +// Atomic and nuclear constants + +var createBohrRadius = /* #__PURE__ */unitFactory('bohrRadius', '5.29177210903e-11', 'm'); +var createClassicalElectronRadius = /* #__PURE__ */unitFactory('classicalElectronRadius', '2.8179403262e-15', 'm'); +var createElectronMass = /* #__PURE__ */unitFactory('electronMass', '9.1093837015e-31', 'kg'); +var createFermiCoupling = /* #__PURE__ */unitFactory('fermiCoupling', '1.1663787e-5', 'GeV^-2'); +var createFineStructure = numberFactory('fineStructure', 7.2973525693e-3); +var createHartreeEnergy = /* #__PURE__ */unitFactory('hartreeEnergy', '4.3597447222071e-18', 'J'); +var createProtonMass = /* #__PURE__ */unitFactory('protonMass', '1.67262192369e-27', 'kg'); +var createDeuteronMass = /* #__PURE__ */unitFactory('deuteronMass', '3.3435830926e-27', 'kg'); +var createNeutronMass = /* #__PURE__ */unitFactory('neutronMass', '1.6749271613e-27', 'kg'); +var createQuantumOfCirculation = /* #__PURE__ */unitFactory('quantumOfCirculation', '3.6369475516e-4', 'm^2 s^-1'); +var createRydberg = /* #__PURE__ */unitFactory('rydberg', '10973731.568160', 'm^-1'); +var createThomsonCrossSection = /* #__PURE__ */unitFactory('thomsonCrossSection', '6.6524587321e-29', 'm^2'); +var createWeakMixingAngle = numberFactory('weakMixingAngle', 0.22290); +var createEfimovFactor = numberFactory('efimovFactor', 22.7); // Physico-chemical constants + +var createAtomicMass = /* #__PURE__ */unitFactory('atomicMass', '1.66053906660e-27', 'kg'); +var createAvogadro = /* #__PURE__ */unitFactory('avogadro', '6.02214076e23', 'mol^-1'); +var createBoltzmann = /* #__PURE__ */unitFactory('boltzmann', '1.380649e-23', 'J K^-1'); +var createFaraday = /* #__PURE__ */unitFactory('faraday', '96485.33212331001', 'C mol^-1'); +var createFirstRadiation = /* #__PURE__ */unitFactory('firstRadiation', '3.7417718521927573e-16', 'W m^2'); // export const createSpectralRadiance = /* #__PURE__ */ unitFactory('spectralRadiance', '1.1910429723971881e-16', 'W m^2 sr^-1') // TODO spectralRadiance + +var createLoschmidt = /* #__PURE__ */unitFactory('loschmidt', '2.686780111798444e25', 'm^-3'); +var createGasConstant = /* #__PURE__ */unitFactory('gasConstant', '8.31446261815324', 'J K^-1 mol^-1'); +var createMolarPlanckConstant = /* #__PURE__ */unitFactory('molarPlanckConstant', '3.990312712893431e-10', 'J s mol^-1'); +var createMolarVolume = /* #__PURE__ */unitFactory('molarVolume', '0.022413969545014137', 'm^3 mol^-1'); +var createSackurTetrode = numberFactory('sackurTetrode', -1.16487052358); +var createSecondRadiation = /* #__PURE__ */unitFactory('secondRadiation', '0.014387768775039337', 'm K'); +var createStefanBoltzmann = /* #__PURE__ */unitFactory('stefanBoltzmann', '5.67037441918443e-8', 'W m^-2 K^-4'); +var createWienDisplacement = /* #__PURE__ */unitFactory('wienDisplacement', '2.897771955e-3', 'm K'); // Adopted values + +var createMolarMass = /* #__PURE__ */unitFactory('molarMass', '0.99999999965e-3', 'kg mol^-1'); +var createMolarMassC12 = /* #__PURE__ */unitFactory('molarMassC12', '11.9999999958e-3', 'kg mol^-1'); +var createGravity = /* #__PURE__ */unitFactory('gravity', '9.80665', 'm s^-2'); // atm is defined in Unit.js +// Natural units + +var createPlanckLength = /* #__PURE__ */unitFactory('planckLength', '1.616255e-35', 'm'); +var createPlanckMass = /* #__PURE__ */unitFactory('planckMass', '2.176435e-8', 'kg'); +var createPlanckTime = /* #__PURE__ */unitFactory('planckTime', '5.391245e-44', 's'); +var createPlanckCharge = /* #__PURE__ */unitFactory('planckCharge', '1.87554603778e-18', 'C'); +var createPlanckTemperature = /* #__PURE__ */unitFactory('planckTemperature', '1.416785e+32', 'K'); // helper function to create a factory function which creates a physical constant, +// a Unit with either a number value or a BigNumber value depending on the configuration + +function unitFactory(name, valueStr, unitStr) { + var dependencies = ['config', 'Unit', 'BigNumber']; + return Object(factory["a" /* factory */])(name, dependencies, function (_ref) { + var config = _ref.config, + Unit = _ref.Unit, + BigNumber = _ref.BigNumber; + // Note that we can parse into number or BigNumber. + // We do not parse into Fractions as that doesn't make sense: we would lose precision of the values + // Therefore we dont use Unit.parse() + var value = config.number === 'BigNumber' ? new BigNumber(valueStr) : parseFloat(valueStr); + var unit = new Unit(value, unitStr); + unit.fixPrefix = true; + return unit; + }); +} // helper function to create a factory function which creates a numeric constant, +// either a number or BigNumber depending on the configuration + + +function numberFactory(name, value) { + var dependencies = ['config', 'BigNumber']; + return Object(factory["a" /* factory */])(name, dependencies, function (_ref2) { + var config = _ref2.config, + BigNumber = _ref2.BigNumber; + return config.number === 'BigNumber' ? new BigNumber(value) : value; + }); +} +// CONCATENATED MODULE: ./src/expression/transform/apply.transform.js + + + + +var apply_transform_name = 'apply'; +var apply_transform_dependencies = ['typed', 'isInteger']; +/** + * Attach a transform function to math.apply + * Adds a property transform containing the transform function. + * + * This transform changed the last `dim` parameter of function apply + * from one-based to zero based + */ + +var createApplyTransform = /* #__PURE__ */Object(factory["a" /* factory */])(apply_transform_name, apply_transform_dependencies, function (_ref) { + var typed = _ref.typed, + isInteger = _ref.isInteger; + var apply = createApply({ + typed: typed, + isInteger: isInteger + }); // @see: comment of concat itself + + return typed('apply', { + '...any': function any(args) { + // change dim from one-based to zero-based + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + + try { + return apply.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/column.transform.js + + + + +var column_transform_name = 'column'; +var column_transform_dependencies = ['typed', 'Index', 'matrix', 'range']; +/** + * Attach a transform function to matrix.column + * Adds a property transform containing the transform function. + * + * This transform changed the last `index` parameter of function column + * from zero-based to one-based + */ + +var createColumnTransform = /* #__PURE__ */Object(factory["a" /* factory */])(column_transform_name, column_transform_dependencies, function (_ref) { + var typed = _ref.typed, + Index = _ref.Index, + matrix = _ref.matrix, + range = _ref.range; + var column = createColumn({ + typed: typed, + Index: Index, + matrix: matrix, + range: range + }); // @see: comment of column itself + + return typed('column', { + '...any': function any(args) { + // change last argument from zero-based to one-based + var lastIndex = args.length - 1; + var last = args[lastIndex]; + + if (Object(is["y" /* isNumber */])(last)) { + args[lastIndex] = last - 1; + } + + try { + return column.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/utils/compileInlineExpression.js + +/** + * Compile an inline expression like "x > 0" + * @param {Node} expression + * @param {Object} math + * @param {Object} scope + * @return {function} Returns a function with one argument which fills in the + * undefined variable (like "x") and evaluates the expression + */ + +function compileInlineExpression(expression, math, scope) { + // find an undefined symbol + var symbol = expression.filter(function (node) { + return Object(is["J" /* isSymbolNode */])(node) && !(node.name in math) && !(node.name in scope); + })[0]; + + if (!symbol) { + throw new Error('No undefined variable found in inline expression "' + expression + '"'); + } // create a test function for this equation + + + var name = symbol.name; // variable name + + var subScope = Object.create(scope); + var eq = expression.compile(); + return function inlineExpression(x) { + subScope[name] = x; + return eq.evaluate(subScope); + }; +} +// CONCATENATED MODULE: ./src/expression/transform/filter.transform.js + + + + + +var filter_transform_name = 'filter'; +var filter_transform_dependencies = ['typed']; +var createFilterTransform = /* #__PURE__ */Object(factory["a" /* factory */])(filter_transform_name, filter_transform_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Attach a transform function to math.filter + * Adds a property transform containing the transform function. + * + * This transform adds support for equations as test function for math.filter, + * so you can do something like 'filter([3, -2, 5], x > 0)'. + */ + function filterTransform(args, math, scope) { + var x, callback; + + if (args[0]) { + x = args[0].compile().evaluate(scope); + } + + if (args[1]) { + if (Object(is["J" /* isSymbolNode */])(args[1]) || Object(is["q" /* isFunctionAssignmentNode */])(args[1])) { + // a function pointer, like filter([3, -2, 5], myTestFunction) + callback = args[1].compile().evaluate(scope); + } else { + // an expression like filter([3, -2, 5], x > 0) + callback = compileInlineExpression(args[1], math, scope); + } + } + + return filter(x, callback); + } + + filterTransform.rawArgs = true; // one based version of function filter + + var filter = typed('filter', { + 'Array, function': _filter, + 'Matrix, function': function MatrixFunction(x, test) { + return x.create(_filter(x.toArray(), test)); + }, + 'Array, RegExp': utils_array["d" /* filterRegExp */], + 'Matrix, RegExp': function MatrixRegExp(x, test) { + return x.create(Object(utils_array["d" /* filterRegExp */])(x.toArray(), test)); + } + }); + return filterTransform; +}, { + isTransformFunction: true +}); +/** + * Filter values in a callback given a callback function + * + * !!! Passes a one-based index !!! + * + * @param {Array} x + * @param {Function} callback + * @return {Array} Returns the filtered array + * @private + */ + +function _filter(x, callback) { + // figure out what number of arguments the callback function expects + var args = maxArgumentCount(callback); + return Object(utils_array["c" /* filter */])(x, function (value, index, array) { + // invoke the callback function with the right number of arguments + if (args === 1) { + return callback(value); + } else if (args === 2) { + return callback(value, [index + 1]); + } else { + // 3 or -1 + return callback(value, [index + 1], array); + } + }); +} +// CONCATENATED MODULE: ./src/expression/transform/forEach.transform.js + + + + + +var forEach_transform_name = 'forEach'; +var forEach_transform_dependencies = ['typed']; +var createForEachTransform = /* #__PURE__ */Object(factory["a" /* factory */])(forEach_transform_name, forEach_transform_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Attach a transform function to math.forEach + * Adds a property transform containing the transform function. + * + * This transform creates a one-based index instead of a zero-based index + */ + function forEachTransform(args, math, scope) { + var x, callback; + + if (args[0]) { + x = args[0].compile().evaluate(scope); + } + + if (args[1]) { + if (Object(is["J" /* isSymbolNode */])(args[1]) || Object(is["q" /* isFunctionAssignmentNode */])(args[1])) { + // a function pointer, like forEach([3, -2, 5], myTestFunction) + callback = args[1].compile().evaluate(scope); + } else { + // an expression like forEach([3, -2, 5], x > 0 ? callback1(x) : callback2(x) ) + callback = compileInlineExpression(args[1], math, scope); + } + } + + return _forEach(x, callback); + } + + forEachTransform.rawArgs = true; // one-based version of forEach + + var _forEach = typed('forEach', { + 'Array | Matrix, function': function ArrayMatrixFunction(array, callback) { + // figure out what number of arguments the callback function expects + var args = maxArgumentCount(callback); + + var recurse = function recurse(value, index) { + if (Array.isArray(value)) { + Object(utils_array["f" /* forEach */])(value, function (child, i) { + // we create a copy of the index array and append the new index value + recurse(child, index.concat(i + 1)); // one based index, hence i+1 + }); + } else { + // invoke the callback function with the right number of arguments + if (args === 1) { + callback(value); + } else if (args === 2) { + callback(value, index); + } else { + // 3 or -1 + callback(value, index, array); + } + } + }; + + recurse(array.valueOf(), []); // pass Array + } + }); + + return forEachTransform; +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/index.transform.js + + +var index_transform_name = 'index'; +var index_transform_dependencies = ['Index']; +var createIndexTransform = /* #__PURE__ */Object(factory["a" /* factory */])(index_transform_name, index_transform_dependencies, function (_ref) { + var Index = _ref.Index; + + /** + * Attach a transform function to math.index + * Adds a property transform containing the transform function. + * + * This transform creates a one-based index instead of a zero-based index + */ + return function indexTransform() { + var args = []; + + for (var i = 0, ii = arguments.length; i < ii; i++) { + var arg = arguments[i]; // change from one-based to zero based, and convert BigNumber to number + + if (Object(is["D" /* isRange */])(arg)) { + arg.start--; + arg.end -= arg.step > 0 ? 0 : 2; + } else if (arg && arg.isSet === true) { + arg = arg.map(function (v) { + return v - 1; + }); + } else if (Object(is["b" /* isArray */])(arg) || Object(is["v" /* isMatrix */])(arg)) { + arg = arg.map(function (v) { + return v - 1; + }); + } else if (Object(is["y" /* isNumber */])(arg)) { + arg--; + } else if (Object(is["e" /* isBigNumber */])(arg)) { + arg = arg.toNumber() - 1; + } else if (typeof arg === 'string') {// leave as is + } else { + throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range'); + } + + args[i] = arg; + } + + var res = new Index(); + Index.apply(res, args); + return res; + }; +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/map.transform.js + + + + + +var map_transform_name = 'map'; +var map_transform_dependencies = ['typed']; +var createMapTransform = /* #__PURE__ */Object(factory["a" /* factory */])(map_transform_name, map_transform_dependencies, function (_ref) { + var typed = _ref.typed; + + /** + * Attach a transform function to math.map + * Adds a property transform containing the transform function. + * + * This transform creates a one-based index instead of a zero-based index + */ + function mapTransform(args, math, scope) { + var x, callback; + + if (args[0]) { + x = args[0].compile().evaluate(scope); + } + + if (args[1]) { + if (Object(is["J" /* isSymbolNode */])(args[1]) || Object(is["q" /* isFunctionAssignmentNode */])(args[1])) { + // a function pointer, like filter([3, -2, 5], myTestFunction) + callback = args[1].compile().evaluate(scope); + } else { + // an expression like filter([3, -2, 5], x > 0) + callback = compileInlineExpression(args[1], math, scope); + } + } + + return map(x, callback); + } + + mapTransform.rawArgs = true; // one-based version of map function + + var map = typed('map', { + 'Array, function': function ArrayFunction(x, callback) { + return map_transform_map(x, callback, x); + }, + 'Matrix, function': function MatrixFunction(x, callback) { + return x.create(map_transform_map(x.valueOf(), callback, x)); + } + }); + return mapTransform; +}, { + isTransformFunction: true +}); +/** + * Map for a multi dimensional array. One-based indexes + * @param {Array} array + * @param {function} callback + * @param {Array} orig + * @return {Array} + * @private + */ + +function map_transform_map(array, callback, orig) { + // figure out what number of arguments the callback function expects + var argsCount = maxArgumentCount(callback); + + function recurse(value, index) { + if (Array.isArray(value)) { + return Object(utils_array["m" /* map */])(value, function (child, i) { + // we create a copy of the index array and append the new index value + return recurse(child, index.concat(i + 1)); // one based index, hence i + 1 + }); + } else { + // invoke the (typed) callback function with the right number of arguments + if (argsCount === 1) { + return callback(value); + } else if (argsCount === 2) { + return callback(value, index); + } else { + // 3 or -1 + return callback(value, index, orig); + } + } + } + + return recurse(array, []); +} +// CONCATENATED MODULE: ./src/expression/transform/max.transform.js + + + + +var max_transform_name = 'max'; +var max_transform_dependencies = ['typed', 'larger']; +var createMaxTransform = /* #__PURE__ */Object(factory["a" /* factory */])(max_transform_name, max_transform_dependencies, function (_ref) { + var typed = _ref.typed, + larger = _ref.larger; + var max = createMax({ + typed: typed, + larger: larger + }); + /** + * Attach a transform function to math.max + * Adds a property transform containing the transform function. + * + * This transform changed the last `dim` parameter of function max + * from one-based to zero based + */ + + return typed('max', { + '...any': function any(args) { + // change last argument dim from one-based to zero-based + if (args.length === 2 && Object(is["i" /* isCollection */])(args[0])) { + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + } + + try { + return max.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/mean.transform.js + + + + +var mean_transform_name = 'mean'; +var mean_transform_dependencies = ['typed', 'add', 'divide']; +var createMeanTransform = /* #__PURE__ */Object(factory["a" /* factory */])(mean_transform_name, mean_transform_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + divide = _ref.divide; + var mean = createMean({ + typed: typed, + add: add, + divide: divide + }); + /** + * Attach a transform function to math.mean + * Adds a property transform containing the transform function. + * + * This transform changed the last `dim` parameter of function mean + * from one-based to zero based + */ + + return typed('mean', { + '...any': function any(args) { + // change last argument dim from one-based to zero-based + if (args.length === 2 && Object(is["i" /* isCollection */])(args[0])) { + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + } + + try { + return mean.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/min.transform.js + + + + +var min_transform_name = 'min'; +var min_transform_dependencies = ['typed', 'smaller']; +var createMinTransform = /* #__PURE__ */Object(factory["a" /* factory */])(min_transform_name, min_transform_dependencies, function (_ref) { + var typed = _ref.typed, + smaller = _ref.smaller; + var min = createMin({ + typed: typed, + smaller: smaller + }); + /** + * Attach a transform function to math.min + * Adds a property transform containing the transform function. + * + * This transform changed the last `dim` parameter of function min + * from one-based to zero based + */ + + return typed('min', { + '...any': function any(args) { + // change last argument dim from one-based to zero-based + if (args.length === 2 && Object(is["i" /* isCollection */])(args[0])) { + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + } + + try { + return min.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/range.transform.js + + +var range_transform_name = 'range'; +var range_transform_dependencies = ['typed', 'config', '?matrix', '?bignumber', 'smaller', 'smallerEq', 'larger', 'largerEq']; +var createRangeTransform = /* #__PURE__ */Object(factory["a" /* factory */])(range_transform_name, range_transform_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + matrix = _ref.matrix, + bignumber = _ref.bignumber, + smaller = _ref.smaller, + smallerEq = _ref.smallerEq, + larger = _ref.larger, + largerEq = _ref.largerEq; + var range = range_createRange({ + typed: typed, + config: config, + matrix: matrix, + bignumber: bignumber, + smaller: smaller, + smallerEq: smallerEq, + larger: larger, + largerEq: largerEq + }); + /** + * Attach a transform function to math.range + * Adds a property transform containing the transform function. + * + * This transform creates a range which includes the end value + */ + + return typed('range', { + '...any': function any(args) { + var lastIndex = args.length - 1; + var last = args[lastIndex]; + + if (typeof last !== 'boolean') { + // append a parameter includeEnd=true + args.push(true); + } + + return range.apply(null, args); + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/row.transform.js + + + + +var row_transform_name = 'row'; +var row_transform_dependencies = ['typed', 'Index', 'matrix', 'range']; +/** + * Attach a transform function to matrix.column + * Adds a property transform containing the transform function. + * + * This transform changed the last `index` parameter of function column + * from zero-based to one-based + */ + +var createRowTransform = /* #__PURE__ */Object(factory["a" /* factory */])(row_transform_name, row_transform_dependencies, function (_ref) { + var typed = _ref.typed, + Index = _ref.Index, + matrix = _ref.matrix, + range = _ref.range; + var row = createRow({ + typed: typed, + Index: Index, + matrix: matrix, + range: range + }); // @see: comment of row itself + + return typed('row', { + '...any': function any(args) { + // change last argument from zero-based to one-based + var lastIndex = args.length - 1; + var last = args[lastIndex]; + + if (Object(is["y" /* isNumber */])(last)) { + args[lastIndex] = last - 1; + } + + try { + return row.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/subset.transform.js + + + +var subset_transform_name = 'subset'; +var subset_transform_dependencies = ['typed', 'matrix']; +var createSubsetTransform = /* #__PURE__ */Object(factory["a" /* factory */])(subset_transform_name, subset_transform_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix; + var subset = createSubset({ + typed: typed, + matrix: matrix + }); + /** + * Attach a transform function to math.subset + * Adds a property transform containing the transform function. + * + * This transform creates a range which includes the end value + */ + + return typed('subset', { + '...any': function any(args) { + try { + return subset.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/concat.transform.js + + + + +var concat_transform_name = 'concat'; +var concat_transform_dependencies = ['typed', 'matrix', 'isInteger']; +var createConcatTransform = /* #__PURE__ */Object(factory["a" /* factory */])(concat_transform_name, concat_transform_dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + isInteger = _ref.isInteger; + var concat = createConcat({ + typed: typed, + matrix: matrix, + isInteger: isInteger + }); + /** + * Attach a transform function to math.range + * Adds a property transform containing the transform function. + * + * This transform changed the last `dim` parameter of function concat + * from one-based to zero based + */ + + return typed('concat', { + '...any': function any(args) { + // change last argument from one-based to zero-based + var lastIndex = args.length - 1; + var last = args[lastIndex]; + + if (Object(is["y" /* isNumber */])(last)) { + args[lastIndex] = last - 1; + } else if (Object(is["e" /* isBigNumber */])(last)) { + args[lastIndex] = last.minus(1); + } + + try { + return concat.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/std.transform.js + + + + +var std_transform_name = 'std'; +var std_transform_dependencies = ['typed', 'sqrt', 'variance']; +/** + * Attach a transform function to math.std + * Adds a property transform containing the transform function. + * + * This transform changed the `dim` parameter of function std + * from one-based to zero based + */ + +var createStdTransform = /* #__PURE__ */Object(factory["a" /* factory */])(std_transform_name, std_transform_dependencies, function (_ref) { + var typed = _ref.typed, + sqrt = _ref.sqrt, + variance = _ref.variance; + var std = createStd({ + typed: typed, + sqrt: sqrt, + variance: variance + }); + return typed('std', { + '...any': function any(args) { + // change last argument dim from one-based to zero-based + if (args.length >= 2 && Object(is["i" /* isCollection */])(args[0])) { + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + } + + try { + return std.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/sum.transform.js + + + + +/** + * Attach a transform function to math.sum + * Adds a property transform containing the transform function. + * + * This transform changed the last `dim` parameter of function mean + * from one-based to zero based + */ + +var sum_transform_name = 'sum'; +var sum_transform_dependencies = ['typed', 'config', 'add', '?bignumber', '?fraction']; +var createSumTransform = /* #__PURE__ */Object(factory["a" /* factory */])(sum_transform_name, sum_transform_dependencies, function (_ref) { + var typed = _ref.typed, + config = _ref.config, + add = _ref.add, + bignumber = _ref.bignumber, + fraction = _ref.fraction; + var sum = createSum({ + typed: typed, + config: config, + add: add, + bignumber: bignumber, + fraction: fraction + }); + return typed(sum_transform_name, { + '...any': function any(args) { + // change last argument dim from one-based to zero-based + if (args.length === 2 && Object(is["i" /* isCollection */])(args[0])) { + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + } + + try { + return sum.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/expression/transform/variance.transform.js + + + + +var variance_transform_name = 'variance'; +var variance_transform_dependencies = ['typed', 'add', 'subtract', 'multiply', 'divide', 'apply', 'isNaN']; +/** + * Attach a transform function to math.var + * Adds a property transform containing the transform function. + * + * This transform changed the `dim` parameter of function var + * from one-based to zero based + */ + +var createVarianceTransform = /* #__PURE__ */Object(factory["a" /* factory */])(variance_transform_name, variance_transform_dependencies, function (_ref) { + var typed = _ref.typed, + add = _ref.add, + subtract = _ref.subtract, + multiply = _ref.multiply, + divide = _ref.divide, + apply = _ref.apply, + isNaN = _ref.isNaN; + var variance = createVariance({ + typed: typed, + add: add, + subtract: subtract, + multiply: multiply, + divide: divide, + apply: apply, + isNaN: isNaN + }); + return typed(variance_transform_name, { + '...any': function any(args) { + // change last argument dim from one-based to zero-based + if (args.length >= 2 && Object(is["i" /* isCollection */])(args[0])) { + var dim = args[1]; + + if (Object(is["y" /* isNumber */])(dim)) { + args[1] = dim - 1; + } else if (Object(is["e" /* isBigNumber */])(dim)) { + args[1] = dim.minus(1); + } + } + + try { + return variance.apply(null, args); + } catch (err) { + throw errorTransform(err); + } + } + }); +}, { + isTransformFunction: true +}); +// CONCATENATED MODULE: ./src/factoriesAny.js + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/***/ }), +/* 22 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, "create", function() { return /* binding */ create; }); + +// EXTERNAL MODULE: ./src/utils/object.js +var utils_object = __webpack_require__(3); + +// EXTERNAL MODULE: ./node_modules/tiny-emitter/index.js +var tiny_emitter = __webpack_require__(18); +var tiny_emitter_default = /*#__PURE__*/__webpack_require__.n(tiny_emitter); + +// CONCATENATED MODULE: ./src/utils/emitter.js + +/** + * Extend given object with emitter functions `on`, `off`, `once`, `emit` + * @param {Object} obj + * @return {Object} obj + */ + +function mixin(obj) { + // create event emitter + var emitter = new tiny_emitter_default.a(); // bind methods to obj (we don't want to expose the emitter.e Array...) + + obj.on = emitter.on.bind(emitter); + obj.off = emitter.off.bind(emitter); + obj.once = emitter.once.bind(emitter); + obj.emit = emitter.emit.bind(emitter); + return obj; +} +// EXTERNAL MODULE: ./src/utils/is.js +var is = __webpack_require__(1); + +// EXTERNAL MODULE: ./src/utils/factory.js +var utils_factory = __webpack_require__(0); + +// EXTERNAL MODULE: ./src/utils/array.js +var array = __webpack_require__(2); + +// EXTERNAL MODULE: ./src/error/ArgumentsError.js +var ArgumentsError = __webpack_require__(13); + +// EXTERNAL MODULE: ./src/utils/log.js +var log = __webpack_require__(8); + +// CONCATENATED MODULE: ./src/core/function/import.js +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + + + + + + + +function importFactory(typed, load, math, importedFactories) { + /** + * Import functions from an object or a module. + * + * This function is only available on a mathjs instance created using `create`. + * + * Syntax: + * + * math.import(functions) + * math.import(functions, options) + * + * Where: + * + * - `functions: Object` + * An object with functions or factories to be imported. + * - `options: Object` An object with import options. Available options: + * - `override: boolean` + * If true, existing functions will be overwritten. False by default. + * - `silent: boolean` + * If true, the function will not throw errors on duplicates or invalid + * types. False by default. + * - `wrap: boolean` + * If true, the functions will be wrapped in a wrapper function + * which converts data types like Matrix to primitive data types like Array. + * The wrapper is needed when extending math.js with libraries which do not + * support these data type. False by default. + * + * Examples: + * + * import { create, all } from 'mathjs' + * import * as numbers from 'numbers' + * + * // create a mathjs instance + * const math = create(all) + * + * // define new functions and variables + * math.import({ + * myvalue: 42, + * hello: function (name) { + * return 'hello, ' + name + '!' + * } + * }) + * + * // use the imported function and variable + * math.myvalue * 2 // 84 + * math.hello('user') // 'hello, user!' + * + * // import the npm module 'numbers' + * // (must be installed first with `npm install numbers`) + * math.import(numbers, {wrap: true}) + * + * math.fibonacci(7) // returns 13 + * + * @param {Object | Array} functions Object with functions to be imported. + * @param {Object} [options] Import options. + */ + function mathImport(functions, options) { + var num = arguments.length; + + if (num !== 1 && num !== 2) { + throw new ArgumentsError["a" /* ArgumentsError */]('import', num, 1, 2); + } + + if (!options) { + options = {}; + } + + function flattenImports(flatValues, value, name) { + if (Object(utils_object["g" /* isLegacyFactory */])(value)) { + // legacy factories don't always have a name, + // let's not handle them via the new flatValues + _importLegacyFactory(value, options); + } else if (Array.isArray(value)) { + value.forEach(function (item) { + return flattenImports(flatValues, item); + }); + } else if (_typeof(value) === 'object') { + for (var _name in value) { + if (Object(utils_object["f" /* hasOwnProperty */])(value, _name)) { + flattenImports(flatValues, value[_name], _name); + } + } + } else if (Object(utils_factory["b" /* isFactory */])(value) || name !== undefined) { + var flatName = Object(utils_factory["b" /* isFactory */])(value) ? isTransformFunctionFactory(value) ? value.fn + '.transform' : // TODO: this is ugly + value.fn : name; // we allow importing the same function twice if it points to the same implementation + + if (Object(utils_object["f" /* hasOwnProperty */])(flatValues, flatName) && flatValues[flatName] !== value && !options.silent) { + throw new Error('Cannot import "' + flatName + '" twice'); + } + + flatValues[flatName] = value; + } else { + if (!options.silent) { + throw new TypeError('Factory, Object, or Array expected'); + } + } + } + + var flatValues = {}; + flattenImports(flatValues, functions); + + for (var name in flatValues) { + if (Object(utils_object["f" /* hasOwnProperty */])(flatValues, name)) { + // console.log('import', name) + var value = flatValues[name]; + + if (Object(utils_factory["b" /* isFactory */])(value)) { + // we ignore name here and enforce the name of the factory + // maybe at some point we do want to allow overriding it + // in that case we can implement an option overrideFactoryNames: true + _importFactory(value, options); + } else if (isSupportedType(value)) { + _import(name, value, options); + } else { + if (!options.silent) { + throw new TypeError('Factory, Object, or Array expected'); + } + } + } + } + } + /** + * Add a property to the math namespace + * @param {string} name + * @param {*} value + * @param {Object} options See import for a description of the options + * @private + */ + + + function _import(name, value, options) { + // TODO: refactor this function, it's to complicated and contains duplicate code + if (options.wrap && typeof value === 'function') { + // create a wrapper around the function + value = _wrap(value); + } // turn a plain function with a typed-function signature into a typed-function + + + if (hasTypedFunctionSignature(value)) { + value = typed(name, _defineProperty({}, value.signature, value)); + } + + if (isTypedFunction(math[name]) && isTypedFunction(value)) { + if (options.override) { + // give the typed function the right name + value = typed(name, value.signatures); + } else { + // merge the existing and typed function + value = typed(math[name], value); + } + + math[name] = value; + delete importedFactories[name]; + + _importTransform(name, value); + + math.emit('import', name, function resolver() { + return value; + }); + return; + } + + if (math[name] === undefined || options.override) { + math[name] = value; + delete importedFactories[name]; + + _importTransform(name, value); + + math.emit('import', name, function resolver() { + return value; + }); + return; + } + + if (!options.silent) { + throw new Error('Cannot import "' + name + '": already exists'); + } + } + + function _importTransform(name, value) { + if (value && typeof value.transform === 'function') { + math.expression.transform[name] = value.transform; + + if (allowedInExpressions(name)) { + math.expression.mathWithTransform[name] = value.transform; + } + } else { + // remove existing transform + delete math.expression.transform[name]; + + if (allowedInExpressions(name)) { + math.expression.mathWithTransform[name] = value; + } + } + } + + function _deleteTransform(name) { + delete math.expression.transform[name]; + + if (allowedInExpressions(name)) { + math.expression.mathWithTransform[name] = math[name]; + } else { + delete math.expression.mathWithTransform[name]; + } + } + /** + * Create a wrapper a round an function which converts the arguments + * to their primitive values (like convert a Matrix to Array) + * @param {Function} fn + * @return {Function} Returns the wrapped function + * @private + */ + + + function _wrap(fn) { + var wrapper = function wrapper() { + var args = []; + + for (var i = 0, len = arguments.length; i < len; i++) { + var arg = arguments[i]; + args[i] = arg && arg.valueOf(); + } + + return fn.apply(math, args); + }; + + if (fn.transform) { + wrapper.transform = fn.transform; + } + + return wrapper; + } + /** + * Import an instance of a factory into math.js + * @param {{factory: Function, name: string, path: string, math: boolean}} factory + * @param {Object} options See import for a description of the options + * @private + */ + // TODO: _importLegacyFactory is deprecated since v6.0.0, clean up some day + + + function _importLegacyFactory(factory, options) { + Object(log["a" /* warnOnce */])('Factories of type { name, factory } are deprecated since v6. ' + 'Please create your factory functions using the math.factory function.'); + + if (typeof factory.name === 'string') { + var name = factory.name; + var existingTransform = (name in math.expression.transform); + var namespace = factory.path ? Object(utils_object["k" /* traverse */])(math, factory.path) : math; + var existing = Object(utils_object["f" /* hasOwnProperty */])(namespace, name) ? namespace[name] : undefined; + + var resolver = function resolver() { + var instance = load(factory); + + if (instance && typeof instance.transform === 'function') { + throw new Error('Transforms cannot be attached to factory functions. ' + 'Please create a separate function for it with exports.path="expression.transform"'); + } + + if (isTypedFunction(existing) && isTypedFunction(instance)) { + if (options.override) {// replace the existing typed function (nothing to do) + } else { + // merge the existing and new typed function + instance = typed(existing, instance); + } + + return instance; + } + + if (existing === undefined || options.override) { + return instance; + } + + if (options.silent) { + return existing; + } else { + throw new Error('Cannot import "' + name + '": already exists'); + } + }; + + if (factory.lazy !== false) { + Object(utils_object["h" /* lazy */])(namespace, name, resolver); + + if (existingTransform) { + _deleteTransform(name); + } else { + if (factory.path === 'expression.transform' || legacyFactoryAllowedInExpressions(factory)) { + Object(utils_object["h" /* lazy */])(math.expression.mathWithTransform, name, resolver); + } + } + } else { + namespace[name] = resolver(); + + if (existingTransform) { + _deleteTransform(name); + } else { + if (factory.path === 'expression.transform' || legacyFactoryAllowedInExpressions(factory)) { + math.expression.mathWithTransform[name] = resolver(); + } + } + } + + var key = factory.path ? factory.path + '.' + factory.name : factory.name; + importedFactories[key] = factory; + math.emit('import', name, resolver, factory.path); + } else { + // unnamed factory. + // no lazy loading + load(factory); + } + } + /** + * Import an instance of a factory into math.js + * @param {function(scope: object)} factory + * @param {Object} options See import for a description of the options + * @param {string} [name=factory.name] Optional custom name + * @private + */ + + + function _importFactory(factory, options) { + var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : factory.fn; + + if (Object(array["b" /* contains */])(name, '.')) { + throw new Error('Factory name should not contain a nested path. ' + 'Name: ' + JSON.stringify(name)); + } + + var namespace = isTransformFunctionFactory(factory) ? math.expression.transform : math; + var existingTransform = (name in math.expression.transform); + var existing = Object(utils_object["f" /* hasOwnProperty */])(namespace, name) ? namespace[name] : undefined; + + var resolver = function resolver() { + // collect all dependencies, handle finding both functions and classes and other special cases + var dependencies = {}; + factory.dependencies.map(utils_factory["c" /* stripOptionalNotation */]).forEach(function (dependency) { + if (Object(array["b" /* contains */])(dependency, '.')) { + throw new Error('Factory dependency should not contain a nested path. ' + 'Name: ' + JSON.stringify(dependency)); + } + + if (dependency === 'math') { + dependencies.math = math; + } else if (dependency === 'mathWithTransform') { + dependencies.mathWithTransform = math.expression.mathWithTransform; + } else if (dependency === 'classes') { + // special case for json reviver + dependencies.classes = math; + } else { + dependencies[dependency] = math[dependency]; + } + }); + var instance = /* #__PURE__ */factory(dependencies); + + if (instance && typeof instance.transform === 'function') { + throw new Error('Transforms cannot be attached to factory functions. ' + 'Please create a separate function for it with exports.path="expression.transform"'); + } + + if (existing === undefined || options.override) { + return instance; + } + + if (isTypedFunction(existing) && isTypedFunction(instance)) { + // merge the existing and new typed function + return typed(existing, instance); + } + + if (options.silent) { + // keep existing, ignore imported function + return existing; + } else { + throw new Error('Cannot import "' + name + '": already exists'); + } + }; // TODO: add unit test with non-lazy factory + + + if (!factory.meta || factory.meta.lazy !== false) { + Object(utils_object["h" /* lazy */])(namespace, name, resolver); // FIXME: remove the `if (existing &&` condition again. Can we make sure subset is loaded before subset.transform? (Name collision, and no dependencies between the two) + + if (existing && existingTransform) { + _deleteTransform(name); + } else { + if (isTransformFunctionFactory(factory) || factoryAllowedInExpressions(factory)) { + Object(utils_object["h" /* lazy */])(math.expression.mathWithTransform, name, function () { + return namespace[name]; + }); + } + } + } else { + namespace[name] = resolver(); // FIXME: remove the `if (existing &&` condition again. Can we make sure subset is loaded before subset.transform? (Name collision, and no dependencies between the two) + + if (existing && existingTransform) { + _deleteTransform(name); + } else { + if (isTransformFunctionFactory(factory) || factoryAllowedInExpressions(factory)) { + Object(utils_object["h" /* lazy */])(math.expression.mathWithTransform, name, function () { + return namespace[name]; + }); + } + } + } // TODO: improve factories, store a list with imports instead which can be re-played + + + importedFactories[name] = factory; + math.emit('import', name, resolver); + } + /** + * Check whether given object is a type which can be imported + * @param {Function | number | string | boolean | null | Unit | Complex} object + * @return {boolean} + * @private + */ + + + function isSupportedType(object) { + return typeof object === 'function' || typeof object === 'number' || typeof object === 'string' || typeof object === 'boolean' || object === null || Object(is["L" /* isUnit */])(object) || Object(is["j" /* isComplex */])(object) || Object(is["e" /* isBigNumber */])(object) || Object(is["o" /* isFraction */])(object) || Object(is["v" /* isMatrix */])(object) || Array.isArray(object); + } + /** + * Test whether a given thing is a typed-function + * @param {*} fn + * @return {boolean} Returns true when `fn` is a typed-function + */ + + + function isTypedFunction(fn) { + return typeof fn === 'function' && _typeof(fn.signatures) === 'object'; + } + + function hasTypedFunctionSignature(fn) { + return typeof fn === 'function' && typeof fn.signature === 'string'; + } + + function allowedInExpressions(name) { + return !Object(utils_object["f" /* hasOwnProperty */])(unsafe, name); + } + + function legacyFactoryAllowedInExpressions(factory) { + return factory.path === undefined && !Object(utils_object["f" /* hasOwnProperty */])(unsafe, factory.name); + } + + function factoryAllowedInExpressions(factory) { + return factory.fn.indexOf('.') === -1 && // FIXME: make checking on path redundant, check on meta data instead + !Object(utils_object["f" /* hasOwnProperty */])(unsafe, factory.fn) && (!factory.meta || !factory.meta.isClass); + } + + function isTransformFunctionFactory(factory) { + return factory !== undefined && factory.meta !== undefined && factory.meta.isTransformFunction === true || false; + } // namespaces and functions not available in the parser for safety reasons + + + var unsafe = { + expression: true, + type: true, + docs: true, + error: true, + json: true, + chain: true // chain method not supported. Note that there is a unit chain too. + + }; + return mathImport; +} +// CONCATENATED MODULE: ./src/core/config.js +var DEFAULT_CONFIG = { + // minimum relative difference between two compared values, + // used by all comparison functions + epsilon: 1e-12, + // type of default matrix output. Choose 'matrix' (default) or 'array' + matrix: 'Matrix', + // type of default number output. Choose 'number' (default) 'BigNumber', or 'Fraction + number: 'number', + // number of significant digits in BigNumbers + precision: 64, + // predictable output type of functions. When true, output type depends only + // on the input types. When false (default), output type can vary depending + // on input values. For example `math.sqrt(-4)` returns `complex('2i')` when + // predictable is false, and returns `NaN` when true. + predictable: false, + // random seed for seeded pseudo random number generation + // null = randomly seed + randomSeed: null +}; +// CONCATENATED MODULE: ./src/core/function/config.js + + +var MATRIX_OPTIONS = ['Matrix', 'Array']; // valid values for option matrix + +var NUMBER_OPTIONS = ['number', 'BigNumber', 'Fraction']; // valid values for option number + +function configFactory(config, emit) { + /** + * Set configuration options for math.js, and get current options. + * Will emit a 'config' event, with arguments (curr, prev, changes). + * + * This function is only available on a mathjs instance created using `create`. + * + * Syntax: + * + * math.config(config: Object): Object + * + * Examples: + * + * + * import { create, all } from 'mathjs' + * + * // create a mathjs instance + * const math = create(all) + * + * math.config().number // outputs 'number' + * math.evaluate('0.4') // outputs number 0.4 + * math.config({number: 'Fraction'}) + * math.evaluate('0.4') // outputs Fraction 2/5 + * + * @param {Object} [options] Available options: + * {number} epsilon + * Minimum relative difference between two + * compared values, used by all comparison functions. + * {string} matrix + * A string 'Matrix' (default) or 'Array'. + * {string} number + * A string 'number' (default), 'BigNumber', or 'Fraction' + * {number} precision + * The number of significant digits for BigNumbers. + * Not applicable for Numbers. + * {string} parenthesis + * How to display parentheses in LaTeX and string + * output. + * {string} randomSeed + * Random seed for seeded pseudo random number generator. + * Set to null to randomly seed. + * @return {Object} Returns the current configuration + */ + function _config(options) { + if (options) { + var prev = Object(utils_object["i" /* mapObject */])(config, utils_object["a" /* clone */]); // validate some of the options + + validateOption(options, 'matrix', MATRIX_OPTIONS); + validateOption(options, 'number', NUMBER_OPTIONS); // merge options + + Object(utils_object["b" /* deepExtend */])(config, options); + var curr = Object(utils_object["i" /* mapObject */])(config, utils_object["a" /* clone */]); + var changes = Object(utils_object["i" /* mapObject */])(options, utils_object["a" /* clone */]); // emit 'config' event + + emit('config', curr, prev, changes); + return curr; + } else { + return Object(utils_object["i" /* mapObject */])(config, utils_object["a" /* clone */]); + } + } // attach the valid options to the function so they can be extended + + + _config.MATRIX_OPTIONS = MATRIX_OPTIONS; + _config.NUMBER_OPTIONS = NUMBER_OPTIONS; // attach the config properties as readonly properties to the config function + + Object.keys(DEFAULT_CONFIG).forEach(function (key) { + Object.defineProperty(_config, key, { + get: function get() { + return config[key]; + }, + enumerable: true, + configurable: true + }); + }); + return _config; +} +/** + * Test whether an Array contains a specific item. + * @param {Array.} array + * @param {string} item + * @return {boolean} + */ + +function contains(array, item) { + return array.indexOf(item) !== -1; +} +/** + * Find a string in an array. Case insensitive search + * @param {Array.} array + * @param {string} item + * @return {number} Returns the index when found. Returns -1 when not found + */ + + +function findIndex(array, item) { + return array.map(function (i) { + return i.toLowerCase(); + }).indexOf(item.toLowerCase()); +} +/** + * Validate an option + * @param {Object} options Object with options + * @param {string} name Name of the option to validate + * @param {Array.} values Array with valid values for this option + */ + + +function validateOption(options, name, values) { + if (options[name] !== undefined && !contains(values, options[name])) { + var index = findIndex(values, options[name]); + + if (index !== -1) { + // right value, wrong casing + // TODO: lower case values are deprecated since v3, remove this warning some day. + console.warn('Warning: Wrong casing for configuration option "' + name + '", should be "' + values[index] + '" instead of "' + options[name] + '".'); + options[name] = values[index]; // change the option to the right casing + } else { + // unknown value + console.warn('Warning: Unknown value "' + options[name] + '" for configuration option "' + name + '". Available options: ' + values.map(JSON.stringify).join(', ') + '.'); + } + } +} +// EXTERNAL MODULE: ./src/error/DimensionError.js +var DimensionError = __webpack_require__(6); + +// EXTERNAL MODULE: ./src/error/IndexError.js +var IndexError = __webpack_require__(10); + +// CONCATENATED MODULE: ./src/core/create.js +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + + + + + + + + + + + + + + +/** + * Create a mathjs instance from given factory functions and optionally config + * + * Usage: + * + * const mathjs1 = create({ createAdd, createMultiply, ...}) + * const config = { number: 'BigNumber' } + * const mathjs2 = create(all, config) + * + * @param {Object} [factories] An object with factory functions + * The object can contain nested objects, + * all nested objects will be flattened. + * @param {Object} [config] Available options: + * {number} epsilon + * Minimum relative difference between two + * compared values, used by all comparison functions. + * {string} matrix + * A string 'Matrix' (default) or 'Array'. + * {string} number + * A string 'number' (default), 'BigNumber', or 'Fraction' + * {number} precision + * The number of significant digits for BigNumbers. + * Not applicable for Numbers. + * {boolean} predictable + * Predictable output type of functions. When true, + * output type depends only on the input types. When + * false (default), output type can vary depending + * on input values. For example `math.sqrt(-4)` + * returns `complex('2i')` when predictable is false, and + * returns `NaN` when true. + * {string} randomSeed + * Random seed for seeded pseudo random number generator. + * Set to null to randomly seed. + * @returns {Object} Returns a bare-bone math.js instance containing + * functions: + * - `import` to add new functions + * - `config` to change configuration + * - `on`, `off`, `once`, `emit` for events + */ + +function create(factories, config) { + var configInternal = _extends({}, DEFAULT_CONFIG, config); // simple test for ES5 support + + + if (typeof Object.create !== 'function') { + throw new Error('ES5 not supported by this JavaScript engine. ' + 'Please load the es5-shim and es5-sham library for compatibility.'); + } // create the mathjs instance + + + var math = mixin({ + // only here for backward compatibility for legacy factory functions + isNumber: is["y" /* isNumber */], + isComplex: is["j" /* isComplex */], + isBigNumber: is["e" /* isBigNumber */], + isFraction: is["o" /* isFraction */], + isUnit: is["L" /* isUnit */], + isString: is["I" /* isString */], + isArray: is["b" /* isArray */], + isMatrix: is["v" /* isMatrix */], + isCollection: is["i" /* isCollection */], + isDenseMatrix: is["n" /* isDenseMatrix */], + isSparseMatrix: is["H" /* isSparseMatrix */], + isRange: is["D" /* isRange */], + isIndex: is["t" /* isIndex */], + isBoolean: is["g" /* isBoolean */], + isResultSet: is["G" /* isResultSet */], + isHelp: is["s" /* isHelp */], + isFunction: is["p" /* isFunction */], + isDate: is["m" /* isDate */], + isRegExp: is["F" /* isRegExp */], + isObject: is["z" /* isObject */], + isNull: is["x" /* isNull */], + isUndefined: is["K" /* isUndefined */], + isAccessorNode: is["a" /* isAccessorNode */], + isArrayNode: is["c" /* isArrayNode */], + isAssignmentNode: is["d" /* isAssignmentNode */], + isBlockNode: is["f" /* isBlockNode */], + isConditionalNode: is["k" /* isConditionalNode */], + isConstantNode: is["l" /* isConstantNode */], + isFunctionAssignmentNode: is["q" /* isFunctionAssignmentNode */], + isFunctionNode: is["r" /* isFunctionNode */], + isIndexNode: is["u" /* isIndexNode */], + isNode: is["w" /* isNode */], + isObjectNode: is["A" /* isObjectNode */], + isOperatorNode: is["B" /* isOperatorNode */], + isParenthesisNode: is["C" /* isParenthesisNode */], + isRangeNode: is["E" /* isRangeNode */], + isSymbolNode: is["J" /* isSymbolNode */], + isChain: is["h" /* isChain */] + }); // load config function and apply provided config + + math.config = configFactory(configInternal, math.emit); + math.expression = { + transform: {}, + mathWithTransform: { + config: math.config + } + }; // cached factories and instances used by function load + + var legacyFactories = []; + var legacyInstances = []; + /** + * Load a function or data type from a factory. + * If the function or data type already exists, the existing instance is + * returned. + * @param {Function} factory + * @returns {*} + */ + + function load(factory) { + if (Object(utils_factory["b" /* isFactory */])(factory)) { + return factory(math); + } + + var firstProperty = factory[Object.keys(factory)[0]]; + + if (Object(utils_factory["b" /* isFactory */])(firstProperty)) { + return firstProperty(math); + } + + if (!Object(utils_object["g" /* isLegacyFactory */])(factory)) { + console.warn('Factory object with properties `type`, `name`, and `factory` expected', factory); + throw new Error('Factory object with properties `type`, `name`, and `factory` expected'); + } + + var index = legacyFactories.indexOf(factory); + var instance; + + if (index === -1) { + // doesn't yet exist + if (factory.math === true) { + // pass with math namespace + instance = factory.factory(math.type, configInternal, load, math.typed, math); + } else { + instance = factory.factory(math.type, configInternal, load, math.typed); + } // append to the cache + + + legacyFactories.push(factory); + legacyInstances.push(instance); + } else { + // already existing function, return the cached instance + instance = legacyInstances[index]; + } + + return instance; + } + + var importedFactories = {}; // load the import function + + function lazyTyped() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return math.typed.apply(math.typed, args); + } + + var internalImport = importFactory(lazyTyped, load, math, importedFactories); + math["import"] = internalImport; // listen for changes in config, import all functions again when changed + // TODO: move this listener into the import function? + + math.on('config', function () { + Object(utils_object["l" /* values */])(importedFactories).forEach(function (factory) { + if (factory && factory.meta && factory.meta.recreateOnConfigChange) { + // FIXME: only re-create when the current instance is the same as was initially created + // FIXME: delete the functions/constants before importing them again? + internalImport(factory, { + override: true + }); + } + }); + }); // the create function exposed on the mathjs instance is bound to + // the factory functions passed before + + math.create = create.bind(null, factories); // export factory function + + math.factory = utils_factory["a" /* factory */]; // import the factory functions like createAdd as an array instead of object, + // else they will get a different naming (`createAdd` instead of `add`). + + math["import"](Object(utils_object["l" /* values */])(Object(utils_object["c" /* deepFlatten */])(factories))); // TODO: deprecated since v6.0.0. Clean up some day + + var movedNames = ['type.isNumber', 'type.isComplex', 'type.isBigNumber', 'type.isFraction', 'type.isUnit', 'type.isString', 'type.isArray', 'type.isMatrix', 'type.isDenseMatrix', 'type.isSparseMatrix', 'type.isCollection', 'type.isRange', 'type.isIndex', 'type.isBoolean', 'type.isResultSet', 'type.isHelp', 'type.isFunction', 'type.isDate', 'type.isRegExp', 'type.isObject', 'type.isNull', 'type.isUndefined', 'type.isAccessorNode', 'type.isArrayNode', 'type.isAssignmentNode', 'type.isBlockNode', 'type.isConditionalNode', 'type.isConstantNode', 'type.isFunctionAssignmentNode', 'type.isFunctionNode', 'type.isIndexNode', 'type.isNode', 'type.isObjectNode', 'type.isOperatorNode', 'type.isParenthesisNode', 'type.isRangeNode', 'type.isSymbolNode', 'type.isChain', 'type.BigNumber', 'type.Chain', 'type.Complex', 'type.Fraction', 'type.Matrix', 'type.DenseMatrix', 'type.SparseMatrix', 'type.Spa', 'type.FibonacciHeap', 'type.ImmutableDenseMatrix', 'type.Index', 'type.Range', 'type.ResultSet', 'type.Unit', 'type.Help', 'type.Parser', 'expression.parse', 'expression.Parser', 'expression.node.AccessorNode', 'expression.node.ArrayNode', 'expression.node.AssignmentNode', 'expression.node.BlockNode', 'expression.node.ConditionalNode', 'expression.node.ConstantNode', 'expression.node.IndexNode', 'expression.node.FunctionAssignmentNode', 'expression.node.FunctionNode', 'expression.node.Node', 'expression.node.ObjectNode', 'expression.node.OperatorNode', 'expression.node.ParenthesisNode', 'expression.node.RangeNode', 'expression.node.RelationalNode', 'expression.node.SymbolNode', 'json.reviver', 'error.ArgumentsError', 'error.DimensionError', 'error.IndexError']; + movedNames.forEach(function (fullName) { + var parts = fullName.split('.'); + var path = Object(array["j" /* initial */])(parts); + var name = Object(array["l" /* last */])(parts); + var obj = Object(utils_object["k" /* traverse */])(math, path); + Object(utils_object["h" /* lazy */])(obj, name, function () { + Object(log["a" /* warnOnce */])("math.".concat(fullName, " is moved to math.").concat(name, " in v6.0.0. ") + 'Please use the new location instead.'); + return math[name]; + }); + }); + Object(utils_object["h" /* lazy */])(math.expression, 'docs', function () { + throw new Error('math.expression.docs has been moved. ' + 'Please import via "import { docs } from \'mathjs\'"'); + }); + math.ArgumentsError = ArgumentsError["a" /* ArgumentsError */]; + math.DimensionError = DimensionError["a" /* DimensionError */]; + math.IndexError = IndexError["a" /* IndexError */]; + return math; +} + +/***/ }) +/******/ ]); +}); + +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).jsyaml=e()}}(function(){return function o(a,s,c){function u(t,e){if(!s[t]){if(!a[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(l)return l(t,!0);var i=new Error("Cannot find module '"+t+"'");throw i.code="MODULE_NOT_FOUND",i}var r=s[t]={exports:{}};a[t][0].call(r.exports,function(e){return u(a[t][1][e]||e)},r,r.exports,o,a,s,c)}return s[t].exports}for(var l="function"==typeof require&&require,e=0;e=i.flowLevel;switch(H(r,n,i.indent,t,function(e){return function(e,t){var n,i;for(n=0,i=e.implicitTypes.length;n"+V(r,i.indent)+Z(L(function(t,n){var e,i,r=/(\n+)([^\n]*)/g,o=function(){var e=t.indexOf("\n");return e=-1!==e?e:t.length,r.lastIndex=e,z(t.slice(0,e),n)}(),a="\n"===t[0]||" "===t[0];for(;i=r.exec(t);){var s=i[1],c=i[2];e=" "===c[0],o+=s+(a||e||""===c?"":"\n")+z(c,n),a=e}return o}(r,t),e));case $:return'"'+function(e){for(var t,n,i,r="",o=0;ot&&o tag resolver accepts not "'+c+'" style');i=s.represent[c](t,c)}e.dump=i}return!0}return!1}function Q(e,t,n,i,r,o){e.tag=null,e.dump=n,J(e,n,!1)||J(e,n,!0);var a=p.call(e.dump);i&&(i=e.flowLevel<0||e.flowLevel>t);var s,c,u="[object Object]"===a||"[object Array]"===a;if(u&&(c=-1!==(s=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||c||2!==e.indent&&0 "+e.dump)}return!0}function X(e,t){var n,i,r=[],o=[];for(function e(t,n,i){var r,o,a;if(null!==t&&"object"==typeof t)if(-1!==(o=n.indexOf(t)))-1===i.indexOf(o)&&i.push(o);else if(n.push(t),Array.isArray(t))for(o=0,a=t.length;ot)&&0!==i)N(e,"bad indentation of a sequence entry");else if(e.lineIndentt?d=1:e.lineIndent===t?d=0:e.lineIndentt?d=1:e.lineIndent===t?d=0:e.lineIndentt)&&($(e,t,b,!0,r)&&(m?d=e.result:h=e.result),m||(U(e,l,p,f,d,h,o,a),f=d=h=null),Y(e,!0,-1),s=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==s)N(e,"bad indentation of a mapping entry");else if(e.lineIndentl&&(l=e.lineIndent),j(o))p++;else{if(e.lineIndent>10),56320+(c-65536&1023)),e.position++}else N(e,"unknown escape sequence");n=i=e.position}else j(s)?(L(e,n,i,!0),B(e,Y(e,!1,t)),n=i=e.position):e.position===e.lineStart&&R(e)?N(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}N(e,"unexpected end of the stream within a double quoted scalar")}(e,p)?m=!0:!function(e){var t,n,i;if(42!==(i=e.input.charCodeAt(e.position)))return!1;for(i=e.input.charCodeAt(++e.position),t=e.position;0!==i&&!I(i)&&!O(i);)i=e.input.charCodeAt(++e.position);return e.position===t&&N(e,"name of an alias node must contain at least one character"),n=e.input.slice(t,e.position),e.anchorMap.hasOwnProperty(n)||N(e,'unidentified alias "'+n+'"'),e.result=e.anchorMap[n],Y(e,!0,-1),!0}(e)?function(e,t,n){var i,r,o,a,s,c,u,l,p=e.kind,f=e.result;if(I(l=e.input.charCodeAt(e.position))||O(l)||35===l||38===l||42===l||33===l||124===l||62===l||39===l||34===l||37===l||64===l||96===l)return!1;if((63===l||45===l)&&(I(i=e.input.charCodeAt(e.position+1))||n&&O(i)))return!1;for(e.kind="scalar",e.result="",r=o=e.position,a=!1;0!==l;){if(58===l){if(I(i=e.input.charCodeAt(e.position+1))||n&&O(i))break}else if(35===l){if(I(e.input.charCodeAt(e.position-1)))break}else{if(e.position===e.lineStart&&R(e)||n&&O(l))break;if(j(l)){if(s=e.line,c=e.lineStart,u=e.lineIndent,Y(e,!1,-1),e.lineIndent>=t){a=!0,l=e.input.charCodeAt(e.position);continue}e.position=o,e.line=s,e.lineStart=c,e.lineIndent=u;break}}a&&(L(e,r,o,!1),B(e,e.line-s),r=o=e.position,a=!1),S(l)||(o=e.position+1),l=e.input.charCodeAt(++e.position)}return L(e,r,o,!1),!!e.result||(e.kind=p,e.result=f,!1)}(e,p,x===n)&&(m=!0,null===e.tag&&(e.tag="?")):(m=!0,null===e.tag&&null===e.anchor||N(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===d&&(m=s&&P(e,f))),null!==e.tag&&"!"!==e.tag)if("?"===e.tag){for(c=0,u=e.implicitTypes.length;c tag; it should be "'+l.kind+'", not "'+e.kind+'"'),l.resolve(e.result)?(e.result=l.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):N(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):N(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||m}function H(e){var t,n,i,r,o=e.position,a=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap={},e.anchorMap={};0!==(r=e.input.charCodeAt(e.position))&&(Y(e,!0,-1),r=e.input.charCodeAt(e.position),!(0t/2-1){n=" ... ",i+=5;break}for(r="",o=this.position;ot/2-1){r=" ... ",o-=5;break}return a=this.buffer.slice(i,o),s.repeat(" ",e)+n+a+r+"\n"+s.repeat(" ",e+this.position-i+n.length)+"^"},i.prototype.toString=function(e){var t,n="";return this.name&&(n+='in "'+this.name+'" '),n+="at line "+(this.line+1)+", column "+(this.column+1),e||(t=this.getSnippet())&&(n+=":\n"+t),n},t.exports=i},{"./common":2}],7:[function(e,t,n){"use strict";var i=e("./common"),r=e("./exception"),o=e("./type");function a(e,t,i){var r=[];return e.include.forEach(function(e){i=a(e,t,i)}),e[t].forEach(function(n){i.forEach(function(e,t){e.tag===n.tag&&e.kind===n.kind&&r.push(t)}),i.push(n)}),i.filter(function(e,t){return-1===r.indexOf(t)})}function s(e){this.include=e.include||[],this.implicit=e.implicit||[],this.explicit=e.explicit||[],this.implicit.forEach(function(e){if(e.loadKind&&"scalar"!==e.loadKind)throw new r("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=a(this,"implicit",[]),this.compiledExplicit=a(this,"explicit",[]),this.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{}};function i(e){n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e>16&255),s.push(a>>8&255),s.push(255&a)),a=a<<6|o.indexOf(i.charAt(t));return 0==(n=r%4*6)?(s.push(a>>16&255),s.push(a>>8&255),s.push(255&a)):18==n?(s.push(a>>10&255),s.push(a>>2&255)):12==n&&s.push(a>>4&255),c?c.from?c.from(s):new c(s):s},predicate:function(e){return c&&c.isBuffer(e)},represent:function(e){var t,n,i="",r=0,o=e.length,a=u;for(t=0;t>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]),r=(r<<8)+e[t];return 0==(n=o%3)?(i+=a[r>>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]):2==n?(i+=a[r>>10&63],i+=a[r>>4&63],i+=a[r<<2&63],i+=a[64]):1==n&&(i+=a[r>>2&63],i+=a[r<<4&63],i+=a[64],i+=a[64]),i}})},{"../type":13}],15:[function(e,t,n){"use strict";var i=e("../type");t.exports=new i("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t=e.length;return 4===t&&("true"===e||"True"===e||"TRUE"===e)||5===t&&("false"===e||"False"===e||"FALSE"===e)},construct:function(e){return"true"===e||"True"===e||"TRUE"===e},predicate:function(e){return"[object Boolean]"===Object.prototype.toString.call(e)},represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})},{"../type":13}],16:[function(e,t,n){"use strict";var i=e("../common"),r=e("../type"),o=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var a=/^[-+]?[0-9]+e/;t.exports=new r("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!o.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n,i,r;return n="-"===(t=e.replace(/_/g,"").toLowerCase())[0]?-1:1,r=[],0<="+-".indexOf(t[0])&&(t=t.slice(1)),".inf"===t?1==n?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:0<=t.indexOf(":")?(t.split(":").forEach(function(e){r.unshift(parseFloat(e,10))}),t=0,i=1,r.forEach(function(e){t+=e*i,i*=60}),n*t):n*parseFloat(t,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||i.isNegativeZero(e))},represent:function(e,t){var n;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(i.isNegativeZero(e))return"-0.0";return n=e.toString(10),a.test(n)?n.replace("e",".e"):n},defaultStyle:"lowercase"})},{"../common":2,"../type":13}],17:[function(e,t,n){"use strict";var i=e("../common"),r=e("../type");t.exports=new r("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,i,r,o=e.length,a=0,s=!1;if(!o)return!1;if("-"!==(t=e[a])&&"+"!==t||(t=e[++a]),"0"===t){if(a+1===o)return!0;if("b"===(t=e[++a])){for(a++;at?-1:t>0?1:+t}),THREE.log=function(){console.log.apply(console,arguments)},THREE.warn=function(){console.warn.apply(console,arguments)},THREE.error=function(){console.error.apply(console,arguments)},THREE.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2},THREE.CullFaceNone=0,THREE.CullFaceBack=1,THREE.CullFaceFront=2,THREE.CullFaceFrontBack=3,THREE.FrontFaceDirectionCW=0,THREE.FrontFaceDirectionCCW=1,THREE.BasicShadowMap=0,THREE.PCFShadowMap=1,THREE.PCFSoftShadowMap=2,THREE.FrontSide=0,THREE.BackSide=1,THREE.DoubleSide=2,THREE.NoShading=0,THREE.FlatShading=1,THREE.SmoothShading=2,THREE.NoColors=0,THREE.FaceColors=1,THREE.VertexColors=2,THREE.NoBlending=0,THREE.NormalBlending=1,THREE.AdditiveBlending=2,THREE.SubtractiveBlending=3,THREE.MultiplyBlending=4,THREE.CustomBlending=5,THREE.AddEquation=100,THREE.SubtractEquation=101,THREE.ReverseSubtractEquation=102,THREE.MinEquation=103,THREE.MaxEquation=104,THREE.ZeroFactor=200,THREE.OneFactor=201,THREE.SrcColorFactor=202,THREE.OneMinusSrcColorFactor=203,THREE.SrcAlphaFactor=204,THREE.OneMinusSrcAlphaFactor=205,THREE.DstAlphaFactor=206,THREE.OneMinusDstAlphaFactor=207,THREE.DstColorFactor=208,THREE.OneMinusDstColorFactor=209,THREE.SrcAlphaSaturateFactor=210,THREE.MultiplyOperation=0,THREE.MixOperation=1,THREE.AddOperation=2,THREE.UVMapping=300,THREE.CubeReflectionMapping=301,THREE.CubeRefractionMapping=302,THREE.EquirectangularReflectionMapping=303,THREE.EquirectangularRefractionMapping=304,THREE.SphericalReflectionMapping=305,THREE.RepeatWrapping=1e3,THREE.ClampToEdgeWrapping=1001,THREE.MirroredRepeatWrapping=1002,THREE.NearestFilter=1003,THREE.NearestMipMapNearestFilter=1004,THREE.NearestMipMapLinearFilter=1005,THREE.LinearFilter=1006,THREE.LinearMipMapNearestFilter=1007,THREE.LinearMipMapLinearFilter=1008,THREE.UnsignedByteType=1009,THREE.ByteType=1010,THREE.ShortType=1011,THREE.UnsignedShortType=1012,THREE.IntType=1013,THREE.UnsignedIntType=1014,THREE.FloatType=1015,THREE.HalfFloatType=1025,THREE.UnsignedShort4444Type=1016,THREE.UnsignedShort5551Type=1017,THREE.UnsignedShort565Type=1018,THREE.AlphaFormat=1019,THREE.RGBFormat=1020,THREE.RGBAFormat=1021,THREE.LuminanceFormat=1022,THREE.LuminanceAlphaFormat=1023,THREE.RGBEFormat=THREE.RGBAFormat,THREE.RGB_S3TC_DXT1_Format=2001,THREE.RGBA_S3TC_DXT1_Format=2002,THREE.RGBA_S3TC_DXT3_Format=2003,THREE.RGBA_S3TC_DXT5_Format=2004,THREE.RGB_PVRTC_4BPPV1_Format=2100,THREE.RGB_PVRTC_2BPPV1_Format=2101,THREE.RGBA_PVRTC_4BPPV1_Format=2102,THREE.RGBA_PVRTC_2BPPV1_Format=2103,THREE.Projector=function(){THREE.error("THREE.Projector has been moved to /examples/js/renderers/Projector.js."),this.projectVector=function(t,e){THREE.warn("THREE.Projector: .projectVector() is now vector.project()."),t.project(e)},this.unprojectVector=function(t,e){THREE.warn("THREE.Projector: .unprojectVector() is now vector.unproject()."),t.unproject(e)},this.pickingRay=function(t,e){THREE.error("THREE.Projector: .pickingRay() is now raycaster.setFromCamera().")}},THREE.CanvasRenderer=function(){THREE.error("THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js"),this.domElement=document.createElement("canvas"),this.clear=function(){},this.render=function(){},this.setClearColor=function(){},this.setSize=function(){}},THREE.Color=function(t){return 3===arguments.length?this.setRGB(arguments[0],arguments[1],arguments[2]):this.set(t)},THREE.Color.prototype={constructor:THREE.Color,r:1,g:1,b:1,set:function(t){return t instanceof THREE.Color?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t),this},setHex:function(t){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,this},setRGB:function(t,e,n){return this.r=t,this.g=e,this.b=n,this},setHSL:function(t,e,n){if(0===e)this.r=this.g=this.b=n;else{var r=function(t,e,n){return 0>n&&(n+=1),n>1&&(n-=1),1/6>n?t+6*(e-t)*n:.5>n?e:2/3>n?t+6*(e-t)*(2/3-n):t},i=.5>=n?n*(1+e):n+e-n*e,o=2*n-i;this.r=r(o,i,t+1/3),this.g=r(o,i,t),this.b=r(o,i,t-1/3)}return this},setStyle:function(t){if(/^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test(t)){var e=/^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec(t);return this.r=Math.min(255,parseInt(e[1],10))/255,this.g=Math.min(255,parseInt(e[2],10))/255,this.b=Math.min(255,parseInt(e[3],10))/255,this}if(/^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test(t)){var e=/^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec(t);return this.r=Math.min(100,parseInt(e[1],10))/100,this.g=Math.min(100,parseInt(e[2],10))/100,this.b=Math.min(100,parseInt(e[3],10))/100,this}if(/^\#([0-9a-f]{6})$/i.test(t)){var e=/^\#([0-9a-f]{6})$/i.exec(t);return this.setHex(parseInt(e[1],16)),this}if(/^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test(t)){var e=/^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(t);return this.setHex(parseInt(e[1]+e[1]+e[2]+e[2]+e[3]+e[3],16)),this}return/^(\w+)$/i.test(t)?(this.setHex(THREE.ColorKeywords[t]),this):void 0},copy:function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},copyGammaToLinear:function(t,e){return void 0===e&&(e=2),this.r=Math.pow(t.r,e),this.g=Math.pow(t.g,e),this.b=Math.pow(t.b,e),this},copyLinearToGamma:function(t,e){void 0===e&&(e=2);var n=e>0?1/e:1;return this.r=Math.pow(t.r,n),this.g=Math.pow(t.g,n),this.b=Math.pow(t.b,n),this},convertGammaToLinear:function(){var t=this.r,e=this.g,n=this.b;return this.r=t*t,this.g=e*e,this.b=n*n,this},convertLinearToGamma:function(){return this.r=Math.sqrt(this.r),this.g=Math.sqrt(this.g),this.b=Math.sqrt(this.b),this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(t){var e,n,r=t||{h:0,s:0,l:0},i=this.r,o=this.g,s=this.b,a=Math.max(i,o,s),u=Math.min(i,o,s),h=(u+a)/2;if(u===a)e=0,n=0;else{var l=a-u;switch(n=.5>=h?l/(a+u):l/(2-a-u),a){case i:e=(o-s)/l+(s>o?6:0);break;case o:e=(s-i)/l+2;break;case s:e=(i-o)/l+4}e/=6}return r.h=e,r.s=n,r.l=h,r},getStyle:function(){return"rgb("+(255*this.r|0)+","+(255*this.g|0)+","+(255*this.b|0)+")"},offsetHSL:function(t,e,n){var r=this.getHSL();return r.h+=t,r.s+=e,r.l+=n,this.setHSL(r.h,r.s,r.l),this},add:function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this},addColors:function(t,e){return this.r=t.r+e.r,this.g=t.g+e.g,this.b=t.b+e.b,this},addScalar:function(t){return this.r+=t,this.g+=t,this.b+=t,this},multiply:function(t){return this.r*=t.r,this.g*=t.g,this.b*=t.b,this},multiplyScalar:function(t){return this.r*=t,this.g*=t,this.b*=t,this},lerp:function(t,e){return this.r+=(t.r-this.r)*e,this.g+=(t.g-this.g)*e,this.b+=(t.b-this.b)*e,this},equals:function(t){return t.r===this.r&&t.g===this.g&&t.b===this.b},fromArray:function(t){return this.r=t[0],this.g=t[1],this.b=t[2],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.r,t[e+1]=this.g,t[e+2]=this.b,t},clone:function(){return(new THREE.Color).setRGB(this.r,this.g,this.b)}},THREE.ColorKeywords={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},THREE.Quaternion=function(t,e,n,r){this._x=t||0,this._y=e||0,this._z=n||0,this._w=void 0!==r?r:1},THREE.Quaternion.prototype={constructor:THREE.Quaternion,_x:0,_y:0,_z:0,_w:0,get x(){return this._x},set x(t){this._x=t,this.onChangeCallback()},get y(){return this._y},set y(t){this._y=t,this.onChangeCallback()},get z(){return this._z},set z(t){this._z=t,this.onChangeCallback()},get w(){return this._w},set w(t){this._w=t,this.onChangeCallback()},set:function(t,e,n,r){return this._x=t,this._y=e,this._z=n,this._w=r,this.onChangeCallback(),this},copy:function(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this.onChangeCallback(),this},setFromEuler:function(t,e){if(t instanceof THREE.Euler==!1)throw new Error("THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var n=Math.cos(t._x/2),r=Math.cos(t._y/2),i=Math.cos(t._z/2),o=Math.sin(t._x/2),s=Math.sin(t._y/2),a=Math.sin(t._z/2);return"XYZ"===t.order?(this._x=o*r*i+n*s*a,this._y=n*s*i-o*r*a,this._z=n*r*a+o*s*i,this._w=n*r*i-o*s*a):"YXZ"===t.order?(this._x=o*r*i+n*s*a,this._y=n*s*i-o*r*a,this._z=n*r*a-o*s*i,this._w=n*r*i+o*s*a):"ZXY"===t.order?(this._x=o*r*i-n*s*a,this._y=n*s*i+o*r*a,this._z=n*r*a+o*s*i,this._w=n*r*i-o*s*a):"ZYX"===t.order?(this._x=o*r*i-n*s*a,this._y=n*s*i+o*r*a,this._z=n*r*a-o*s*i,this._w=n*r*i+o*s*a):"YZX"===t.order?(this._x=o*r*i+n*s*a,this._y=n*s*i+o*r*a,this._z=n*r*a-o*s*i,this._w=n*r*i-o*s*a):"XZY"===t.order&&(this._x=o*r*i-n*s*a,this._y=n*s*i-o*r*a,this._z=n*r*a+o*s*i,this._w=n*r*i+o*s*a),e!==!1&&this.onChangeCallback(),this},setFromAxisAngle:function(t,e){var n=e/2,r=Math.sin(n);return this._x=t.x*r,this._y=t.y*r,this._z=t.z*r,this._w=Math.cos(n),this.onChangeCallback(),this},setFromRotationMatrix:function(t){var e,n=t.elements,r=n[0],i=n[4],o=n[8],s=n[1],a=n[5],u=n[9],h=n[2],l=n[6],c=n[10],p=r+a+c;return p>0?(e=.5/Math.sqrt(p+1),this._w=.25/e,this._x=(l-u)*e,this._y=(o-h)*e,this._z=(s-i)*e):r>a&&r>c?(e=2*Math.sqrt(1+r-a-c),this._w=(l-u)/e,this._x=.25*e,this._y=(i+s)/e,this._z=(o+h)/e):a>c?(e=2*Math.sqrt(1+a-r-c),this._w=(o-h)/e,this._x=(i+s)/e,this._y=.25*e,this._z=(u+l)/e):(e=2*Math.sqrt(1+c-r-a),this._w=(s-i)/e,this._x=(o+h)/e,this._y=(u+l)/e,this._z=.25*e),this.onChangeCallback(),this},setFromUnitVectors:function(){var t,e,n=1e-6;return function(r,i){return void 0===t&&(t=new THREE.Vector3),e=r.dot(i)+1,n>e?(e=0,Math.abs(r.x)>Math.abs(r.z)?t.set(-r.y,r.x,0):t.set(0,-r.z,r.y)):t.crossVectors(r,i),this._x=t.x,this._y=t.y,this._z=t.z,this._w=e,this.normalize(),this}}(),inverse:function(){return this.conjugate().normalize(),this},conjugate:function(){return this._x*=-1,this._y*=-1,this._z*=-1,this.onChangeCallback(),this},dot:function(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this.onChangeCallback(),this},multiply:function(t,e){return void 0!==e?(THREE.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)},multiplyQuaternions:function(t,e){var n=t._x,r=t._y,i=t._z,o=t._w,s=e._x,a=e._y,u=e._z,h=e._w;return this._x=n*h+o*s+r*u-i*a,this._y=r*h+o*a+i*s-n*u,this._z=i*h+o*u+n*a-r*s,this._w=o*h-n*s-r*a-i*u,this.onChangeCallback(),this},multiplyVector3:function(t){return THREE.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead."),t.applyQuaternion(this)},slerp:function(t,e){if(0===e)return this;if(1===e)return this.copy(t);var n=this._x,r=this._y,i=this._z,o=this._w,s=o*t._w+n*t._x+r*t._y+i*t._z;if(0>s?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,s=-s):this.copy(t),s>=1)return this._w=o,this._x=n,this._y=r,this._z=i,this;var a=Math.acos(s),u=Math.sqrt(1-s*s);if(Math.abs(u)<.001)return this._w=.5*(o+this._w),this._x=.5*(n+this._x),this._y=.5*(r+this._y),this._z=.5*(i+this._z),this;var h=Math.sin((1-e)*a)/u,l=Math.sin(e*a)/u;return this._w=o*h+this._w*l,this._x=n*h+this._x*l,this._y=r*h+this._y*l,this._z=i*h+this._z*l,this.onChangeCallback(),this},equals:function(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w},fromArray:function(t,e){return void 0===e&&(e=0),this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this.onChangeCallback(),this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t},onChange:function(t){return this.onChangeCallback=t,this},onChangeCallback:function(){},clone:function(){return new THREE.Quaternion(this._x,this._y,this._z,this._w)}},THREE.Quaternion.slerp=function(t,e,n,r){return n.copy(t).slerp(e,r)},THREE.Vector2=function(t,e){this.x=t||0,this.y=e||0},THREE.Vector2.prototype={constructor:THREE.Vector2,set:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}},copy:function(t){return this.x=t.x,this.y=t.y,this},add:function(t,e){return void 0!==e?(THREE.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this)},addScalar:function(t){return this.x+=t,this.y+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this},sub:function(t,e){return void 0!==e?(THREE.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this)},subScalar:function(t){return this.x-=t,this.y-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this},multiplyScalar:function(t){return this.x*=t,this.y*=t,this},divide:function(t){return this.x/=t.x,this.y/=t.y,this},divideScalar:function(t){if(0!==t){var e=1/t;this.x*=e,this.y*=e}else this.x=0,this.y=0;return this},min:function(t){return this.x>t.x&&(this.x=t.x),this.y>t.y&&(this.y=t.y),this},max:function(t){return this.xe.x&&(this.x=e.x),this.ye.y&&(this.y=e.y),this},clampScalar:function(){var t,e;return function(n,r){return void 0===t&&(t=new THREE.Vector2,e=new THREE.Vector2),t.set(n,n),e.set(r,r),this.clamp(t,e)}}(),floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this},negate:function(){return this.x=-this.x,this.y=-this.y,this},dot:function(t){return this.x*t.x+this.y*t.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},normalize:function(){return this.divideScalar(this.length())},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,n=this.y-t.y;return e*e+n*n},setLength:function(t){var e=this.length();return 0!==e&&t!==e&&this.multiplyScalar(t/e),this},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this},lerpVectors:function(t,e,n){return this.subVectors(e,t).multiplyScalar(n).add(t),this},equals:function(t){return t.x===this.x&&t.y===this.y},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t},fromAttribute:function(t,e,n){return void 0===n&&(n=0),e=e*t.itemSize+n,this.x=t.array[e],this.y=t.array[e+1],this},clone:function(){return new THREE.Vector2(this.x,this.y)}},THREE.Vector3=function(t,e,n){this.x=t||0,this.y=e||0,this.z=n||0},THREE.Vector3.prototype={constructor:THREE.Vector3,set:function(t,e,n){return this.x=t,this.y=e,this.z=n,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setZ:function(t){return this.z=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},add:function(t,e){return void 0!==e?(THREE.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this)},addScalar:function(t){return this.x+=t,this.y+=t,this.z+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this},sub:function(t,e){return void 0!==e?(THREE.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this)},subScalar:function(t){return this.x-=t,this.y-=t,this.z-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this},multiply:function(t,e){return void 0!==e?(THREE.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(this.x*=t.x,this.y*=t.y,this.z*=t.z,this)},multiplyScalar:function(t){return this.x*=t,this.y*=t,this.z*=t,this},multiplyVectors:function(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this},applyEuler:function(){var t;return function(e){return e instanceof THREE.Euler==!1&&THREE.error("THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order."),void 0===t&&(t=new THREE.Quaternion),this.applyQuaternion(t.setFromEuler(e)),this}}(),applyAxisAngle:function(){var t;return function(e,n){return void 0===t&&(t=new THREE.Quaternion),this.applyQuaternion(t.setFromAxisAngle(e,n)),this}}(),applyMatrix3:function(t){var e=this.x,n=this.y,r=this.z,i=t.elements;return this.x=i[0]*e+i[3]*n+i[6]*r,this.y=i[1]*e+i[4]*n+i[7]*r,this.z=i[2]*e+i[5]*n+i[8]*r,this},applyMatrix4:function(t){var e=this.x,n=this.y,r=this.z,i=t.elements;return this.x=i[0]*e+i[4]*n+i[8]*r+i[12],this.y=i[1]*e+i[5]*n+i[9]*r+i[13],this.z=i[2]*e+i[6]*n+i[10]*r+i[14],this},applyProjection:function(t){var e=this.x,n=this.y,r=this.z,i=t.elements,o=1/(i[3]*e+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*e+i[4]*n+i[8]*r+i[12])*o,this.y=(i[1]*e+i[5]*n+i[9]*r+i[13])*o,this.z=(i[2]*e+i[6]*n+i[10]*r+i[14])*o,this},applyQuaternion:function(t){var e=this.x,n=this.y,r=this.z,i=t.x,o=t.y,s=t.z,a=t.w,u=a*e+o*r-s*n,h=a*n+s*e-i*r,l=a*r+i*n-o*e,c=-i*e-o*n-s*r;return this.x=u*a+c*-i+h*-s-l*-o,this.y=h*a+c*-o+l*-i-u*-s,this.z=l*a+c*-s+u*-o-h*-i,this},project:function(){var t;return function(e){return void 0===t&&(t=new THREE.Matrix4),t.multiplyMatrices(e.projectionMatrix,t.getInverse(e.matrixWorld)),this.applyProjection(t)}}(),unproject:function(){var t;return function(e){return void 0===t&&(t=new THREE.Matrix4),t.multiplyMatrices(e.matrixWorld,t.getInverse(e.projectionMatrix)),this.applyProjection(t)}}(),transformDirection:function(t){var e=this.x,n=this.y,r=this.z,i=t.elements;return this.x=i[0]*e+i[4]*n+i[8]*r,this.y=i[1]*e+i[5]*n+i[9]*r,this.z=i[2]*e+i[6]*n+i[10]*r,this.normalize(),this},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this},divideScalar:function(t){if(0!==t){var e=1/t;this.x*=e,this.y*=e,this.z*=e}else this.x=0,this.y=0,this.z=0;return this},min:function(t){return this.x>t.x&&(this.x=t.x),this.y>t.y&&(this.y=t.y),this.z>t.z&&(this.z=t.z),this},max:function(t){return this.xe.x&&(this.x=e.x),this.ye.y&&(this.y=e.y),this.ze.z&&(this.z=e.z),this},clampScalar:function(){var t,e;return function(n,r){return void 0===t&&(t=new THREE.Vector3,e=new THREE.Vector3),t.set(n,n,n),e.set(r,r,r),this.clamp(t,e)}}(),floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(t){var e=this.length();return 0!==e&&t!==e&&this.multiplyScalar(t/e),this},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this},lerpVectors:function(t,e,n){return this.subVectors(e,t).multiplyScalar(n).add(t),this},cross:function(t,e){if(void 0!==e)return THREE.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e);var n=this.x,r=this.y,i=this.z;return this.x=r*t.z-i*t.y,this.y=i*t.x-n*t.z,this.z=n*t.y-r*t.x,this},crossVectors:function(t,e){var n=t.x,r=t.y,i=t.z,o=e.x,s=e.y,a=e.z;return this.x=r*a-i*s,this.y=i*o-n*a,this.z=n*s-r*o,this},projectOnVector:function(){var t,e;return function(n){return void 0===t&&(t=new THREE.Vector3),t.copy(n).normalize(),e=this.dot(t),this.copy(t).multiplyScalar(e)}}(),projectOnPlane:function(){var t;return function(e){return void 0===t&&(t=new THREE.Vector3),t.copy(this).projectOnVector(e),this.sub(t)}}(),reflect:function(){var t;return function(e){return void 0===t&&(t=new THREE.Vector3),this.sub(t.copy(e).multiplyScalar(2*this.dot(e)))}}(),angleTo:function(t){var e=this.dot(t)/(this.length()*t.length());return Math.acos(THREE.Math.clamp(e,-1,1))},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,n=this.y-t.y,r=this.z-t.z;return e*e+n*n+r*r},setEulerFromRotationMatrix:function(t,e){THREE.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.")},setEulerFromQuaternion:function(t,e){THREE.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.")},getPositionFromMatrix:function(t){return THREE.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition()."),this.setFromMatrixPosition(t)},getScaleFromMatrix:function(t){return THREE.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale()."),this.setFromMatrixScale(t)},getColumnFromMatrix:function(t,e){return THREE.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn()."),this.setFromMatrixColumn(t,e)},setFromMatrixPosition:function(t){return this.x=t.elements[12],this.y=t.elements[13],this.z=t.elements[14],this},setFromMatrixScale:function(t){var e=this.set(t.elements[0],t.elements[1],t.elements[2]).length(),n=this.set(t.elements[4],t.elements[5],t.elements[6]).length(),r=this.set(t.elements[8],t.elements[9],t.elements[10]).length();return this.x=e,this.y=n,this.z=r,this},setFromMatrixColumn:function(t,e){var n=4*t,r=e.elements;return this.x=r[n],this.y=r[n+1],this.z=r[n+2],this},equals:function(t){return t.x===this.x&&t.y===this.y&&t.z===this.z},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this.z=t[e+2],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t},fromAttribute:function(t,e,n){return void 0===n&&(n=0),e=e*t.itemSize+n,this.x=t.array[e],this.y=t.array[e+1],this.z=t.array[e+2],this},clone:function(){return new THREE.Vector3(this.x,this.y,this.z)}},THREE.Vector4=function(t,e,n,r){this.x=t||0,this.y=e||0,this.z=n||0,this.w=void 0!==r?r:1},THREE.Vector4.prototype={constructor:THREE.Vector4,set:function(t,e,n,r){return this.x=t,this.y=e,this.z=n,this.w=r,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setZ:function(t){return this.z=t,this},setW:function(t){return this.w=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=void 0!==t.w?t.w:1,this},add:function(t,e){return void 0!==e?(THREE.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this)},addScalar:function(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this},sub:function(t,e){return void 0!==e?(THREE.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this)},subScalar:function(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this},multiplyScalar:function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},applyMatrix4:function(t){var e=this.x,n=this.y,r=this.z,i=this.w,o=t.elements;return this.x=o[0]*e+o[4]*n+o[8]*r+o[12]*i,this.y=o[1]*e+o[5]*n+o[9]*r+o[13]*i,this.z=o[2]*e+o[6]*n+o[10]*r+o[14]*i,this.w=o[3]*e+o[7]*n+o[11]*r+o[15]*i,this},divideScalar:function(t){if(0!==t){var e=1/t;this.x*=e,this.y*=e,this.z*=e,this.w*=e}else this.x=0,this.y=0,this.z=0,this.w=1;return this},setAxisAngleFromQuaternion:function(t){this.w=2*Math.acos(t.w);var e=Math.sqrt(1-t.w*t.w);return 1e-4>e?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this},setAxisAngleFromRotationMatrix:function(t){var e,n,r,i,o=.01,s=.1,a=t.elements,u=a[0],h=a[4],l=a[8],c=a[1],p=a[5],f=a[9],d=a[2],m=a[6],v=a[10];if(Math.abs(h-c)E&&g>y?o>g?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(g),r=_/n,i=b/n):E>y?o>E?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(E),n=_/r,i=T/r):o>y?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(y),n=b/i,r=T/i),this.set(n,r,i,e),this}var x=Math.sqrt((m-f)*(m-f)+(l-d)*(l-d)+(c-h)*(c-h));return Math.abs(x)<.001&&(x=1),this.x=(m-f)/x,this.y=(l-d)/x,this.z=(c-h)/x,this.w=Math.acos((u+p+v-1)/2),this},min:function(t){return this.x>t.x&&(this.x=t.x),this.y>t.y&&(this.y=t.y),this.z>t.z&&(this.z=t.z),this.w>t.w&&(this.w=t.w),this},max:function(t){return this.xe.x&&(this.x=e.x),this.ye.y&&(this.y=e.y),this.ze.z&&(this.z=e.z),this.we.w&&(this.w=e.w),this},clampScalar:function(){var t,e;return function(n,r){return void 0===t&&(t=new THREE.Vector4,e=new THREE.Vector4),t.set(n,n,n,n),e.set(r,r,r,r),this.clamp(t,e)}}(),floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this.w=this.w<0?Math.ceil(this.w):Math.floor(this.w),this},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length())},setLength:function(t){var e=this.length();return 0!==e&&t!==e&&this.multiplyScalar(t/e),this},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this},lerpVectors:function(t,e,n){return this.subVectors(e,t).multiplyScalar(n).add(t),this},equals:function(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t},fromAttribute:function(t,e,n){return void 0===n&&(n=0),e=e*t.itemSize+n,this.x=t.array[e],this.y=t.array[e+1],this.z=t.array[e+2],this.w=t.array[e+3],this; +},clone:function(){return new THREE.Vector4(this.x,this.y,this.z,this.w)}},THREE.Euler=function(t,e,n,r){this._x=t||0,this._y=e||0,this._z=n||0,this._order=r||THREE.Euler.DefaultOrder},THREE.Euler.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"],THREE.Euler.DefaultOrder="XYZ",THREE.Euler.prototype={constructor:THREE.Euler,_x:0,_y:0,_z:0,_order:THREE.Euler.DefaultOrder,get x(){return this._x},set x(t){this._x=t,this.onChangeCallback()},get y(){return this._y},set y(t){this._y=t,this.onChangeCallback()},get z(){return this._z},set z(t){this._z=t,this.onChangeCallback()},get order(){return this._order},set order(t){this._order=t,this.onChangeCallback()},set:function(t,e,n,r){return this._x=t,this._y=e,this._z=n,this._order=r||this._order,this.onChangeCallback(),this},copy:function(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this.onChangeCallback(),this},setFromRotationMatrix:function(t,e,n){var r=THREE.Math.clamp,i=t.elements,o=i[0],s=i[4],a=i[8],u=i[1],h=i[5],l=i[9],c=i[2],p=i[6],f=i[10];return e=e||this._order,"XYZ"===e?(this._y=Math.asin(r(a,-1,1)),Math.abs(a)<.99999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-s,o)):(this._x=Math.atan2(p,h),this._z=0)):"YXZ"===e?(this._x=Math.asin(-r(l,-1,1)),Math.abs(l)<.99999?(this._y=Math.atan2(a,f),this._z=Math.atan2(u,h)):(this._y=Math.atan2(-c,o),this._z=0)):"ZXY"===e?(this._x=Math.asin(r(p,-1,1)),Math.abs(p)<.99999?(this._y=Math.atan2(-c,f),this._z=Math.atan2(-s,h)):(this._y=0,this._z=Math.atan2(u,o))):"ZYX"===e?(this._y=Math.asin(-r(c,-1,1)),Math.abs(c)<.99999?(this._x=Math.atan2(p,f),this._z=Math.atan2(u,o)):(this._x=0,this._z=Math.atan2(-s,h))):"YZX"===e?(this._z=Math.asin(r(u,-1,1)),Math.abs(u)<.99999?(this._x=Math.atan2(-l,h),this._y=Math.atan2(-c,o)):(this._x=0,this._y=Math.atan2(a,f))):"XZY"===e?(this._z=Math.asin(-r(s,-1,1)),Math.abs(s)<.99999?(this._x=Math.atan2(p,h),this._y=Math.atan2(a,o)):(this._x=Math.atan2(-l,f),this._y=0)):THREE.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+e),this._order=e,n!==!1&&this.onChangeCallback(),this},setFromQuaternion:function(){var t;return function(e,n,r){return void 0===t&&(t=new THREE.Matrix4),t.makeRotationFromQuaternion(e),this.setFromRotationMatrix(t,n,r),this}}(),setFromVector3:function(t,e){return this.set(t.x,t.y,t.z,e||this._order)},reorder:function(){var t=new THREE.Quaternion;return function(e){t.setFromEuler(this),this.setFromQuaternion(t,e)}}(),equals:function(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order},fromArray:function(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this.onChangeCallback(),this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t},toVector3:function(t){return t?t.set(this._x,this._y,this._z):new THREE.Vector3(this._x,this._y,this._z)},onChange:function(t){return this.onChangeCallback=t,this},onChangeCallback:function(){},clone:function(){return new THREE.Euler(this._x,this._y,this._z,this._order)}},THREE.Line3=function(t,e){this.start=void 0!==t?t:new THREE.Vector3,this.end=void 0!==e?e:new THREE.Vector3},THREE.Line3.prototype={constructor:THREE.Line3,set:function(t,e){return this.start.copy(t),this.end.copy(e),this},copy:function(t){return this.start.copy(t.start),this.end.copy(t.end),this},center:function(t){var e=t||new THREE.Vector3;return e.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(t){var e=t||new THREE.Vector3;return e.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(t,e){var n=e||new THREE.Vector3;return this.delta(n).multiplyScalar(t).add(this.start)},closestPointToPointParameter:function(){var t=new THREE.Vector3,e=new THREE.Vector3;return function(n,r){t.subVectors(n,this.start),e.subVectors(this.end,this.start);var i=e.dot(e),o=e.dot(t),s=o/i;return r&&(s=THREE.Math.clamp(s,0,1)),s}}(),closestPointToPoint:function(t,e,n){var r=this.closestPointToPointParameter(t,e),i=n||new THREE.Vector3;return this.delta(i).multiplyScalar(r).add(this.start)},applyMatrix4:function(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this},equals:function(t){return t.start.equals(this.start)&&t.end.equals(this.end)},clone:function(){return(new THREE.Line3).copy(this)}},THREE.Box2=function(t,e){this.min=void 0!==t?t:new THREE.Vector2(1/0,1/0),this.max=void 0!==e?e:new THREE.Vector2(-(1/0),-(1/0))},THREE.Box2.prototype={constructor:THREE.Box2,set:function(t,e){return this.min.copy(t),this.max.copy(e),this},setFromPoints:function(t){this.makeEmpty();for(var e=0,n=t.length;n>e;e++)this.expandByPoint(t[e]);return this},setFromCenterAndSize:function(){var t=new THREE.Vector2;return function(e,n){var r=t.copy(n).multiplyScalar(.5);return this.min.copy(e).sub(r),this.max.copy(e).add(r),this}}(),copy:function(t){return this.min.copy(t.min),this.max.copy(t.max),this},makeEmpty:function(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-(1/0),this},empty:function(){return this.max.xthis.max.x||t.ythis.max.y?!1:!0},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y?!0:!1},getParameter:function(t,e){var n=e||new THREE.Vector2;return n.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))},isIntersectionBox:function(t){return t.max.xthis.max.x||t.max.ythis.max.y?!1:!0},clampPoint:function(t,e){var n=e||new THREE.Vector2;return n.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new THREE.Vector2;return function(e){var n=t.copy(e).clamp(this.min,this.max);return n.sub(e).length()}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)},clone:function(){return(new THREE.Box2).copy(this)}},THREE.Box3=function(t,e){this.min=void 0!==t?t:new THREE.Vector3(1/0,1/0,1/0),this.max=void 0!==e?e:new THREE.Vector3(-(1/0),-(1/0),-(1/0))},THREE.Box3.prototype={constructor:THREE.Box3,set:function(t,e){return this.min.copy(t),this.max.copy(e),this},setFromPoints:function(t){this.makeEmpty();for(var e=0,n=t.length;n>e;e++)this.expandByPoint(t[e]);return this},setFromCenterAndSize:function(){var t=new THREE.Vector3;return function(e,n){var r=t.copy(n).multiplyScalar(.5);return this.min.copy(e).sub(r),this.max.copy(e).add(r),this}}(),setFromObject:function(){var t=new THREE.Vector3;return function(e){var n=this;return e.updateMatrixWorld(!0),this.makeEmpty(),e.traverse(function(e){var r=e.geometry;if(void 0!==r)if(r instanceof THREE.Geometry)for(var i=r.vertices,o=0,s=i.length;s>o;o++)t.copy(i[o]),t.applyMatrix4(e.matrixWorld),n.expandByPoint(t);else if(r instanceof THREE.BufferGeometry&&void 0!==r.attributes.position)for(var a=r.attributes.position.array,o=0,s=a.length;s>o;o+=3)t.set(a[o],a[o+1],a[o+2]),t.applyMatrix4(e.matrixWorld),n.expandByPoint(t)}),this}}(),copy:function(t){return this.min.copy(t.min),this.max.copy(t.max),this},makeEmpty:function(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-(1/0),this},empty:function(){return this.max.xthis.max.x||t.ythis.max.y||t.zthis.max.z?!1:!0},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z?!0:!1},getParameter:function(t,e){var n=e||new THREE.Vector3;return n.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))},isIntersectionBox:function(t){return t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z?!1:!0},clampPoint:function(t,e){var n=e||new THREE.Vector3;return n.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new THREE.Vector3;return function(e){var n=t.copy(e).clamp(this.min,this.max);return n.sub(e).length()}}(),getBoundingSphere:function(){var t=new THREE.Vector3;return function(e){var n=e||new THREE.Sphere;return n.center=this.center(),n.radius=.5*this.size(t).length(),n}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},applyMatrix4:function(){var t=[new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3];return function(e){return t[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),t[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),t[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),t[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),t[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),t[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),t[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),t[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.makeEmpty(),this.setFromPoints(t),this}}(),translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)},clone:function(){return(new THREE.Box3).copy(this)}},THREE.Matrix3=function(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1]),arguments.length>0&&THREE.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")},THREE.Matrix3.prototype={constructor:THREE.Matrix3,set:function(t,e,n,r,i,o,s,a,u){var h=this.elements;return h[0]=t,h[3]=e,h[6]=n,h[1]=r,h[4]=i,h[7]=o,h[2]=s,h[5]=a,h[8]=u,this},identity:function(){return this.set(1,0,0,0,1,0,0,0,1),this},copy:function(t){var e=t.elements;return this.set(e[0],e[3],e[6],e[1],e[4],e[7],e[2],e[5],e[8]),this},multiplyVector3:function(t){return THREE.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead."),t.applyMatrix3(this)},multiplyVector3Array:function(t){return THREE.warn("THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead."),this.applyToVector3Array(t)},applyToVector3Array:function(){var t=new THREE.Vector3;return function(e,n,r){void 0===n&&(n=0),void 0===r&&(r=e.length);for(var i=0,o=n;r>i;i+=3,o+=3)t.x=e[o],t.y=e[o+1],t.z=e[o+2],t.applyMatrix3(this),e[o]=t.x,e[o+1]=t.y,e[o+2]=t.z;return e}}(),multiplyScalar:function(t){var e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this},determinant:function(){var t=this.elements,e=t[0],n=t[1],r=t[2],i=t[3],o=t[4],s=t[5],a=t[6],u=t[7],h=t[8];return e*o*h-e*s*u-n*i*h+n*s*a+r*i*u-r*o*a},getInverse:function(t,e){var n=t.elements,r=this.elements;r[0]=n[10]*n[5]-n[6]*n[9],r[1]=-n[10]*n[1]+n[2]*n[9],r[2]=n[6]*n[1]-n[2]*n[5],r[3]=-n[10]*n[4]+n[6]*n[8],r[4]=n[10]*n[0]-n[2]*n[8],r[5]=-n[6]*n[0]+n[2]*n[4],r[6]=n[9]*n[4]-n[5]*n[8],r[7]=-n[9]*n[0]+n[1]*n[8],r[8]=n[5]*n[0]-n[1]*n[4];var i=n[0]*r[0]+n[1]*r[3]+n[2]*r[6];if(0===i){var o="Matrix3.getInverse(): can't invert matrix, determinant is 0";if(e)throw new Error(o);return THREE.warn(o),this.identity(),this}return this.multiplyScalar(1/i),this},transpose:function(){var t,e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this},flattenToArrayOffset:function(t,e){var n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t},getNormalMatrix:function(t){return this.getInverse(t).transpose(),this},transposeIntoArray:function(t){var e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this},fromArray:function(t){return this.elements.set(t),this},toArray:function(){var t=this.elements;return[t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8]]},clone:function(){return(new THREE.Matrix3).fromArray(this.elements)}},THREE.Matrix4=function(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),arguments.length>0&&THREE.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")},THREE.Matrix4.prototype={constructor:THREE.Matrix4,set:function(t,e,n,r,i,o,s,a,u,h,l,c,p,f,d,m){var v=this.elements;return v[0]=t,v[4]=e,v[8]=n,v[12]=r,v[1]=i,v[5]=o,v[9]=s,v[13]=a,v[2]=u,v[6]=h,v[10]=l,v[14]=c,v[3]=p,v[7]=f,v[11]=d,v[15]=m,this},identity:function(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this},copy:function(t){return this.elements.set(t.elements),this},extractPosition:function(t){return THREE.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(t)},copyPosition:function(t){var e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this},extractBasis:function(t,e,n){var r=this.elements;return t.set(r[0],r[1],r[2]),e.set(r[4],r[5],r[6]),n.set(r[8],r[9],r[10]),this},makeBasis:function(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this},extractRotation:function(){var t=new THREE.Vector3;return function(e){var n=this.elements,r=e.elements,i=1/t.set(r[0],r[1],r[2]).length(),o=1/t.set(r[4],r[5],r[6]).length(),s=1/t.set(r[8],r[9],r[10]).length();return n[0]=r[0]*i,n[1]=r[1]*i,n[2]=r[2]*i,n[4]=r[4]*o,n[5]=r[5]*o,n[6]=r[6]*o,n[8]=r[8]*s,n[9]=r[9]*s,n[10]=r[10]*s,this}}(),makeRotationFromEuler:function(t){t instanceof THREE.Euler==!1&&THREE.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var e=this.elements,n=t.x,r=t.y,i=t.z,o=Math.cos(n),s=Math.sin(n),a=Math.cos(r),u=Math.sin(r),h=Math.cos(i),l=Math.sin(i);if("XYZ"===t.order){var c=o*h,p=o*l,f=s*h,d=s*l;e[0]=a*h,e[4]=-a*l,e[8]=u,e[1]=p+f*u,e[5]=c-d*u,e[9]=-s*a,e[2]=d-c*u,e[6]=f+p*u,e[10]=o*a}else if("YXZ"===t.order){var m=a*h,v=a*l,g=u*h,E=u*l;e[0]=m+E*s,e[4]=g*s-v,e[8]=o*u,e[1]=o*l,e[5]=o*h,e[9]=-s,e[2]=v*s-g,e[6]=E+m*s,e[10]=o*a}else if("ZXY"===t.order){var m=a*h,v=a*l,g=u*h,E=u*l;e[0]=m-E*s,e[4]=-o*l,e[8]=g+v*s,e[1]=v+g*s,e[5]=o*h,e[9]=E-m*s,e[2]=-o*u,e[6]=s,e[10]=o*a}else if("ZYX"===t.order){var c=o*h,p=o*l,f=s*h,d=s*l;e[0]=a*h,e[4]=f*u-p,e[8]=c*u+d,e[1]=a*l,e[5]=d*u+c,e[9]=p*u-f,e[2]=-u,e[6]=s*a,e[10]=o*a}else if("YZX"===t.order){var y=o*a,_=o*u,b=s*a,T=s*u;e[0]=a*h,e[4]=T-y*l,e[8]=b*l+_,e[1]=l,e[5]=o*h,e[9]=-s*h,e[2]=-u*h,e[6]=_*l+b,e[10]=y-T*l}else if("XZY"===t.order){var y=o*a,_=o*u,b=s*a,T=s*u;e[0]=a*h,e[4]=-l,e[8]=u*h,e[1]=y*l+T,e[5]=o*h,e[9]=_*l-b,e[2]=b*l-_,e[6]=s*h,e[10]=T*l+y}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},setRotationFromQuaternion:function(t){return THREE.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion()."),this.makeRotationFromQuaternion(t)},makeRotationFromQuaternion:function(t){var e=this.elements,n=t.x,r=t.y,i=t.z,o=t.w,s=n+n,a=r+r,u=i+i,h=n*s,l=n*a,c=n*u,p=r*a,f=r*u,d=i*u,m=o*s,v=o*a,g=o*u;return e[0]=1-(p+d),e[4]=l-g,e[8]=c+v,e[1]=l+g,e[5]=1-(h+d),e[9]=f-m,e[2]=c-v,e[6]=f+m,e[10]=1-(h+p),e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},lookAt:function(){var t=new THREE.Vector3,e=new THREE.Vector3,n=new THREE.Vector3;return function(r,i,o){var s=this.elements;return n.subVectors(r,i).normalize(),0===n.length()&&(n.z=1),t.crossVectors(o,n).normalize(),0===t.length()&&(n.x+=1e-4,t.crossVectors(o,n).normalize()),e.crossVectors(n,t),s[0]=t.x,s[4]=e.x,s[8]=n.x,s[1]=t.y,s[5]=e.y,s[9]=n.y,s[2]=t.z,s[6]=e.z,s[10]=n.z,this}}(),multiply:function(t,e){return void 0!==e?(THREE.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)},multiplyMatrices:function(t,e){var n=t.elements,r=e.elements,i=this.elements,o=n[0],s=n[4],a=n[8],u=n[12],h=n[1],l=n[5],c=n[9],p=n[13],f=n[2],d=n[6],m=n[10],v=n[14],g=n[3],E=n[7],y=n[11],_=n[15],b=r[0],T=r[4],x=r[8],w=r[12],R=r[1],H=r[5],M=r[9],S=r[13],k=r[2],A=r[6],C=r[10],P=r[14],L=r[3],z=r[7],O=r[11],D=r[15];return i[0]=o*b+s*R+a*k+u*L,i[4]=o*T+s*H+a*A+u*z,i[8]=o*x+s*M+a*C+u*O,i[12]=o*w+s*S+a*P+u*D,i[1]=h*b+l*R+c*k+p*L,i[5]=h*T+l*H+c*A+p*z,i[9]=h*x+l*M+c*C+p*O,i[13]=h*w+l*S+c*P+p*D,i[2]=f*b+d*R+m*k+v*L,i[6]=f*T+d*H+m*A+v*z,i[10]=f*x+d*M+m*C+v*O,i[14]=f*w+d*S+m*P+v*D,i[3]=g*b+E*R+y*k+_*L,i[7]=g*T+E*H+y*A+_*z,i[11]=g*x+E*M+y*C+_*O,i[15]=g*w+E*S+y*P+_*D,this},multiplyToArray:function(t,e,n){var r=this.elements;return this.multiplyMatrices(t,e),n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],n[4]=r[4],n[5]=r[5],n[6]=r[6],n[7]=r[7],n[8]=r[8],n[9]=r[9],n[10]=r[10],n[11]=r[11],n[12]=r[12],n[13]=r[13],n[14]=r[14],n[15]=r[15],this},multiplyScalar:function(t){var e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this},multiplyVector3:function(t){return THREE.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead."),t.applyProjection(this)},multiplyVector4:function(t){return THREE.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead."),t.applyMatrix4(this)},multiplyVector3Array:function(t){return THREE.warn("THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead."),this.applyToVector3Array(t)},applyToVector3Array:function(){var t=new THREE.Vector3;return function(e,n,r){void 0===n&&(n=0),void 0===r&&(r=e.length);for(var i=0,o=n;r>i;i+=3,o+=3)t.x=e[o],t.y=e[o+1],t.z=e[o+2],t.applyMatrix4(this),e[o]=t.x,e[o+1]=t.y,e[o+2]=t.z;return e}}(),rotateAxis:function(t){THREE.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead."),t.transformDirection(this)},crossVector:function(t){return THREE.warn("THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead."),t.applyMatrix4(this)},determinant:function(){var t=this.elements,e=t[0],n=t[4],r=t[8],i=t[12],o=t[1],s=t[5],a=t[9],u=t[13],h=t[2],l=t[6],c=t[10],p=t[14],f=t[3],d=t[7],m=t[11],v=t[15];return f*(+i*a*l-r*u*l-i*s*c+n*u*c+r*s*p-n*a*p)+d*(+e*a*p-e*u*c+i*o*c-r*o*p+r*u*h-i*a*h)+m*(+e*u*l-e*s*p-i*o*l+n*o*p+i*s*h-n*u*h)+v*(-r*s*h-e*a*l+e*s*c+r*o*l-n*o*c+n*a*h)},transpose:function(){var t,e=this.elements;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this},flattenToArrayOffset:function(t,e){var n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t[e+9]=n[9],t[e+10]=n[10],t[e+11]=n[11],t[e+12]=n[12],t[e+13]=n[13],t[e+14]=n[14],t[e+15]=n[15],t},getPosition:function(){var t=new THREE.Vector3;return function(){THREE.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.");var e=this.elements;return t.set(e[12],e[13],e[14])}}(),setPosition:function(t){var e=this.elements;return e[12]=t.x,e[13]=t.y,e[14]=t.z,this},getInverse:function(t,e){var n=this.elements,r=t.elements,i=r[0],o=r[4],s=r[8],a=r[12],u=r[1],h=r[5],l=r[9],c=r[13],p=r[2],f=r[6],d=r[10],m=r[14],v=r[3],g=r[7],E=r[11],y=r[15];n[0]=l*m*g-c*d*g+c*f*E-h*m*E-l*f*y+h*d*y,n[4]=a*d*g-s*m*g-a*f*E+o*m*E+s*f*y-o*d*y,n[8]=s*c*g-a*l*g+a*h*E-o*c*E-s*h*y+o*l*y,n[12]=a*l*f-s*c*f-a*h*d+o*c*d+s*h*m-o*l*m,n[1]=c*d*v-l*m*v-c*p*E+u*m*E+l*p*y-u*d*y,n[5]=s*m*v-a*d*v+a*p*E-i*m*E-s*p*y+i*d*y,n[9]=a*l*v-s*c*v-a*u*E+i*c*E+s*u*y-i*l*y,n[13]=s*c*p-a*l*p+a*u*d-i*c*d-s*u*m+i*l*m,n[2]=h*m*v-c*f*v+c*p*g-u*m*g-h*p*y+u*f*y,n[6]=a*f*v-o*m*v-a*p*g+i*m*g+o*p*y-i*f*y,n[10]=o*c*v-a*h*v+a*u*g-i*c*g-o*u*y+i*h*y,n[14]=a*h*p-o*c*p-a*u*f+i*c*f+o*u*m-i*h*m,n[3]=l*f*v-h*d*v-l*p*g+u*d*g+h*p*E-u*f*E,n[7]=o*d*v-s*f*v+s*p*g-i*d*g-o*p*E+i*f*E,n[11]=s*h*v-o*l*v-s*u*g+i*l*g+o*u*E-i*h*E,n[15]=o*l*p-s*h*p+s*u*f-i*l*f-o*u*d+i*h*d;var _=i*n[0]+u*n[4]+p*n[8]+v*n[12];if(0==_){var b="THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";if(e)throw new Error(b);return THREE.warn(b),this.identity(),this}return this.multiplyScalar(1/_),this},translate:function(t){THREE.error("THREE.Matrix4: .translate() has been removed.")},rotateX:function(t){THREE.error("THREE.Matrix4: .rotateX() has been removed.")},rotateY:function(t){THREE.error("THREE.Matrix4: .rotateY() has been removed.")},rotateZ:function(t){THREE.error("THREE.Matrix4: .rotateZ() has been removed.")},rotateByAxis:function(t,e){THREE.error("THREE.Matrix4: .rotateByAxis() has been removed.")},scale:function(t){var e=this.elements,n=t.x,r=t.y,i=t.z;return e[0]*=n,e[4]*=r,e[8]*=i,e[1]*=n,e[5]*=r,e[9]*=i,e[2]*=n,e[6]*=r,e[10]*=i,e[3]*=n,e[7]*=r,e[11]*=i,this},getMaxScaleOnAxis:function(){var t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],n=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],r=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,Math.max(n,r)))},makeTranslation:function(t,e,n){return this.set(1,0,0,t,0,1,0,e,0,0,1,n,0,0,0,1),this},makeRotationX:function(t){var e=Math.cos(t),n=Math.sin(t);return this.set(1,0,0,0,0,e,-n,0,0,n,e,0,0,0,0,1),this},makeRotationY:function(t){var e=Math.cos(t),n=Math.sin(t);return this.set(e,0,n,0,0,1,0,0,-n,0,e,0,0,0,0,1),this},makeRotationZ:function(t){var e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,0,n,e,0,0,0,0,1,0,0,0,0,1),this},makeRotationAxis:function(t,e){var n=Math.cos(e),r=Math.sin(e),i=1-n,o=t.x,s=t.y,a=t.z,u=i*o,h=i*s;return this.set(u*o+n,u*s-r*a,u*a+r*s,0,u*s+r*a,h*s+n,h*a-r*o,0,u*a-r*s,h*a+r*o,i*a*a+n,0,0,0,0,1),this},makeScale:function(t,e,n){return this.set(t,0,0,0,0,e,0,0,0,0,n,0,0,0,0,1),this},compose:function(t,e,n){return this.makeRotationFromQuaternion(e),this.scale(n),this.setPosition(t),this},decompose:function(){var t=new THREE.Vector3,e=new THREE.Matrix4;return function(n,r,i){var o=this.elements,s=t.set(o[0],o[1],o[2]).length(),a=t.set(o[4],o[5],o[6]).length(),u=t.set(o[8],o[9],o[10]).length(),h=this.determinant();0>h&&(s=-s),n.x=o[12],n.y=o[13],n.z=o[14],e.elements.set(this.elements);var l=1/s,c=1/a,p=1/u;return e.elements[0]*=l,e.elements[1]*=l,e.elements[2]*=l,e.elements[4]*=c,e.elements[5]*=c,e.elements[6]*=c,e.elements[8]*=p,e.elements[9]*=p,e.elements[10]*=p,r.setFromRotationMatrix(e),i.x=s,i.y=a,i.z=u,this}}(),makeFrustum:function(t,e,n,r,i,o){var s=this.elements,a=2*i/(e-t),u=2*i/(r-n),h=(e+t)/(e-t),l=(r+n)/(r-n),c=-(o+i)/(o-i),p=-2*o*i/(o-i);return s[0]=a,s[4]=0,s[8]=h,s[12]=0,s[1]=0,s[5]=u,s[9]=l,s[13]=0,s[2]=0,s[6]=0,s[10]=c,s[14]=p,s[3]=0,s[7]=0,s[11]=-1,s[15]=0,this},makePerspective:function(t,e,n,r){var i=n*Math.tan(THREE.Math.degToRad(.5*t)),o=-i,s=o*e,a=i*e;return this.makeFrustum(s,a,o,i,n,r)},makeOrthographic:function(t,e,n,r,i,o){var s=this.elements,a=e-t,u=n-r,h=o-i,l=(e+t)/a,c=(n+r)/u,p=(o+i)/h;return s[0]=2/a,s[4]=0,s[8]=0,s[12]=-l,s[1]=0,s[5]=2/u,s[9]=0,s[13]=-c,s[2]=0,s[6]=0,s[10]=-2/h,s[14]=-p,s[3]=0,s[7]=0,s[11]=0,s[15]=1,this},fromArray:function(t){return this.elements.set(t),this},toArray:function(){var t=this.elements;return[t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15]]},clone:function(){return(new THREE.Matrix4).fromArray(this.elements)}},THREE.Ray=function(t,e){this.origin=void 0!==t?t:new THREE.Vector3,this.direction=void 0!==e?e:new THREE.Vector3},THREE.Ray.prototype={constructor:THREE.Ray,set:function(t,e){return this.origin.copy(t),this.direction.copy(e),this},copy:function(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this},at:function(t,e){var n=e||new THREE.Vector3;return n.copy(this.direction).multiplyScalar(t).add(this.origin)},recast:function(){var t=new THREE.Vector3;return function(e){return this.origin.copy(this.at(e,t)),this}}(),closestPointToPoint:function(t,e){var n=e||new THREE.Vector3;n.subVectors(t,this.origin);var r=n.dot(this.direction);return 0>r?n.copy(this.origin):n.copy(this.direction).multiplyScalar(r).add(this.origin)},distanceToPoint:function(){var t=new THREE.Vector3;return function(e){var n=t.subVectors(e,this.origin).dot(this.direction);return 0>n?this.origin.distanceTo(e):(t.copy(this.direction).multiplyScalar(n).add(this.origin),t.distanceTo(e))}}(),distanceSqToSegment:function(){var t=new THREE.Vector3,e=new THREE.Vector3,n=new THREE.Vector3;return function(r,i,o,s){t.copy(r).add(i).multiplyScalar(.5),e.copy(i).sub(r).normalize(),n.copy(this.origin).sub(t);var a,u,h,l,c=.5*r.distanceTo(i),p=-this.direction.dot(e),f=n.dot(this.direction),d=-n.dot(e),m=n.lengthSq(),v=Math.abs(1-p*p);if(v>0)if(a=p*d-f,u=p*f-d,l=c*v,a>=0)if(u>=-l)if(l>=u){var g=1/v;a*=g,u*=g,h=a*(a+p*u+2*f)+u*(p*a+u+2*d)+m}else u=c,a=Math.max(0,-(p*u+f)),h=-a*a+u*(u+2*d)+m;else u=-c,a=Math.max(0,-(p*u+f)),h=-a*a+u*(u+2*d)+m;else-l>=u?(a=Math.max(0,-(-p*c+f)),u=a>0?-c:Math.min(Math.max(-c,-d),c),h=-a*a+u*(u+2*d)+m):l>=u?(a=0,u=Math.min(Math.max(-c,-d),c),h=u*(u+2*d)+m):(a=Math.max(0,-(p*c+f)),u=a>0?c:Math.min(Math.max(-c,-d),c),h=-a*a+u*(u+2*d)+m);else u=p>0?-c:c,a=Math.max(0,-(p*u+f)),h=-a*a+u*(u+2*d)+m;return o&&o.copy(this.direction).multiplyScalar(a).add(this.origin),s&&s.copy(e).multiplyScalar(u).add(t),h}}(),isIntersectionSphere:function(t){return this.distanceToPoint(t.center)<=t.radius},intersectSphere:function(){var t=new THREE.Vector3;return function(e,n){t.subVectors(e.center,this.origin);var r=t.dot(this.direction),i=t.dot(t)-r*r,o=e.radius*e.radius;if(i>o)return null;var s=Math.sqrt(o-i),a=r-s,u=r+s;return 0>a&&0>u?null:0>a?this.at(u,n):this.at(a,n)}}(),isIntersectionPlane:function(t){var e=t.distanceToPoint(this.origin);if(0===e)return!0;var n=t.normal.dot(this.direction);return 0>n*e?!0:!1},distanceToPlane:function(t){var e=t.normal.dot(this.direction);if(0==e)return 0==t.distanceToPoint(this.origin)?0:null;var n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null},intersectPlane:function(t,e){var n=this.distanceToPlane(t);return null===n?null:this.at(n,e)},isIntersectionBox:function(){var t=new THREE.Vector3;return function(e){return null!==this.intersectBox(e,t)}}(),intersectBox:function(t,e){var n,r,i,o,s,a,u=1/this.direction.x,h=1/this.direction.y,l=1/this.direction.z,c=this.origin;return u>=0?(n=(t.min.x-c.x)*u,r=(t.max.x-c.x)*u):(n=(t.max.x-c.x)*u,r=(t.min.x-c.x)*u),h>=0?(i=(t.min.y-c.y)*h,o=(t.max.y-c.y)*h):(i=(t.max.y-c.y)*h,o=(t.min.y-c.y)*h),n>o||i>r?null:((i>n||n!==n)&&(n=i),(r>o||r!==r)&&(r=o),l>=0?(s=(t.min.z-c.z)*l,a=(t.max.z-c.z)*l):(s=(t.max.z-c.z)*l,a=(t.min.z-c.z)*l),n>a||s>r?null:((s>n||n!==n)&&(n=s),(r>a||r!==r)&&(r=a),0>r?null:this.at(n>=0?n:r,e)))},intersectTriangle:function(){var t=new THREE.Vector3,e=new THREE.Vector3,n=new THREE.Vector3,r=new THREE.Vector3;return function(i,o,s,a,u){e.subVectors(o,i),n.subVectors(s,i),r.crossVectors(e,n);var h,l=this.direction.dot(r);if(l>0){if(a)return null;h=1}else{if(!(0>l))return null;h=-1,l=-l}t.subVectors(this.origin,i);var c=h*this.direction.dot(n.crossVectors(t,n));if(0>c)return null;var p=h*this.direction.dot(e.cross(t));if(0>p)return null;if(c+p>l)return null;var f=-h*t.dot(r);return 0>f?null:this.at(f/l,u)}}(),applyMatrix4:function(t){return this.direction.add(this.origin).applyMatrix4(t),this.origin.applyMatrix4(t),this.direction.sub(this.origin),this.direction.normalize(),this},equals:function(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)},clone:function(){return(new THREE.Ray).copy(this)}},THREE.Sphere=function(t,e){this.center=void 0!==t?t:new THREE.Vector3,this.radius=void 0!==e?e:0},THREE.Sphere.prototype={constructor:THREE.Sphere,set:function(t,e){return this.center.copy(t),this.radius=e,this},setFromPoints:function(){var t=new THREE.Box3;return function(e,n){var r=this.center;void 0!==n?r.copy(n):t.setFromPoints(e).center(r);for(var i=0,o=0,s=e.length;s>o;o++)i=Math.max(i,r.distanceToSquared(e[o]));return this.radius=Math.sqrt(i),this}}(),copy:function(t){return this.center.copy(t.center),this.radius=t.radius,this},empty:function(){return this.radius<=0},containsPoint:function(t){return t.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(t){return t.distanceTo(this.center)-this.radius},intersectsSphere:function(t){var e=this.radius+t.radius;return t.center.distanceToSquared(this.center)<=e*e},clampPoint:function(t,e){var n=this.center.distanceToSquared(t),r=e||new THREE.Vector3;return r.copy(t),n>this.radius*this.radius&&(r.sub(this.center).normalize(),r.multiplyScalar(this.radius).add(this.center)),r},getBoundingBox:function(t){var e=t||new THREE.Box3;return e.set(this.center,this.center),e.expandByScalar(this.radius),e},applyMatrix4:function(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this},translate:function(t){return this.center.add(t),this},equals:function(t){return t.center.equals(this.center)&&t.radius===this.radius},clone:function(){return(new THREE.Sphere).copy(this)}},THREE.Frustum=function(t,e,n,r,i,o){this.planes=[void 0!==t?t:new THREE.Plane,void 0!==e?e:new THREE.Plane,void 0!==n?n:new THREE.Plane,void 0!==r?r:new THREE.Plane,void 0!==i?i:new THREE.Plane,void 0!==o?o:new THREE.Plane]},THREE.Frustum.prototype={constructor:THREE.Frustum,set:function(t,e,n,r,i,o){var s=this.planes;return s[0].copy(t),s[1].copy(e),s[2].copy(n),s[3].copy(r),s[4].copy(i),s[5].copy(o),this},copy:function(t){for(var e=this.planes,n=0;6>n;n++)e[n].copy(t.planes[n]);return this},setFromMatrix:function(t){var e=this.planes,n=t.elements,r=n[0],i=n[1],o=n[2],s=n[3],a=n[4],u=n[5],h=n[6],l=n[7],c=n[8],p=n[9],f=n[10],d=n[11],m=n[12],v=n[13],g=n[14],E=n[15];return e[0].setComponents(s-r,l-a,d-c,E-m).normalize(),e[1].setComponents(s+r,l+a,d+c,E+m).normalize(),e[2].setComponents(s+i,l+u,d+p,E+v).normalize(),e[3].setComponents(s-i,l-u,d-p,E-v).normalize(),e[4].setComponents(s-o,l-h,d-f,E-g).normalize(),e[5].setComponents(s+o,l+h,d+f,E+g).normalize(),this},intersectsObject:function(){var t=new THREE.Sphere;return function(e){var n=e.geometry;return null===n.boundingSphere&&n.computeBoundingSphere(),t.copy(n.boundingSphere),t.applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSphere:function(t){for(var e=this.planes,n=t.center,r=-t.radius,i=0;6>i;i++){var o=e[i].distanceToPoint(n);if(r>o)return!1}return!0},intersectsBox:function(){var t=new THREE.Vector3,e=new THREE.Vector3;return function(n){for(var r=this.planes,i=0;6>i;i++){var o=r[i];t.x=o.normal.x>0?n.min.x:n.max.x,e.x=o.normal.x>0?n.max.x:n.min.x,t.y=o.normal.y>0?n.min.y:n.max.y,e.y=o.normal.y>0?n.max.y:n.min.y,t.z=o.normal.z>0?n.min.z:n.max.z,e.z=o.normal.z>0?n.max.z:n.min.z;var s=o.distanceToPoint(t),a=o.distanceToPoint(e);if(0>s&&0>a)return!1}return!0}}(),containsPoint:function(t){for(var e=this.planes,n=0;6>n;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0},clone:function(){return(new THREE.Frustum).copy(this); +}},THREE.Plane=function(t,e){this.normal=void 0!==t?t:new THREE.Vector3(1,0,0),this.constant=void 0!==e?e:0},THREE.Plane.prototype={constructor:THREE.Plane,set:function(t,e){return this.normal.copy(t),this.constant=e,this},setComponents:function(t,e,n,r){return this.normal.set(t,e,n),this.constant=r,this},setFromNormalAndCoplanarPoint:function(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this},setFromCoplanarPoints:function(){var t=new THREE.Vector3,e=new THREE.Vector3;return function(n,r,i){var o=t.subVectors(i,r).cross(e.subVectors(n,r)).normalize();return this.setFromNormalAndCoplanarPoint(o,n),this}}(),copy:function(t){return this.normal.copy(t.normal),this.constant=t.constant,this},normalize:function(){var t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this},negate:function(){return this.constant*=-1,this.normal.negate(),this},distanceToPoint:function(t){return this.normal.dot(t)+this.constant},distanceToSphere:function(t){return this.distanceToPoint(t.center)-t.radius},projectPoint:function(t,e){return this.orthoPoint(t,e).sub(t).negate()},orthoPoint:function(t,e){var n=this.distanceToPoint(t),r=e||new THREE.Vector3;return r.copy(this.normal).multiplyScalar(n)},isIntersectionLine:function(t){var e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return 0>e&&n>0||0>n&&e>0},intersectLine:function(){var t=new THREE.Vector3;return function(e,n){var r=n||new THREE.Vector3,i=e.delta(t),o=this.normal.dot(i);if(0==o)return 0==this.distanceToPoint(e.start)?r.copy(e.start):void 0;var s=-(e.start.dot(this.normal)+this.constant)/o;return 0>s||s>1?void 0:r.copy(i).multiplyScalar(s).add(e.start)}}(),coplanarPoint:function(t){var e=t||new THREE.Vector3;return e.copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var t=new THREE.Vector3,e=new THREE.Vector3,n=new THREE.Matrix3;return function(r,i){var o=i||n.getNormalMatrix(r),s=t.copy(this.normal).applyMatrix3(o),a=this.coplanarPoint(e);return a.applyMatrix4(r),this.setFromNormalAndCoplanarPoint(s,a),this}}(),translate:function(t){return this.constant=this.constant-t.dot(this.normal),this},equals:function(t){return t.normal.equals(this.normal)&&t.constant==this.constant},clone:function(){return(new THREE.Plane).copy(this)}},THREE.Math={generateUUID:function(){var t,e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),n=new Array(36),r=0;return function(){for(var i=0;36>i;i++)8==i||13==i||18==i||23==i?n[i]="-":14==i?n[i]="4":(2>=r&&(r=33554432+16777216*Math.random()|0),t=15&r,r>>=4,n[i]=e[19==i?3&t|8:t]);return n.join("")}}(),clamp:function(t,e,n){return e>t?e:t>n?n:t},clampBottom:function(t,e){return e>t?e:t},mapLinear:function(t,e,n,r,i){return r+(t-e)*(i-r)/(n-e)},smoothstep:function(t,e,n){return e>=t?0:t>=n?1:(t=(t-e)/(n-e),t*t*(3-2*t))},smootherstep:function(t,e,n){return e>=t?0:t>=n?1:(t=(t-e)/(n-e),t*t*t*(t*(6*t-15)+10))},random16:function(){return(65280*Math.random()+255*Math.random())/65535},randInt:function(t,e){return Math.floor(this.randFloat(t,e))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},degToRad:function(){var t=Math.PI/180;return function(e){return e*t}}(),radToDeg:function(){var t=180/Math.PI;return function(e){return e*t}}(),isPowerOfTwo:function(t){return 0===(t&t-1)&&0!==t},nextPowerOfTwo:function(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}},THREE.Spline=function(t){function e(t,e,n,r,i,o,s){var a=.5*(n-t),u=.5*(r-e);return(2*(e-n)+a+u)*s+(-3*(e-n)-2*a-u)*o+a*i+e}this.points=t;var n,r,i,o,s,a,u,h,l,c=[],p={x:0,y:0,z:0};this.initFromArray=function(t){this.points=[];for(var e=0;ethis.points.length-2?this.points.length-1:r+1,c[3]=r>this.points.length-3?this.points.length-1:r+2,a=this.points[c[0]],u=this.points[c[1]],h=this.points[c[2]],l=this.points[c[3]],o=i*i,s=i*o,p.x=e(a.x,u.x,h.x,l.x,i,o,s),p.y=e(a.y,u.y,h.y,l.y,i,o,s),p.z=e(a.z,u.z,h.z,l.z,i,o,s),p},this.getControlPointsArray=function(){var t,e,n=this.points.length,r=[];for(t=0;n>t;t++)e=this.points[t],r[t]=[e.x,e.y,e.z];return r},this.getLength=function(t){var e,n,r,i,o=0,s=0,a=0,u=new THREE.Vector3,h=new THREE.Vector3,l=[],c=0;for(l[0]=0,t||(t=100),r=this.points.length*t,u.copy(this.points[0]),e=1;r>e;e++)n=e/r,i=this.getPoint(n),h.copy(i),c+=h.distanceTo(u),u.copy(i),o=(this.points.length-1)*n,s=Math.floor(o),s!=a&&(l[s]=c,a=s);return l[l.length]=c,{chunks:l,total:c}},this.reparametrizeByArcLength=function(t){var e,n,r,i,o,s,a,u,h=[],l=new THREE.Vector3,c=this.getLength();for(h.push(l.copy(this.points[0]).clone()),e=1;en;n++)r=i+n*(1/a)*(o-i),u=this.getPoint(r),h.push(l.copy(u).clone());h.push(l.copy(this.points[e]).clone())}this.points=h}},THREE.Triangle=function(t,e,n){this.a=void 0!==t?t:new THREE.Vector3,this.b=void 0!==e?e:new THREE.Vector3,this.c=void 0!==n?n:new THREE.Vector3},THREE.Triangle.normal=function(){var t=new THREE.Vector3;return function(e,n,r,i){var o=i||new THREE.Vector3;o.subVectors(r,n),t.subVectors(e,n),o.cross(t);var s=o.lengthSq();return s>0?o.multiplyScalar(1/Math.sqrt(s)):o.set(0,0,0)}}(),THREE.Triangle.barycoordFromPoint=function(){var t=new THREE.Vector3,e=new THREE.Vector3,n=new THREE.Vector3;return function(r,i,o,s,a){t.subVectors(s,i),e.subVectors(o,i),n.subVectors(r,i);var u=t.dot(t),h=t.dot(e),l=t.dot(n),c=e.dot(e),p=e.dot(n),f=u*c-h*h,d=a||new THREE.Vector3;if(0==f)return d.set(-2,-1,-1);var m=1/f,v=(c*l-h*p)*m,g=(u*p-h*l)*m;return d.set(1-v-g,g,v)}}(),THREE.Triangle.containsPoint=function(){var t=new THREE.Vector3;return function(e,n,r,i){var o=THREE.Triangle.barycoordFromPoint(e,n,r,i,t);return o.x>=0&&o.y>=0&&o.x+o.y<=1}}(),THREE.Triangle.prototype={constructor:THREE.Triangle,set:function(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this},setFromPointsAndIndices:function(t,e,n,r){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[r]),this},copy:function(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this},area:function(){var t=new THREE.Vector3,e=new THREE.Vector3;return function(){return t.subVectors(this.c,this.b),e.subVectors(this.a,this.b),.5*t.cross(e).length()}}(),midpoint:function(t){var e=t||new THREE.Vector3;return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(t){return THREE.Triangle.normal(this.a,this.b,this.c,t)},plane:function(t){var e=t||new THREE.Plane;return e.setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(t,e){return THREE.Triangle.barycoordFromPoint(t,this.a,this.b,this.c,e)},containsPoint:function(t){return THREE.Triangle.containsPoint(t,this.a,this.b,this.c)},equals:function(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)},clone:function(){return(new THREE.Triangle).copy(this)}},THREE.Clock=function(t){this.autoStart=void 0!==t?t:!0,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1},THREE.Clock.prototype={constructor:THREE.Clock,start:function(){this.startTime=void 0!==self.performance&&void 0!==self.performance.now?self.performance.now():Date.now(),this.oldTime=this.startTime,this.running=!0},stop:function(){this.getElapsedTime(),this.running=!1},getElapsedTime:function(){return this.getDelta(),this.elapsedTime},getDelta:function(){var t=0;if(this.autoStart&&!this.running&&this.start(),this.running){var e=void 0!==self.performance&&void 0!==self.performance.now?self.performance.now():Date.now();t=.001*(e-this.oldTime),this.oldTime=e,this.elapsedTime+=t}return t}},THREE.EventDispatcher=function(){},THREE.EventDispatcher.prototype={constructor:THREE.EventDispatcher,apply:function(t){t.addEventListener=THREE.EventDispatcher.prototype.addEventListener,t.hasEventListener=THREE.EventDispatcher.prototype.hasEventListener,t.removeEventListener=THREE.EventDispatcher.prototype.removeEventListener,t.dispatchEvent=THREE.EventDispatcher.prototype.dispatchEvent},addEventListener:function(t,e){void 0===this._listeners&&(this._listeners={});var n=this._listeners;void 0===n[t]&&(n[t]=[]),-1===n[t].indexOf(e)&&n[t].push(e)},hasEventListener:function(t,e){if(void 0===this._listeners)return!1;var n=this._listeners;return void 0!==n[t]&&-1!==n[t].indexOf(e)?!0:!1},removeEventListener:function(t,e){if(void 0!==this._listeners){var n=this._listeners,r=n[t];if(void 0!==r){var i=r.indexOf(e);-1!==i&&r.splice(i,1)}}},dispatchEvent:function(t){if(void 0!==this._listeners){var e=this._listeners,n=e[t.type];if(void 0!==n){t.target=this;for(var r=[],i=n.length,o=0;i>o;o++)r[o]=n[o];for(var o=0;i>o;o++)r[o].call(this,t)}}}},function(t){t.Raycaster=function(e,n,r,i){this.ray=new t.Ray(e,n),this.near=r||0,this.far=i||1/0,this.params={Sprite:{},Mesh:{},PointCloud:{threshold:1},LOD:{},Line:{}}};var e=function(t,e){return t.distance-e.distance},n=function(t,e,r,i){if(t.raycast(e,r),i===!0)for(var o=t.children,s=0,a=o.length;a>s;s++)n(o[s],e,r,!0)};t.Raycaster.prototype={constructor:t.Raycaster,precision:1e-4,linePrecision:1,set:function(t,e){this.ray.set(t,e)},setFromCamera:function(e,n){n instanceof t.PerspectiveCamera?(this.ray.origin.copy(n.position),this.ray.direction.set(e.x,e.y,.5).unproject(n).sub(n.position).normalize()):n instanceof t.OrthographicCamera?(this.ray.origin.set(e.x,e.y,-1).unproject(n),this.ray.direction.set(0,0,-1).transformDirection(n.matrixWorld)):t.error("THREE.Raycaster: Unsupported camera type.")},intersectObject:function(t,r){var i=[];return n(t,this,i,r),i.sort(e),i},intersectObjects:function(r,i){var o=[];if(r instanceof Array==!1)return t.warn("THREE.Raycaster.intersectObjects: objects is not an Array."),o;for(var s=0,a=r.length;a>s;s++)n(r[s],this,o,i);return o.sort(e),o}}}(THREE),THREE.Object3D=function(){Object.defineProperty(this,"id",{value:THREE.Object3DIdCount++}),this.uuid=THREE.Math.generateUUID(),this.name="",this.type="Object3D",this.parent=void 0,this.children=[],this.up=THREE.Object3D.DefaultUp.clone();var t=new THREE.Vector3,e=new THREE.Euler,n=new THREE.Quaternion,r=new THREE.Vector3(1,1,1),i=function(){n.setFromEuler(e,!1)},o=function(){e.setFromQuaternion(n,void 0,!1)};e.onChange(i),n.onChange(o),Object.defineProperties(this,{position:{enumerable:!0,value:t},rotation:{enumerable:!0,value:e},quaternion:{enumerable:!0,value:n},scale:{enumerable:!0,value:r}}),this.rotationAutoUpdate=!0,this.matrix=new THREE.Matrix4,this.matrixWorld=new THREE.Matrix4,this.matrixAutoUpdate=!0,this.matrixWorldNeedsUpdate=!1,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.userData={}},THREE.Object3D.DefaultUp=new THREE.Vector3(0,1,0),THREE.Object3D.prototype={constructor:THREE.Object3D,get eulerOrder(){return THREE.warn("THREE.Object3D: .eulerOrder has been moved to .rotation.order."),this.rotation.order},set eulerOrder(t){THREE.warn("THREE.Object3D: .eulerOrder has been moved to .rotation.order."),this.rotation.order=t},get useQuaternion(){THREE.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set useQuaternion(t){THREE.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},applyMatrix:function(t){this.matrix.multiplyMatrices(t,this.matrix),this.matrix.decompose(this.position,this.quaternion,this.scale)},setRotationFromAxisAngle:function(t,e){this.quaternion.setFromAxisAngle(t,e)},setRotationFromEuler:function(t){this.quaternion.setFromEuler(t,!0)},setRotationFromMatrix:function(t){this.quaternion.setFromRotationMatrix(t)},setRotationFromQuaternion:function(t){this.quaternion.copy(t)},rotateOnAxis:function(){var t=new THREE.Quaternion;return function(e,n){return t.setFromAxisAngle(e,n),this.quaternion.multiply(t),this}}(),rotateX:function(){var t=new THREE.Vector3(1,0,0);return function(e){return this.rotateOnAxis(t,e)}}(),rotateY:function(){var t=new THREE.Vector3(0,1,0);return function(e){return this.rotateOnAxis(t,e)}}(),rotateZ:function(){var t=new THREE.Vector3(0,0,1);return function(e){return this.rotateOnAxis(t,e)}}(),translateOnAxis:function(){var t=new THREE.Vector3;return function(e,n){return t.copy(e).applyQuaternion(this.quaternion),this.position.add(t.multiplyScalar(n)),this}}(),translate:function(t,e){return THREE.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead."),this.translateOnAxis(e,t)},translateX:function(){var t=new THREE.Vector3(1,0,0);return function(e){return this.translateOnAxis(t,e)}}(),translateY:function(){var t=new THREE.Vector3(0,1,0);return function(e){return this.translateOnAxis(t,e)}}(),translateZ:function(){var t=new THREE.Vector3(0,0,1);return function(e){return this.translateOnAxis(t,e)}}(),localToWorld:function(t){return t.applyMatrix4(this.matrixWorld)},worldToLocal:function(){var t=new THREE.Matrix4;return function(e){return e.applyMatrix4(t.getInverse(this.matrixWorld))}}(),lookAt:function(){var t=new THREE.Matrix4;return function(e){t.lookAt(e,this.position,this.up),this.quaternion.setFromRotationMatrix(t)}}(),add:function(t){if(arguments.length>1){for(var e=0;e1)for(var e=0;en;n++){var i=this.children[n],o=i.getObjectByProperty(t,e);if(void 0!==o)return o}return void 0},getWorldPosition:function(t){var e=t||new THREE.Vector3;return this.updateMatrixWorld(!0),e.setFromMatrixPosition(this.matrixWorld)},getWorldQuaternion:function(){var t=new THREE.Vector3,e=new THREE.Vector3;return function(n){var r=n||new THREE.Quaternion;return this.updateMatrixWorld(!0),this.matrixWorld.decompose(t,r,e),r}}(),getWorldRotation:function(){var t=new THREE.Quaternion;return function(e){var n=e||new THREE.Euler;return this.getWorldQuaternion(t),n.setFromQuaternion(t,this.rotation.order,!1)}}(),getWorldScale:function(){var t=new THREE.Vector3,e=new THREE.Quaternion;return function(n){var r=n||new THREE.Vector3;return this.updateMatrixWorld(!0),this.matrixWorld.decompose(t,e,r),r}}(),getWorldDirection:function(){var t=new THREE.Quaternion;return function(e){var n=e||new THREE.Vector3;return this.getWorldQuaternion(t),n.set(0,0,1).applyQuaternion(t)}}(),raycast:function(){},traverse:function(t){t(this);for(var e=0,n=this.children.length;n>e;e++)this.children[e].traverse(t)},traverseVisible:function(t){if(this.visible!==!1){t(this);for(var e=0,n=this.children.length;n>e;e++)this.children[e].traverseVisible(t)}},traverseAncestors:function(t){this.parent&&(t(this.parent),this.parent.traverseAncestors(t))},updateMatrix:function(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0},updateMatrixWorld:function(t){this.matrixAutoUpdate===!0&&this.updateMatrix(),(this.matrixWorldNeedsUpdate===!0||t===!0)&&(void 0===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,t=!0);for(var e=0,n=this.children.length;n>e;e++)this.children[e].updateMatrixWorld(t)},toJSON:function(){var t={metadata:{version:4.3,type:"Object",generator:"ObjectExporter"}},e={},n=function(n){if(void 0===t.geometries&&(t.geometries=[]),void 0===e[n.uuid]){var r=n.toJSON();delete r.metadata,e[n.uuid]=r,t.geometries.push(r)}return n.uuid},r={},i=function(e){if(void 0===t.materials&&(t.materials=[]),void 0===r[e.uuid]){var n=e.toJSON();delete n.metadata,r[e.uuid]=n,t.materials.push(n)}return e.uuid},o=function(t){var e={};if(e.uuid=t.uuid,e.type=t.type,""!==t.name&&(e.name=t.name),"{}"!==JSON.stringify(t.userData)&&(e.userData=t.userData),t.visible!==!0&&(e.visible=t.visible),t instanceof THREE.PerspectiveCamera?(e.fov=t.fov,e.aspect=t.aspect,e.near=t.near,e.far=t.far):t instanceof THREE.OrthographicCamera?(e.left=t.left,e.right=t.right,e.top=t.top,e.bottom=t.bottom,e.near=t.near,e.far=t.far):t instanceof THREE.AmbientLight?e.color=t.color.getHex():t instanceof THREE.DirectionalLight?(e.color=t.color.getHex(),e.intensity=t.intensity):t instanceof THREE.PointLight?(e.color=t.color.getHex(),e.intensity=t.intensity,e.distance=t.distance,e.decay=t.decay):t instanceof THREE.SpotLight?(e.color=t.color.getHex(),e.intensity=t.intensity,e.distance=t.distance,e.angle=t.angle,e.exponent=t.exponent,e.decay=t.decay):t instanceof THREE.HemisphereLight?(e.color=t.color.getHex(),e.groundColor=t.groundColor.getHex()):t instanceof THREE.Mesh||t instanceof THREE.Line||t instanceof THREE.PointCloud?(e.geometry=n(t.geometry),e.material=i(t.material),t instanceof THREE.Line&&(e.mode=t.mode)):t instanceof THREE.Sprite&&(e.material=i(t.material)),e.matrix=t.matrix.toArray(),t.children.length>0){e.children=[];for(var r=0;re;e++)t.vertexNormals[e]=this.vertexNormals[e].clone();for(var e=0,n=this.vertexColors.length;n>e;e++)t.vertexColors[e]=this.vertexColors[e].clone();for(var e=0,n=this.vertexTangents.length;n>e;e++)t.vertexTangents[e]=this.vertexTangents[e].clone();return t}},THREE.Face4=function(t,e,n,r,i,o,s){return THREE.warn("THREE.Face4 has been removed. A THREE.Face3 will be created instead."),new THREE.Face3(t,e,n,i,o,s)},THREE.BufferAttribute=function(t,e){this.array=t,this.itemSize=e,this.needsUpdate=!1},THREE.BufferAttribute.prototype={constructor:THREE.BufferAttribute,get length(){return this.array.length},copyAt:function(t,e,n){t*=this.itemSize,n*=e.itemSize;for(var r=0,i=this.itemSize;i>r;r++)this.array[t+r]=e.array[n+r];return this},set:function(t,e){return void 0===e&&(e=0),this.array.set(t,e),this},setX:function(t,e){return this.array[t*this.itemSize]=e,this},setY:function(t,e){return this.array[t*this.itemSize+1]=e,this},setZ:function(t,e){return this.array[t*this.itemSize+2]=e,this},setXY:function(t,e,n){return t*=this.itemSize,this.array[t]=e,this.array[t+1]=n,this},setXYZ:function(t,e,n,r){return t*=this.itemSize,this.array[t]=e,this.array[t+1]=n,this.array[t+2]=r,this},setXYZW:function(t,e,n,r,i){return t*=this.itemSize,this.array[t]=e,this.array[t+1]=n,this.array[t+2]=r,this.array[t+3]=i,this},clone:function(){return new THREE.BufferAttribute(new this.array.constructor(this.array),this.itemSize)}},THREE.Int8Attribute=function(t,e){return THREE.warn("THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead."),new THREE.BufferAttribute(t,e)},THREE.Uint8Attribute=function(t,e){return THREE.warn("THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead."),new THREE.BufferAttribute(t,e)},THREE.Uint8ClampedAttribute=function(t,e){return THREE.warn("THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead."),new THREE.BufferAttribute(t,e)},THREE.Int16Attribute=function(t,e){return THREE.warn("THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead."),new THREE.BufferAttribute(t,e)},THREE.Uint16Attribute=function(t,e){return THREE.warn("THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead."),new THREE.BufferAttribute(t,e)},THREE.Int32Attribute=function(t,e){return THREE.warn("THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead."),new THREE.BufferAttribute(t,e)},THREE.Uint32Attribute=function(t,e){return THREE.warn("THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead."),new THREE.BufferAttribute(t,e)},THREE.Float32Attribute=function(t,e){return THREE.warn("THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead."),new THREE.BufferAttribute(t,e)},THREE.Float64Attribute=function(t,e){return THREE.warn("THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead."),new THREE.BufferAttribute(t,e)},THREE.DynamicBufferAttribute=function(t,e){THREE.BufferAttribute.call(this,t,e),this.updateRange={offset:0,count:-1}},THREE.DynamicBufferAttribute.prototype=Object.create(THREE.BufferAttribute.prototype),THREE.DynamicBufferAttribute.prototype.constructor=THREE.DynamicBufferAttribute,THREE.DynamicBufferAttribute.prototype.clone=function(){return new THREE.DynamicBufferAttribute(new this.array.constructor(this.array),this.itemSize)},THREE.BufferGeometry=function(){Object.defineProperty(this,"id",{value:THREE.GeometryIdCount++}),this.uuid=THREE.Math.generateUUID(),this.name="",this.type="BufferGeometry",this.attributes={},this.attributesKeys=[],this.drawcalls=[],this.offsets=this.drawcalls,this.boundingBox=null,this.boundingSphere=null},THREE.BufferGeometry.prototype={constructor:THREE.BufferGeometry,addAttribute:function(t,e){return e instanceof THREE.BufferAttribute==!1?(THREE.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),void(this.attributes[t]={array:arguments[1],itemSize:arguments[2]})):(this.attributes[t]=e,void(this.attributesKeys=Object.keys(this.attributes)))},getAttribute:function(t){return this.attributes[t]},addDrawCall:function(t,e,n){this.drawcalls.push({start:t,count:e,index:void 0!==n?n:0})},applyMatrix:function(t){var e=this.attributes.position;void 0!==e&&(t.applyToVector3Array(e.array),e.needsUpdate=!0);var n=this.attributes.normal;if(void 0!==n){var r=(new THREE.Matrix3).getNormalMatrix(t);r.applyToVector3Array(n.array),n.needsUpdate=!0}null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere()},center:function(){this.computeBoundingBox();var t=this.boundingBox.center().negate();return this.applyMatrix((new THREE.Matrix4).setPosition(t)),t},fromGeometry:function(t,e){e=e||{vertexColors:THREE.NoColors};var n=t.vertices,r=t.faces,i=t.faceVertexUvs,o=e.vertexColors,s=i[0].length>0,a=3==r[0].vertexNormals.length,u=new Float32Array(3*r.length*3);this.addAttribute("position",new THREE.BufferAttribute(u,3));var h=new Float32Array(3*r.length*3);if(this.addAttribute("normal",new THREE.BufferAttribute(h,3)),o!==THREE.NoColors){var l=new Float32Array(3*r.length*3);this.addAttribute("color",new THREE.BufferAttribute(l,3))}if(s===!0){var c=new Float32Array(3*r.length*2);this.addAttribute("uv",new THREE.BufferAttribute(c,2))}for(var p=0,f=0,d=0;pr;r+=3)t.set(e[r],e[r+1],e[r+2]),n.expandByPoint(t)}(void 0===e||0===e.length)&&(this.boundingBox.min.set(0,0,0),this.boundingBox.max.set(0,0,0)),(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&THREE.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.')}}(),computeBoundingSphere:function(){var t=new THREE.Box3,e=new THREE.Vector3;return function(){null===this.boundingSphere&&(this.boundingSphere=new THREE.Sphere);var n=this.attributes.position.array;if(n){t.makeEmpty();for(var r=this.boundingSphere.center,i=0,o=n.length;o>i;i+=3)e.set(n[i],n[i+1],n[i+2]),t.expandByPoint(e);t.center(r);for(var s=0,i=0,o=n.length;o>i;i+=3)e.set(n[i],n[i+1],n[i+2]),s=Math.max(s,r.distanceToSquared(e));this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&THREE.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.')}}}(),computeFaceNormals:function(){},computeVertexNormals:function(){var t=this.attributes;if(t.position){var e=t.position.array;if(void 0===t.normal)this.addAttribute("normal",new THREE.BufferAttribute(new Float32Array(e.length),3));else for(var n=t.normal.array,r=0,i=n.length;i>r;r++)n[r]=0;var o,s,a,n=t.normal.array,u=new THREE.Vector3,h=new THREE.Vector3,l=new THREE.Vector3,c=new THREE.Vector3,p=new THREE.Vector3;if(t.index)for(var f=t.index.array,d=this.offsets.length>0?this.offsets:[{start:0,count:f.length,index:0}],m=0,v=d.length;v>m;++m)for(var g=d[m].start,E=d[m].count,y=d[m].index,r=g,i=g+E;i>r;r+=3)o=3*(y+f[r]),s=3*(y+f[r+1]),a=3*(y+f[r+2]),u.fromArray(e,o),h.fromArray(e,s),l.fromArray(e,a),c.subVectors(l,h),p.subVectors(u,h),c.cross(p),n[o]+=c.x,n[o+1]+=c.y,n[o+2]+=c.z,n[s]+=c.x,n[s+1]+=c.y,n[s+2]+=c.z,n[a]+=c.x,n[a+1]+=c.y,n[a+2]+=c.z;else for(var r=0,i=e.length;i>r;r+=9)u.fromArray(e,r),h.fromArray(e,r+3),l.fromArray(e,r+6),c.subVectors(l,h),p.subVectors(u,h),c.cross(p),n[r]=c.x,n[r+1]=c.y,n[r+2]=c.z,n[r+3]=c.x,n[r+4]=c.y,n[r+5]=c.z,n[r+6]=c.x,n[r+7]=c.y,n[r+8]=c.z;this.normalizeNormals(),t.normal.needsUpdate=!0}},computeTangents:function(){function t(t,e,n){k.fromArray(r,3*t),A.fromArray(r,3*e),C.fromArray(r,3*n),P.fromArray(o,2*t),L.fromArray(o,2*e),z.fromArray(o,2*n),c=A.x-k.x,p=C.x-k.x,f=A.y-k.y,d=C.y-k.y,m=A.z-k.z,v=C.z-k.z,g=L.x-P.x,E=z.x-P.x,y=L.y-P.y,_=z.y-P.y,b=1/(g*_-E*y),O.set((_*c-y*p)*b,(_*f-y*d)*b,(_*m-y*v)*b),D.set((g*p-E*c)*b,(g*d-E*f)*b,(g*v-E*m)*b),u[t].add(O),u[e].add(O),u[n].add(O),h[t].add(D),h[e].add(D),h[n].add(D)}function e(t){q.fromArray(i,3*t),X.copy(q),I=u[t],G.copy(I),G.sub(q.multiplyScalar(q.dot(I))).normalize(),W.crossVectors(X,I),j=W.dot(h[t]),V=0>j?-1:1,a[4*t]=G.x,a[4*t+1]=G.y,a[4*t+2]=G.z,a[4*t+3]=V}if(void 0===this.attributes.index||void 0===this.attributes.position||void 0===this.attributes.normal||void 0===this.attributes.uv)return void THREE.warn("THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()");var n=this.attributes.index.array,r=this.attributes.position.array,i=this.attributes.normal.array,o=this.attributes.uv.array,s=r.length/3;void 0===this.attributes.tangent&&this.addAttribute("tangent",new THREE.BufferAttribute(new Float32Array(4*s),4));for(var a=this.attributes.tangent.array,u=[],h=[],l=0;s>l;l++)u[l]=new THREE.Vector3,h[l]=new THREE.Vector3;var c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k=new THREE.Vector3,A=new THREE.Vector3,C=new THREE.Vector3,P=new THREE.Vector2,L=new THREE.Vector2,z=new THREE.Vector2,O=new THREE.Vector3,D=new THREE.Vector3;0===this.drawcalls.length&&this.addDrawCall(0,n.length,0);var F=this.drawcalls;for(w=0,R=F.length;R>w;++w){var U=F[w].start,B=F[w].count,N=F[w].index;for(T=U,x=U+B;x>T;T+=3)H=N+n[T],M=N+n[T+1],S=N+n[T+2],t(H,M,S)}var V,I,j,G=new THREE.Vector3,W=new THREE.Vector3,q=new THREE.Vector3,X=new THREE.Vector3;for(w=0,R=F.length;R>w;++w){var U=F[w].start,B=F[w].count,N=F[w].index;for(T=U,x=U+B;x>T;T+=3)H=N+n[T],M=N+n[T+1],S=N+n[T+2],e(H),e(M),e(S)}},computeOffsets:function(t){void 0===t&&(t=65535);for(var e=this.attributes.index.array,n=this.attributes.position.array,r=e.length/3,i=new Uint16Array(e.length),o=0,s=0,a=[{start:0,count:0,index:0}],u=a[0],h=0,l=0,c=new Int32Array(6),p=new Int32Array(n.length),f=new Int32Array(n.length),d=0;dm;m++){l=0;for(var v=0;3>v;v++){var g=e[3*m+v];-1==p[g]?(c[2*v]=g,c[2*v+1]=-1,l++):p[g]u.index+t){var y={start:o,count:0,index:s};a.push(y),u=y;for(var _=0;6>_;_+=2){var b=c[_+1];b>-1&&b_;_+=2){var g=c[_],b=c[_+1];-1===b&&(b=s++),p[g]=b,f[b]=g,i[o++]=b-u.index,u.count++}}return this.reorderBuffers(i,f,s),this.offsets=a,this.drawcalls=a,a},merge:function(t,e){if(t instanceof THREE.BufferGeometry==!1)return void THREE.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",t);void 0===e&&(e=0);var n=this.attributes;for(var r in n)if(void 0!==t.attributes[r])for(var i=n[r],o=i.array,s=t.attributes[r],a=s.array,u=s.itemSize,h=0,l=u*e;ho;o+=3)t=i[o],e=i[o+1],n=i[o+2],r=1/Math.sqrt(t*t+e*e+n*n),i[o]*=r,i[o+1]*=r,i[o+2]*=r},reorderBuffers:function(t,e,n){var r={};for(var i in this.attributes)if("index"!=i){var o=this.attributes[i].array;r[i]=new o.constructor(this.attributes[i].itemSize*n)}for(var s=0;n>s;s++){var a=e[s];for(var i in this.attributes)if("index"!=i)for(var u=this.attributes[i].array,h=this.attributes[i].itemSize,l=r[i],c=0;h>c;c++)l[s*h+c]=u[a*h+c]}this.attributes.index.array=t;for(var i in this.attributes)"index"!=i&&(this.attributes[i].array=r[i],this.attributes[i].numItems=this.attributes[i].itemSize*n)},toJSON:function(){var t={metadata:{version:4,type:"BufferGeometry",generator:"BufferGeometryExporter"},uuid:this.uuid,type:this.type,data:{attributes:{}}},e=this.attributes,n=this.offsets,r=this.boundingSphere; +for(var i in e){var o=e[i],s=Array.prototype.slice.call(o.array);t.data.attributes[i]={itemSize:o.itemSize,type:o.array.constructor.name,array:s}}return n.length>0&&(t.data.offsets=JSON.parse(JSON.stringify(n))),null!==r&&(t.data.boundingSphere={center:r.center.toArray(),radius:r.radius}),t},clone:function(){var t=new THREE.BufferGeometry;for(var e in this.attributes){var n=this.attributes[e];t.addAttribute(e,n.clone())}for(var r=0,i=this.offsets.length;i>r;r++){var o=this.offsets[r];t.offsets.push({start:o.start,index:o.index,count:o.count})}return t},dispose:function(){this.dispatchEvent({type:"dispose"})}},THREE.EventDispatcher.prototype.apply(THREE.BufferGeometry.prototype),THREE.Geometry=function(){Object.defineProperty(this,"id",{value:THREE.GeometryIdCount++}),this.uuid=THREE.Math.generateUUID(),this.name="",this.type="Geometry",this.vertices=[],this.colors=[],this.faces=[],this.faceVertexUvs=[[]],this.morphTargets=[],this.morphColors=[],this.morphNormals=[],this.skinWeights=[],this.skinIndices=[],this.lineDistances=[],this.boundingBox=null,this.boundingSphere=null,this.hasTangents=!1,this.dynamic=!0,this.verticesNeedUpdate=!1,this.elementsNeedUpdate=!1,this.uvsNeedUpdate=!1,this.normalsNeedUpdate=!1,this.tangentsNeedUpdate=!1,this.colorsNeedUpdate=!1,this.lineDistancesNeedUpdate=!1,this.groupsNeedUpdate=!1},THREE.Geometry.prototype={constructor:THREE.Geometry,applyMatrix:function(t){for(var e=(new THREE.Matrix3).getNormalMatrix(t),n=0,r=this.vertices.length;r>n;n++){var i=this.vertices[n];i.applyMatrix4(t)}for(var n=0,r=this.faces.length;r>n;n++){var o=this.faces[n];o.normal.applyMatrix3(e).normalize();for(var s=0,a=o.vertexNormals.length;a>s;s++)o.vertexNormals[s].applyMatrix3(e).normalize()}null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this.verticesNeedUpdate=!0,this.normalsNeedUpdate=!0},fromBufferGeometry:function(t){for(var e=this,n=t.attributes,r=n.position.array,i=void 0!==n.index?n.index.array:void 0,o=void 0!==n.normal?n.normal.array:void 0,s=void 0!==n.color?n.color.array:void 0,a=void 0!==n.uv?n.uv.array:void 0,u=[],h=[],l=0,c=0;l0)for(var l=0;lc;c+=3)p(g+i[c],g+i[c+1],g+i[c+2]);else for(var l=0;ln;n++){var i=this.faces[n],o=this.vertices[i.a],s=this.vertices[i.b],a=this.vertices[i.c];t.subVectors(a,s),e.subVectors(o,s),t.cross(e),t.normalize(),i.normal.copy(t)}},computeVertexNormals:function(t){var e,n,r,i,o,s;for(s=new Array(this.vertices.length),e=0,n=this.vertices.length;n>e;e++)s[e]=new THREE.Vector3;if(t){var a,u,h,l=new THREE.Vector3,c=new THREE.Vector3;for(r=0,i=this.faces.length;i>r;r++)o=this.faces[r],a=this.vertices[o.a],u=this.vertices[o.b],h=this.vertices[o.c],l.subVectors(h,u),c.subVectors(a,u),l.cross(c),s[o.a].add(l),s[o.b].add(l),s[o.c].add(l)}else for(r=0,i=this.faces.length;i>r;r++)o=this.faces[r],s[o.a].add(o.normal),s[o.b].add(o.normal),s[o.c].add(o.normal);for(e=0,n=this.vertices.length;n>e;e++)s[e].normalize();for(r=0,i=this.faces.length;i>r;r++)o=this.faces[r],o.vertexNormals[0]=s[o.a].clone(),o.vertexNormals[1]=s[o.b].clone(),o.vertexNormals[2]=s[o.c].clone()},computeMorphNormals:function(){var t,e,n,r,i;for(n=0,r=this.faces.length;r>n;n++)for(i=this.faces[n],i.__originalFaceNormal?i.__originalFaceNormal.copy(i.normal):i.__originalFaceNormal=i.normal.clone(),i.__originalVertexNormals||(i.__originalVertexNormals=[]),t=0,e=i.vertexNormals.length;e>t;t++)i.__originalVertexNormals[t]?i.__originalVertexNormals[t].copy(i.vertexNormals[t]):i.__originalVertexNormals[t]=i.vertexNormals[t].clone();var o=new THREE.Geometry;for(o.faces=this.faces,t=0,e=this.morphTargets.length;e>t;t++){if(!this.morphNormals[t]){this.morphNormals[t]={},this.morphNormals[t].faceNormals=[],this.morphNormals[t].vertexNormals=[];var s,a,u=this.morphNormals[t].faceNormals,h=this.morphNormals[t].vertexNormals;for(n=0,r=this.faces.length;r>n;n++)s=new THREE.Vector3,a={a:new THREE.Vector3,b:new THREE.Vector3,c:new THREE.Vector3},u.push(s),h.push(a)}var l=this.morphNormals[t];o.vertices=this.morphTargets[t].vertices,o.computeFaceNormals(),o.computeVertexNormals();var s,a;for(n=0,r=this.faces.length;r>n;n++)i=this.faces[n],s=l.faceNormals[n],a=l.vertexNormals[n],s.copy(i.normal),a.a.copy(i.vertexNormals[0]),a.b.copy(i.vertexNormals[1]),a.c.copy(i.vertexNormals[2])}for(n=0,r=this.faces.length;r>n;n++)i=this.faces[n],i.normal=i.__originalFaceNormal,i.vertexNormals=i.__originalVertexNormals},computeTangents:function(){function t(t,e,n,r,i,o,s){h=t.vertices[e],l=t.vertices[n],c=t.vertices[r],p=u[i],f=u[o],d=u[s],m=l.x-h.x,v=c.x-h.x,g=l.y-h.y,E=c.y-h.y,y=l.z-h.z,_=c.z-h.z,b=f.x-p.x,T=d.x-p.x,x=f.y-p.y,w=d.y-p.y,R=1/(b*w-T*x),C.set((w*m-x*v)*R,(w*g-x*E)*R,(w*y-x*_)*R),P.set((b*v-T*m)*R,(b*E-T*g)*R,(b*_-T*y)*R),k[e].add(C),k[n].add(C),k[r].add(C),A[e].add(P),A[n].add(P),A[r].add(P)}var e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k=[],A=[],C=new THREE.Vector3,P=new THREE.Vector3,L=new THREE.Vector3,z=new THREE.Vector3,O=new THREE.Vector3;for(r=0,i=this.vertices.length;i>r;r++)k[r]=new THREE.Vector3,A[r]=new THREE.Vector3;for(e=0,n=this.faces.length;n>e;e++)a=this.faces[e],u=this.faceVertexUvs[0][e],t(this,a.a,a.b,a.c,0,1,2);var D=["a","b","c","d"];for(e=0,n=this.faces.length;n>e;e++)for(a=this.faces[e],o=0;oM?-1:1,a.vertexTangents[o]=new THREE.Vector4(L.x,L.y,L.z,S);this.hasTangents=!0},computeLineDistances:function(){for(var t=0,e=this.vertices,n=0,r=e.length;r>n;n++)n>0&&(t+=e[n].distanceTo(e[n-1])),this.lineDistances[n]=t},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new THREE.Box3),this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new THREE.Sphere),this.boundingSphere.setFromPoints(this.vertices)},merge:function(t,e,n){if(t instanceof THREE.Geometry==!1)return void THREE.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",t);var r,i=this.vertices.length,o=this.vertices,s=t.vertices,a=this.faces,u=t.faces,h=this.faceVertexUvs[0],l=t.faceVertexUvs[0];void 0===n&&(n=0),void 0!==e&&(r=(new THREE.Matrix3).getNormalMatrix(e));for(var c=0,p=s.length;p>c;c++){var f=s[c],d=f.clone();void 0!==e&&d.applyMatrix4(e),o.push(d)}for(c=0,p=u.length;p>c;c++){var m,v,g,E=u[c],y=E.vertexNormals,_=E.vertexColors;m=new THREE.Face3(E.a+i,E.b+i,E.c+i),m.normal.copy(E.normal),void 0!==r&&m.normal.applyMatrix3(r).normalize();for(var b=0,T=y.length;T>b;b++)v=y[b].clone(),void 0!==r&&v.applyMatrix3(r).normalize(),m.vertexNormals.push(v);m.color.copy(E.color);for(var b=0,T=_.length;T>b;b++)g=_[b],m.vertexColors.push(g.clone());m.materialIndex=E.materialIndex+n,a.push(m)}for(c=0,p=l.length;p>c;c++){var x=l[c],w=[];if(void 0!==x){for(var b=0,T=x.length;T>b;b++)w.push(x[b].clone());h.push(w)}}},mergeMesh:function(t){return t instanceof THREE.Mesh==!1?void THREE.error("THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.",t):(t.matrixAutoUpdate&&t.updateMatrix(),void this.merge(t.geometry,t.matrix))},mergeVertices:function(){var t,e,n,r,i,o,s,a,u={},h=[],l=[],c=4,p=Math.pow(10,c);for(n=0,r=this.vertices.length;r>n;n++)t=this.vertices[n],e=Math.round(t.x*p)+"_"+Math.round(t.y*p)+"_"+Math.round(t.z*p),void 0===u[e]?(u[e]=n,h.push(this.vertices[n]),l[n]=h.length-1):l[n]=l[u[e]];var f=[];for(n=0,r=this.faces.length;r>n;n++){i=this.faces[n],i.a=l[i.a],i.b=l[i.b],i.c=l[i.c],o=[i.a,i.b,i.c];for(var d=-1,m=0;3>m;m++)if(o[m]==o[(m+1)%3]){d=m,f.push(n);break}}for(n=f.length-1;n>=0;n--){var v=f[n];for(this.faces.splice(v,1),s=0,a=this.faceVertexUvs.length;a>s;s++)this.faceVertexUvs[s].splice(v,1)}var g=this.vertices.length-h.length;return this.vertices=h,g},toJSON:function(){function t(t,e,n){return n?t|1<0,T=g.vertexNormals.length>0,x=1!==g.color.r||1!==g.color.g||1!==g.color.b,w=g.vertexColors.length>0,R=0;if(R=t(R,0,0),R=t(R,1,E),R=t(R,2,y),R=t(R,3,_),R=t(R,4,b),R=t(R,5,T),R=t(R,6,x),R=t(R,7,w),l.push(R),l.push(g.a,g.b,g.c),_){var H=this.faceVertexUvs[0][u];l.push(r(H[0]),r(H[1]),r(H[2]))}if(b&&l.push(e(g.normal)),T){var M=g.vertexNormals;l.push(e(M[0]),e(M[1]),e(M[2]))}if(x&&l.push(n(g.color)),w){var S=g.vertexColors;l.push(n(S[0]),n(S[1]),n(S[2]))}}return i.data={},i.data.vertices=a,i.data.normals=c,f.length>0&&(i.data.colors=f),m.length>0&&(i.data.uvs=[m]),i.data.faces=l,i},clone:function(){for(var t=new THREE.Geometry,e=this.vertices,n=0,r=e.length;r>n;n++)t.vertices.push(e[n].clone());for(var i=this.faces,n=0,r=i.length;r>n;n++)t.faces.push(i[n].clone());for(var n=0,r=this.faceVertexUvs.length;r>n;n++){var o=this.faceVertexUvs[n];void 0===t.faceVertexUvs[n]&&(t.faceVertexUvs[n]=[]);for(var s=0,a=o.length;a>s;s++){for(var u=o[s],h=[],l=0,c=u.length;c>l;l++){var p=u[l];h.push(p.clone())}t.faceVertexUvs[n].push(h)}}return t},dispose:function(){this.dispatchEvent({type:"dispose"})}},THREE.EventDispatcher.prototype.apply(THREE.Geometry.prototype),THREE.GeometryIdCount=0,THREE.Camera=function(){THREE.Object3D.call(this),this.type="Camera",this.matrixWorldInverse=new THREE.Matrix4,this.projectionMatrix=new THREE.Matrix4},THREE.Camera.prototype=Object.create(THREE.Object3D.prototype),THREE.Camera.prototype.constructor=THREE.Camera,THREE.Camera.prototype.getWorldDirection=function(){var t=new THREE.Quaternion;return function(e){var n=e||new THREE.Vector3;return this.getWorldQuaternion(t),n.set(0,0,-1).applyQuaternion(t)}}(),THREE.Camera.prototype.lookAt=function(){var t=new THREE.Matrix4;return function(e){t.lookAt(this.position,e,this.up),this.quaternion.setFromRotationMatrix(t)}}(),THREE.Camera.prototype.clone=function(t){return void 0===t&&(t=new THREE.Camera),THREE.Object3D.prototype.clone.call(this,t),t.matrixWorldInverse.copy(this.matrixWorldInverse),t.projectionMatrix.copy(this.projectionMatrix),t},THREE.CubeCamera=function(t,e,n){THREE.Object3D.call(this),this.type="CubeCamera";var r=90,i=1,o=new THREE.PerspectiveCamera(r,i,t,e);o.up.set(0,-1,0),o.lookAt(new THREE.Vector3(1,0,0)),this.add(o);var s=new THREE.PerspectiveCamera(r,i,t,e);s.up.set(0,-1,0),s.lookAt(new THREE.Vector3(-1,0,0)),this.add(s);var a=new THREE.PerspectiveCamera(r,i,t,e);a.up.set(0,0,1),a.lookAt(new THREE.Vector3(0,1,0)),this.add(a);var u=new THREE.PerspectiveCamera(r,i,t,e);u.up.set(0,0,-1),u.lookAt(new THREE.Vector3(0,-1,0)),this.add(u);var h=new THREE.PerspectiveCamera(r,i,t,e);h.up.set(0,-1,0),h.lookAt(new THREE.Vector3(0,0,1)),this.add(h);var l=new THREE.PerspectiveCamera(r,i,t,e);l.up.set(0,-1,0),l.lookAt(new THREE.Vector3(0,0,-1)),this.add(l),this.renderTarget=new THREE.WebGLRenderTargetCube(n,n,{format:THREE.RGBFormat,magFilter:THREE.LinearFilter,minFilter:THREE.LinearFilter}),this.updateCubeMap=function(t,e){var n=this.renderTarget,r=n.generateMipmaps;n.generateMipmaps=!1,n.activeCubeFace=0,t.render(e,o,n),n.activeCubeFace=1,t.render(e,s,n),n.activeCubeFace=2,t.render(e,a,n),n.activeCubeFace=3,t.render(e,u,n),n.activeCubeFace=4,t.render(e,h,n),n.generateMipmaps=r,n.activeCubeFace=5,t.render(e,l,n)}},THREE.CubeCamera.prototype=Object.create(THREE.Object3D.prototype),THREE.CubeCamera.prototype.constructor=THREE.CubeCamera,THREE.OrthographicCamera=function(t,e,n,r,i,o){THREE.Camera.call(this),this.type="OrthographicCamera",this.zoom=1,this.left=t,this.right=e,this.top=n,this.bottom=r,this.near=void 0!==i?i:.1,this.far=void 0!==o?o:2e3,this.updateProjectionMatrix()},THREE.OrthographicCamera.prototype=Object.create(THREE.Camera.prototype),THREE.OrthographicCamera.prototype.constructor=THREE.OrthographicCamera,THREE.OrthographicCamera.prototype.updateProjectionMatrix=function(){var t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2;this.projectionMatrix.makeOrthographic(n-t,n+t,r+e,r-e,this.near,this.far)},THREE.OrthographicCamera.prototype.clone=function(){var t=new THREE.OrthographicCamera;return THREE.Camera.prototype.clone.call(this,t),t.zoom=this.zoom,t.left=this.left,t.right=this.right,t.top=this.top,t.bottom=this.bottom,t.near=this.near,t.far=this.far,t.projectionMatrix.copy(this.projectionMatrix),t},THREE.PerspectiveCamera=function(t,e,n,r){THREE.Camera.call(this),this.type="PerspectiveCamera",this.zoom=1,this.fov=void 0!==t?t:50,this.aspect=void 0!==e?e:1,this.near=void 0!==n?n:.1,this.far=void 0!==r?r:2e3,this.updateProjectionMatrix()},THREE.PerspectiveCamera.prototype=Object.create(THREE.Camera.prototype),THREE.PerspectiveCamera.prototype.constructor=THREE.PerspectiveCamera,THREE.PerspectiveCamera.prototype.setLens=function(t,e){void 0===e&&(e=24),this.fov=2*THREE.Math.radToDeg(Math.atan(e/(2*t))),this.updateProjectionMatrix()},THREE.PerspectiveCamera.prototype.setViewOffset=function(t,e,n,r,i,o){this.fullWidth=t,this.fullHeight=e,this.x=n,this.y=r,this.width=i,this.height=o,this.updateProjectionMatrix()},THREE.PerspectiveCamera.prototype.updateProjectionMatrix=function(){var t=THREE.Math.radToDeg(2*Math.atan(Math.tan(.5*THREE.Math.degToRad(this.fov))/this.zoom));if(this.fullWidth){var e=this.fullWidth/this.fullHeight,n=Math.tan(THREE.Math.degToRad(.5*t))*this.near,r=-n,i=e*r,o=e*n,s=Math.abs(o-i),a=Math.abs(n-r);this.projectionMatrix.makeFrustum(i+this.x*s/this.fullWidth,i+(this.x+this.width)*s/this.fullWidth,n-(this.y+this.height)*a/this.fullHeight,n-this.y*a/this.fullHeight,this.near,this.far)}else this.projectionMatrix.makePerspective(t,this.aspect,this.near,this.far)},THREE.PerspectiveCamera.prototype.clone=function(){var t=new THREE.PerspectiveCamera;return THREE.Camera.prototype.clone.call(this,t),t.zoom=this.zoom,t.fov=this.fov,t.aspect=this.aspect,t.near=this.near,t.far=this.far,t.projectionMatrix.copy(this.projectionMatrix),t},THREE.Light=function(t){THREE.Object3D.call(this),this.type="Light",this.color=new THREE.Color(t)},THREE.Light.prototype=Object.create(THREE.Object3D.prototype),THREE.Light.prototype.constructor=THREE.Light,THREE.Light.prototype.clone=function(t){return void 0===t&&(t=new THREE.Light),THREE.Object3D.prototype.clone.call(this,t),t.color.copy(this.color),t},THREE.AmbientLight=function(t){THREE.Light.call(this,t),this.type="AmbientLight"},THREE.AmbientLight.prototype=Object.create(THREE.Light.prototype),THREE.AmbientLight.prototype.constructor=THREE.AmbientLight,THREE.AmbientLight.prototype.clone=function(){var t=new THREE.AmbientLight;return THREE.Light.prototype.clone.call(this,t),t},THREE.AreaLight=function(t,e){THREE.Light.call(this,t),this.type="AreaLight",this.normal=new THREE.Vector3(0,-1,0),this.right=new THREE.Vector3(1,0,0),this.intensity=void 0!==e?e:1,this.width=1,this.height=1,this.constantAttenuation=1.5,this.linearAttenuation=.5,this.quadraticAttenuation=.1},THREE.AreaLight.prototype=Object.create(THREE.Light.prototype),THREE.AreaLight.prototype.constructor=THREE.AreaLight,THREE.DirectionalLight=function(t,e){THREE.Light.call(this,t),this.type="DirectionalLight",this.position.set(0,1,0),this.target=new THREE.Object3D,this.intensity=void 0!==e?e:1,this.castShadow=!1,this.onlyShadow=!1,this.shadowCameraNear=50,this.shadowCameraFar=5e3,this.shadowCameraLeft=-500,this.shadowCameraRight=500,this.shadowCameraTop=500,this.shadowCameraBottom=-500,this.shadowCameraVisible=!1,this.shadowBias=0,this.shadowDarkness=.5,this.shadowMapWidth=512,this.shadowMapHeight=512,this.shadowCascade=!1,this.shadowCascadeOffset=new THREE.Vector3(0,0,-1e3),this.shadowCascadeCount=2,this.shadowCascadeBias=[0,0,0],this.shadowCascadeWidth=[512,512,512],this.shadowCascadeHeight=[512,512,512],this.shadowCascadeNearZ=[-1,.99,.998],this.shadowCascadeFarZ=[.99,.998,1],this.shadowCascadeArray=[],this.shadowMap=null,this.shadowMapSize=null,this.shadowCamera=null,this.shadowMatrix=null},THREE.DirectionalLight.prototype=Object.create(THREE.Light.prototype),THREE.DirectionalLight.prototype.constructor=THREE.DirectionalLight,THREE.DirectionalLight.prototype.clone=function(){var t=new THREE.DirectionalLight;return THREE.Light.prototype.clone.call(this,t),t.target=this.target.clone(),t.intensity=this.intensity,t.castShadow=this.castShadow,t.onlyShadow=this.onlyShadow,t.shadowCameraNear=this.shadowCameraNear,t.shadowCameraFar=this.shadowCameraFar,t.shadowCameraLeft=this.shadowCameraLeft,t.shadowCameraRight=this.shadowCameraRight,t.shadowCameraTop=this.shadowCameraTop,t.shadowCameraBottom=this.shadowCameraBottom,t.shadowCameraVisible=this.shadowCameraVisible,t.shadowBias=this.shadowBias,t.shadowDarkness=this.shadowDarkness,t.shadowMapWidth=this.shadowMapWidth,t.shadowMapHeight=this.shadowMapHeight,t.shadowCascade=this.shadowCascade,t.shadowCascadeOffset.copy(this.shadowCascadeOffset),t.shadowCascadeCount=this.shadowCascadeCount,t.shadowCascadeBias=this.shadowCascadeBias.slice(0),t.shadowCascadeWidth=this.shadowCascadeWidth.slice(0),t.shadowCascadeHeight=this.shadowCascadeHeight.slice(0),t.shadowCascadeNearZ=this.shadowCascadeNearZ.slice(0),t.shadowCascadeFarZ=this.shadowCascadeFarZ.slice(0),t},THREE.HemisphereLight=function(t,e,n){THREE.Light.call(this,t),this.type="HemisphereLight",this.position.set(0,100,0),this.groundColor=new THREE.Color(e),this.intensity=void 0!==n?n:1},THREE.HemisphereLight.prototype=Object.create(THREE.Light.prototype),THREE.HemisphereLight.prototype.constructor=THREE.HemisphereLight,THREE.HemisphereLight.prototype.clone=function(){var t=new THREE.HemisphereLight;return THREE.Light.prototype.clone.call(this,t),t.groundColor.copy(this.groundColor),t.intensity=this.intensity,t},THREE.PointLight=function(t,e,n,r){THREE.Light.call(this,t),this.type="PointLight",this.intensity=void 0!==e?e:1,this.distance=void 0!==n?n:0,this.decay=void 0!==r?r:1},THREE.PointLight.prototype=Object.create(THREE.Light.prototype),THREE.PointLight.prototype.constructor=THREE.PointLight,THREE.PointLight.prototype.clone=function(){var t=new THREE.PointLight;return THREE.Light.prototype.clone.call(this,t),t.intensity=this.intensity,t.distance=this.distance,t.decay=this.decay,t},THREE.SpotLight=function(t,e,n,r,i,o){THREE.Light.call(this,t),this.type="SpotLight",this.position.set(0,1,0),this.target=new THREE.Object3D,this.intensity=void 0!==e?e:1,this.distance=void 0!==n?n:0,this.angle=void 0!==r?r:Math.PI/3,this.exponent=void 0!==i?i:10,this.decay=void 0!==o?o:1,this.castShadow=!1,this.onlyShadow=!1,this.shadowCameraNear=50,this.shadowCameraFar=5e3,this.shadowCameraFov=50,this.shadowCameraVisible=!1,this.shadowBias=0,this.shadowDarkness=.5,this.shadowMapWidth=512,this.shadowMapHeight=512,this.shadowMap=null,this.shadowMapSize=null,this.shadowCamera=null,this.shadowMatrix=null},THREE.SpotLight.prototype=Object.create(THREE.Light.prototype),THREE.SpotLight.prototype.constructor=THREE.SpotLight,THREE.SpotLight.prototype.clone=function(){var t=new THREE.SpotLight;return THREE.Light.prototype.clone.call(this,t),t.target=this.target.clone(),t.intensity=this.intensity,t.distance=this.distance,t.angle=this.angle,t.exponent=this.exponent,t.decay=this.decay,t.castShadow=this.castShadow,t.onlyShadow=this.onlyShadow,t.shadowCameraNear=this.shadowCameraNear,t.shadowCameraFar=this.shadowCameraFar,t.shadowCameraFov=this.shadowCameraFov,t.shadowCameraVisible=this.shadowCameraVisible,t.shadowBias=this.shadowBias,t.shadowDarkness=this.shadowDarkness,t.shadowMapWidth=this.shadowMapWidth,t.shadowMapHeight=this.shadowMapHeight,t},THREE.Cache={files:{},add:function(t,e){this.files[t]=e},get:function(t){return this.files[t]},remove:function(t){delete this.files[t]},clear:function(){this.files={}}},THREE.Loader=function(t){this.showStatus=t,this.statusDomElement=t?THREE.Loader.prototype.addStatusElement():null,this.imageLoader=new THREE.ImageLoader,this.onLoadStart=function(){},this.onLoadProgress=function(){},this.onLoadComplete=function(){}},THREE.Loader.prototype={constructor:THREE.Loader,crossOrigin:void 0,addStatusElement:function(){var t=document.createElement("div");return t.style.position="absolute",t.style.right="0px",t.style.top="0px",t.style.fontSize="0.8em",t.style.textAlign="left",t.style.background="rgba(0,0,0,0.25)",t.style.color="#fff",t.style.width="120px",t.style.padding="0.5em 0.5em 0.5em 0.5em",t.style.zIndex=1e3,t.innerHTML="Loading ...",t},updateProgress:function(t){var e="Loaded ";e+=t.total?(100*t.loaded/t.total).toFixed(0)+"%":(t.loaded/1024).toFixed(2)+" KB",this.statusDomElement.innerHTML=e},extractUrlBase:function(t){var e=t.split("/");return 1===e.length?"./":(e.pop(),e.join("/")+"/")},initMaterials:function(t,e){for(var n=[],r=0;re;e++){var r=t[e];if(r instanceof THREE.ShaderMaterial)return!0}return!1},createMaterial:function(t,e){function n(t){var e=Math.log(t)/Math.LN2;return Math.pow(2,Math.round(e))}function r(t,r,i,s,a,u,h){var l,c=e+i,p=THREE.Loader.Handlers.get(c);if(null!==p?l=p.load(c):(l=new THREE.Texture,p=o.imageLoader,p.crossOrigin=o.crossOrigin,p.load(c,function(t){if(THREE.Math.isPowerOfTwo(t.width)===!1||THREE.Math.isPowerOfTwo(t.height)===!1){var e=n(t.width),r=n(t.height),i=document.createElement("canvas");i.width=e,i.height=r;var o=i.getContext("2d");o.drawImage(t,0,0,e,r),l.image=i}else l.image=t;l.needsUpdate=!0})),l.sourceFile=i,s&&(l.repeat.set(s[0],s[1]),1!==s[0]&&(l.wrapS=THREE.RepeatWrapping),1!==s[1]&&(l.wrapT=THREE.RepeatWrapping)),a&&l.offset.set(a[0],a[1]),u){var f={repeat:THREE.RepeatWrapping,mirror:THREE.MirroredRepeatWrapping};void 0!==f[u[0]]&&(l.wrapS=f[u[0]]),void 0!==f[u[1]]&&(l.wrapT=f[u[1]])}h&&(l.anisotropy=h),t[r]=l}function i(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]}var o=this,s="MeshLambertMaterial",a={color:15658734,opacity:1,map:null,lightMap:null,normalMap:null,bumpMap:null,wireframe:!1};if(t.shading){var u=t.shading.toLowerCase();"phong"===u?s="MeshPhongMaterial":"basic"===u&&(s="MeshBasicMaterial")}void 0!==t.blending&&void 0!==THREE[t.blending]&&(a.blending=THREE[t.blending]),void 0!==t.transparent&&(a.transparent=t.transparent),void 0!==t.opacity&&t.opacity<1&&(a.transparent=!0),void 0!==t.depthTest&&(a.depthTest=t.depthTest),void 0!==t.depthWrite&&(a.depthWrite=t.depthWrite),void 0!==t.visible&&(a.visible=t.visible),void 0!==t.flipSided&&(a.side=THREE.BackSide),void 0!==t.doubleSided&&(a.side=THREE.DoubleSide),void 0!==t.wireframe&&(a.wireframe=t.wireframe),void 0!==t.vertexColors&&("face"===t.vertexColors?a.vertexColors=THREE.FaceColors:t.vertexColors&&(a.vertexColors=THREE.VertexColors)),t.colorDiffuse?a.color=i(t.colorDiffuse):t.DbgColor&&(a.color=t.DbgColor),t.colorSpecular&&(a.specular=i(t.colorSpecular)),t.colorEmissive&&(a.emissive=i(t.colorEmissive)),void 0!==t.transparency&&(console.warn("THREE.Loader: transparency has been renamed to opacity"),t.opacity=t.transparency),void 0!==t.opacity&&(a.opacity=t.opacity),t.specularCoef&&(a.shininess=t.specularCoef),t.mapDiffuse&&e&&r(a,"map",t.mapDiffuse,t.mapDiffuseRepeat,t.mapDiffuseOffset,t.mapDiffuseWrap,t.mapDiffuseAnisotropy),t.mapLight&&e&&r(a,"lightMap",t.mapLight,t.mapLightRepeat,t.mapLightOffset,t.mapLightWrap,t.mapLightAnisotropy),t.mapBump&&e&&r(a,"bumpMap",t.mapBump,t.mapBumpRepeat,t.mapBumpOffset,t.mapBumpWrap,t.mapBumpAnisotropy),t.mapNormal&&e&&r(a,"normalMap",t.mapNormal,t.mapNormalRepeat,t.mapNormalOffset,t.mapNormalWrap,t.mapNormalAnisotropy),t.mapSpecular&&e&&r(a,"specularMap",t.mapSpecular,t.mapSpecularRepeat,t.mapSpecularOffset,t.mapSpecularWrap,t.mapSpecularAnisotropy),t.mapAlpha&&e&&r(a,"alphaMap",t.mapAlpha,t.mapAlphaRepeat,t.mapAlphaOffset,t.mapAlphaWrap,t.mapAlphaAnisotropy),t.mapBumpScale&&(a.bumpScale=t.mapBumpScale),t.mapNormalFactor&&(a.normalScale=new THREE.Vector2(t.mapNormalFactor,t.mapNormalFactor));var h=new THREE[s](a);return void 0!==t.DbgName&&(h.name=t.DbgName),h}},THREE.Loader.Handlers={handlers:[],add:function(t,e){this.handlers.push(t,e)},get:function(t){for(var e=0,n=this.handlers.length;n>e;e+=2){var r=this.handlers[e],i=this.handlers[e+1];if(r.test(t))return i}return null}},THREE.XHRLoader=function(t){this.manager=void 0!==t?t:THREE.DefaultLoadingManager},THREE.XHRLoader.prototype={constructor:THREE.XHRLoader,load:function(t,e,n,r){var i=this,o=THREE.Cache.get(t);if(void 0!==o)return void(e&&e(o));var s=new XMLHttpRequest;s.open("GET",t,!0),s.addEventListener("load",function(n){THREE.Cache.add(t,this.response),e&&e(this.response),i.manager.itemEnd(t)},!1),void 0!==n&&s.addEventListener("progress",function(t){n(t)},!1),void 0!==r&&s.addEventListener("error",function(t){r(t)},!1),void 0!==this.crossOrigin&&(s.crossOrigin=this.crossOrigin),void 0!==this.responseType&&(s.responseType=this.responseType),s.send(null),i.manager.itemStart(t)},setResponseType:function(t){this.responseType=t},setCrossOrigin:function(t){this.crossOrigin=t}},THREE.ImageLoader=function(t){this.manager=void 0!==t?t:THREE.DefaultLoadingManager},THREE.ImageLoader.prototype={constructor:THREE.ImageLoader,load:function(t,e,n,r){var i=this,o=THREE.Cache.get(t);if(void 0!==o)return void e(o);var s=document.createElement("img");return s.addEventListener("load",function(n){THREE.Cache.add(t,this),e&&e(this),i.manager.itemEnd(t)},!1),void 0!==n&&s.addEventListener("progress",function(t){n(t)},!1),void 0!==r&&s.addEventListener("error",function(t){r(t)},!1),void 0!==this.crossOrigin&&(s.crossOrigin=this.crossOrigin),s.src=t,i.manager.itemStart(t),s},setCrossOrigin:function(t){this.crossOrigin=t}},THREE.JSONLoader=function(t){THREE.Loader.call(this,t),this.withCredentials=!1},THREE.JSONLoader.prototype=Object.create(THREE.Loader.prototype),THREE.JSONLoader.prototype.constructor=THREE.JSONLoader,THREE.JSONLoader.prototype.load=function(t,e,n){n=n&&"string"==typeof n?n:this.extractUrlBase(t),this.onLoadStart(),this.loadAjaxJSON(this,t,e,n)},THREE.JSONLoader.prototype.loadAjaxJSON=function(t,e,n,r,i){var o=new XMLHttpRequest,s=0;o.onreadystatechange=function(){if(o.readyState===o.DONE)if(200===o.status||0===o.status){if(o.responseText){var a=JSON.parse(o.responseText),u=a.metadata;if(void 0!==u){if("object"===u.type)return void THREE.error("THREE.JSONLoader: "+e+" should be loaded with THREE.ObjectLoader instead.");if("scene"===u.type)return void THREE.error("THREE.JSONLoader: "+e+" seems to be a Scene. Use THREE.SceneLoader instead.")}var h=t.parse(a,r);n(h.geometry,h.materials)}else THREE.error("THREE.JSONLoader: "+e+" seems to be unreachable or the file is empty.");t.onLoadComplete()}else THREE.error("THREE.JSONLoader: Couldn't load "+e+" ("+o.status+")");else o.readyState===o.LOADING?i&&(0===s&&(s=o.getResponseHeader("Content-Length")),i({total:s,loaded:o.responseText.length})):o.readyState===o.HEADERS_RECEIVED&&void 0!==i&&(s=o.getResponseHeader("Content-Length"))},o.open("GET",e,!0),o.withCredentials=this.withCredentials,o.send(null)},THREE.JSONLoader.prototype.parse=function(t,e){function n(e){function n(t,e){return t&1<r;r++)o.faceVertexUvs[r]=[]}for(a=0,u=P.length;u>a;)b=new THREE.Vector3,b.x=P[a++]*e,b.y=P[a++]*e,b.z=P[a++]*e,o.vertices.push(b);for(a=0,u=C.length;u>a;)if(f=C[a++],d=n(f,0),m=n(f,1),v=n(f,3),g=n(f,4),E=n(f,5),y=n(f,6),_=n(f,7),d){if(x=new THREE.Face3,x.a=C[a],x.b=C[a+1],x.c=C[a+3],w=new THREE.Face3,w.a=C[a+1],w.b=C[a+2],w.c=C[a+3],a+=4,m&&(p=C[a++],x.materialIndex=p,w.materialIndex=p),s=o.faces.length,v)for(r=0;O>r;r++)for(M=t.uvs[r],o.faceVertexUvs[r][s]=[],o.faceVertexUvs[r][s+1]=[],i=0;4>i;i++)c=C[a++],k=M[2*c],A=M[2*c+1],S=new THREE.Vector2(k,A),2!==i&&o.faceVertexUvs[r][s].push(S),0!==i&&o.faceVertexUvs[r][s+1].push(S);if(g&&(l=3*C[a++],x.normal.set(L[l++],L[l++],L[l]),w.normal.copy(x.normal)),E)for(r=0;4>r;r++)l=3*C[a++],H=new THREE.Vector3(L[l++],L[l++],L[l]),2!==r&&x.vertexNormals.push(H),0!==r&&w.vertexNormals.push(H);if(y&&(h=C[a++],R=z[h],x.color.setHex(R),w.color.setHex(R)),_)for(r=0;4>r;r++)h=C[a++],R=z[h],2!==r&&x.vertexColors.push(new THREE.Color(R)),0!==r&&w.vertexColors.push(new THREE.Color(R));o.faces.push(x),o.faces.push(w)}else{if(T=new THREE.Face3,T.a=C[a++],T.b=C[a++],T.c=C[a++],m&&(p=C[a++],T.materialIndex=p),s=o.faces.length,v)for(r=0;O>r;r++)for(M=t.uvs[r],o.faceVertexUvs[r][s]=[],i=0;3>i;i++)c=C[a++],k=M[2*c],A=M[2*c+1],S=new THREE.Vector2(k,A),o.faceVertexUvs[r][s].push(S);if(g&&(l=3*C[a++],T.normal.set(L[l++],L[l++],L[l])),E)for(r=0;3>r;r++)l=3*C[a++],H=new THREE.Vector3(L[l++],L[l++],L[l]),T.vertexNormals.push(H);if(y&&(h=C[a++],T.color.setHex(z[h])),_)for(r=0;3>r;r++)h=C[a++],T.vertexColors.push(new THREE.Color(z[h]));o.faces.push(T)}}function r(){var e=void 0!==t.influencesPerVertex?t.influencesPerVertex:2;if(t.skinWeights)for(var n=0,r=t.skinWeights.length;r>n;n+=e){var i=t.skinWeights[n],s=e>1?t.skinWeights[n+1]:0,a=e>2?t.skinWeights[n+2]:0,u=e>3?t.skinWeights[n+3]:0;o.skinWeights.push(new THREE.Vector4(i,s,a,u))}if(t.skinIndices)for(var n=0,r=t.skinIndices.length;r>n;n+=e){var h=t.skinIndices[n],l=e>1?t.skinIndices[n+1]:0,c=e>2?t.skinIndices[n+2]:0,p=e>3?t.skinIndices[n+3]:0;o.skinIndices.push(new THREE.Vector4(h,l,c,p))}o.bones=t.bones,o.bones&&o.bones.length>0&&(o.skinWeights.length!==o.skinIndices.length||o.skinIndices.length!==o.vertices.length)&&THREE.warn("THREE.JSONLoader: When skinning, number of vertices ("+o.vertices.length+"), skinIndices ("+o.skinIndices.length+"), and skinWeights ("+o.skinWeights.length+") should match."),o.animation=t.animation,o.animations=t.animations}function i(e){if(void 0!==t.morphTargets){var n,r,i,s,a,u;for(n=0,r=t.morphTargets.length;r>n;n++)for(o.morphTargets[n]={},o.morphTargets[n].name=t.morphTargets[n].name,o.morphTargets[n].vertices=[],a=o.morphTargets[n].vertices,u=t.morphTargets[n].vertices,i=0,s=u.length;s>i;i+=3){var h=new THREE.Vector3;h.x=u[i]*e,h.y=u[i+1]*e,h.z=u[i+2]*e,a.push(h)}}if(void 0!==t.morphColors){var n,r,l,c,p,f,d;for(n=0,r=t.morphColors.length;r>n;n++)for(o.morphColors[n]={}, +o.morphColors[n].name=t.morphColors[n].name,o.morphColors[n].colors=[],p=o.morphColors[n].colors,f=t.morphColors[n].colors,l=0,c=f.length;c>l;l+=3)d=new THREE.Color(16755200),d.setRGB(f[l],f[l+1],f[l+2]),p.push(d)}}var o=new THREE.Geometry,s=void 0!==t.scale?1/t.scale:1;if(n(s),r(),i(s),o.computeFaceNormals(),o.computeBoundingSphere(),void 0===t.materials||0===t.materials.length)return{geometry:o};var a=this.initMaterials(t.materials,e);return this.needsTangents(a)&&o.computeTangents(),{geometry:o,materials:a}},THREE.LoadingManager=function(t,e,n){var r=this,i=0,o=0;this.onLoad=t,this.onProgress=e,this.onError=n,this.itemStart=function(t){o++},this.itemEnd=function(t){i++,void 0!==r.onProgress&&r.onProgress(t,i,o),i===o&&void 0!==r.onLoad&&r.onLoad()}},THREE.DefaultLoadingManager=new THREE.LoadingManager,THREE.BufferGeometryLoader=function(t){this.manager=void 0!==t?t:THREE.DefaultLoadingManager},THREE.BufferGeometryLoader.prototype={constructor:THREE.BufferGeometryLoader,load:function(t,e,n,r){var i=this,o=new THREE.XHRLoader(i.manager);o.setCrossOrigin(this.crossOrigin),o.load(t,function(t){e(i.parse(JSON.parse(t)))},n,r)},setCrossOrigin:function(t){this.crossOrigin=t},parse:function(t){var e=new THREE.BufferGeometry,n=t.data.attributes;for(var r in n){var i=n[r],o=new self[i.type](i.array);e.addAttribute(r,new THREE.BufferAttribute(o,i.itemSize))}var s=t.data.offsets;void 0!==s&&(e.offsets=JSON.parse(JSON.stringify(s)));var a=t.data.boundingSphere;if(void 0!==a){var u=new THREE.Vector3;void 0!==a.center&&u.fromArray(a.center),e.boundingSphere=new THREE.Sphere(u,a.radius)}return e}},THREE.MaterialLoader=function(t){this.manager=void 0!==t?t:THREE.DefaultLoadingManager},THREE.MaterialLoader.prototype={constructor:THREE.MaterialLoader,load:function(t,e,n,r){var i=this,o=new THREE.XHRLoader(i.manager);o.setCrossOrigin(this.crossOrigin),o.load(t,function(t){e(i.parse(JSON.parse(t)))},n,r)},setCrossOrigin:function(t){this.crossOrigin=t},parse:function(t){var e=new THREE[t.type];if(void 0!==t.color&&e.color.setHex(t.color),void 0!==t.emissive&&e.emissive.setHex(t.emissive),void 0!==t.specular&&e.specular.setHex(t.specular),void 0!==t.shininess&&(e.shininess=t.shininess),void 0!==t.uniforms&&(e.uniforms=t.uniforms),void 0!==t.vertexShader&&(e.vertexShader=t.vertexShader),void 0!==t.fragmentShader&&(e.fragmentShader=t.fragmentShader),void 0!==t.vertexColors&&(e.vertexColors=t.vertexColors),void 0!==t.shading&&(e.shading=t.shading),void 0!==t.blending&&(e.blending=t.blending),void 0!==t.side&&(e.side=t.side),void 0!==t.opacity&&(e.opacity=t.opacity),void 0!==t.transparent&&(e.transparent=t.transparent),void 0!==t.wireframe&&(e.wireframe=t.wireframe),void 0!==t.size&&(e.size=t.size),void 0!==t.sizeAttenuation&&(e.sizeAttenuation=t.sizeAttenuation),void 0!==t.materials)for(var n=0,r=t.materials.length;r>n;n++)e.materials.push(this.parse(t.materials[n]));return e}},THREE.ObjectLoader=function(t){this.manager=void 0!==t?t:THREE.DefaultLoadingManager,this.texturePath=""},THREE.ObjectLoader.prototype={constructor:THREE.ObjectLoader,load:function(t,e,n,r){""===this.texturePath&&(this.texturePath=t.substring(0,t.lastIndexOf("/")+1));var i=this,o=new THREE.XHRLoader(i.manager);o.setCrossOrigin(this.crossOrigin),o.load(t,function(t){i.parse(JSON.parse(t),e)},n,r)},setTexturePath:function(t){this.texturePath=t},setCrossOrigin:function(t){this.crossOrigin=t},parse:function(t,e){var n=this.parseGeometries(t.geometries),r=this.parseImages(t.images,function(){void 0!==e&&e(s)}),i=this.parseTextures(t.textures,r),o=this.parseMaterials(t.materials,i),s=this.parseObject(t.object,n,o);return(void 0===t.images||0===t.images.length)&&void 0!==e&&e(s),s},parseGeometries:function(t){var e={};if(void 0!==t)for(var n=new THREE.JSONLoader,r=new THREE.BufferGeometryLoader,i=0,o=t.length;o>i;i++){var s,a=t[i];switch(a.type){case"PlaneGeometry":case"PlaneBufferGeometry":s=new THREE[a.type](a.width,a.height,a.widthSegments,a.heightSegments);break;case"BoxGeometry":case"CubeGeometry":s=new THREE.BoxGeometry(a.width,a.height,a.depth,a.widthSegments,a.heightSegments,a.depthSegments);break;case"CircleGeometry":s=new THREE.CircleGeometry(a.radius,a.segments);break;case"CylinderGeometry":s=new THREE.CylinderGeometry(a.radiusTop,a.radiusBottom,a.height,a.radialSegments,a.heightSegments,a.openEnded);break;case"SphereGeometry":s=new THREE.SphereGeometry(a.radius,a.widthSegments,a.heightSegments,a.phiStart,a.phiLength,a.thetaStart,a.thetaLength);break;case"IcosahedronGeometry":s=new THREE.IcosahedronGeometry(a.radius,a.detail);break;case"TorusGeometry":s=new THREE.TorusGeometry(a.radius,a.tube,a.radialSegments,a.tubularSegments,a.arc);break;case"TorusKnotGeometry":s=new THREE.TorusKnotGeometry(a.radius,a.tube,a.radialSegments,a.tubularSegments,a.p,a.q,a.heightScale);break;case"BufferGeometry":s=r.parse(a);break;case"Geometry":s=n.parse(a.data).geometry}s.uuid=a.uuid,void 0!==a.name&&(s.name=a.name),e[a.uuid]=s}return e},parseMaterials:function(t,e){var n={};if(void 0!==t)for(var r=function(t){return void 0===e[t]&&THREE.warn("THREE.ObjectLoader: Undefined texture",t),e[t]},i=new THREE.MaterialLoader,o=0,s=t.length;s>o;o++){var a=t[o],u=i.parse(a);u.uuid=a.uuid,void 0!==a.name&&(u.name=a.name),void 0!==a.map&&(u.map=r(a.map)),void 0!==a.bumpMap&&(u.bumpMap=r(a.bumpMap),a.bumpScale&&(u.bumpScale=new THREE.Vector2(a.bumpScale,a.bumpScale))),void 0!==a.alphaMap&&(u.alphaMap=r(a.alphaMap)),void 0!==a.envMap&&(u.envMap=r(a.envMap)),void 0!==a.normalMap&&(u.normalMap=r(a.normalMap),a.normalScale&&(u.normalScale=new THREE.Vector2(a.normalScale,a.normalScale))),void 0!==a.lightMap&&(u.lightMap=r(a.lightMap)),void 0!==a.specularMap&&(u.specularMap=r(a.specularMap)),n[a.uuid]=u}return n},parseImages:function(t,e){var n=this,r={};if(void 0!==t&&t.length>0){var i=new THREE.LoadingManager(e),o=new THREE.ImageLoader(i);o.setCrossOrigin(this.crossOrigin);for(var s=function(t){return n.manager.itemStart(t),o.load(t,function(){n.manager.itemEnd(t)})},a=0,u=t.length;u>a;a++){var h=t[a],l=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(h.url)?h.url:n.texturePath+h.url;r[h.uuid]=s(l)}}return r},parseTextures:function(t,e){var n={};if(void 0!==t)for(var r=0,i=t.length;i>r;r++){var o=t[r];void 0===o.image&&THREE.warn('THREE.ObjectLoader: No "image" speficied for',o.uuid),void 0===e[o.image]&&THREE.warn("THREE.ObjectLoader: Undefined image",o.image);var s=new THREE.Texture(e[o.image]);s.needsUpdate=!0,s.uuid=o.uuid,void 0!==o.name&&(s.name=o.name),void 0!==o.repeat&&(s.repeat=new THREE.Vector2(o.repeat[0],o.repeat[1])),void 0!==o.minFilter&&(s.minFilter=THREE[o.minFilter]),void 0!==o.magFilter&&(s.magFilter=THREE[o.magFilter]),void 0!==o.anisotropy&&(s.anisotropy=o.anisotropy),o.wrap instanceof Array&&(s.wrapS=THREE[o.wrap[0]],s.wrapT=THREE[o.wrap[1]]),n[o.uuid]=s}return n},parseObject:function(){var t=new THREE.Matrix4;return function(e,n,r){var i,o=function(t){return void 0===n[t]&&THREE.warn("THREE.ObjectLoader: Undefined geometry",t),n[t]},s=function(t){return void 0===r[t]&&THREE.warn("THREE.ObjectLoader: Undefined material",t),r[t]};switch(e.type){case"Scene":i=new THREE.Scene;break;case"PerspectiveCamera":i=new THREE.PerspectiveCamera(e.fov,e.aspect,e.near,e.far);break;case"OrthographicCamera":i=new THREE.OrthographicCamera(e.left,e.right,e.top,e.bottom,e.near,e.far);break;case"AmbientLight":i=new THREE.AmbientLight(e.color);break;case"DirectionalLight":i=new THREE.DirectionalLight(e.color,e.intensity);break;case"PointLight":i=new THREE.PointLight(e.color,e.intensity,e.distance,e.decay);break;case"SpotLight":i=new THREE.SpotLight(e.color,e.intensity,e.distance,e.angle,e.exponent,e.decay);break;case"HemisphereLight":i=new THREE.HemisphereLight(e.color,e.groundColor,e.intensity);break;case"Mesh":i=new THREE.Mesh(o(e.geometry),s(e.material));break;case"Line":i=new THREE.Line(o(e.geometry),s(e.material),e.mode);break;case"PointCloud":i=new THREE.PointCloud(o(e.geometry),s(e.material));break;case"Sprite":i=new THREE.Sprite(s(e.material));break;case"Group":i=new THREE.Group;break;default:i=new THREE.Object3D}if(i.uuid=e.uuid,void 0!==e.name&&(i.name=e.name),void 0!==e.matrix?(t.fromArray(e.matrix),t.decompose(i.position,i.quaternion,i.scale)):(void 0!==e.position&&i.position.fromArray(e.position),void 0!==e.rotation&&i.rotation.fromArray(e.rotation),void 0!==e.scale&&i.scale.fromArray(e.scale)),void 0!==e.visible&&(i.visible=e.visible),void 0!==e.userData&&(i.userData=e.userData),void 0!==e.children)for(var a in e.children)i.add(this.parseObject(e.children[a],n,r));return i}}()},THREE.TextureLoader=function(t){this.manager=void 0!==t?t:THREE.DefaultLoadingManager},THREE.TextureLoader.prototype={constructor:THREE.TextureLoader,load:function(t,e,n,r){var i=this,o=new THREE.ImageLoader(i.manager);o.setCrossOrigin(this.crossOrigin),o.load(t,function(t){var n=new THREE.Texture(t);n.needsUpdate=!0,void 0!==e&&e(n)},n,r)},setCrossOrigin:function(t){this.crossOrigin=t}},THREE.DataTextureLoader=THREE.BinaryTextureLoader=function(){this._parser=null},THREE.BinaryTextureLoader.prototype={constructor:THREE.BinaryTextureLoader,load:function(t,e,n,r){var i=this,o=new THREE.DataTexture,s=new THREE.XHRLoader;return s.setResponseType("arraybuffer"),s.load(t,function(t){var n=i._parser(t);n&&(void 0!==n.image?o.image=n.image:void 0!==n.data&&(o.image.width=n.width,o.image.height=n.height,o.image.data=n.data),o.wrapS=void 0!==n.wrapS?n.wrapS:THREE.ClampToEdgeWrapping,o.wrapT=void 0!==n.wrapT?n.wrapT:THREE.ClampToEdgeWrapping,o.magFilter=void 0!==n.magFilter?n.magFilter:THREE.LinearFilter,o.minFilter=void 0!==n.minFilter?n.minFilter:THREE.LinearMipMapLinearFilter,o.anisotropy=void 0!==n.anisotropy?n.anisotropy:1,void 0!==n.format&&(o.format=n.format),void 0!==n.type&&(o.type=n.type),void 0!==n.mipmaps&&(o.mipmaps=n.mipmaps),1===n.mipmapCount&&(o.minFilter=THREE.LinearFilter),o.needsUpdate=!0,e&&e(o,n))},n,r),o}},THREE.CompressedTextureLoader=function(){this._parser=null},THREE.CompressedTextureLoader.prototype={constructor:THREE.CompressedTextureLoader,load:function(t,e,n){var r=this,i=[],o=new THREE.CompressedTexture;o.image=i;var s=new THREE.XHRLoader;if(s.setResponseType("arraybuffer"),t instanceof Array)for(var a=0,u=function(n){s.load(t[n],function(t){var s=r._parser(t,!0);i[n]={width:s.width,height:s.height,format:s.format,mipmaps:s.mipmaps},a+=1,6===a&&(1==s.mipmapCount&&(o.minFilter=THREE.LinearFilter),o.format=s.format,o.needsUpdate=!0,e&&e(o))})},h=0,l=t.length;l>h;++h)u(h);else s.load(t,function(t){var n=r._parser(t,!0);if(n.isCubemap)for(var s=n.mipmaps.length/n.mipmapCount,a=0;s>a;a++){i[a]={mipmaps:[]};for(var u=0;ue;e++)t.materials.push(this.materials[e].toJSON());return t},clone:function(){for(var t=new THREE.MeshFaceMaterial,e=0;es){var u=e.closestPointToPoint(t);u.applyMatrix4(i.matrixWorld);var h=n.ray.origin.distanceTo(u);r.push({distance:h,distanceToRay:s,point:u.clone(),index:o,face:null,object:i})}};if(o instanceof THREE.BufferGeometry){var l=o.attributes,c=l.position.array;if(void 0!==l.index){var p=l.index.array,f=o.offsets;if(0===f.length){var d={start:0,count:p.length,index:0};f=[d]}for(var m=0,v=f.length;v>m;++m)for(var g=f[m].start,E=f[m].count,y=f[m].index,_=g,b=g+E;b>_;_++){var T=y+p[_];u.fromArray(c,3*T),h(u,T)}}else for(var x=c.length/3,_=0;x>_;_++)u.set(c[3*_],c[3*_+1],c[3*_+2]),h(u,_)}else for(var w=this.geometry.vertices,_=0;_b;b+=p){var T=_+d[b],x=_+d[b+1];u.fromArray(m,3*T),h.fromArray(m,3*x);var w=e.distanceSqToSegment(u,h,c,l);if(!(w>s)){var R=e.origin.distanceTo(c);Rr.far||i.push({distance:R,point:l.clone().applyMatrix4(this.matrixWorld),index:b,offsetIndex:g,face:null,faceIndex:null,object:this})}}}else for(var m=f.position.array,b=0;bs)){var R=e.origin.distanceTo(c);Rr.far||i.push({distance:R,point:l.clone().applyMatrix4(this.matrixWorld),index:b,face:null,faceIndex:null,object:this})}}}else if(a instanceof THREE.Geometry)for(var H=a.vertices,M=H.length,b=0;M-1>b;b+=p){var w=e.distanceSqToSegment(H[b],H[b+1],c,l);if(!(w>s)){var R=e.origin.distanceTo(c);Rr.far||i.push({distance:R,point:l.clone().applyMatrix4(this.matrixWorld),index:b,face:null,faceIndex:null,object:this})}}}}}(),THREE.Line.prototype.clone=function(t){return void 0===t&&(t=new THREE.Line(this.geometry,this.material,this.mode)),THREE.Object3D.prototype.clone.call(this,t),t},THREE.Mesh=function(t,e){THREE.Object3D.call(this),this.type="Mesh",this.geometry=void 0!==t?t:new THREE.Geometry,this.material=void 0!==e?e:new THREE.MeshBasicMaterial({color:16777215*Math.random()}),this.updateMorphTargets()},THREE.Mesh.prototype=Object.create(THREE.Object3D.prototype),THREE.Mesh.prototype.constructor=THREE.Mesh,THREE.Mesh.prototype.updateMorphTargets=function(){if(void 0!==this.geometry.morphTargets&&this.geometry.morphTargets.length>0){this.morphTargetBase=-1,this.morphTargetForcedOrder=[],this.morphTargetInfluences=[],this.morphTargetDictionary={};for(var t=0,e=this.geometry.morphTargets.length;e>t;t++)this.morphTargetInfluences.push(0),this.morphTargetDictionary[this.geometry.morphTargets[t].name]=t}},THREE.Mesh.prototype.getMorphTargetIndexByName=function(t){return void 0!==this.morphTargetDictionary[t]?this.morphTargetDictionary[t]:(THREE.warn("THREE.Mesh.getMorphTargetIndexByName: morph target "+t+" does not exist. Returning 0."),0)},THREE.Mesh.prototype.raycast=function(){var t=new THREE.Matrix4,e=new THREE.Ray,n=new THREE.Sphere,r=new THREE.Vector3,i=new THREE.Vector3,o=new THREE.Vector3;return function(s,a){var u=this.geometry;if(null===u.boundingSphere&&u.computeBoundingSphere(),n.copy(u.boundingSphere),n.applyMatrix4(this.matrixWorld),s.ray.isIntersectionSphere(n)!==!1&&(t.getInverse(this.matrixWorld),e.copy(s.ray).applyMatrix4(t),null===u.boundingBox||e.isIntersectionBox(u.boundingBox)!==!1))if(u instanceof THREE.BufferGeometry){var h=this.material;if(void 0===h)return;var l,c,p,f=u.attributes,d=s.precision;if(void 0!==f.index){var m=f.index.array,v=f.position.array,g=u.offsets;0===g.length&&(g=[{start:0,count:m.length,index:0}]);for(var E=0,y=g.length;y>E;++E)for(var _=g[E].start,b=g[E].count,T=g[E].index,x=_,w=_+b;w>x;x+=3){if(l=T+m[x],c=T+m[x+1],p=T+m[x+2],r.fromArray(v,3*l),i.fromArray(v,3*c),o.fromArray(v,3*p),h.side===THREE.BackSide)var R=e.intersectTriangle(o,i,r,!0);else var R=e.intersectTriangle(r,i,o,h.side!==THREE.DoubleSide);if(null!==R){R.applyMatrix4(this.matrixWorld);var H=s.ray.origin.distanceTo(R);d>H||Hs.far||a.push({distance:H,point:R,face:new THREE.Face3(l,c,p,THREE.Triangle.normal(r,i,o)),faceIndex:null,object:this})}}}else for(var v=f.position.array,x=0,M=0,w=v.length;w>x;x+=3,M+=9){if(l=x,c=x+1,p=x+2,r.fromArray(v,M),i.fromArray(v,M+3),o.fromArray(v,M+6),h.side===THREE.BackSide)var R=e.intersectTriangle(o,i,r,!0);else var R=e.intersectTriangle(r,i,o,h.side!==THREE.DoubleSide);if(null!==R){R.applyMatrix4(this.matrixWorld);var H=s.ray.origin.distanceTo(R);d>H||Hs.far||a.push({distance:H,point:R,face:new THREE.Face3(l,c,p,THREE.Triangle.normal(r,i,o)),faceIndex:null,object:this})}}}else if(u instanceof THREE.Geometry)for(var l,c,p,S=this.material instanceof THREE.MeshFaceMaterial,k=S===!0?this.material.materials:null,d=s.precision,A=u.vertices,C=0,P=u.faces.length;P>C;C++){var L=u.faces[C],h=S===!0?k[L.materialIndex]:this.material;if(void 0!==h){if(l=A[L.a],c=A[L.b],p=A[L.c],h.morphTargets===!0){var z=u.morphTargets,O=this.morphTargetInfluences;r.set(0,0,0),i.set(0,0,0),o.set(0,0,0);for(var D=0,F=z.length;F>D;D++){var U=O[D];if(0!==U){var B=z[D].vertices;r.x+=(B[L.a].x-l.x)*U,r.y+=(B[L.a].y-l.y)*U,r.z+=(B[L.a].z-l.z)*U,i.x+=(B[L.b].x-c.x)*U,i.y+=(B[L.b].y-c.y)*U,i.z+=(B[L.b].z-c.z)*U,o.x+=(B[L.c].x-p.x)*U,o.y+=(B[L.c].y-p.y)*U,o.z+=(B[L.c].z-p.z)*U}}r.add(l),i.add(c),o.add(p),l=r,c=i,p=o}if(h.side===THREE.BackSide)var R=e.intersectTriangle(p,c,l,!0);else var R=e.intersectTriangle(l,c,p,h.side!==THREE.DoubleSide);if(null!==R){R.applyMatrix4(this.matrixWorld);var H=s.ray.origin.distanceTo(R);d>H||Hs.far||a.push({distance:H,point:R,face:L,faceIndex:C,object:this})}}}}}(),THREE.Mesh.prototype.clone=function(t,e){return void 0===t&&(t=new THREE.Mesh(this.geometry,this.material)),THREE.Object3D.prototype.clone.call(this,t,e),t},THREE.Bone=function(t){THREE.Object3D.call(this),this.type="Bone",this.skin=t},THREE.Bone.prototype=Object.create(THREE.Object3D.prototype),THREE.Bone.prototype.constructor=THREE.Bone,THREE.Skeleton=function(t,e,n){if(this.useVertexTexture=void 0!==n?n:!0,this.identityMatrix=new THREE.Matrix4,t=t||[],this.bones=t.slice(0),this.useVertexTexture){var r;r=this.bones.length>256?64:this.bones.length>64?32:this.bones.length>16?16:8,this.boneTextureWidth=r,this.boneTextureHeight=r,this.boneMatrices=new Float32Array(this.boneTextureWidth*this.boneTextureHeight*4),this.boneTexture=new THREE.DataTexture(this.boneMatrices,this.boneTextureWidth,this.boneTextureHeight,THREE.RGBAFormat,THREE.FloatType),this.boneTexture.minFilter=THREE.NearestFilter,this.boneTexture.magFilter=THREE.NearestFilter,this.boneTexture.generateMipmaps=!1,this.boneTexture.flipY=!1}else this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===e)this.calculateInverses();else if(this.bones.length===e.length)this.boneInverses=e.slice(0);else{THREE.warn("THREE.Skeleton bonInverses is the wrong length."),this.boneInverses=[];for(var i=0,o=this.bones.length;o>i;i++)this.boneInverses.push(new THREE.Matrix4)}},THREE.Skeleton.prototype.calculateInverses=function(){this.boneInverses=[];for(var t=0,e=this.bones.length;e>t;t++){var n=new THREE.Matrix4;this.bones[t]&&n.getInverse(this.bones[t].matrixWorld),this.boneInverses.push(n)}},THREE.Skeleton.prototype.pose=function(){for(var t,e=0,n=this.bones.length;n>e;e++)t=this.bones[e],t&&t.matrixWorld.getInverse(this.boneInverses[e]);for(var e=0,n=this.bones.length;n>e;e++)t=this.bones[e],t&&(t.parent?(t.matrix.getInverse(t.parent.matrixWorld),t.matrix.multiply(t.matrixWorld)):t.matrix.copy(t.matrixWorld),t.matrix.decompose(t.position,t.quaternion,t.scale))},THREE.Skeleton.prototype.update=function(){var t=new THREE.Matrix4;return function(){for(var e=0,n=this.bones.length;n>e;e++){var r=this.bones[e]?this.bones[e].matrixWorld:this.identityMatrix;t.multiplyMatrices(r,this.boneInverses[e]),t.flattenToArrayOffset(this.boneMatrices,16*e)}this.useVertexTexture&&(this.boneTexture.needsUpdate=!0)}}(),THREE.SkinnedMesh=function(t,e,n){THREE.Mesh.call(this,t,e),this.type="SkinnedMesh",this.bindMode="attached",this.bindMatrix=new THREE.Matrix4,this.bindMatrixInverse=new THREE.Matrix4;var r=[];if(this.geometry&&void 0!==this.geometry.bones){for(var i,o,s,a,u,h=0,l=this.geometry.bones.length;l>h;++h)o=this.geometry.bones[h],s=o.pos,a=o.rotq,u=o.scl,i=new THREE.Bone(this),r.push(i),i.name=o.name,i.position.set(s[0],s[1],s[2]),i.quaternion.set(a[0],a[1],a[2],a[3]),void 0!==u?i.scale.set(u[0],u[1],u[2]):i.scale.set(1,1,1);for(var h=0,l=this.geometry.bones.length;l>h;++h)o=this.geometry.bones[h],-1!==o.parent?r[o.parent].add(r[h]):this.add(r[h])}this.normalizeSkinWeights(),this.updateMatrixWorld(!0),this.bind(new THREE.Skeleton(r,void 0,n))},THREE.SkinnedMesh.prototype=Object.create(THREE.Mesh.prototype),THREE.SkinnedMesh.prototype.constructor=THREE.SkinnedMesh,THREE.SkinnedMesh.prototype.bind=function(t,e){this.skeleton=t,void 0===e&&(this.updateMatrixWorld(!0),e=this.matrixWorld),this.bindMatrix.copy(e),this.bindMatrixInverse.getInverse(e)},THREE.SkinnedMesh.prototype.pose=function(){this.skeleton.pose()},THREE.SkinnedMesh.prototype.normalizeSkinWeights=function(){if(this.geometry instanceof THREE.Geometry)for(var t=0;ti;i++){var s=t.morphTargets[i],a=s.name.match(r);if(a&&a.length>1){var u=a[1];n[u]||(n[u]={start:1/0,end:-(1/0)});var h=n[u];ih.end&&(h.end=i),e||(e=u)}}t.firstAnimation=e},THREE.MorphAnimMesh.prototype.setAnimationLabel=function(t,e,n){this.geometry.animations||(this.geometry.animations={}),this.geometry.animations[t]={start:e,end:n}},THREE.MorphAnimMesh.prototype.playAnimation=function(t,e){var n=this.geometry.animations[t];n?(this.setFrameRange(n.start,n.end),this.duration=1e3*((n.end-n.start)/e),this.time=0):THREE.warn("THREE.MorphAnimMesh: animation["+t+"] undefined in .playAnimation()")},THREE.MorphAnimMesh.prototype.updateAnimation=function(t){var e=this.duration/this.length;this.time+=this.direction*t,this.mirroredLoop?(this.time>this.duration||this.time<0)&&(this.direction*=-1,this.time>this.duration&&(this.time=this.duration,this.directionBackwards=!0),this.time<0&&(this.time=0,this.directionBackwards=!1)):(this.time=this.time%this.duration,this.time<0&&(this.time+=this.duration));var n=this.startKeyframe+THREE.Math.clamp(Math.floor(this.time/e),0,this.length-1);n!==this.currentKeyframe&&(this.morphTargetInfluences[this.lastKeyframe]=0,this.morphTargetInfluences[this.currentKeyframe]=1,this.morphTargetInfluences[n]=0,this.lastKeyframe=this.currentKeyframe,this.currentKeyframe=n);var r=this.time%e/e;this.directionBackwards&&(r=1-r),this.morphTargetInfluences[this.currentKeyframe]=r,this.morphTargetInfluences[this.lastKeyframe]=1-r},THREE.MorphAnimMesh.prototype.interpolateTargets=function(t,e,n){for(var r=this.morphTargetInfluences,i=0,o=r.length;o>i;i++)r[i]=0;t>-1&&(r[t]=1-n),e>-1&&(r[e]=n)},THREE.MorphAnimMesh.prototype.clone=function(t){return void 0===t&&(t=new THREE.MorphAnimMesh(this.geometry,this.material)),t.duration=this.duration,t.mirroredLoop=this.mirroredLoop,t.time=this.time,t.lastKeyframe=this.lastKeyframe,t.currentKeyframe=this.currentKeyframe,t.direction=this.direction,t.directionBackwards=this.directionBackwards,THREE.Mesh.prototype.clone.call(this,t),t},THREE.LOD=function(){THREE.Object3D.call(this),this.objects=[]},THREE.LOD.prototype=Object.create(THREE.Object3D.prototype),THREE.LOD.prototype.constructor=THREE.LOD,THREE.LOD.prototype.addLevel=function(t,e){void 0===e&&(e=0),e=Math.abs(e);for(var n=0;ne&&!(t1){t.setFromMatrixPosition(n.matrixWorld),e.setFromMatrixPosition(this.matrixWorld);var r=t.distanceTo(e);this.objects[0].object.visible=!0;for(var i=1,o=this.objects.length;o>i&&r>=this.objects[i].distance;i++)this.objects[i-1].object.visible=!1,this.objects[i].object.visible=!0;for(;o>i;i++)this.objects[i].object.visible=!1}}}(),THREE.LOD.prototype.clone=function(t){void 0===t&&(t=new THREE.LOD),THREE.Object3D.prototype.clone.call(this,t);for(var e=0,n=this.objects.length;n>e;e++){var r=this.objects[e].object.clone();r.visible=0===e,t.addLevel(r,this.objects[e].distance)}return t},THREE.Sprite=function(){var t=new Uint16Array([0,1,2,0,2,3]),e=new Float32Array([-.5,-.5,0,.5,-.5,0,.5,.5,0,-.5,.5,0]),n=new Float32Array([0,0,1,0,1,1,0,1]),r=new THREE.BufferGeometry;return r.addAttribute("index",new THREE.BufferAttribute(t,1)),r.addAttribute("position",new THREE.BufferAttribute(e,3)),r.addAttribute("uv",new THREE.BufferAttribute(n,2)),function(t){THREE.Object3D.call(this),this.type="Sprite",this.geometry=r,this.material=void 0!==t?t:new THREE.SpriteMaterial}}(),THREE.Sprite.prototype=Object.create(THREE.Object3D.prototype),THREE.Sprite.prototype.constructor=THREE.Sprite,THREE.Sprite.prototype.raycast=function(){var t=new THREE.Vector3;return function(e,n){t.setFromMatrixPosition(this.matrixWorld);var r=e.ray.distanceToPoint(t);r>this.scale.x||n.push({distance:r,point:this.position,face:null,object:this})}}(),THREE.Sprite.prototype.clone=function(t){return void 0===t&&(t=new THREE.Sprite(this.material)),THREE.Object3D.prototype.clone.call(this,t),t},THREE.Particle=THREE.Sprite,THREE.LensFlare=function(t,e,n,r,i){THREE.Object3D.call(this),this.lensFlares=[],this.positionScreen=new THREE.Vector3,this.customUpdateCallback=void 0,void 0!==t&&this.add(t,e,n,r,i)},THREE.LensFlare.prototype=Object.create(THREE.Object3D.prototype),THREE.LensFlare.prototype.constructor=THREE.LensFlare,THREE.LensFlare.prototype.add=function(t,e,n,r,i,o){void 0===e&&(e=-1),void 0===n&&(n=0),void 0===o&&(o=1),void 0===i&&(i=new THREE.Color(16777215)),void 0===r&&(r=THREE.NormalBlending),n=Math.min(n,Math.max(0,n)),this.lensFlares.push({texture:t,size:e,distance:n,x:0,y:0,z:0,scale:1,rotation:1,opacity:o,color:i,blending:r})},THREE.LensFlare.prototype.updateLensFlares=function(){var t,e,n=this.lensFlares.length,r=2*-this.positionScreen.x,i=2*-this.positionScreen.y;for(t=0;n>t;t++)e=this.lensFlares[t],e.x=this.positionScreen.x+r*e.distance,e.y=this.positionScreen.y+i*e.distance,e.wantedRotation=e.x*Math.PI*.25,e.rotation+=.25*(e.wantedRotation-e.rotation)},THREE.Scene=function(){THREE.Object3D.call(this),this.type="Scene",this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0},THREE.Scene.prototype=Object.create(THREE.Object3D.prototype),THREE.Scene.prototype.constructor=THREE.Scene,THREE.Scene.prototype.clone=function(t){return void 0===t&&(t=new THREE.Scene),THREE.Object3D.prototype.clone.call(this,t),null!==this.fog&&(t.fog=this.fog.clone()),null!==this.overrideMaterial&&(t.overrideMaterial=this.overrideMaterial.clone()),t.autoUpdate=this.autoUpdate,t.matrixAutoUpdate=this.matrixAutoUpdate,t},THREE.Fog=function(t,e,n){this.name="",this.color=new THREE.Color(t),this.near=void 0!==e?e:1,this.far=void 0!==n?n:1e3},THREE.Fog.prototype.clone=function(){return new THREE.Fog(this.color.getHex(),this.near,this.far)},THREE.FogExp2=function(t,e){this.name="",this.color=new THREE.Color(t),this.density=void 0!==e?e:25e-5},THREE.FogExp2.prototype.clone=function(){return new THREE.FogExp2(this.color.getHex(),this.density)},THREE.ShaderChunk={},THREE.ShaderChunk.common="#define PI 3.14159\n#define PI2 6.28318\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n\nfloat square( in float a ) { return a*a; }\nvec2 square( in vec2 a ) { return vec2( a.x*a.x, a.y*a.y ); }\nvec3 square( in vec3 a ) { return vec3( a.x*a.x, a.y*a.y, a.z*a.z ); }\nvec4 square( in vec4 a ) { return vec4( a.x*a.x, a.y*a.y, a.z*a.z, a.w*a.w ); }\nfloat saturate( in float a ) { return clamp( a, 0.0, 1.0 ); }\nvec2 saturate( in vec2 a ) { return clamp( a, 0.0, 1.0 ); }\nvec3 saturate( in vec3 a ) { return clamp( a, 0.0, 1.0 ); }\nvec4 saturate( in vec4 a ) { return clamp( a, 0.0, 1.0 ); }\nfloat average( in float a ) { return a; }\nfloat average( in vec2 a ) { return ( a.x + a.y) * 0.5; }\nfloat average( in vec3 a ) { return ( a.x + a.y + a.z) / 3.0; }\nfloat average( in vec4 a ) { return ( a.x + a.y + a.z + a.w) * 0.25; }\nfloat whiteCompliment( in float a ) { return saturate( 1.0 - a ); }\nvec2 whiteCompliment( in vec2 a ) { return saturate( vec2(1.0) - a ); }\nvec3 whiteCompliment( in vec3 a ) { return saturate( vec3(1.0) - a ); }\nvec4 whiteCompliment( in vec4 a ) { return saturate( vec4(1.0) - a ); }\nvec3 transformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( matrix * vec4( normal, 0.0 ) ).xyz );\n}\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\nvec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal) {\n float distance = dot( planeNormal, point-pointOnPlane );\n return point - distance * planeNormal;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return pointOnLine + lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) );\n}\nfloat calcLightAttenuation( float lightDistance, float cutoffDistance, float decayExponent ) {\n if ( decayExponent > 0.0 ) {\n return pow( saturate( 1.0 - lightDistance / cutoffDistance ), decayExponent );\n }\n return 1.0;\n}\n\nvec3 inputToLinear( in vec3 a ) {\n#ifdef GAMMA_INPUT\n return pow( a, vec3( float( GAMMA_FACTOR ) ) );\n#else\n return a;\n#endif\n}\nvec3 linearToOutput( in vec3 a ) {\n#ifdef GAMMA_OUTPUT\n return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );\n#else\n return a;\n#endif\n}\n",THREE.ShaderChunk.alphatest_fragment="#ifdef ALPHATEST\n\n if ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n",THREE.ShaderChunk.lights_lambert_vertex="vLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\n vLightBack = vec3( 0.0 );\n\n#endif\n\ntransformedNormal = normalize( transformedNormal );\n\n#if MAX_DIR_LIGHTS > 0\n\nfor( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 dirVector = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n float dotProduct = dot( transformedNormal, dirVector );\n vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += directionalLightColor[ i ] * directionalLightWeighting;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;\n\n #endif\n\n}\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n lVector = normalize( lVector );\n float dotProduct = dot( transformedNormal, lVector );\n\n vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += pointLightColor[ i ] * pointLightWeighting * attenuation;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += pointLightColor[ i ] * pointLightWeightingBack * attenuation;\n\n #endif\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n float dotProduct = dot( transformedNormal, lVector );\n vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += spotLightColor[ i ] * spotLightWeighting * attenuation * spotEffect;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += spotLightColor[ i ] * spotLightWeightingBack * attenuation * spotEffect;\n\n #endif\n\n }\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lVector = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n float dotProduct = dot( transformedNormal, lVector );\n\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;\n\n vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );\n\n #endif\n\n }\n\n#endif\n\nvLightFront += ambientLightColor;\n\n#ifdef DOUBLE_SIDED\n\n vLightBack += ambientLightColor;\n\n#endif\n",THREE.ShaderChunk.map_particle_pars_fragment="#ifdef USE_MAP\n\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n\n#endif\n",THREE.ShaderChunk.default_vertex="#ifdef USE_SKINNING\n\n vec4 mvPosition = modelViewMatrix * skinned;\n\n#elif defined( USE_MORPHTARGETS )\n\n vec4 mvPosition = modelViewMatrix * vec4( morphed, 1.0 );\n\n#else\n\n vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\n#endif\n\ngl_Position = projectionMatrix * mvPosition;\n",THREE.ShaderChunk.map_pars_fragment="#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n varying vec2 vUv;\n\n#endif\n\n#ifdef USE_MAP\n\n uniform sampler2D map;\n\n#endif",THREE.ShaderChunk.skinnormal_vertex="#ifdef USE_SKINNING\n\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n #ifdef USE_MORPHNORMALS\n\n vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );\n\n #else\n\n vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );\n\n #endif\n\n#endif\n",THREE.ShaderChunk.logdepthbuf_pars_vertex="#ifdef USE_LOGDEPTHBUF\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n varying float vFragDepth;\n\n #endif\n\n uniform float logDepthBufFC;\n\n#endif",THREE.ShaderChunk.lightmap_pars_vertex="#ifdef USE_LIGHTMAP\n\n varying vec2 vUv2;\n\n#endif",THREE.ShaderChunk.lights_phong_fragment="#ifndef FLAT_SHADED\n\n vec3 normal = normalize( vNormal );\n\n #ifdef DOUBLE_SIDED\n\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n\n #endif\n\n#else\n\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n\n#endif\n\nvec3 viewPosition = normalize( vViewPosition );\n\n#ifdef USE_NORMALMAP\n\n normal = perturbNormal2Arb( -vViewPosition, normal );\n\n#elif defined( USE_BUMPMAP )\n\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n\nvec3 totalDiffuseLight = vec3( 0.0 );\nvec3 totalSpecularLight = vec3( 0.0 );\n\n#if MAX_POINT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n\n #ifdef WRAP_AROUND\n\n float pointDiffuseWeightFull = max( dotProduct, 0.0 );\n float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float pointDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += pointLightColor[ i ] * pointDiffuseWeight * attenuation;\n\n // specular\n\n vec3 pointHalfVector = normalize( lVector + viewPosition );\n float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );\n float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * attenuation * specularNormalization;\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n\n #ifdef WRAP_AROUND\n\n float spotDiffuseWeightFull = max( dotProduct, 0.0 );\n float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float spotDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += spotLightColor[ i ] * spotDiffuseWeight * attenuation * spotEffect;\n\n // specular\n\n vec3 spotHalfVector = normalize( lVector + viewPosition );\n float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );\n float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * attenuation * specularNormalization * spotEffect;\n\n }\n\n }\n\n#endif\n\n#if MAX_DIR_LIGHTS > 0\n\n for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 dirVector = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, dirVector );\n\n #ifdef WRAP_AROUND\n\n float dirDiffuseWeightFull = max( dotProduct, 0.0 );\n float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float dirDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += directionalLightColor[ i ] * dirDiffuseWeight;\n\n // specular\n\n vec3 dirHalfVector = normalize( dirVector + viewPosition );\n float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );\n float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );\n\n /*\n // fresnel term from skin shader\n const float F0 = 0.128;\n\n float base = 1.0 - dot( viewPosition, dirHalfVector );\n float exponential = pow( base, 5.0 );\n\n float fresnel = exponential + F0 * ( 1.0 - exponential );\n */\n\n /*\n // fresnel term from fresnel shader\n const float mFresnelBias = 0.08;\n const float mFresnelScale = 0.3;\n const float mFresnelPower = 5.0;\n\n float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );\n */\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n // dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;\n\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lVector = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n\n vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n totalDiffuseLight += hemiColor;\n\n // specular (sky light)\n\n vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );\n float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;\n float hemiSpecularWeightSky = specularStrength * max( pow( max( hemiDotNormalHalfSky, 0.0 ), shininess ), 0.0 );\n\n // specular (ground light)\n\n vec3 lVectorGround = -lVector;\n\n vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );\n float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;\n float hemiSpecularWeightGround = specularStrength * max( pow( max( hemiDotNormalHalfGround, 0.0 ), shininess ), 0.0 );\n\n float dotProductGround = dot( normal, lVectorGround );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );\n vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );\n totalSpecularLight += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );\n\n }\n\n#endif\n\n#ifdef METAL\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + ambientLightColor ) * specular + totalSpecularLight + emissive;\n\n#else\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + ambientLightColor ) + totalSpecularLight + emissive;\n\n#endif\n", +THREE.ShaderChunk.fog_pars_fragment="#ifdef USE_FOG\n\n uniform vec3 fogColor;\n\n #ifdef FOG_EXP2\n\n uniform float fogDensity;\n\n #else\n\n uniform float fogNear;\n uniform float fogFar;\n #endif\n\n#endif",THREE.ShaderChunk.morphnormal_vertex="#ifdef USE_MORPHNORMALS\n\n vec3 morphedNormal = vec3( 0.0 );\n\n morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n\n morphedNormal += normal;\n\n#endif",THREE.ShaderChunk.envmap_pars_fragment="#ifdef USE_ENVMAP\n\n uniform float reflectivity;\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n uniform float flipEnvMap;\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n uniform float refractionRatio;\n\n #else\n\n varying vec3 vReflect;\n\n #endif\n\n#endif\n",THREE.ShaderChunk.logdepthbuf_fragment="#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif",THREE.ShaderChunk.normalmap_pars_fragment="#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( vUv.st );\n vec2 st1 = dFdy( vUv.st );\n\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normalize( surf_norm );\n\n vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n mapN.xy = normalScale * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n\n }\n\n#endif\n",THREE.ShaderChunk.lights_phong_pars_vertex="#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n",THREE.ShaderChunk.lightmap_pars_fragment="#ifdef USE_LIGHTMAP\n\n varying vec2 vUv2;\n uniform sampler2D lightMap;\n\n#endif",THREE.ShaderChunk.shadowmap_vertex="#ifdef USE_SHADOWMAP\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;\n\n }\n\n#endif",THREE.ShaderChunk.lights_phong_vertex="#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n vWorldPosition = worldPosition.xyz;\n\n#endif",THREE.ShaderChunk.map_fragment="#ifdef USE_MAP\n\n vec4 texelColor = texture2D( map, vUv );\n\n texelColor.xyz = inputToLinear( texelColor.xyz );\n\n diffuseColor *= texelColor;\n\n#endif",THREE.ShaderChunk.lightmap_vertex="#ifdef USE_LIGHTMAP\n\n vUv2 = uv2;\n\n#endif",THREE.ShaderChunk.map_particle_fragment="#ifdef USE_MAP\n\n diffuseColor *= texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\n#endif\n",THREE.ShaderChunk.color_pars_fragment="#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif\n",THREE.ShaderChunk.color_vertex="#ifdef USE_COLOR\n\n vColor.xyz = inputToLinear( color.xyz );\n\n#endif",THREE.ShaderChunk.skinning_vertex="#ifdef USE_SKINNING\n\n #ifdef USE_MORPHTARGETS\n\n vec4 skinVertex = bindMatrix * vec4( morphed, 1.0 );\n\n #else\n\n vec4 skinVertex = bindMatrix * vec4( position, 1.0 );\n\n #endif\n\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n skinned = bindMatrixInverse * skinned;\n\n#endif\n",THREE.ShaderChunk.envmap_pars_vertex="#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n varying vec3 vReflect;\n\n uniform float refractionRatio;\n\n#endif\n",THREE.ShaderChunk.linear_to_gamma_fragment="\n outgoingLight = linearToOutput( outgoingLight );\n",THREE.ShaderChunk.color_pars_vertex="#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif",THREE.ShaderChunk.lights_lambert_pars_vertex="uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n\n#ifdef WRAP_AROUND\n\n uniform vec3 wrapRGB;\n\n#endif\n",THREE.ShaderChunk.map_pars_vertex="#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n\n#endif\n",THREE.ShaderChunk.envmap_fragment="#ifdef USE_ENVMAP\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\n // Transforming Normal Vectors with the Inverse Transformation\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n #else\n\n vec3 reflectVec = vReflect;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n #else\n float flipNormal = 1.0;\n #endif\n\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n vec4 envColor = texture2D( envMap, sampleUV );\n\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize((viewMatrix * vec4( reflectVec, 0.0 )).xyz + vec3(0.0,0.0,1.0));\n vec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n #endif\n\n envColor.xyz = inputToLinear( envColor.xyz );\n\n #ifdef ENVMAP_BLENDING_MULTIPLY\n\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_MIX )\n\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_ADD )\n\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n #endif\n\n#endif\n",THREE.ShaderChunk.specularmap_pars_fragment="#ifdef USE_SPECULARMAP\n\n uniform sampler2D specularMap;\n\n#endif",THREE.ShaderChunk.logdepthbuf_vertex="#ifdef USE_LOGDEPTHBUF\n\n gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n vFragDepth = 1.0 + gl_Position.w;\n\n#else\n\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\n #endif\n\n#endif",THREE.ShaderChunk.morphtarget_pars_vertex="#ifdef USE_MORPHTARGETS\n\n #ifndef USE_MORPHNORMALS\n\n uniform float morphTargetInfluences[ 8 ];\n\n #else\n\n uniform float morphTargetInfluences[ 4 ];\n\n #endif\n\n#endif",THREE.ShaderChunk.specularmap_fragment="float specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n\n#else\n\n specularStrength = 1.0;\n\n#endif",THREE.ShaderChunk.fog_fragment="#ifdef USE_FOG\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n\n #else\n\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n\n #endif\n\n #ifdef FOG_EXP2\n\n float fogFactor = exp2( - square( fogDensity ) * square( depth ) * LOG2 );\n fogFactor = whiteCompliment( fogFactor );\n\n #else\n\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n\n #endif\n \n outgoingLight = mix( outgoingLight, fogColor, fogFactor );\n\n#endif",THREE.ShaderChunk.bumpmap_pars_fragment="#ifdef USE_BUMPMAP\n\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n\n // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\n // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\n\n // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n vec2 dHdxy_fwd() {\n\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\n\n float Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n return vec2( dBx, dBy );\n\n }\n\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm; // normalized\n\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n\n float fDet = dot( vSigmaX, R1 );\n\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n\n }\n\n#endif\n",THREE.ShaderChunk.defaultnormal_vertex="#ifdef USE_SKINNING\n\n vec3 objectNormal = skinnedNormal.xyz;\n\n#elif defined( USE_MORPHNORMALS )\n\n vec3 objectNormal = morphedNormal;\n\n#else\n\n vec3 objectNormal = normal;\n\n#endif\n\n#ifdef FLIP_SIDED\n\n objectNormal = -objectNormal;\n\n#endif\n\nvec3 transformedNormal = normalMatrix * objectNormal;\n",THREE.ShaderChunk.lights_phong_pars_fragment="uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n\n#ifdef WRAP_AROUND\n\n uniform vec3 wrapRGB;\n\n#endif\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n varying vec3 vNormal;\n\n#endif\n",THREE.ShaderChunk.skinbase_vertex="#ifdef USE_SKINNING\n\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif",THREE.ShaderChunk.map_vertex="#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n\n#endif",THREE.ShaderChunk.lightmap_fragment="#ifdef USE_LIGHTMAP\n\n outgoingLight *= diffuseColor.xyz * texture2D( lightMap, vUv2 ).xyz;\n\n#endif",THREE.ShaderChunk.shadowmap_pars_vertex="#ifdef USE_SHADOWMAP\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n uniform mat4 shadowMatrix[ MAX_SHADOWS ];\n\n#endif",THREE.ShaderChunk.color_fragment="#ifdef USE_COLOR\n\n diffuseColor.rgb *= vColor;\n\n#endif",THREE.ShaderChunk.morphtarget_vertex="#ifdef USE_MORPHTARGETS\n\n vec3 morphed = vec3( 0.0 );\n morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\n #ifndef USE_MORPHNORMALS\n\n morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\n #endif\n\n morphed += position;\n\n#endif",THREE.ShaderChunk.envmap_vertex="#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n vec3 worldNormal = transformDirection( objectNormal, modelMatrix );\n\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vReflect = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n#endif\n",THREE.ShaderChunk.shadowmap_fragment="#ifdef USE_SHADOWMAP\n\n #ifdef SHADOWMAP_DEBUG\n\n vec3 frustumColors[3];\n frustumColors[0] = vec3( 1.0, 0.5, 0.0 );\n frustumColors[1] = vec3( 0.0, 1.0, 0.8 );\n frustumColors[2] = vec3( 0.0, 0.5, 1.0 );\n\n #endif\n\n #ifdef SHADOWMAP_CASCADE\n\n int inFrustumCount = 0;\n\n #endif\n\n float fDepth;\n vec3 shadowColor = vec3( 1.0 );\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;\n\n // if ( something && something ) breaks ATI OpenGL shader compiler\n // if ( all( something, something ) ) using this instead\n\n bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n bool inFrustum = all( inFrustumVec );\n\n // don't shadow pixels outside of light frustum\n // use just first frustum (for cascades)\n // don't shadow pixels behind far plane of light frustum\n\n #ifdef SHADOWMAP_CASCADE\n\n inFrustumCount += int( inFrustum );\n bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );\n\n #else\n\n bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n #endif\n\n bool frustumTest = all( frustumTestVec );\n\n if ( frustumTest ) {\n\n shadowCoord.z += shadowBias[ i ];\n\n #if defined( SHADOWMAP_TYPE_PCF )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n /*\n // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL\n // must enroll loop manually\n\n for ( float y = -1.25; y <= 1.25; y += 1.25 )\n for ( float x = -1.25; x <= 1.25; x += 1.25 ) {\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );\n\n // doesn't seem to produce any noticeable visual difference compared to simple texture2D lookup\n //vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );\n\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n shadow += 1.0;\n\n }\n\n shadow /= 9.0;\n\n */\n\n const float shadowDelta = 1.0 / 9.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.25 * xPixelOffset;\n float dy0 = -1.25 * yPixelOffset;\n float dx1 = 1.25 * xPixelOffset;\n float dy1 = 1.25 * yPixelOffset;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.0 * xPixelOffset;\n float dy0 = -1.0 * yPixelOffset;\n float dx1 = 1.0 * xPixelOffset;\n float dy1 = 1.0 * yPixelOffset;\n\n mat3 shadowKernel;\n mat3 depthKernel;\n\n depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n\n vec3 shadowZ = vec3( shadowCoord.z );\n shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));\n shadowKernel[0] *= vec3(0.25);\n\n shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));\n shadowKernel[1] *= vec3(0.25);\n\n shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));\n shadowKernel[2] *= vec3(0.25);\n\n vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );\n\n shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );\n shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );\n\n vec4 shadowValues;\n shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );\n shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );\n shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );\n shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );\n\n shadow = dot( shadowValues, vec4( 1.0 ) );\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #else\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n\n // spot with multiple shadows is darker\n\n shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );\n\n // spot with multiple shadows has the same color as single shadow spot\n\n // shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );\n\n #endif\n\n }\n\n\n #ifdef SHADOWMAP_DEBUG\n\n #ifdef SHADOWMAP_CASCADE\n\n if ( inFrustum && inFrustumCount == 1 ) outgoingLight *= frustumColors[ i ];\n\n #else\n\n if ( inFrustum ) outgoingLight *= frustumColors[ i ];\n\n #endif\n\n #endif\n\n }\n\n // NOTE: I am unsure if this is correct in linear space. -bhouston, Dec 29, 2014\n shadowColor = inputToLinear( shadowColor );\n\n outgoingLight = outgoingLight * shadowColor;\n\n#endif\n",THREE.ShaderChunk.worldpos_vertex="#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\n #ifdef USE_SKINNING\n\n vec4 worldPosition = modelMatrix * skinned;\n\n #elif defined( USE_MORPHTARGETS )\n\n vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );\n\n #else\n\n vec4 worldPosition = modelMatrix * vec4( position, 1.0 );\n\n #endif\n\n#endif\n",THREE.ShaderChunk.shadowmap_pars_fragment="#ifdef USE_SHADOWMAP\n\n uniform sampler2D shadowMap[ MAX_SHADOWS ];\n uniform vec2 shadowMapSize[ MAX_SHADOWS ];\n\n uniform float shadowDarkness[ MAX_SHADOWS ];\n uniform float shadowBias[ MAX_SHADOWS ];\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n\n float unpackDepth( const in vec4 rgba_depth ) {\n\n const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n float depth = dot( rgba_depth, bit_shift );\n return depth;\n\n }\n\n#endif",THREE.ShaderChunk.skinning_pars_vertex="#ifdef USE_SKINNING\n\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n\n #ifdef BONE_TEXTURE\n\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n\n mat4 getBoneMatrix( const in float i ) {\n\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n\n y = dy * ( y + 0.5 );\n\n vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n mat4 bone = mat4( v1, v2, v3, v4 );\n\n return bone;\n\n }\n\n #else\n\n uniform mat4 boneGlobalMatrices[ MAX_BONES ];\n\n mat4 getBoneMatrix( const in float i ) {\n\n mat4 bone = boneGlobalMatrices[ int(i) ];\n return bone;\n\n }\n\n #endif\n\n#endif\n",THREE.ShaderChunk.logdepthbuf_pars_fragment="#ifdef USE_LOGDEPTHBUF\n\n uniform float logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n #extension GL_EXT_frag_depth : enable\n varying float vFragDepth;\n\n #endif\n\n#endif",THREE.ShaderChunk.alphamap_fragment="#ifdef USE_ALPHAMAP\n\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n",THREE.ShaderChunk.alphamap_pars_fragment="#ifdef USE_ALPHAMAP\n\n uniform sampler2D alphaMap;\n\n#endif\n",THREE.UniformsUtils={merge:function(t){for(var e={},n=0;n dashSize ) {"," discard;"," }"," vec3 outgoingLight = vec3( 0.0 );"," vec4 diffuseColor = vec4( diffuse, opacity );",THREE.ShaderChunk.logdepthbuf_fragment,THREE.ShaderChunk.color_fragment," outgoingLight = diffuseColor.rgb;",THREE.ShaderChunk.fog_fragment," gl_FragColor = vec4( outgoingLight, diffuseColor.a );","}"].join("\n")},depth:{uniforms:{mNear:{type:"f",value:1},mFar:{type:"f",value:2e3},opacity:{type:"f",value:1}},vertexShader:[THREE.ShaderChunk.common,THREE.ShaderChunk.morphtarget_pars_vertex,THREE.ShaderChunk.logdepthbuf_pars_vertex,"void main() {",THREE.ShaderChunk.morphtarget_vertex,THREE.ShaderChunk.default_vertex,THREE.ShaderChunk.logdepthbuf_vertex,"}"].join("\n"),fragmentShader:["uniform float mNear;","uniform float mFar;","uniform float opacity;",THREE.ShaderChunk.common,THREE.ShaderChunk.logdepthbuf_pars_fragment,"void main() {",THREE.ShaderChunk.logdepthbuf_fragment," #ifdef USE_LOGDEPTHBUF_EXT"," float depth = gl_FragDepthEXT / gl_FragCoord.w;"," #else"," float depth = gl_FragCoord.z / gl_FragCoord.w;"," #endif"," float color = 1.0 - smoothstep( mNear, mFar, depth );"," gl_FragColor = vec4( vec3( color ), opacity );","}"].join("\n")},normal:{uniforms:{opacity:{type:"f",value:1}},vertexShader:["varying vec3 vNormal;",THREE.ShaderChunk.common,THREE.ShaderChunk.morphtarget_pars_vertex,THREE.ShaderChunk.logdepthbuf_pars_vertex,"void main() {"," vNormal = normalize( normalMatrix * normal );",THREE.ShaderChunk.morphtarget_vertex,THREE.ShaderChunk.default_vertex,THREE.ShaderChunk.logdepthbuf_vertex,"}"].join("\n"),fragmentShader:["uniform float opacity;","varying vec3 vNormal;",THREE.ShaderChunk.common,THREE.ShaderChunk.logdepthbuf_pars_fragment,"void main() {"," gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",THREE.ShaderChunk.logdepthbuf_fragment,"}"].join("\n")},cube:{uniforms:{tCube:{type:"t",value:null},tFlip:{type:"f",value:-1}},vertexShader:["varying vec3 vWorldPosition;",THREE.ShaderChunk.common,THREE.ShaderChunk.logdepthbuf_pars_vertex,"void main() {"," vWorldPosition = transformDirection( position, modelMatrix );"," gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",THREE.ShaderChunk.logdepthbuf_vertex,"}"].join("\n"),fragmentShader:["uniform samplerCube tCube;","uniform float tFlip;","varying vec3 vWorldPosition;",THREE.ShaderChunk.common,THREE.ShaderChunk.logdepthbuf_pars_fragment,"void main() {"," gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",THREE.ShaderChunk.logdepthbuf_fragment,"}"].join("\n")},equirect:{uniforms:{tEquirect:{type:"t",value:null},tFlip:{type:"f",value:-1}},vertexShader:["varying vec3 vWorldPosition;",THREE.ShaderChunk.common,THREE.ShaderChunk.logdepthbuf_pars_vertex,"void main() {"," vWorldPosition = transformDirection( position, modelMatrix );"," gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",THREE.ShaderChunk.logdepthbuf_vertex,"}"].join("\n"),fragmentShader:["uniform sampler2D tEquirect;","uniform float tFlip;","varying vec3 vWorldPosition;",THREE.ShaderChunk.common,THREE.ShaderChunk.logdepthbuf_pars_fragment,"void main() {","vec3 direction = normalize( vWorldPosition );","vec2 sampleUV;","sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );","sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;","gl_FragColor = texture2D( tEquirect, sampleUV );",THREE.ShaderChunk.logdepthbuf_fragment,"}"].join("\n")},depthRGBA:{uniforms:{},vertexShader:[THREE.ShaderChunk.common,THREE.ShaderChunk.morphtarget_pars_vertex,THREE.ShaderChunk.skinning_pars_vertex,THREE.ShaderChunk.logdepthbuf_pars_vertex,"void main() {",THREE.ShaderChunk.skinbase_vertex,THREE.ShaderChunk.morphtarget_vertex,THREE.ShaderChunk.skinning_vertex,THREE.ShaderChunk.default_vertex,THREE.ShaderChunk.logdepthbuf_vertex,"}"].join("\n"),fragmentShader:[THREE.ShaderChunk.common,THREE.ShaderChunk.logdepthbuf_pars_fragment,"vec4 pack_depth( const in float depth ) {"," const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );"," const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );"," vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );"," res -= res.xxyz * bit_mask;"," return res;","}","void main() {",THREE.ShaderChunk.logdepthbuf_fragment," #ifdef USE_LOGDEPTHBUF_EXT"," gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );"," #else"," gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );"," #endif","}"].join("\n")}},THREE.WebGLRenderer=function(t){function e(t){t.__webglVertexBuffer=At.createBuffer(),t.__webglColorBuffer=At.createBuffer(),Ct.info.memory.geometries++}function n(t){t.__webglVertexBuffer=At.createBuffer(),t.__webglColorBuffer=At.createBuffer(),t.__webglLineDistanceBuffer=At.createBuffer(),Ct.info.memory.geometries++}function r(t){t.__webglVertexBuffer=At.createBuffer(),t.__webglNormalBuffer=At.createBuffer(),t.__webglTangentBuffer=At.createBuffer(),t.__webglColorBuffer=At.createBuffer(),t.__webglUVBuffer=At.createBuffer(),t.__webglUV2Buffer=At.createBuffer(),t.__webglSkinIndicesBuffer=At.createBuffer(),t.__webglSkinWeightsBuffer=At.createBuffer(),t.__webglFaceBuffer=At.createBuffer(),t.__webglLineBuffer=At.createBuffer();var e=t.numMorphTargets;if(e){t.__webglMorphTargetsBuffers=[];for(var n=0,r=e;r>n;n++)t.__webglMorphTargetsBuffers.push(At.createBuffer())}var i=t.numMorphNormals;if(i){t.__webglMorphNormalsBuffers=[];for(var n=0,r=i;r>n;n++)t.__webglMorphNormalsBuffers.push(At.createBuffer())}Ct.info.memory.geometries++}function i(t){var e=t.geometry,n=t.material,r=e.vertices.length;if(n.attributes){void 0===e.__webglCustomAttributesList&&(e.__webglCustomAttributesList=[]);for(var i in n.attributes){var o=n.attributes[i];if(!o.__webglInitialized||o.createUniqueBuffers){o.__webglInitialized=!0;var s=1;"v2"===o.type?s=2:"v3"===o.type?s=3:"v4"===o.type?s=4:"c"===o.type&&(s=3),o.size=s,o.array=new Float32Array(r*s),o.buffer=At.createBuffer(),o.buffer.belongsToAttribute=i,o.needsUpdate=!0}e.__webglCustomAttributesList.push(o)}}}function o(t,e){var n=t.vertices.length;t.__vertexArray=new Float32Array(3*n),t.__colorArray=new Float32Array(3*n),t.__webglParticleCount=n,i(e)}function s(t,e){var n=t.vertices.length;t.__vertexArray=new Float32Array(3*n),t.__colorArray=new Float32Array(3*n),t.__lineDistanceArray=new Float32Array(1*n),t.__webglLineCount=n,i(e)}function a(t,e){var n=e.geometry,r=t.faces3,i=3*r.length,o=1*r.length,s=3*r.length,a=u(e,t);t.__vertexArray=new Float32Array(3*i),t.__normalArray=new Float32Array(3*i),t.__colorArray=new Float32Array(3*i),t.__uvArray=new Float32Array(2*i),n.faceVertexUvs.length>1&&(t.__uv2Array=new Float32Array(2*i)),n.hasTangents&&(t.__tangentArray=new Float32Array(4*i)),e.geometry.skinWeights.length&&e.geometry.skinIndices.length&&(t.__skinIndexArray=new Float32Array(4*i),t.__skinWeightArray=new Float32Array(4*i));var h=null!==te.get("OES_element_index_uint")&&o>21845?Uint32Array:Uint16Array;t.__typeArray=h,t.__faceArray=new h(3*o),t.__lineArray=new h(2*s);var l=t.numMorphTargets;if(l){t.__morphTargetsArrays=[];for(var c=0,p=l;p>c;c++)t.__morphTargetsArrays.push(new Float32Array(3*i))}var f=t.numMorphNormals;if(f){t.__morphNormalsArrays=[];for(var c=0,p=f;p>c;c++)t.__morphNormalsArrays.push(new Float32Array(3*i))}if(t.__webglFaceCount=3*o,t.__webglLineCount=2*s,a.attributes){void 0===t.__webglCustomAttributesList&&(t.__webglCustomAttributesList=[]);for(var d in a.attributes){var m=a.attributes[d],v={};for(var g in m)v[g]=m[g];if(!v.__webglInitialized||v.createUniqueBuffers){v.__webglInitialized=!0;var E=1;"v2"===v.type?E=2:"v3"===v.type?E=3:"v4"===v.type?E=4:"c"===v.type&&(E=3),v.size=E,v.array=new Float32Array(i*E),v.buffer=At.createBuffer(),v.buffer.belongsToAttribute=d,m.needsUpdate=!0,v.__original=m}t.__webglCustomAttributesList.push(v)}}t.__inittedArrays=!0}function u(t,e){return t.material instanceof THREE.MeshFaceMaterial?t.material.materials[e.materialIndex]:t.material}function h(t){return t instanceof THREE.MeshPhongMaterial==!1&&t.shading===THREE.FlatShading}function l(t,e,n){var r,i,o,s,a,u,h,l,c,p,f,d=t.vertices,m=d.length,v=t.colors,g=v.length,E=t.__vertexArray,y=t.__colorArray,_=t.verticesNeedUpdate,b=t.colorsNeedUpdate,T=t.__webglCustomAttributesList;if(_){for(r=0;m>r;r++)o=d[r],s=3*r,E[s]=o.x,E[s+1]=o.y,E[s+2]=o.z;At.bindBuffer(At.ARRAY_BUFFER,t.__webglVertexBuffer),At.bufferData(At.ARRAY_BUFFER,E,e)}if(b){for(i=0;g>i;i++)a=v[i],s=3*i,y[s]=a.r,y[s+1]=a.g,y[s+2]=a.b;At.bindBuffer(At.ARRAY_BUFFER,t.__webglColorBuffer),At.bufferData(At.ARRAY_BUFFER,y,e)}if(T)for(u=0,h=T.length;h>u;u++){if(f=T[u],f.needsUpdate&&(void 0===f.boundTo||"vertices"===f.boundTo))if(c=f.value.length,s=0,1===f.size)for(l=0;c>l;l++)f.array[l]=f.value[l];else if(2===f.size)for(l=0;c>l;l++)p=f.value[l],f.array[s]=p.x,f.array[s+1]=p.y,s+=2;else if(3===f.size)if("c"===f.type)for(l=0;c>l;l++)p=f.value[l],f.array[s]=p.r,f.array[s+1]=p.g,f.array[s+2]=p.b,s+=3;else for(l=0;c>l;l++)p=f.value[l],f.array[s]=p.x,f.array[s+1]=p.y,f.array[s+2]=p.z,s+=3;else if(4===f.size)for(l=0;c>l;l++)p=f.value[l],f.array[s]=p.x,f.array[s+1]=p.y,f.array[s+2]=p.z,f.array[s+3]=p.w,s+=4;At.bindBuffer(At.ARRAY_BUFFER,f.buffer),At.bufferData(At.ARRAY_BUFFER,f.array,e),f.needsUpdate=!1}}function c(t,e){var n,r,i,o,s,a,u,h,l,c,p,f,d=t.vertices,m=t.colors,v=t.lineDistances,g=d.length,E=m.length,y=v.length,_=t.__vertexArray,b=t.__colorArray,T=t.__lineDistanceArray,x=t.verticesNeedUpdate,w=t.colorsNeedUpdate,R=t.lineDistancesNeedUpdate,H=t.__webglCustomAttributesList;if(x){for(n=0;g>n;n++)o=d[n],s=3*n,_[s]=o.x,_[s+1]=o.y,_[s+2]=o.z;At.bindBuffer(At.ARRAY_BUFFER,t.__webglVertexBuffer),At.bufferData(At.ARRAY_BUFFER,_,e)}if(w){for(r=0;E>r;r++)a=m[r],s=3*r,b[s]=a.r,b[s+1]=a.g,b[s+2]=a.b;At.bindBuffer(At.ARRAY_BUFFER,t.__webglColorBuffer),At.bufferData(At.ARRAY_BUFFER,b,e)}if(R){for(i=0;y>i;i++)T[i]=v[i];At.bindBuffer(At.ARRAY_BUFFER,t.__webglLineDistanceBuffer),At.bufferData(At.ARRAY_BUFFER,T,e)}if(H)for(u=0,h=H.length;h>u;u++)if(f=H[u],f.needsUpdate&&(void 0===f.boundTo||"vertices"===f.boundTo)){if(s=0,c=f.value.length,1===f.size)for(l=0;c>l;l++)f.array[l]=f.value[l];else if(2===f.size)for(l=0;c>l;l++)p=f.value[l],f.array[s]=p.x,f.array[s+1]=p.y,s+=2;else if(3===f.size)if("c"===f.type)for(l=0;c>l;l++)p=f.value[l],f.array[s]=p.r,f.array[s+1]=p.g,f.array[s+2]=p.b,s+=3;else for(l=0;c>l;l++)p=f.value[l],f.array[s]=p.x,f.array[s+1]=p.y,f.array[s+2]=p.z,s+=3;else if(4===f.size)for(l=0;c>l;l++)p=f.value[l],f.array[s]=p.x,f.array[s+1]=p.y,f.array[s+2]=p.z,f.array[s+3]=p.w,s+=4;At.bindBuffer(At.ARRAY_BUFFER,f.buffer),At.bufferData(At.ARRAY_BUFFER,f.array,e),f.needsUpdate=!1}}function p(t,e,n,r,i){if(t.__inittedArrays){var o,s,a,u,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k,A,C,P,L,z,O,D,F,U,B,N,V,I,j,G,W,q,X,Y=h(i),Z=0,K=0,Q=0,J=0,$=0,tt=0,et=0,nt=0,rt=0,it=0,ot=0,st=0,at=t.__vertexArray,ut=t.__uvArray,ht=t.__uv2Array,lt=t.__normalArray,ct=t.__tangentArray,pt=t.__colorArray,ft=t.__skinIndexArray,dt=t.__skinWeightArray,mt=t.__morphTargetsArrays,vt=t.__morphNormalsArrays,gt=t.__webglCustomAttributesList,Et=t.__faceArray,yt=t.__lineArray,_t=e.geometry,bt=_t.verticesNeedUpdate,Tt=_t.elementsNeedUpdate,xt=_t.uvsNeedUpdate,wt=_t.normalsNeedUpdate,Rt=_t.tangentsNeedUpdate,Ht=_t.colorsNeedUpdate,Mt=_t.morphTargetsNeedUpdate,St=_t.vertices,kt=t.faces3,Ct=_t.faces,Pt=_t.faceVertexUvs[0],Lt=_t.faceVertexUvs[1],zt=_t.skinIndices,Ot=_t.skinWeights,Dt=_t.morphTargets,Ft=_t.morphNormals;if(bt){for(o=0,s=kt.length;s>o;o++)u=Ct[kt[o]],g=St[u.a],E=St[u.b],y=St[u.c],at[K]=g.x,at[K+1]=g.y,at[K+2]=g.z,at[K+3]=E.x,at[K+4]=E.y,at[K+5]=E.z,at[K+6]=y.x,at[K+7]=y.y,at[K+8]=y.z,K+=9;At.bindBuffer(At.ARRAY_BUFFER,t.__webglVertexBuffer),At.bufferData(At.ARRAY_BUFFER,at,n)}if(Mt)for(N=0,V=Dt.length;V>N;N++){for(ot=0,o=0,s=kt.length;s>o;o++)G=kt[o],u=Ct[G],g=Dt[N].vertices[u.a],E=Dt[N].vertices[u.b],y=Dt[N].vertices[u.c],I=mt[N],I[ot]=g.x,I[ot+1]=g.y,I[ot+2]=g.z,I[ot+3]=E.x,I[ot+4]=E.y,I[ot+5]=E.z,I[ot+6]=y.x,I[ot+7]=y.y,I[ot+8]=y.z,i.morphNormals&&(Y?(x=Ft[N].faceNormals[G],w=x,R=x):(W=Ft[N].vertexNormals[G],x=W.a,w=W.b,R=W.c),j=vt[N],j[ot]=x.x,j[ot+1]=x.y,j[ot+2]=x.z,j[ot+3]=w.x,j[ot+4]=w.y,j[ot+5]=w.z,j[ot+6]=R.x,j[ot+7]=R.y,j[ot+8]=R.z),ot+=9;At.bindBuffer(At.ARRAY_BUFFER,t.__webglMorphTargetsBuffers[N]),At.bufferData(At.ARRAY_BUFFER,mt[N],n),i.morphNormals&&(At.bindBuffer(At.ARRAY_BUFFER,t.__webglMorphNormalsBuffers[N]),At.bufferData(At.ARRAY_BUFFER,vt[N],n))}if(Ot.length){for(o=0,s=kt.length;s>o;o++)u=Ct[kt[o]],k=Ot[u.a],A=Ot[u.b],C=Ot[u.c],dt[it]=k.x,dt[it+1]=k.y,dt[it+2]=k.z,dt[it+3]=k.w,dt[it+4]=A.x,dt[it+5]=A.y,dt[it+6]=A.z,dt[it+7]=A.w,dt[it+8]=C.x,dt[it+9]=C.y,dt[it+10]=C.z,dt[it+11]=C.w,P=zt[u.a],L=zt[u.b],z=zt[u.c],ft[it]=P.x,ft[it+1]=P.y,ft[it+2]=P.z,ft[it+3]=P.w,ft[it+4]=L.x,ft[it+5]=L.y,ft[it+6]=L.z,ft[it+7]=L.w,ft[it+8]=z.x,ft[it+9]=z.y,ft[it+10]=z.z,ft[it+11]=z.w,it+=12;it>0&&(At.bindBuffer(At.ARRAY_BUFFER,t.__webglSkinIndicesBuffer),At.bufferData(At.ARRAY_BUFFER,ft,n),At.bindBuffer(At.ARRAY_BUFFER,t.__webglSkinWeightsBuffer),At.bufferData(At.ARRAY_BUFFER,dt,n))}if(Ht){for(o=0,s=kt.length;s>o;o++)u=Ct[kt[o]],p=u.vertexColors,f=u.color,3===p.length&&i.vertexColors===THREE.VertexColors?(H=p[0],M=p[1],S=p[2]):(H=f,M=f,S=f),pt[rt]=H.r,pt[rt+1]=H.g,pt[rt+2]=H.b,pt[rt+3]=M.r,pt[rt+4]=M.g,pt[rt+5]=M.b,pt[rt+6]=S.r,pt[rt+7]=S.g,pt[rt+8]=S.b,rt+=9;rt>0&&(At.bindBuffer(At.ARRAY_BUFFER,t.__webglColorBuffer),At.bufferData(At.ARRAY_BUFFER,pt,n))}if(Rt&&_t.hasTangents){for(o=0,s=kt.length;s>o;o++)u=Ct[kt[o]],d=u.vertexTangents,_=d[0],b=d[1],T=d[2],ct[et]=_.x,ct[et+1]=_.y,ct[et+2]=_.z,ct[et+3]=_.w,ct[et+4]=b.x,ct[et+5]=b.y,ct[et+6]=b.z,ct[et+7]=b.w,ct[et+8]=T.x,ct[et+9]=T.y,ct[et+10]=T.z,ct[et+11]=T.w,et+=12;At.bindBuffer(At.ARRAY_BUFFER,t.__webglTangentBuffer),At.bufferData(At.ARRAY_BUFFER,ct,n)}if(wt){for(o=0,s=kt.length;s>o;o++)if(u=Ct[kt[o]],l=u.vertexNormals,c=u.normal,3===l.length&&Y===!1)for(O=0;3>O;O++)F=l[O],lt[tt]=F.x,lt[tt+1]=F.y,lt[tt+2]=F.z,tt+=3;else for(O=0;3>O;O++)lt[tt]=c.x,lt[tt+1]=c.y,lt[tt+2]=c.z,tt+=3;At.bindBuffer(At.ARRAY_BUFFER,t.__webglNormalBuffer),At.bufferData(At.ARRAY_BUFFER,lt,n)}if(xt&&Pt){for(o=0,s=kt.length;s>o;o++)if(a=kt[o],m=Pt[a],void 0!==m)for(O=0;3>O;O++)U=m[O],ut[Q]=U.x,ut[Q+1]=U.y,Q+=2;Q>0&&(At.bindBuffer(At.ARRAY_BUFFER,t.__webglUVBuffer),At.bufferData(At.ARRAY_BUFFER,ut,n))}if(xt&&Lt){for(o=0,s=kt.length;s>o;o++)if(a=kt[o],v=Lt[a],void 0!==v)for(O=0;3>O;O++)B=v[O],ht[J]=B.x,ht[J+1]=B.y,J+=2;J>0&&(At.bindBuffer(At.ARRAY_BUFFER,t.__webglUV2Buffer),At.bufferData(At.ARRAY_BUFFER,ht,n))}if(Tt){for(o=0,s=kt.length;s>o;o++)Et[$]=Z,Et[$+1]=Z+1,Et[$+2]=Z+2,$+=3,yt[nt]=Z,yt[nt+1]=Z+1,yt[nt+2]=Z,yt[nt+3]=Z+2,yt[nt+4]=Z+1,yt[nt+5]=Z+2,nt+=6,Z+=3;At.bindBuffer(At.ELEMENT_ARRAY_BUFFER,t.__webglFaceBuffer),At.bufferData(At.ELEMENT_ARRAY_BUFFER,Et,n),At.bindBuffer(At.ELEMENT_ARRAY_BUFFER,t.__webglLineBuffer),At.bufferData(At.ELEMENT_ARRAY_BUFFER,yt,n)}if(gt)for(O=0,D=gt.length;D>O;O++)if(X=gt[O],X.__original.needsUpdate){if(st=0,1===X.size){if(void 0===X.boundTo||"vertices"===X.boundTo)for(o=0,s=kt.length;s>o;o++)u=Ct[kt[o]],X.array[st]=X.value[u.a],X.array[st+1]=X.value[u.b],X.array[st+2]=X.value[u.c],st+=3;else if("faces"===X.boundTo)for(o=0,s=kt.length;s>o;o++)q=X.value[kt[o]],X.array[st]=q,X.array[st+1]=q,X.array[st+2]=q,st+=3}else if(2===X.size){if(void 0===X.boundTo||"vertices"===X.boundTo)for(o=0,s=kt.length;s>o;o++)u=Ct[kt[o]],g=X.value[u.a],E=X.value[u.b],y=X.value[u.c],X.array[st]=g.x,X.array[st+1]=g.y,X.array[st+2]=E.x,X.array[st+3]=E.y,X.array[st+4]=y.x,X.array[st+5]=y.y,st+=6;else if("faces"===X.boundTo)for(o=0,s=kt.length;s>o;o++)q=X.value[kt[o]],g=q,E=q,y=q,X.array[st]=g.x,X.array[st+1]=g.y,X.array[st+2]=E.x,X.array[st+3]=E.y,X.array[st+4]=y.x,X.array[st+5]=y.y,st+=6}else if(3===X.size){var Ut;if(Ut="c"===X.type?["r","g","b"]:["x","y","z"],void 0===X.boundTo||"vertices"===X.boundTo)for(o=0,s=kt.length;s>o;o++)u=Ct[kt[o]],g=X.value[u.a],E=X.value[u.b],y=X.value[u.c],X.array[st]=g[Ut[0]],X.array[st+1]=g[Ut[1]],X.array[st+2]=g[Ut[2]],X.array[st+3]=E[Ut[0]],X.array[st+4]=E[Ut[1]],X.array[st+5]=E[Ut[2]],X.array[st+6]=y[Ut[0]],X.array[st+7]=y[Ut[1]],X.array[st+8]=y[Ut[2]],st+=9;else if("faces"===X.boundTo)for(o=0,s=kt.length;s>o;o++)q=X.value[kt[o]],g=q,E=q,y=q,X.array[st]=g[Ut[0]],X.array[st+1]=g[Ut[1]],X.array[st+2]=g[Ut[2]],X.array[st+3]=E[Ut[0]],X.array[st+4]=E[Ut[1]],X.array[st+5]=E[Ut[2]],X.array[st+6]=y[Ut[0]],X.array[st+7]=y[Ut[1]],X.array[st+8]=y[Ut[2]],st+=9;else if("faceVertices"===X.boundTo)for(o=0,s=kt.length;s>o;o++)q=X.value[kt[o]],g=q[0],E=q[1],y=q[2],X.array[st]=g[Ut[0]],X.array[st+1]=g[Ut[1]],X.array[st+2]=g[Ut[2]],X.array[st+3]=E[Ut[0]],X.array[st+4]=E[Ut[1]],X.array[st+5]=E[Ut[2]],X.array[st+6]=y[Ut[0]],X.array[st+7]=y[Ut[1]],X.array[st+8]=y[Ut[2]],st+=9}else if(4===X.size)if(void 0===X.boundTo||"vertices"===X.boundTo)for(o=0,s=kt.length;s>o;o++)u=Ct[kt[o]],g=X.value[u.a],E=X.value[u.b],y=X.value[u.c],X.array[st]=g.x,X.array[st+1]=g.y,X.array[st+2]=g.z,X.array[st+3]=g.w,X.array[st+4]=E.x,X.array[st+5]=E.y,X.array[st+6]=E.z,X.array[st+7]=E.w,X.array[st+8]=y.x,X.array[st+9]=y.y,X.array[st+10]=y.z,X.array[st+11]=y.w,st+=12;else if("faces"===X.boundTo)for(o=0,s=kt.length;s>o;o++)q=X.value[kt[o]],g=q,E=q,y=q,X.array[st]=g.x,X.array[st+1]=g.y,X.array[st+2]=g.z,X.array[st+3]=g.w,X.array[st+4]=E.x,X.array[st+5]=E.y,X.array[st+6]=E.z,X.array[st+7]=E.w,X.array[st+8]=y.x,X.array[st+9]=y.y,X.array[st+10]=y.z,X.array[st+11]=y.w,st+=12;else if("faceVertices"===X.boundTo)for(o=0,s=kt.length;s>o;o++)q=X.value[kt[o]],g=q[0],E=q[1],y=q[2],X.array[st]=g.x,X.array[st+1]=g.y,X.array[st+2]=g.z,X.array[st+3]=g.w,X.array[st+4]=E.x,X.array[st+5]=E.y,X.array[st+6]=E.z,X.array[st+7]=E.w,X.array[st+8]=y.x,X.array[st+9]=y.y,X.array[st+10]=y.z,X.array[st+11]=y.w,st+=12;At.bindBuffer(At.ARRAY_BUFFER,X.buffer),At.bufferData(At.ARRAY_BUFFER,X.array,n)}r&&(delete t.__inittedArrays,delete t.__colorArray,delete t.__normalArray,delete t.__tangentArray,delete t.__uvArray,delete t.__uv2Array,delete t.__faceArray,delete t.__vertexArray,delete t.__lineArray,delete t.__skinIndexArray,delete t.__skinWeightArray)}}function f(t,e,n,r){for(var i=n.attributes,o=e.attributes,s=e.attributesKeys,a=0,u=s.length;u>a;a++){var h=s[a],l=o[h];if(l>=0){var c=i[h];if(void 0!==c){var p=c.itemSize;At.bindBuffer(At.ARRAY_BUFFER,c.buffer),$t.enableAttribute(l),At.vertexAttribPointer(l,p,At.FLOAT,!1,0,r*p*4)}else void 0!==t.defaultAttributeValues&&(2===t.defaultAttributeValues[h].length?At.vertexAttrib2fv(l,t.defaultAttributeValues[h]):3===t.defaultAttributeValues[h].length&&At.vertexAttrib3fv(l,t.defaultAttributeValues[h]))}}$t.disableUnusedAttributes()}function d(t,e,n){var r=t.program.attributes;if(-1!==n.morphTargetBase&&r.position>=0?(At.bindBuffer(At.ARRAY_BUFFER,e.__webglMorphTargetsBuffers[n.morphTargetBase]),$t.enableAttribute(r.position),At.vertexAttribPointer(r.position,3,At.FLOAT,!1,0,0)):r.position>=0&&(At.bindBuffer(At.ARRAY_BUFFER,e.__webglVertexBuffer),$t.enableAttribute(r.position),At.vertexAttribPointer(r.position,3,At.FLOAT,!1,0,0)),n.morphTargetForcedOrder.length)for(var i,o=0,s=n.morphTargetForcedOrder,a=n.morphTargetInfluences;o=0&&(At.bindBuffer(At.ARRAY_BUFFER,e.__webglMorphTargetsBuffers[s[o]]),$t.enableAttribute(i),At.vertexAttribPointer(i,3,At.FLOAT,!1,0,0)),i=r["morphNormal"+o],i>=0&&t.morphNormals&&(At.bindBuffer(At.ARRAY_BUFFER,e.__webglMorphNormalsBuffers[s[o]]),$t.enableAttribute(i),At.vertexAttribPointer(i,3,At.FLOAT,!1,0,0)),n.__webglMorphTargetInfluences[o]=a[s[o]],o++;else{var u=[],a=n.morphTargetInfluences,h=n.geometry.morphTargets;a.length>h.length&&(console.warn("THREE.WebGLRenderer: Influences array is bigger than morphTargets array."),a.length=h.length);for(var l=0,c=a.length;c>l;l++){var p=a[l];u.push([p,l])}u.length>t.numSupportedMorphTargets?(u.sort(g),u.length=t.numSupportedMorphTargets):u.length>t.numSupportedMorphNormals?u.sort(g):0===u.length&&u.push([0,0]);for(var i,o=0,f=t.numSupportedMorphTargets;f>o;o++)if(u[o]){var d=u[o][1];i=r["morphTarget"+o],i>=0&&(At.bindBuffer(At.ARRAY_BUFFER,e.__webglMorphTargetsBuffers[d]),$t.enableAttribute(i),At.vertexAttribPointer(i,3,At.FLOAT,!1,0,0)),i=r["morphNormal"+o],i>=0&&t.morphNormals&&(At.bindBuffer(At.ARRAY_BUFFER,e.__webglMorphNormalsBuffers[d]),$t.enableAttribute(i),At.vertexAttribPointer(i,3,At.FLOAT,!1,0,0)),n.__webglMorphTargetInfluences[o]=a[d]}else n.__webglMorphTargetInfluences[o]=0}null!==t.program.uniforms.morphTargetInfluences&&At.uniform1fv(t.program.uniforms.morphTargetInfluences,n.__webglMorphTargetInfluences)}function m(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function v(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function g(t,e){return e[0]-t[0]}function E(t){if(t.visible!==!1){if(t instanceof THREE.Scene||t instanceof THREE.Group);else if(x(t),t instanceof THREE.Light)xt.push(t);else if(t instanceof THREE.Sprite)St.push(t);else if(t instanceof THREE.LensFlare)kt.push(t);else{var e=wt[t.id];if(e&&(t.frustumCulled===!1||Wt.intersectsObject(t)===!0))for(var n=0,r=e.length;r>n;n++){var i=e[n];T(i),i.render=!0,Ct.sortObjects===!0&&(Xt.setFromMatrixPosition(t.matrixWorld),Xt.applyProjection(qt),i.z=Xt.z)}}for(var n=0,r=t.children.length;r>n;n++)E(t.children[n])}}function y(t,e,n,r,i){for(var o,s=0,a=t.length;a>s;s++){var u=t[s],h=u.object,l=u.buffer;if(Z(h,e),i)o=i;else{if(o=u.material,!o)continue;z(o)}Ct.setMaterialFaces(o),l instanceof THREE.BufferGeometry?Ct.renderBufferDirect(e,n,r,o,l,h):Ct.renderBuffer(e,n,r,o,l,h)}}function _(t,e,n,r,i,o){for(var s,a=0,u=t.length;u>a;a++){var h=t[a],l=h.object;if(l.visible){if(o)s=o;else{if(s=h[e],!s)continue;z(s)}Ct.renderImmediateObject(n,r,i,s,l)}}}function b(t){var e=t.object,n=e.material;n.transparent?(t.transparent=n,t.opaque=null):(t.opaque=n,t.transparent=null)}function T(t){var e=t.object,n=t.buffer,r=e.geometry,i=e.material;if(i instanceof THREE.MeshFaceMaterial){var o=r instanceof THREE.BufferGeometry?0:n.materialIndex;i=i.materials[o],t.material=i,i.transparent?Mt.push(t):Ht.push(t)}else i&&(t.material=i,i.transparent?Mt.push(t):Ht.push(t))}function x(t){void 0===t.__webglInit&&(t.__webglInit=!0,t._modelViewMatrix=new THREE.Matrix4,t._normalMatrix=new THREE.Matrix3,t.addEventListener("removed",_e));var r=t.geometry;if(void 0===r||void 0===r.__webglInit&&(r.__webglInit=!0,r.addEventListener("dispose",be),r instanceof THREE.BufferGeometry?Ct.info.memory.geometries++:t instanceof THREE.Mesh?R(t,r):t instanceof THREE.Line?void 0===r.__webglVertexBuffer&&(n(r),s(r,t),r.verticesNeedUpdate=!0,r.colorsNeedUpdate=!0,r.lineDistancesNeedUpdate=!0):t instanceof THREE.PointCloud&&void 0===r.__webglVertexBuffer&&(e(r),o(r,t),r.verticesNeedUpdate=!0,r.colorsNeedUpdate=!0)),void 0===t.__webglActive)if(t.__webglActive=!0,t instanceof THREE.Mesh){if(r instanceof THREE.BufferGeometry)H(wt,r,t);else if(r instanceof THREE.Geometry)for(var i=Ae[r.id],a=0,u=i.length;u>a;a++)H(wt,i[a],t)}else t instanceof THREE.Line||t instanceof THREE.PointCloud?H(wt,r,t):(t instanceof THREE.ImmediateRenderObject||t.immediateRenderCallback)&&M(Rt,t)}function w(t,e){for(var n,r,i=te.get("OES_element_index_uint")?4294967296:65535,o={},s=t.morphTargets.length,a=t.morphNormals.length,u={},h=[],l=0,c=t.faces.length;c>l;l++){var p=t.faces[l],f=e?p.materialIndex:0;f in o||(o[f]={hash:f,counter:0}),n=o[f].hash+"_"+o[f].counter,n in u||(r={id:Ce++,faces3:[],materialIndex:f,vertices:0,numMorphTargets:s,numMorphNormals:a},u[n]=r,h.push(r)),u[n].vertices+3>i&&(o[f].counter+=1,n=o[f].hash+"_"+o[f].counter,n in u||(r={id:Ce++,faces3:[],materialIndex:f,vertices:0,numMorphTargets:s,numMorphNormals:a},u[n]=r,h.push(r))),u[n].faces3.push(l),u[n].vertices+=3}return h}function R(t,e){var n=t.material,i=!1;(void 0===Ae[e.id]||e.groupsNeedUpdate===!0)&&(delete wt[t.id],Ae[e.id]=w(e,n instanceof THREE.MeshFaceMaterial),e.groupsNeedUpdate=!1);for(var o=Ae[e.id],s=0,u=o.length;u>s;s++){var h=o[s];void 0===h.__webglVertexBuffer?(r(h),a(h,t),e.verticesNeedUpdate=!0,e.morphTargetsNeedUpdate=!0,e.elementsNeedUpdate=!0,e.uvsNeedUpdate=!0,e.normalsNeedUpdate=!0,e.tangentsNeedUpdate=!0,e.colorsNeedUpdate=!0,i=!0):i=!1,(i||void 0===t.__webglActive)&&H(wt,h,t)}t.__webglActive=!0}function H(t,e,n){var r=n.id;t[r]=t[r]||[],t[r].push({id:r,buffer:e,object:n,material:null,z:0})}function M(t,e){t.push({id:null,object:e,opaque:null,transparent:null,z:0})}function S(t){var e=t.geometry;if(e instanceof THREE.BufferGeometry)for(var n=e.attributes,r=e.attributesKeys,i=0,o=r.length;o>i;i++){var s=r[i],a=n[s],h="index"===s?At.ELEMENT_ARRAY_BUFFER:At.ARRAY_BUFFER;void 0===a.buffer?(a.buffer=At.createBuffer(),At.bindBuffer(h,a.buffer),At.bufferData(h,a.array,a instanceof THREE.DynamicBufferAttribute?At.DYNAMIC_DRAW:At.STATIC_DRAW),a.needsUpdate=!1):a.needsUpdate===!0&&(At.bindBuffer(h,a.buffer),void 0===a.updateRange||-1===a.updateRange.count?At.bufferSubData(h,0,a.array):0===a.updateRange.count?console.error("THREE.WebGLRenderer.updateObject: using updateRange for THREE.DynamicBufferAttribute and marked as needsUpdate but count is 0, ensure you are using set methods or updating manually."):(At.bufferSubData(h,a.updateRange.offset*a.array.BYTES_PER_ELEMENT,a.array.subarray(a.updateRange.offset,a.updateRange.offset+a.updateRange.count)),a.updateRange.count=0),a.needsUpdate=!1)}else if(t instanceof THREE.Mesh){e.groupsNeedUpdate===!0&&R(t,e);for(var f=Ae[e.id],i=0,d=f.length;d>i;i++){var m=f[i],v=u(t,m),g=v.attributes&&k(v);(e.verticesNeedUpdate||e.morphTargetsNeedUpdate||e.elementsNeedUpdate||e.uvsNeedUpdate||e.normalsNeedUpdate||e.colorsNeedUpdate||e.tangentsNeedUpdate||g)&&p(m,t,At.DYNAMIC_DRAW,!e.dynamic,v)}e.verticesNeedUpdate=!1,e.morphTargetsNeedUpdate=!1,e.elementsNeedUpdate=!1,e.uvsNeedUpdate=!1,e.normalsNeedUpdate=!1,e.colorsNeedUpdate=!1,e.tangentsNeedUpdate=!1,v.attributes&&A(v)}else if(t instanceof THREE.Line){var v=u(t,e),g=v.attributes&&k(v);(e.verticesNeedUpdate||e.colorsNeedUpdate||e.lineDistancesNeedUpdate||g)&&c(e,At.DYNAMIC_DRAW),e.verticesNeedUpdate=!1,e.colorsNeedUpdate=!1,e.lineDistancesNeedUpdate=!1,v.attributes&&A(v)}else if(t instanceof THREE.PointCloud){var v=u(t,e),g=v.attributes&&k(v);(e.verticesNeedUpdate||e.colorsNeedUpdate||g)&&l(e,At.DYNAMIC_DRAW,t),e.verticesNeedUpdate=!1,e.colorsNeedUpdate=!1,v.attributes&&A(v)}}function k(t){for(var e in t.attributes)if(t.attributes[e].needsUpdate)return!0;return!1}function A(t){for(var e in t.attributes)t.attributes[e].needsUpdate=!1}function C(t){t instanceof THREE.Mesh||t instanceof THREE.PointCloud||t instanceof THREE.Line?delete wt[t.id]:(t instanceof THREE.ImmediateRenderObject||t.immediateRenderCallback)&&P(Rt,t),delete t.__webglInit,delete t._modelViewMatrix,delete t._normalMatrix,delete t.__webglActive}function P(t,e){for(var n=t.length-1;n>=0;n--)t[n].object===e&&t.splice(n,1)}function L(t,e,n,r){t.addEventListener("dispose",we);var i=Pe[t.type];if(i){var o=THREE.ShaderLib[i];t.__webglShader={uniforms:THREE.UniformsUtils.clone(o.uniforms),vertexShader:o.vertexShader,fragmentShader:o.fragmentShader}}else t.__webglShader={uniforms:t.uniforms,vertexShader:t.vertexShader,fragmentShader:t.fragmentShader};var s=ut(e),a=ht(e),u=at(r),h={precision:ft,supportsVertexTextures:ue,map:!!t.map,envMap:!!t.envMap,envMapMode:t.envMap&&t.envMap.mapping,lightMap:!!t.lightMap,bumpMap:!!t.bumpMap,normalMap:!!t.normalMap,specularMap:!!t.specularMap,alphaMap:!!t.alphaMap,combine:t.combine,vertexColors:t.vertexColors,fog:n,useFog:t.fog,fogExp:n instanceof THREE.FogExp2,flatShading:t.shading===THREE.FlatShading,sizeAttenuation:t.sizeAttenuation,logarithmicDepthBuffer:_t,skinning:t.skinning,maxBones:u,useVertexTexture:he&&r&&r.skeleton&&r.skeleton.useVertexTexture,morphTargets:t.morphTargets,morphNormals:t.morphNormals,maxMorphTargets:Ct.maxMorphTargets,maxMorphNormals:Ct.maxMorphNormals,maxDirLights:s.directional,maxPointLights:s.point,maxSpotLights:s.spot,maxHemiLights:s.hemi,maxShadows:a,shadowMapEnabled:Ct.shadowMapEnabled&&r.receiveShadow&&a>0,shadowMapType:Ct.shadowMapType,shadowMapDebug:Ct.shadowMapDebug, +shadowMapCascade:Ct.shadowMapCascade,alphaTest:t.alphaTest,metal:t.metal,wrapAround:t.wrapAround,doubleSided:t.side===THREE.DoubleSide,flipSided:t.side===THREE.BackSide},l=[];if(i?l.push(i):(l.push(t.fragmentShader),l.push(t.vertexShader)),void 0!==t.defines)for(var c in t.defines)l.push(c),l.push(t.defines[c]);for(var c in h)l.push(c),l.push(h[c]);for(var p,f=l.join(),d=0,m=Pt.length;m>d;d++){var v=Pt[d];if(v.code===f){p=v,p.usedTimes++;break}}void 0===p&&(p=new THREE.WebGLProgram(Ct,f,t,h),Pt.push(p),Ct.info.memory.programs=Pt.length),t.program=p;var g=p.attributes;if(t.morphTargets){t.numSupportedMorphTargets=0;for(var E,y="morphTarget",_=0;_=0&&t.numSupportedMorphTargets++}if(t.morphNormals){t.numSupportedMorphNormals=0;var E,y="morphNormal";for(_=0;_=0&&t.numSupportedMorphNormals++}t.uniformsList=[];for(var b in t.__webglShader.uniforms){var T=t.program.uniforms[b];T&&t.uniformsList.push([t.__webglShader.uniforms[b],T])}}function z(t){t.transparent===!0?$t.setBlending(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha):$t.setBlending(THREE.NoBlending),$t.setDepthTest(t.depthTest),$t.setDepthWrite(t.depthWrite),$t.setColorWrite(t.colorWrite),$t.setPolygonOffset(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits)}function O(t,e,n,r,i){Ut=0,r.needsUpdate&&(r.program&&ke(r),L(r,e,n,i),r.needsUpdate=!1),r.morphTargets&&(i.__webglMorphTargetInfluences||(i.__webglMorphTargetInfluences=new Float32Array(Ct.maxMorphTargets)));var o=!1,s=!1,a=!1,u=r.program,h=u.uniforms,l=r.__webglShader.uniforms;if(u.id!==Lt&&(At.useProgram(u.program),Lt=u.id,o=!0,s=!0,a=!0),r.id!==Ot&&(-1===Ot&&(a=!0),Ot=r.id,s=!0),(o||t!==Ft)&&(At.uniformMatrix4fv(h.projectionMatrix,!1,t.projectionMatrix.elements),_t&&At.uniform1f(h.logDepthBufFC,2/(Math.log(t.far+1)/Math.LN2)),t!==Ft&&(Ft=t),(r instanceof THREE.ShaderMaterial||r instanceof THREE.MeshPhongMaterial||r.envMap)&&null!==h.cameraPosition&&(Xt.setFromMatrixPosition(t.matrixWorld),At.uniform3f(h.cameraPosition,Xt.x,Xt.y,Xt.z)),(r instanceof THREE.MeshPhongMaterial||r instanceof THREE.MeshLambertMaterial||r instanceof THREE.MeshBasicMaterial||r instanceof THREE.ShaderMaterial||r.skinning)&&null!==h.viewMatrix&&At.uniformMatrix4fv(h.viewMatrix,!1,t.matrixWorldInverse.elements)),r.skinning)if(i.bindMatrix&&null!==h.bindMatrix&&At.uniformMatrix4fv(h.bindMatrix,!1,i.bindMatrix.elements),i.bindMatrixInverse&&null!==h.bindMatrixInverse&&At.uniformMatrix4fv(h.bindMatrixInverse,!1,i.bindMatrixInverse.elements),he&&i.skeleton&&i.skeleton.useVertexTexture){if(null!==h.boneTexture){var c=X();At.uniform1i(h.boneTexture,c),Ct.setTexture(i.skeleton.boneTexture,c)}null!==h.boneTextureWidth&&At.uniform1i(h.boneTextureWidth,i.skeleton.boneTextureWidth),null!==h.boneTextureHeight&&At.uniform1i(h.boneTextureHeight,i.skeleton.boneTextureHeight)}else i.skeleton&&i.skeleton.boneMatrices&&null!==h.boneGlobalMatrices&&At.uniformMatrix4fv(h.boneGlobalMatrices,!1,i.skeleton.boneMatrices);return s&&(n&&r.fog&&N(l,n),(r instanceof THREE.MeshPhongMaterial||r instanceof THREE.MeshLambertMaterial||r.lights)&&(Zt&&(a=!0,Q(e),Zt=!1),a?(j(l,Kt),G(l,!0)):G(l,!1)),(r instanceof THREE.MeshBasicMaterial||r instanceof THREE.MeshLambertMaterial||r instanceof THREE.MeshPhongMaterial)&&D(l,r),r instanceof THREE.LineBasicMaterial?F(l,r):r instanceof THREE.LineDashedMaterial?(F(l,r),U(l,r)):r instanceof THREE.PointCloudMaterial?B(l,r):r instanceof THREE.MeshPhongMaterial?V(l,r):r instanceof THREE.MeshLambertMaterial?I(l,r):r instanceof THREE.MeshDepthMaterial?(l.mNear.value=t.near,l.mFar.value=t.far,l.opacity.value=r.opacity):r instanceof THREE.MeshNormalMaterial&&(l.opacity.value=r.opacity),i.receiveShadow&&!r._shadowPass&&W(l,e),Y(r.uniformsList)),q(h,i),null!==h.modelMatrix&&At.uniformMatrix4fv(h.modelMatrix,!1,i.matrixWorld.elements),u}function D(t,e){t.opacity.value=e.opacity,t.diffuse.value=e.color,t.map.value=e.map,t.lightMap.value=e.lightMap,t.specularMap.value=e.specularMap,t.alphaMap.value=e.alphaMap,e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale));var n;if(e.map?n=e.map:e.specularMap?n=e.specularMap:e.normalMap?n=e.normalMap:e.bumpMap?n=e.bumpMap:e.alphaMap&&(n=e.alphaMap),void 0!==n){var r=n.offset,i=n.repeat;t.offsetRepeat.value.set(r.x,r.y,i.x,i.y)}t.envMap.value=e.envMap,t.flipEnvMap.value=e.envMap instanceof THREE.WebGLRenderTargetCube?1:-1,t.reflectivity.value=e.reflectivity,t.refractionRatio.value=e.refractionRatio}function F(t,e){t.diffuse.value=e.color,t.opacity.value=e.opacity}function U(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}function B(t,e){if(t.psColor.value=e.color,t.opacity.value=e.opacity,t.size.value=e.size,t.scale.value=lt.height/2,t.map.value=e.map,null!==e.map){var n=e.map.offset,r=e.map.repeat;t.offsetRepeat.value.set(n.x,n.y,r.x,r.y)}}function N(t,e){t.fogColor.value=e.color,e instanceof THREE.Fog?(t.fogNear.value=e.near,t.fogFar.value=e.far):e instanceof THREE.FogExp2&&(t.fogDensity.value=e.density)}function V(t,e){t.shininess.value=e.shininess,t.emissive.value=e.emissive,t.specular.value=e.specular,e.wrapAround&&t.wrapRGB.value.copy(e.wrapRGB)}function I(t,e){t.emissive.value=e.emissive,e.wrapAround&&t.wrapRGB.value.copy(e.wrapRGB)}function j(t,e){t.ambientLightColor.value=e.ambient,t.directionalLightColor.value=e.directional.colors,t.directionalLightDirection.value=e.directional.positions,t.pointLightColor.value=e.point.colors,t.pointLightPosition.value=e.point.positions,t.pointLightDistance.value=e.point.distances,t.pointLightDecay.value=e.point.decays,t.spotLightColor.value=e.spot.colors,t.spotLightPosition.value=e.spot.positions,t.spotLightDistance.value=e.spot.distances,t.spotLightDirection.value=e.spot.directions,t.spotLightAngleCos.value=e.spot.anglesCos,t.spotLightExponent.value=e.spot.exponents,t.spotLightDecay.value=e.spot.decays,t.hemisphereLightSkyColor.value=e.hemi.skyColors,t.hemisphereLightGroundColor.value=e.hemi.groundColors,t.hemisphereLightDirection.value=e.hemi.positions}function G(t,e){t.ambientLightColor.needsUpdate=e,t.directionalLightColor.needsUpdate=e,t.directionalLightDirection.needsUpdate=e,t.pointLightColor.needsUpdate=e,t.pointLightPosition.needsUpdate=e,t.pointLightDistance.needsUpdate=e,t.pointLightDecay.needsUpdate=e,t.spotLightColor.needsUpdate=e,t.spotLightPosition.needsUpdate=e,t.spotLightDistance.needsUpdate=e,t.spotLightDirection.needsUpdate=e,t.spotLightAngleCos.needsUpdate=e,t.spotLightExponent.needsUpdate=e,t.spotLightDecay.needsUpdate=e,t.hemisphereLightSkyColor.needsUpdate=e,t.hemisphereLightGroundColor.needsUpdate=e,t.hemisphereLightDirection.needsUpdate=e}function W(t,e){if(t.shadowMatrix)for(var n=0,r=0,i=e.length;i>r;r++){var o=e[r];o.castShadow&&(o instanceof THREE.SpotLight||o instanceof THREE.DirectionalLight&&!o.shadowCascade)&&(t.shadowMap.value[n]=o.shadowMap,t.shadowMapSize.value[n]=o.shadowMapSize,t.shadowMatrix.value[n]=o.shadowMatrix,t.shadowDarkness.value[n]=o.shadowDarkness,t.shadowBias.value[n]=o.shadowBias,n++)}}function q(t,e){At.uniformMatrix4fv(t.modelViewMatrix,!1,e._modelViewMatrix.elements),t.normalMatrix&&At.uniformMatrix3fv(t.normalMatrix,!1,e._normalMatrix.elements)}function X(){var t=Ut;return t>=ie&&THREE.warn("WebGLRenderer: trying to use "+t+" texture units while this GPU supports only "+ie),Ut+=1,t}function Y(t){for(var e,n,r,i=0,o=t.length;o>i;i++){var s=t[i][0];if(s.needsUpdate!==!1){var a=s.type,u=s.value,h=t[i][1];switch(a){case"1i":At.uniform1i(h,u);break;case"1f":At.uniform1f(h,u);break;case"2f":At.uniform2f(h,u[0],u[1]);break;case"3f":At.uniform3f(h,u[0],u[1],u[2]);break;case"4f":At.uniform4f(h,u[0],u[1],u[2],u[3]);break;case"1iv":At.uniform1iv(h,u);break;case"3iv":At.uniform3iv(h,u);break;case"1fv":At.uniform1fv(h,u);break;case"2fv":At.uniform2fv(h,u);break;case"3fv":At.uniform3fv(h,u);break;case"4fv":At.uniform4fv(h,u);break;case"Matrix3fv":At.uniformMatrix3fv(h,!1,u);break;case"Matrix4fv":At.uniformMatrix4fv(h,!1,u);break;case"i":At.uniform1i(h,u);break;case"f":At.uniform1f(h,u);break;case"v2":At.uniform2f(h,u.x,u.y);break;case"v3":At.uniform3f(h,u.x,u.y,u.z);break;case"v4":At.uniform4f(h,u.x,u.y,u.z,u.w);break;case"c":At.uniform3f(h,u.r,u.g,u.b);break;case"iv1":At.uniform1iv(h,u);break;case"iv":At.uniform3iv(h,u);break;case"fv1":At.uniform1fv(h,u);break;case"fv":At.uniform3fv(h,u);break;case"v2v":void 0===s._array&&(s._array=new Float32Array(2*u.length));for(var l=0,c=u.length;c>l;l++)r=2*l,s._array[r]=u[l].x,s._array[r+1]=u[l].y;At.uniform2fv(h,s._array);break;case"v3v":void 0===s._array&&(s._array=new Float32Array(3*u.length));for(var l=0,c=u.length;c>l;l++)r=3*l,s._array[r]=u[l].x,s._array[r+1]=u[l].y,s._array[r+2]=u[l].z;At.uniform3fv(h,s._array);break;case"v4v":void 0===s._array&&(s._array=new Float32Array(4*u.length));for(var l=0,c=u.length;c>l;l++)r=4*l,s._array[r]=u[l].x,s._array[r+1]=u[l].y,s._array[r+2]=u[l].z,s._array[r+3]=u[l].w;At.uniform4fv(h,s._array);break;case"m3":At.uniformMatrix3fv(h,!1,u.elements);break;case"m3v":void 0===s._array&&(s._array=new Float32Array(9*u.length));for(var l=0,c=u.length;c>l;l++)u[l].flattenToArrayOffset(s._array,9*l);At.uniformMatrix3fv(h,!1,s._array);break;case"m4":At.uniformMatrix4fv(h,!1,u.elements);break;case"m4v":void 0===s._array&&(s._array=new Float32Array(16*u.length));for(var l=0,c=u.length;c>l;l++)u[l].flattenToArrayOffset(s._array,16*l);At.uniformMatrix4fv(h,!1,s._array);break;case"t":if(e=u,n=X(),At.uniform1i(h,n),!e)continue;e instanceof THREE.CubeTexture||e.image instanceof Array&&6===e.image.length?tt(e,n):e instanceof THREE.WebGLRenderTargetCube?et(e,n):Ct.setTexture(e,n);break;case"tv":void 0===s._array&&(s._array=[]);for(var l=0,c=s.value.length;c>l;l++)s._array[l]=X();At.uniform1iv(h,s._array);for(var l=0,c=s.value.length;c>l;l++)e=s.value[l],n=s._array[l],e&&Ct.setTexture(e,n);break;default:THREE.warn("THREE.WebGLRenderer: Unknown uniform type: "+a)}}}}function Z(t,e){t._modelViewMatrix.multiplyMatrices(e.matrixWorldInverse,t.matrixWorld),t._normalMatrix.getNormalMatrix(t._modelViewMatrix)}function K(t,e,n,r){t[e]=n.r*r,t[e+1]=n.g*r,t[e+2]=n.b*r}function Q(t){var e,n,r,i,o,s,a,u,h=0,l=0,c=0,p=Kt,f=p.directional.colors,d=p.directional.positions,m=p.point.colors,v=p.point.positions,g=p.point.distances,E=p.point.decays,y=p.spot.colors,_=p.spot.positions,b=p.spot.distances,T=p.spot.directions,x=p.spot.anglesCos,w=p.spot.exponents,R=p.spot.decays,H=p.hemi.skyColors,M=p.hemi.groundColors,S=p.hemi.positions,k=0,A=0,C=0,P=0,L=0,z=0,O=0,D=0,F=0,U=0,B=0,N=0;for(e=0,n=t.length;n>e;e++)if(r=t[e],!r.onlyShadow)if(i=r.color,a=r.intensity,u=r.distance,r instanceof THREE.AmbientLight){if(!r.visible)continue;h+=i.r,l+=i.g,c+=i.b}else if(r instanceof THREE.DirectionalLight){if(L+=1,!r.visible)continue;Yt.setFromMatrixPosition(r.matrixWorld),Xt.setFromMatrixPosition(r.target.matrixWorld),Yt.sub(Xt),Yt.normalize(),F=3*k,d[F]=Yt.x,d[F+1]=Yt.y,d[F+2]=Yt.z,K(f,F,i,a),k+=1}else if(r instanceof THREE.PointLight){if(z+=1,!r.visible)continue;U=3*A,K(m,U,i,a),Xt.setFromMatrixPosition(r.matrixWorld),v[U]=Xt.x,v[U+1]=Xt.y,v[U+2]=Xt.z,g[A]=u,E[A]=0===r.distance?0:r.decay,A+=1}else if(r instanceof THREE.SpotLight){if(O+=1,!r.visible)continue;B=3*C,K(y,B,i,a),Yt.setFromMatrixPosition(r.matrixWorld),_[B]=Yt.x,_[B+1]=Yt.y,_[B+2]=Yt.z,b[C]=u,Xt.setFromMatrixPosition(r.target.matrixWorld),Yt.sub(Xt),Yt.normalize(),T[B]=Yt.x,T[B+1]=Yt.y,T[B+2]=Yt.z,x[C]=Math.cos(r.angle),w[C]=r.exponent,R[C]=0===r.distance?0:r.decay,C+=1}else if(r instanceof THREE.HemisphereLight){if(D+=1,!r.visible)continue;Yt.setFromMatrixPosition(r.matrixWorld),Yt.normalize(),N=3*P,S[N]=Yt.x,S[N+1]=Yt.y,S[N+2]=Yt.z,o=r.color,s=r.groundColor,K(H,N,o,a),K(M,N,s,a),P+=1}for(e=3*k,n=Math.max(f.length,3*L);n>e;e++)f[e]=0;for(e=3*A,n=Math.max(m.length,3*z);n>e;e++)m[e]=0;for(e=3*C,n=Math.max(y.length,3*O);n>e;e++)y[e]=0;for(e=3*P,n=Math.max(H.length,3*D);n>e;e++)H[e]=0;for(e=3*P,n=Math.max(M.length,3*D);n>e;e++)M[e]=0;p.directional.length=k,p.point.length=A,p.spot.length=C,p.hemi.length=P,p.ambient[0]=h,p.ambient[1]=l,p.ambient[2]=c}function J(t,e,n){var r;n?(At.texParameteri(t,At.TEXTURE_WRAP_S,st(e.wrapS)),At.texParameteri(t,At.TEXTURE_WRAP_T,st(e.wrapT)),At.texParameteri(t,At.TEXTURE_MAG_FILTER,st(e.magFilter)),At.texParameteri(t,At.TEXTURE_MIN_FILTER,st(e.minFilter))):(At.texParameteri(t,At.TEXTURE_WRAP_S,At.CLAMP_TO_EDGE),At.texParameteri(t,At.TEXTURE_WRAP_T,At.CLAMP_TO_EDGE),(e.wrapS!==THREE.ClampToEdgeWrapping||e.wrapT!==THREE.ClampToEdgeWrapping)&&THREE.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping. ( "+e.sourceFile+" )"),At.texParameteri(t,At.TEXTURE_MAG_FILTER,ot(e.magFilter)),At.texParameteri(t,At.TEXTURE_MIN_FILTER,ot(e.minFilter)),e.minFilter!==THREE.NearestFilter&&e.minFilter!==THREE.LinearFilter&&THREE.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. ( "+e.sourceFile+" )")),r=te.get("EXT_texture_filter_anisotropic"),r&&e.type!==THREE.FloatType&&e.type!==THREE.HalfFloatType&&(e.anisotropy>1||e.__currentAnisotropy)&&(At.texParameterf(t,r.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(e.anisotropy,Ct.getMaxAnisotropy())),e.__currentAnisotropy=e.anisotropy)}function $(t,e){if(t.width>e||t.height>e){var n=e/Math.max(t.width,t.height),r=document.createElement("canvas");r.width=Math.floor(t.width*n),r.height=Math.floor(t.height*n);var i=r.getContext("2d");return i.drawImage(t,0,0,t.width,t.height,0,0,r.width,r.height),THREE.warn("THREE.WebGLRenderer: image is too big ("+t.width+"x"+t.height+"). Resized to "+r.width+"x"+r.height,t),r}return t}function tt(t,e){if(6===t.image.length)if(t.needsUpdate){t.image.__webglTextureCube||(t.addEventListener("dispose",Te),t.image.__webglTextureCube=At.createTexture(),Ct.info.memory.textures++),At.activeTexture(At.TEXTURE0+e),At.bindTexture(At.TEXTURE_CUBE_MAP,t.image.__webglTextureCube),At.pixelStorei(At.UNPACK_FLIP_Y_WEBGL,t.flipY);for(var n=t instanceof THREE.CompressedTexture,r=t.image[0]instanceof THREE.DataTexture,i=[],o=0;6>o;o++)!Ct.autoScaleCubemaps||n||r?i[o]=r?t.image[o].image:t.image[o]:i[o]=$(t.image[o],ae);var s=i[0],a=THREE.Math.isPowerOfTwo(s.width)&&THREE.Math.isPowerOfTwo(s.height),u=st(t.format),h=st(t.type);J(At.TEXTURE_CUBE_MAP,t,a);for(var o=0;6>o;o++)if(n)for(var l,c=i[o].mipmaps,p=0,f=c.length;f>p;p++)l=c[p],t.format!==THREE.RGBAFormat&&t.format!==THREE.RGBFormat?de().indexOf(u)>-1?At.compressedTexImage2D(At.TEXTURE_CUBE_MAP_POSITIVE_X+o,p,u,l.width,l.height,0,l.data):THREE.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()"):At.texImage2D(At.TEXTURE_CUBE_MAP_POSITIVE_X+o,p,u,l.width,l.height,0,u,h,l.data);else r?At.texImage2D(At.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,u,i[o].width,i[o].height,0,u,h,i[o].data):At.texImage2D(At.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,u,u,h,i[o]);t.generateMipmaps&&a&&At.generateMipmap(At.TEXTURE_CUBE_MAP),t.needsUpdate=!1,t.onUpdate&&t.onUpdate()}else At.activeTexture(At.TEXTURE0+e),At.bindTexture(At.TEXTURE_CUBE_MAP,t.image.__webglTextureCube)}function et(t,e){At.activeTexture(At.TEXTURE0+e),At.bindTexture(At.TEXTURE_CUBE_MAP,t.__webglTexture)}function nt(t,e,n){At.bindFramebuffer(At.FRAMEBUFFER,t),At.framebufferTexture2D(At.FRAMEBUFFER,At.COLOR_ATTACHMENT0,n,e.__webglTexture,0)}function rt(t,e){At.bindRenderbuffer(At.RENDERBUFFER,t),e.depthBuffer&&!e.stencilBuffer?(At.renderbufferStorage(At.RENDERBUFFER,At.DEPTH_COMPONENT16,e.width,e.height),At.framebufferRenderbuffer(At.FRAMEBUFFER,At.DEPTH_ATTACHMENT,At.RENDERBUFFER,t)):e.depthBuffer&&e.stencilBuffer?(At.renderbufferStorage(At.RENDERBUFFER,At.DEPTH_STENCIL,e.width,e.height),At.framebufferRenderbuffer(At.FRAMEBUFFER,At.DEPTH_STENCIL_ATTACHMENT,At.RENDERBUFFER,t)):At.renderbufferStorage(At.RENDERBUFFER,At.RGBA4,e.width,e.height)}function it(t){t instanceof THREE.WebGLRenderTargetCube?(At.bindTexture(At.TEXTURE_CUBE_MAP,t.__webglTexture),At.generateMipmap(At.TEXTURE_CUBE_MAP),At.bindTexture(At.TEXTURE_CUBE_MAP,null)):(At.bindTexture(At.TEXTURE_2D,t.__webglTexture),At.generateMipmap(At.TEXTURE_2D),At.bindTexture(At.TEXTURE_2D,null))}function ot(t){return t===THREE.NearestFilter||t===THREE.NearestMipMapNearestFilter||t===THREE.NearestMipMapLinearFilter?At.NEAREST:At.LINEAR}function st(t){var e;if(t===THREE.RepeatWrapping)return At.REPEAT;if(t===THREE.ClampToEdgeWrapping)return At.CLAMP_TO_EDGE;if(t===THREE.MirroredRepeatWrapping)return At.MIRRORED_REPEAT;if(t===THREE.NearestFilter)return At.NEAREST;if(t===THREE.NearestMipMapNearestFilter)return At.NEAREST_MIPMAP_NEAREST;if(t===THREE.NearestMipMapLinearFilter)return At.NEAREST_MIPMAP_LINEAR;if(t===THREE.LinearFilter)return At.LINEAR;if(t===THREE.LinearMipMapNearestFilter)return At.LINEAR_MIPMAP_NEAREST;if(t===THREE.LinearMipMapLinearFilter)return At.LINEAR_MIPMAP_LINEAR;if(t===THREE.UnsignedByteType)return At.UNSIGNED_BYTE;if(t===THREE.UnsignedShort4444Type)return At.UNSIGNED_SHORT_4_4_4_4;if(t===THREE.UnsignedShort5551Type)return At.UNSIGNED_SHORT_5_5_5_1;if(t===THREE.UnsignedShort565Type)return At.UNSIGNED_SHORT_5_6_5;if(t===THREE.ByteType)return At.BYTE;if(t===THREE.ShortType)return At.SHORT;if(t===THREE.UnsignedShortType)return At.UNSIGNED_SHORT;if(t===THREE.IntType)return At.INT;if(t===THREE.UnsignedIntType)return At.UNSIGNED_INT;if(t===THREE.FloatType)return At.FLOAT;if(e=te.get("OES_texture_half_float"),null!==e&&t===THREE.HalfFloatType)return e.HALF_FLOAT_OES;if(t===THREE.AlphaFormat)return At.ALPHA;if(t===THREE.RGBFormat)return At.RGB;if(t===THREE.RGBAFormat)return At.RGBA;if(t===THREE.LuminanceFormat)return At.LUMINANCE;if(t===THREE.LuminanceAlphaFormat)return At.LUMINANCE_ALPHA;if(t===THREE.AddEquation)return At.FUNC_ADD;if(t===THREE.SubtractEquation)return At.FUNC_SUBTRACT;if(t===THREE.ReverseSubtractEquation)return At.FUNC_REVERSE_SUBTRACT;if(t===THREE.ZeroFactor)return At.ZERO;if(t===THREE.OneFactor)return At.ONE;if(t===THREE.SrcColorFactor)return At.SRC_COLOR;if(t===THREE.OneMinusSrcColorFactor)return At.ONE_MINUS_SRC_COLOR;if(t===THREE.SrcAlphaFactor)return At.SRC_ALPHA;if(t===THREE.OneMinusSrcAlphaFactor)return At.ONE_MINUS_SRC_ALPHA;if(t===THREE.DstAlphaFactor)return At.DST_ALPHA;if(t===THREE.OneMinusDstAlphaFactor)return At.ONE_MINUS_DST_ALPHA;if(t===THREE.DstColorFactor)return At.DST_COLOR;if(t===THREE.OneMinusDstColorFactor)return At.ONE_MINUS_DST_COLOR;if(t===THREE.SrcAlphaSaturateFactor)return At.SRC_ALPHA_SATURATE;if(e=te.get("WEBGL_compressed_texture_s3tc"),null!==e){if(t===THREE.RGB_S3TC_DXT1_Format)return e.COMPRESSED_RGB_S3TC_DXT1_EXT;if(t===THREE.RGBA_S3TC_DXT1_Format)return e.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(t===THREE.RGBA_S3TC_DXT3_Format)return e.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(t===THREE.RGBA_S3TC_DXT5_Format)return e.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e=te.get("WEBGL_compressed_texture_pvrtc"),null!==e){if(t===THREE.RGB_PVRTC_4BPPV1_Format)return e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(t===THREE.RGB_PVRTC_2BPPV1_Format)return e.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(t===THREE.RGBA_PVRTC_4BPPV1_Format)return e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(t===THREE.RGBA_PVRTC_2BPPV1_Format)return e.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e=te.get("EXT_blend_minmax"),null!==e){if(t===THREE.MinEquation)return e.MIN_EXT;if(t===THREE.MaxEquation)return e.MAX_EXT}return 0}function at(t){if(he&&t&&t.skeleton&&t.skeleton.useVertexTexture)return 1024;var e=At.getParameter(At.MAX_VERTEX_UNIFORM_VECTORS),n=Math.floor((e-20)/4),r=n;return void 0!==t&&t instanceof THREE.SkinnedMesh&&(r=Math.min(t.skeleton.bones.length,r),ro;o++){var a=t[o];a.onlyShadow||a.visible===!1||(a instanceof THREE.DirectionalLight&&e++,a instanceof THREE.PointLight&&n++,a instanceof THREE.SpotLight&&r++,a instanceof THREE.HemisphereLight&&i++)}return{directional:e,point:n,spot:r,hemi:i}}function ht(t){for(var e=0,n=0,r=t.length;r>n;n++){var i=t[n];i.castShadow&&(i instanceof THREE.SpotLight&&e++,i instanceof THREE.DirectionalLight&&!i.shadowCascade&&e++)}return e}console.log("THREE.WebGLRenderer",THREE.REVISION),t=t||{};var lt=void 0!==t.canvas?t.canvas:document.createElement("canvas"),ct=void 0!==t.context?t.context:null,pt=1,ft=void 0!==t.precision?t.precision:"highp",dt=void 0!==t.alpha?t.alpha:!1,mt=void 0!==t.depth?t.depth:!0,vt=void 0!==t.stencil?t.stencil:!0,gt=void 0!==t.antialias?t.antialias:!1,Et=void 0!==t.premultipliedAlpha?t.premultipliedAlpha:!0,yt=void 0!==t.preserveDrawingBuffer?t.preserveDrawingBuffer:!1,_t=void 0!==t.logarithmicDepthBuffer?t.logarithmicDepthBuffer:!1,bt=new THREE.Color(0),Tt=0,xt=[],wt={},Rt=[],Ht=[],Mt=[],St=[],kt=[];this.domElement=lt,this.context=null,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.gammaFactor=2,this.gammaInput=!1,this.gammaOutput=!1,this.shadowMapEnabled=!1,this.shadowMapType=THREE.PCFShadowMap,this.shadowMapCullFace=THREE.CullFaceFront,this.shadowMapDebug=!1,this.shadowMapCascade=!1,this.maxMorphTargets=8,this.maxMorphNormals=4,this.autoScaleCubemaps=!0,this.info={memory:{programs:0,geometries:0,textures:0},render:{calls:0,vertices:0,faces:0,points:0}};var At,Ct=this,Pt=[],Lt=null,zt=null,Ot=-1,Dt="",Ft=null,Ut=0,Bt=0,Nt=0,Vt=lt.width,It=lt.height,jt=0,Gt=0,Wt=new THREE.Frustum,qt=new THREE.Matrix4,Xt=new THREE.Vector3,Yt=new THREE.Vector3,Zt=!0,Kt={ambient:[0,0,0],directional:{length:0,colors:[],positions:[]},point:{length:0,colors:[],positions:[],distances:[],decays:[]},spot:{length:0,colors:[],positions:[],distances:[],directions:[],anglesCos:[],exponents:[],decays:[]},hemi:{length:0,skyColors:[],groundColors:[],positions:[]}};try{var Qt={alpha:dt,depth:mt,stencil:vt,antialias:gt,premultipliedAlpha:Et,preserveDrawingBuffer:yt};if(At=ct||lt.getContext("webgl",Qt)||lt.getContext("experimental-webgl",Qt),null===At)throw null!==lt.getContext("webgl")?"Error creating WebGL context with your selected attributes.":"Error creating WebGL context.";lt.addEventListener("webglcontextlost",function(t){t.preventDefault(),re(),ne(),wt={}},!1)}catch(Jt){THREE.error("THREE.WebGLRenderer: "+Jt)}var $t=new THREE.WebGLState(At,st);void 0===At.getShaderPrecisionFormat&&(At.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}});var te=new THREE.WebGLExtensions(At);te.get("OES_texture_float"),te.get("OES_texture_float_linear"),te.get("OES_texture_half_float"),te.get("OES_texture_half_float_linear"),te.get("OES_standard_derivatives"),_t&&te.get("EXT_frag_depth");var ee=function(t,e,n,r){Et===!0&&(t*=r,e*=r,n*=r),At.clearColor(t,e,n,r)},ne=function(){At.clearColor(0,0,0,1),At.clearDepth(1),At.clearStencil(0),At.enable(At.DEPTH_TEST),At.depthFunc(At.LEQUAL),At.frontFace(At.CCW),At.cullFace(At.BACK),At.enable(At.CULL_FACE),At.enable(At.BLEND),At.blendEquation(At.FUNC_ADD),At.blendFunc(At.SRC_ALPHA,At.ONE_MINUS_SRC_ALPHA),At.viewport(Bt,Nt,Vt,It),ee(bt.r,bt.g,bt.b,Tt)},re=function(){Lt=null,Ft=null,Dt="",Ot=-1,Zt=!0,$t.reset()};ne(),this.context=At,this.state=$t;var ie=At.getParameter(At.MAX_TEXTURE_IMAGE_UNITS),oe=At.getParameter(At.MAX_VERTEX_TEXTURE_IMAGE_UNITS),se=At.getParameter(At.MAX_TEXTURE_SIZE),ae=At.getParameter(At.MAX_CUBE_MAP_TEXTURE_SIZE),ue=oe>0,he=ue&&te.get("OES_texture_float"),le=At.getShaderPrecisionFormat(At.VERTEX_SHADER,At.HIGH_FLOAT),ce=At.getShaderPrecisionFormat(At.VERTEX_SHADER,At.MEDIUM_FLOAT),pe=At.getShaderPrecisionFormat(At.FRAGMENT_SHADER,At.HIGH_FLOAT),fe=At.getShaderPrecisionFormat(At.FRAGMENT_SHADER,At.MEDIUM_FLOAT),de=function(){var t;return function(){if(void 0!==t)return t;if(t=[],te.get("WEBGL_compressed_texture_pvrtc")||te.get("WEBGL_compressed_texture_s3tc"))for(var e=At.getParameter(At.COMPRESSED_TEXTURE_FORMATS),n=0;n0&&pe.precision>0,ve=ce.precision>0&&fe.precision>0;"highp"!==ft||me||(ve?(ft="mediump",THREE.warn("THREE.WebGLRenderer: highp not supported, using mediump.")):(ft="lowp",THREE.warn("THREE.WebGLRenderer: highp and mediump not supported, using lowp."))),"mediump"!==ft||ve||(ft="lowp",THREE.warn("THREE.WebGLRenderer: mediump not supported, using lowp."));var ge=new THREE.ShadowMapPlugin(this,xt,wt,Rt),Ee=new THREE.SpritePlugin(this,St),ye=new THREE.LensFlarePlugin(this,kt);this.getContext=function(){return At},this.forceContextLoss=function(){te.get("WEBGL_lose_context").loseContext()},this.supportsVertexTextures=function(){return ue},this.supportsFloatTextures=function(){return te.get("OES_texture_float")},this.supportsHalfFloatTextures=function(){return te.get("OES_texture_half_float")},this.supportsStandardDerivatives=function(){return te.get("OES_standard_derivatives")},this.supportsCompressedTextureS3TC=function(){return te.get("WEBGL_compressed_texture_s3tc")},this.supportsCompressedTexturePVRTC=function(){return te.get("WEBGL_compressed_texture_pvrtc")},this.supportsBlendMinMax=function(){return te.get("EXT_blend_minmax")},this.getMaxAnisotropy=function(){var t;return function(){if(void 0!==t)return t;var e=te.get("EXT_texture_filter_anisotropic");return t=null!==e?At.getParameter(e.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0}}(),this.getPrecision=function(){return ft},this.getPixelRatio=function(){return pt},this.setPixelRatio=function(t){pt=t},this.setSize=function(t,e,n){lt.width=t*pt,lt.height=e*pt,n!==!1&&(lt.style.width=t+"px",lt.style.height=e+"px"),this.setViewport(0,0,t,e)},this.setViewport=function(t,e,n,r){Bt=t*pt,Nt=e*pt,Vt=n*pt,It=r*pt,At.viewport(Bt,Nt,Vt,It)},this.setScissor=function(t,e,n,r){At.scissor(t*pt,e*pt,n*pt,r*pt)},this.enableScissorTest=function(t){t?At.enable(At.SCISSOR_TEST):At.disable(At.SCISSOR_TEST)},this.getClearColor=function(){return bt},this.setClearColor=function(t,e){bt.set(t),Tt=void 0!==e?e:1,ee(bt.r,bt.g,bt.b,Tt)},this.getClearAlpha=function(){return Tt},this.setClearAlpha=function(t){Tt=t,ee(bt.r,bt.g,bt.b,Tt)},this.clear=function(t,e,n){var r=0;(void 0===t||t)&&(r|=At.COLOR_BUFFER_BIT),(void 0===e||e)&&(r|=At.DEPTH_BUFFER_BIT),(void 0===n||n)&&(r|=At.STENCIL_BUFFER_BIT),At.clear(r)},this.clearColor=function(){At.clear(At.COLOR_BUFFER_BIT)},this.clearDepth=function(){At.clear(At.DEPTH_BUFFER_BIT)},this.clearStencil=function(){At.clear(At.STENCIL_BUFFER_BIT)},this.clearTarget=function(t,e,n,r){this.setRenderTarget(t),this.clear(e,n,r)},this.resetGLState=re;var _e=function(t){var e=t.target;e.traverse(function(t){t.removeEventListener("remove",_e),C(t)})},be=function(t){var e=t.target;e.removeEventListener("dispose",be),He(e)},Te=function(t){var e=t.target;e.removeEventListener("dispose",Te),Me(e),Ct.info.memory.textures--},xe=function(t){var e=t.target;e.removeEventListener("dispose",xe),Se(e),Ct.info.memory.textures--},we=function(t){var e=t.target;e.removeEventListener("dispose",we),ke(e)},Re=function(t){for(var e=["__webglVertexBuffer","__webglNormalBuffer","__webglTangentBuffer","__webglColorBuffer","__webglUVBuffer","__webglUV2Buffer","__webglSkinIndicesBuffer","__webglSkinWeightsBuffer","__webglFaceBuffer","__webglLineBuffer","__webglLineDistanceBuffer"],n=0,r=e.length;r>n;n++){var i=e[n];void 0!==t[i]&&(At.deleteBuffer(t[i]),delete t[i])}if(void 0!==t.__webglCustomAttributesList){for(var i in t.__webglCustomAttributesList)At.deleteBuffer(t.__webglCustomAttributesList[i].buffer);delete t.__webglCustomAttributesList}Ct.info.memory.geometries--},He=function(t){if(delete t.__webglInit,t instanceof THREE.BufferGeometry){for(var e in t.attributes){var n=t.attributes[e];void 0!==n.buffer&&(At.deleteBuffer(n.buffer),delete n.buffer)}Ct.info.memory.geometries--}else{var r=Ae[t.id];if(void 0!==r){for(var i=0,o=r.length;o>i;i++){var s=r[i];if(void 0!==s.numMorphTargets){for(var a=0,u=s.numMorphTargets;u>a;a++)At.deleteBuffer(s.__webglMorphTargetsBuffers[a]);delete s.__webglMorphTargetsBuffers}if(void 0!==s.numMorphNormals){for(var a=0,u=s.numMorphNormals;u>a;a++)At.deleteBuffer(s.__webglMorphNormalsBuffers[a]);delete s.__webglMorphNormalsBuffers}Re(s)}delete Ae[t.id]}else Re(t)}Dt=""},Me=function(t){if(t.image&&t.image.__webglTextureCube)At.deleteTexture(t.image.__webglTextureCube),delete t.image.__webglTextureCube;else{if(void 0===t.__webglInit)return;At.deleteTexture(t.__webglTexture),delete t.__webglTexture,delete t.__webglInit}},Se=function(t){if(t&&void 0!==t.__webglTexture){if(At.deleteTexture(t.__webglTexture),delete t.__webglTexture,t instanceof THREE.WebGLRenderTargetCube)for(var e=0;6>e;e++)At.deleteFramebuffer(t.__webglFramebuffer[e]),At.deleteRenderbuffer(t.__webglRenderbuffer[e]);else At.deleteFramebuffer(t.__webglFramebuffer),At.deleteRenderbuffer(t.__webglRenderbuffer);delete t.__webglFramebuffer,delete t.__webglRenderbuffer}},ke=function(t){var e=t.program.program;if(void 0!==e){t.program=void 0;var n,r,i,o=!1;for(n=0,r=Pt.length;r>n;n++)if(i=Pt[n],i.program===e){i.usedTimes--,0===i.usedTimes&&(o=!0);break}if(o===!0){var s=[];for(n=0,r=Pt.length;r>n;n++)i=Pt[n],i.program!==e&&s.push(i);Pt=s,At.deleteProgram(e),Ct.info.memory.programs--}}};this.renderBufferImmediate=function(t,e,n){if($t.initAttributes(),t.hasPositions&&!t.__webglVertexBuffer&&(t.__webglVertexBuffer=At.createBuffer()),t.hasNormals&&!t.__webglNormalBuffer&&(t.__webglNormalBuffer=At.createBuffer()),t.hasUvs&&!t.__webglUvBuffer&&(t.__webglUvBuffer=At.createBuffer()),t.hasColors&&!t.__webglColorBuffer&&(t.__webglColorBuffer=At.createBuffer()),t.hasPositions&&(At.bindBuffer(At.ARRAY_BUFFER,t.__webglVertexBuffer),At.bufferData(At.ARRAY_BUFFER,t.positionArray,At.DYNAMIC_DRAW),$t.enableAttribute(e.attributes.position),At.vertexAttribPointer(e.attributes.position,3,At.FLOAT,!1,0,0)),t.hasNormals){if(At.bindBuffer(At.ARRAY_BUFFER,t.__webglNormalBuffer),n instanceof THREE.MeshPhongMaterial==!1&&n.shading===THREE.FlatShading){var r,i,o,s,a,u,h,l,c,p,f,d,m,v,g=3*t.count;for(v=0;g>v;v+=9)m=t.normalArray,s=m[v],h=m[v+1],p=m[v+2],a=m[v+3],l=m[v+4],f=m[v+5],u=m[v+6],c=m[v+7],d=m[v+8],r=(s+a+u)/3,i=(h+l+c)/3,o=(p+f+d)/3,m[v]=r,m[v+1]=i,m[v+2]=o,m[v+3]=r,m[v+4]=i,m[v+5]=o,m[v+6]=r,m[v+7]=i,m[v+8]=o}At.bufferData(At.ARRAY_BUFFER,t.normalArray,At.DYNAMIC_DRAW),$t.enableAttribute(e.attributes.normal),At.vertexAttribPointer(e.attributes.normal,3,At.FLOAT,!1,0,0)}t.hasUvs&&n.map&&(At.bindBuffer(At.ARRAY_BUFFER,t.__webglUvBuffer),At.bufferData(At.ARRAY_BUFFER,t.uvArray,At.DYNAMIC_DRAW),$t.enableAttribute(e.attributes.uv),At.vertexAttribPointer(e.attributes.uv,2,At.FLOAT,!1,0,0)),t.hasColors&&n.vertexColors!==THREE.NoColors&&(At.bindBuffer(At.ARRAY_BUFFER,t.__webglColorBuffer),At.bufferData(At.ARRAY_BUFFER,t.colorArray,At.DYNAMIC_DRAW),$t.enableAttribute(e.attributes.color),At.vertexAttribPointer(e.attributes.color,3,At.FLOAT,!1,0,0)),$t.disableUnusedAttributes(),At.drawArrays(At.TRIANGLES,0,t.count),t.count=0},this.renderBufferDirect=function(t,e,n,r,i,o){if(r.visible!==!1){S(o);var s=O(t,e,n,r,o),a=!1,u=r.wireframe?1:0,h="direct_"+i.id+"_"+s.id+"_"+u;if(h!==Dt&&(Dt=h,a=!0),a&&$t.initAttributes(),o instanceof THREE.Mesh){var l=r.wireframe===!0?At.LINES:At.TRIANGLES,c=i.attributes.index;if(c){var p,d;c.array instanceof Uint32Array&&te.get("OES_element_index_uint")?(p=At.UNSIGNED_INT,d=4):(p=At.UNSIGNED_SHORT,d=2);var m=i.offsets;if(0===m.length)a&&(f(r,s,i,0),At.bindBuffer(At.ELEMENT_ARRAY_BUFFER,c.buffer)),At.drawElements(l,c.array.length,p,0),Ct.info.render.calls++,Ct.info.render.vertices+=c.array.length,Ct.info.render.faces+=c.array.length/3;else{a=!0;for(var v=0,g=m.length;g>v;v++){var E=m[v].index;a&&(f(r,s,i,E),At.bindBuffer(At.ELEMENT_ARRAY_BUFFER,c.buffer)),At.drawElements(l,m[v].count,p,m[v].start*d),Ct.info.render.calls++,Ct.info.render.vertices+=m[v].count,Ct.info.render.faces+=m[v].count/3}}}else{a&&f(r,s,i,0); +var y=i.attributes.position;At.drawArrays(l,0,y.array.length/y.itemSize),Ct.info.render.calls++,Ct.info.render.vertices+=y.array.length/y.itemSize,Ct.info.render.faces+=y.array.length/(3*y.itemSize)}}else if(o instanceof THREE.PointCloud){var l=At.POINTS,c=i.attributes.index;if(c){var p,d;c.array instanceof Uint32Array&&te.get("OES_element_index_uint")?(p=At.UNSIGNED_INT,d=4):(p=At.UNSIGNED_SHORT,d=2);var m=i.offsets;if(0===m.length)a&&(f(r,s,i,0),At.bindBuffer(At.ELEMENT_ARRAY_BUFFER,c.buffer)),At.drawElements(l,c.array.length,p,0),Ct.info.render.calls++,Ct.info.render.points+=c.array.length;else{m.length>1&&(a=!0);for(var v=0,g=m.length;g>v;v++){var E=m[v].index;a&&(f(r,s,i,E),At.bindBuffer(At.ELEMENT_ARRAY_BUFFER,c.buffer)),At.drawElements(l,m[v].count,p,m[v].start*d),Ct.info.render.calls++,Ct.info.render.points+=m[v].count}}}else{a&&f(r,s,i,0);var y=i.attributes.position,m=i.offsets;if(0===m.length)At.drawArrays(l,0,y.array.length/3),Ct.info.render.calls++,Ct.info.render.points+=y.array.length/3;else for(var v=0,g=m.length;g>v;v++)At.drawArrays(l,m[v].index,m[v].count),Ct.info.render.calls++,Ct.info.render.points+=m[v].count}}else if(o instanceof THREE.Line){var l=o.mode===THREE.LineStrip?At.LINE_STRIP:At.LINES;$t.setLineWidth(r.linewidth*pt);var c=i.attributes.index;if(c){var p,d;c.array instanceof Uint32Array?(p=At.UNSIGNED_INT,d=4):(p=At.UNSIGNED_SHORT,d=2);var m=i.offsets;if(0===m.length)a&&(f(r,s,i,0),At.bindBuffer(At.ELEMENT_ARRAY_BUFFER,c.buffer)),At.drawElements(l,c.array.length,p,0),Ct.info.render.calls++,Ct.info.render.vertices+=c.array.length;else{m.length>1&&(a=!0);for(var v=0,g=m.length;g>v;v++){var E=m[v].index;a&&(f(r,s,i,E),At.bindBuffer(At.ELEMENT_ARRAY_BUFFER,c.buffer)),At.drawElements(l,m[v].count,p,m[v].start*d),Ct.info.render.calls++,Ct.info.render.vertices+=m[v].count}}}else{a&&f(r,s,i,0);var y=i.attributes.position,m=i.offsets;if(0===m.length)At.drawArrays(l,0,y.array.length/3),Ct.info.render.calls++,Ct.info.render.vertices+=y.array.length/3;else for(var v=0,g=m.length;g>v;v++)At.drawArrays(l,m[v].index,m[v].count),Ct.info.render.calls++,Ct.info.render.vertices+=m[v].count}}}},this.renderBuffer=function(t,e,n,r,i,o){if(r.visible!==!1){S(o);var s=O(t,e,n,r,o),a=s.attributes,u=!1,h=r.wireframe?1:0,l=i.id+"_"+s.id+"_"+h;if(l!==Dt&&(Dt=l,u=!0),u&&$t.initAttributes(),!r.morphTargets&&a.position>=0?u&&(At.bindBuffer(At.ARRAY_BUFFER,i.__webglVertexBuffer),$t.enableAttribute(a.position),At.vertexAttribPointer(a.position,3,At.FLOAT,!1,0,0)):o.morphTargetBase&&d(r,i,o),u){if(i.__webglCustomAttributesList)for(var c=0,p=i.__webglCustomAttributesList.length;p>c;c++){var f=i.__webglCustomAttributesList[c];a[f.buffer.belongsToAttribute]>=0&&(At.bindBuffer(At.ARRAY_BUFFER,f.buffer),$t.enableAttribute(a[f.buffer.belongsToAttribute]),At.vertexAttribPointer(a[f.buffer.belongsToAttribute],f.size,At.FLOAT,!1,0,0))}a.color>=0&&(o.geometry.colors.length>0||o.geometry.faces.length>0?(At.bindBuffer(At.ARRAY_BUFFER,i.__webglColorBuffer),$t.enableAttribute(a.color),At.vertexAttribPointer(a.color,3,At.FLOAT,!1,0,0)):void 0!==r.defaultAttributeValues&&At.vertexAttrib3fv(a.color,r.defaultAttributeValues.color)),a.normal>=0&&(At.bindBuffer(At.ARRAY_BUFFER,i.__webglNormalBuffer),$t.enableAttribute(a.normal),At.vertexAttribPointer(a.normal,3,At.FLOAT,!1,0,0)),a.tangent>=0&&(At.bindBuffer(At.ARRAY_BUFFER,i.__webglTangentBuffer),$t.enableAttribute(a.tangent),At.vertexAttribPointer(a.tangent,4,At.FLOAT,!1,0,0)),a.uv>=0&&(o.geometry.faceVertexUvs[0]?(At.bindBuffer(At.ARRAY_BUFFER,i.__webglUVBuffer),$t.enableAttribute(a.uv),At.vertexAttribPointer(a.uv,2,At.FLOAT,!1,0,0)):void 0!==r.defaultAttributeValues&&At.vertexAttrib2fv(a.uv,r.defaultAttributeValues.uv)),a.uv2>=0&&(o.geometry.faceVertexUvs[1]?(At.bindBuffer(At.ARRAY_BUFFER,i.__webglUV2Buffer),$t.enableAttribute(a.uv2),At.vertexAttribPointer(a.uv2,2,At.FLOAT,!1,0,0)):void 0!==r.defaultAttributeValues&&At.vertexAttrib2fv(a.uv2,r.defaultAttributeValues.uv2)),r.skinning&&a.skinIndex>=0&&a.skinWeight>=0&&(At.bindBuffer(At.ARRAY_BUFFER,i.__webglSkinIndicesBuffer),$t.enableAttribute(a.skinIndex),At.vertexAttribPointer(a.skinIndex,4,At.FLOAT,!1,0,0),At.bindBuffer(At.ARRAY_BUFFER,i.__webglSkinWeightsBuffer),$t.enableAttribute(a.skinWeight),At.vertexAttribPointer(a.skinWeight,4,At.FLOAT,!1,0,0)),a.lineDistance>=0&&(At.bindBuffer(At.ARRAY_BUFFER,i.__webglLineDistanceBuffer),$t.enableAttribute(a.lineDistance),At.vertexAttribPointer(a.lineDistance,1,At.FLOAT,!1,0,0))}if($t.disableUnusedAttributes(),o instanceof THREE.Mesh){var m=i.__typeArray===Uint32Array?At.UNSIGNED_INT:At.UNSIGNED_SHORT;r.wireframe?($t.setLineWidth(r.wireframeLinewidth*pt),u&&At.bindBuffer(At.ELEMENT_ARRAY_BUFFER,i.__webglLineBuffer),At.drawElements(At.LINES,i.__webglLineCount,m,0)):(u&&At.bindBuffer(At.ELEMENT_ARRAY_BUFFER,i.__webglFaceBuffer),At.drawElements(At.TRIANGLES,i.__webglFaceCount,m,0)),Ct.info.render.calls++,Ct.info.render.vertices+=i.__webglFaceCount,Ct.info.render.faces+=i.__webglFaceCount/3}else if(o instanceof THREE.Line){var v=o.mode===THREE.LineStrip?At.LINE_STRIP:At.LINES;$t.setLineWidth(r.linewidth*pt),At.drawArrays(v,0,i.__webglLineCount),Ct.info.render.calls++}else o instanceof THREE.PointCloud&&(At.drawArrays(At.POINTS,0,i.__webglParticleCount),Ct.info.render.calls++,Ct.info.render.points+=i.__webglParticleCount)}},this.render=function(t,e,n,r){if(e instanceof THREE.Camera==!1)return void THREE.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");var i=t.fog;Dt="",Ot=-1,Ft=null,Zt=!0,t.autoUpdate===!0&&t.updateMatrixWorld(),void 0===e.parent&&e.updateMatrixWorld(),t.traverse(function(t){t instanceof THREE.SkinnedMesh&&t.skeleton.update()}),e.matrixWorldInverse.getInverse(e.matrixWorld),qt.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),Wt.setFromMatrix(qt),xt.length=0,Ht.length=0,Mt.length=0,St.length=0,kt.length=0,E(t),Ct.sortObjects===!0&&(Ht.sort(m),Mt.sort(v)),ge.render(t,e),Ct.info.render.calls=0,Ct.info.render.vertices=0,Ct.info.render.faces=0,Ct.info.render.points=0,this.setRenderTarget(n),(this.autoClear||r)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil);for(var o=0,s=Rt.length;s>o;o++){var a=Rt[o],u=a.object;u.visible&&(Z(u,e),b(a))}if(t.overrideMaterial){var h=t.overrideMaterial;z(h),y(Ht,e,xt,i,h),y(Mt,e,xt,i,h),_(Rt,"",e,xt,i,h)}else $t.setBlending(THREE.NoBlending),y(Ht,e,xt,i,null),_(Rt,"opaque",e,xt,i,null),y(Mt,e,xt,i,null),_(Rt,"transparent",e,xt,i,null);Ee.render(t,e),ye.render(t,e,jt,Gt),n&&n.generateMipmaps&&n.minFilter!==THREE.NearestFilter&&n.minFilter!==THREE.LinearFilter&&it(n),$t.setDepthTest(!0),$t.setDepthWrite(!0),$t.setColorWrite(!0)},this.renderImmediateObject=function(t,e,n,r,i){var o=O(t,e,n,r,i);Dt="",Ct.setMaterialFaces(r),i.immediateRenderCallback?i.immediateRenderCallback(o,At,Wt):i.render(function(t){Ct.renderBufferImmediate(t,o,r)})};var Ae={},Ce=0,Pe={MeshDepthMaterial:"depth",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointCloudMaterial:"particle_basic"};this.setFaceCulling=function(t,e){t===THREE.CullFaceNone?At.disable(At.CULL_FACE):(e===THREE.FrontFaceDirectionCW?At.frontFace(At.CW):At.frontFace(At.CCW),t===THREE.CullFaceBack?At.cullFace(At.BACK):t===THREE.CullFaceFront?At.cullFace(At.FRONT):At.cullFace(At.FRONT_AND_BACK),At.enable(At.CULL_FACE))},this.setMaterialFaces=function(t){$t.setDoubleSided(t.side===THREE.DoubleSide),$t.setFlipSided(t.side===THREE.BackSide)},this.uploadTexture=function(t){void 0===t.__webglInit&&(t.__webglInit=!0,t.addEventListener("dispose",Te),t.__webglTexture=At.createTexture(),Ct.info.memory.textures++),At.bindTexture(At.TEXTURE_2D,t.__webglTexture),At.pixelStorei(At.UNPACK_FLIP_Y_WEBGL,t.flipY),At.pixelStorei(At.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),At.pixelStorei(At.UNPACK_ALIGNMENT,t.unpackAlignment),t.image=$(t.image,se);var e=t.image,n=THREE.Math.isPowerOfTwo(e.width)&&THREE.Math.isPowerOfTwo(e.height),r=st(t.format),i=st(t.type);J(At.TEXTURE_2D,t,n);var o,s=t.mipmaps;if(t instanceof THREE.DataTexture)if(s.length>0&&n){for(var a=0,u=s.length;u>a;a++)o=s[a],At.texImage2D(At.TEXTURE_2D,a,r,o.width,o.height,0,r,i,o.data);t.generateMipmaps=!1}else At.texImage2D(At.TEXTURE_2D,0,r,e.width,e.height,0,r,i,e.data);else if(t instanceof THREE.CompressedTexture)for(var a=0,u=s.length;u>a;a++)o=s[a],t.format!==THREE.RGBAFormat&&t.format!==THREE.RGBFormat?de().indexOf(r)>-1?At.compressedTexImage2D(At.TEXTURE_2D,a,r,o.width,o.height,0,o.data):THREE.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):At.texImage2D(At.TEXTURE_2D,a,r,o.width,o.height,0,r,i,o.data);else if(s.length>0&&n){for(var a=0,u=s.length;u>a;a++)o=s[a],At.texImage2D(At.TEXTURE_2D,a,r,r,i,o);t.generateMipmaps=!1}else At.texImage2D(At.TEXTURE_2D,0,r,r,i,t.image);t.generateMipmaps&&n&&At.generateMipmap(At.TEXTURE_2D),t.needsUpdate=!1,t.onUpdate&&t.onUpdate()},this.setTexture=function(t,e){At.activeTexture(At.TEXTURE0+e),t.needsUpdate?Ct.uploadTexture(t):At.bindTexture(At.TEXTURE_2D,t.__webglTexture)},this.setRenderTarget=function(t){var e=t instanceof THREE.WebGLRenderTargetCube;if(t&&void 0===t.__webglFramebuffer){void 0===t.depthBuffer&&(t.depthBuffer=!0),void 0===t.stencilBuffer&&(t.stencilBuffer=!0),t.addEventListener("dispose",xe),t.__webglTexture=At.createTexture(),Ct.info.memory.textures++;var n=THREE.Math.isPowerOfTwo(t.width)&&THREE.Math.isPowerOfTwo(t.height),r=st(t.format),i=st(t.type);if(e){t.__webglFramebuffer=[],t.__webglRenderbuffer=[],At.bindTexture(At.TEXTURE_CUBE_MAP,t.__webglTexture),J(At.TEXTURE_CUBE_MAP,t,n);for(var o=0;6>o;o++)t.__webglFramebuffer[o]=At.createFramebuffer(),t.__webglRenderbuffer[o]=At.createRenderbuffer(),At.texImage2D(At.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,r,t.width,t.height,0,r,i,null),nt(t.__webglFramebuffer[o],t,At.TEXTURE_CUBE_MAP_POSITIVE_X+o),rt(t.__webglRenderbuffer[o],t);n&&At.generateMipmap(At.TEXTURE_CUBE_MAP)}else t.__webglFramebuffer=At.createFramebuffer(),t.shareDepthFrom?t.__webglRenderbuffer=t.shareDepthFrom.__webglRenderbuffer:t.__webglRenderbuffer=At.createRenderbuffer(),At.bindTexture(At.TEXTURE_2D,t.__webglTexture),J(At.TEXTURE_2D,t,n),At.texImage2D(At.TEXTURE_2D,0,r,t.width,t.height,0,r,i,null),nt(t.__webglFramebuffer,t,At.TEXTURE_2D),t.shareDepthFrom?t.depthBuffer&&!t.stencilBuffer?At.framebufferRenderbuffer(At.FRAMEBUFFER,At.DEPTH_ATTACHMENT,At.RENDERBUFFER,t.__webglRenderbuffer):t.depthBuffer&&t.stencilBuffer&&At.framebufferRenderbuffer(At.FRAMEBUFFER,At.DEPTH_STENCIL_ATTACHMENT,At.RENDERBUFFER,t.__webglRenderbuffer):rt(t.__webglRenderbuffer,t),n&&At.generateMipmap(At.TEXTURE_2D);e?At.bindTexture(At.TEXTURE_CUBE_MAP,null):At.bindTexture(At.TEXTURE_2D,null),At.bindRenderbuffer(At.RENDERBUFFER,null),At.bindFramebuffer(At.FRAMEBUFFER,null)}var s,a,u,h,l;t?(s=e?t.__webglFramebuffer[t.activeCubeFace]:t.__webglFramebuffer,a=t.width,u=t.height,h=0,l=0):(s=null,a=Vt,u=It,h=Bt,l=Nt),s!==zt&&(At.bindFramebuffer(At.FRAMEBUFFER,s),At.viewport(h,l,a,u),zt=s),jt=a,Gt=u},this.readRenderTargetPixels=function(t,e,n,r,i,o){if(!(t instanceof THREE.WebGLRenderTarget))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");if(t.__webglFramebuffer){if(t.format!==THREE.RGBAFormat)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA format. readPixels can read only RGBA format.");var s=!1;t.__webglFramebuffer!==zt&&(At.bindFramebuffer(At.FRAMEBUFFER,t.__webglFramebuffer),s=!0),At.checkFramebufferStatus(At.FRAMEBUFFER)===At.FRAMEBUFFER_COMPLETE?At.readPixels(e,n,r,i,At.RGBA,At.UNSIGNED_BYTE,o):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."),s&&At.bindFramebuffer(At.FRAMEBUFFER,zt)}},this.initMaterial=function(){THREE.warn("THREE.WebGLRenderer: .initMaterial() has been removed.")},this.addPrePlugin=function(){THREE.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.")},this.addPostPlugin=function(){THREE.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},this.updateShadowMap=function(){THREE.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")}},THREE.WebGLRenderTarget=function(t,e,n){this.width=t,this.height=e,n=n||{},this.wrapS=void 0!==n.wrapS?n.wrapS:THREE.ClampToEdgeWrapping,this.wrapT=void 0!==n.wrapT?n.wrapT:THREE.ClampToEdgeWrapping,this.magFilter=void 0!==n.magFilter?n.magFilter:THREE.LinearFilter,this.minFilter=void 0!==n.minFilter?n.minFilter:THREE.LinearMipMapLinearFilter,this.anisotropy=void 0!==n.anisotropy?n.anisotropy:1,this.offset=new THREE.Vector2(0,0),this.repeat=new THREE.Vector2(1,1),this.format=void 0!==n.format?n.format:THREE.RGBAFormat,this.type=void 0!==n.type?n.type:THREE.UnsignedByteType,this.depthBuffer=void 0!==n.depthBuffer?n.depthBuffer:!0,this.stencilBuffer=void 0!==n.stencilBuffer?n.stencilBuffer:!0,this.generateMipmaps=!0,this.shareDepthFrom=void 0!==n.shareDepthFrom?n.shareDepthFrom:null},THREE.WebGLRenderTarget.prototype={constructor:THREE.WebGLRenderTarget,setSize:function(t,e){this.width=t,this.height=e},clone:function(){var t=new THREE.WebGLRenderTarget(this.width,this.height);return t.wrapS=this.wrapS,t.wrapT=this.wrapT,t.magFilter=this.magFilter,t.minFilter=this.minFilter,t.anisotropy=this.anisotropy,t.offset.copy(this.offset),t.repeat.copy(this.repeat),t.format=this.format,t.type=this.type,t.depthBuffer=this.depthBuffer,t.stencilBuffer=this.stencilBuffer,t.generateMipmaps=this.generateMipmaps,t.shareDepthFrom=this.shareDepthFrom,t},dispose:function(){this.dispatchEvent({type:"dispose"})}},THREE.EventDispatcher.prototype.apply(THREE.WebGLRenderTarget.prototype),THREE.WebGLRenderTargetCube=function(t,e,n){THREE.WebGLRenderTarget.call(this,t,e,n),this.activeCubeFace=0},THREE.WebGLRenderTargetCube.prototype=Object.create(THREE.WebGLRenderTarget.prototype),THREE.WebGLRenderTargetCube.prototype.constructor=THREE.WebGLRenderTargetCube,THREE.WebGLExtensions=function(t){var e={};this.get=function(n){if(void 0!==e[n])return e[n];var r;switch(n){case"EXT_texture_filter_anisotropic":r=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":r=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":r=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:r=t.getExtension(n)}return null===r&&THREE.warn("THREE.WebGLRenderer: "+n+" extension not supported."),e[n]=r,r}},THREE.WebGLProgram=function(){var t=0,e=function(t){var e,n,r=[];for(var i in t)e=t[i],e!==!1&&(n="#define "+i+" "+e,r.push(n));return r.join("\n")},n=function(t,e,n){for(var r={},i=0,o=n.length;o>i;i++){var s=n[i];r[s]=t.getUniformLocation(e,s)}return r},r=function(t,e,n){for(var r={},i=0,o=n.length;o>i;i++){var s=n[i];r[s]=t.getAttribLocation(e,s)}return r};return function(i,o,s,a){var u=i,h=u.context,l=s.defines,c=s.__webglShader.uniforms,p=s.attributes,f=s.__webglShader.vertexShader,d=s.__webglShader.fragmentShader,m=s.index0AttributeName;void 0===m&&a.morphTargets===!0&&(m="position");var v="SHADOWMAP_TYPE_BASIC";a.shadowMapType===THREE.PCFShadowMap?v="SHADOWMAP_TYPE_PCF":a.shadowMapType===THREE.PCFSoftShadowMap&&(v="SHADOWMAP_TYPE_PCF_SOFT");var g="ENVMAP_TYPE_CUBE",E="ENVMAP_MODE_REFLECTION",y="ENVMAP_BLENDING_MULTIPLY";if(a.envMap){switch(s.envMap.mapping){case THREE.CubeReflectionMapping:case THREE.CubeRefractionMapping:g="ENVMAP_TYPE_CUBE";break;case THREE.EquirectangularReflectionMapping:case THREE.EquirectangularRefractionMapping:g="ENVMAP_TYPE_EQUIREC";break;case THREE.SphericalReflectionMapping:g="ENVMAP_TYPE_SPHERE"}switch(s.envMap.mapping){case THREE.CubeRefractionMapping:case THREE.EquirectangularRefractionMapping:E="ENVMAP_MODE_REFRACTION"}switch(s.combine){case THREE.MultiplyOperation:y="ENVMAP_BLENDING_MULTIPLY";break;case THREE.MixOperation:y="ENVMAP_BLENDING_MIX";break;case THREE.AddOperation:y="ENVMAP_BLENDING_ADD"}}var _,b,T=i.gammaFactor>0?i.gammaFactor:1,x=e(l),w=h.createProgram();s instanceof THREE.RawShaderMaterial?(_="",b=""):(_=["precision "+a.precision+" float;","precision "+a.precision+" int;",x,a.supportsVertexTextures?"#define VERTEX_TEXTURES":"",u.gammaInput?"#define GAMMA_INPUT":"",u.gammaOutput?"#define GAMMA_OUTPUT":"","#define GAMMA_FACTOR "+T,"#define MAX_DIR_LIGHTS "+a.maxDirLights,"#define MAX_POINT_LIGHTS "+a.maxPointLights,"#define MAX_SPOT_LIGHTS "+a.maxSpotLights,"#define MAX_HEMI_LIGHTS "+a.maxHemiLights,"#define MAX_SHADOWS "+a.maxShadows,"#define MAX_BONES "+a.maxBones,a.map?"#define USE_MAP":"",a.envMap?"#define USE_ENVMAP":"",a.envMap?"#define "+E:"",a.lightMap?"#define USE_LIGHTMAP":"",a.bumpMap?"#define USE_BUMPMAP":"",a.normalMap?"#define USE_NORMALMAP":"",a.specularMap?"#define USE_SPECULARMAP":"",a.alphaMap?"#define USE_ALPHAMAP":"",a.vertexColors?"#define USE_COLOR":"",a.flatShading?"#define FLAT_SHADED":"",a.skinning?"#define USE_SKINNING":"",a.useVertexTexture?"#define BONE_TEXTURE":"",a.morphTargets?"#define USE_MORPHTARGETS":"",a.morphNormals?"#define USE_MORPHNORMALS":"",a.wrapAround?"#define WRAP_AROUND":"",a.doubleSided?"#define DOUBLE_SIDED":"",a.flipSided?"#define FLIP_SIDED":"",a.shadowMapEnabled?"#define USE_SHADOWMAP":"",a.shadowMapEnabled?"#define "+v:"",a.shadowMapDebug?"#define SHADOWMAP_DEBUG":"",a.shadowMapCascade?"#define SHADOWMAP_CASCADE":"",a.sizeAttenuation?"#define USE_SIZEATTENUATION":"",a.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","attribute vec2 uv2;","#ifdef USE_COLOR"," attribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS"," attribute vec3 morphTarget0;"," attribute vec3 morphTarget1;"," attribute vec3 morphTarget2;"," attribute vec3 morphTarget3;"," #ifdef USE_MORPHNORMALS"," attribute vec3 morphNormal0;"," attribute vec3 morphNormal1;"," attribute vec3 morphNormal2;"," attribute vec3 morphNormal3;"," #else"," attribute vec3 morphTarget4;"," attribute vec3 morphTarget5;"," attribute vec3 morphTarget6;"," attribute vec3 morphTarget7;"," #endif","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",""].join("\n"),b=["precision "+a.precision+" float;","precision "+a.precision+" int;",a.bumpMap||a.normalMap||a.flatShading?"#extension GL_OES_standard_derivatives : enable":"",x,"#define MAX_DIR_LIGHTS "+a.maxDirLights,"#define MAX_POINT_LIGHTS "+a.maxPointLights,"#define MAX_SPOT_LIGHTS "+a.maxSpotLights,"#define MAX_HEMI_LIGHTS "+a.maxHemiLights,"#define MAX_SHADOWS "+a.maxShadows,a.alphaTest?"#define ALPHATEST "+a.alphaTest:"",u.gammaInput?"#define GAMMA_INPUT":"",u.gammaOutput?"#define GAMMA_OUTPUT":"","#define GAMMA_FACTOR "+T,a.useFog&&a.fog?"#define USE_FOG":"",a.useFog&&a.fogExp?"#define FOG_EXP2":"",a.map?"#define USE_MAP":"",a.envMap?"#define USE_ENVMAP":"",a.envMap?"#define "+g:"",a.envMap?"#define "+E:"",a.envMap?"#define "+y:"",a.lightMap?"#define USE_LIGHTMAP":"",a.bumpMap?"#define USE_BUMPMAP":"",a.normalMap?"#define USE_NORMALMAP":"",a.specularMap?"#define USE_SPECULARMAP":"",a.alphaMap?"#define USE_ALPHAMAP":"",a.vertexColors?"#define USE_COLOR":"",a.flatShading?"#define FLAT_SHADED":"",a.metal?"#define METAL":"",a.wrapAround?"#define WRAP_AROUND":"",a.doubleSided?"#define DOUBLE_SIDED":"",a.flipSided?"#define FLIP_SIDED":"",a.shadowMapEnabled?"#define USE_SHADOWMAP":"",a.shadowMapEnabled?"#define "+v:"",a.shadowMapDebug?"#define SHADOWMAP_DEBUG":"",a.shadowMapCascade?"#define SHADOWMAP_CASCADE":"",a.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",""].join("\n"));var R=new THREE.WebGLShader(h,h.VERTEX_SHADER,_+f),H=new THREE.WebGLShader(h,h.FRAGMENT_SHADER,b+d);h.attachShader(w,R),h.attachShader(w,H),void 0!==m&&h.bindAttribLocation(w,0,m),h.linkProgram(w);var M=h.getProgramInfoLog(w);h.getProgramParameter(w,h.LINK_STATUS)===!1&&THREE.error("THREE.WebGLProgram: shader error: "+h.getError(),"gl.VALIDATE_STATUS",h.getProgramParameter(w,h.VALIDATE_STATUS),"gl.getPRogramInfoLog",M),""!==M&&THREE.warn("THREE.WebGLProgram: gl.getProgramInfoLog()"+M),h.deleteShader(R),h.deleteShader(H);var S=["viewMatrix","modelViewMatrix","projectionMatrix","normalMatrix","modelMatrix","cameraPosition","morphTargetInfluences","bindMatrix","bindMatrixInverse"];a.useVertexTexture?(S.push("boneTexture"),S.push("boneTextureWidth"),S.push("boneTextureHeight")):S.push("boneGlobalMatrices"),a.logarithmicDepthBuffer&&S.push("logDepthBufFC");for(var k in c)S.push(k);this.uniforms=n(h,w,S),S=["position","normal","uv","uv2","tangent","color","skinIndex","skinWeight","lineDistance"];for(var A=0;At;t++)n[t]=0},this.enableAttribute=function(e){n[e]=1,0===r[e]&&(t.enableVertexAttribArray(e),r[e]=1)},this.disableUnusedAttributes=function(){for(var e=0,i=r.length;i>e;e++)r[e]!==n[e]&&(t.disableVertexAttribArray(e),r[e]=0)},this.setBlending=function(n,r,c,p,f,d,m){n!==i&&(n===THREE.NoBlending?t.disable(t.BLEND):n===THREE.AdditiveBlending?(t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.SRC_ALPHA,t.ONE)):n===THREE.SubtractiveBlending?(t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ZERO,t.ONE_MINUS_SRC_COLOR)):n===THREE.MultiplyBlending?(t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ZERO,t.SRC_COLOR)):n===THREE.CustomBlending?t.enable(t.BLEND):(t.enable(t.BLEND),t.blendEquationSeparate(t.FUNC_ADD,t.FUNC_ADD),t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA)),i=n),n===THREE.CustomBlending?(f=f||r,d=d||c,m=m||p,(r!==o||f!==u)&&(t.blendEquationSeparate(e(r),e(f)),o=r,u=f),(c!==s||p!==a||d!==h||m!==l)&&(t.blendFuncSeparate(e(c),e(p),e(d),e(m)),s=c,a=p,h=d,l=m)):(o=null,s=null,a=null,u=null,h=null,l=null)},this.setDepthTest=function(e){c!==e&&(e?t.enable(t.DEPTH_TEST):t.disable(t.DEPTH_TEST),c=e)},this.setDepthWrite=function(e){p!==e&&(t.depthMask(e),p=e)},this.setColorWrite=function(e){f!==e&&(t.colorMask(e,e,e,e),f=e)},this.setDoubleSided=function(e){d!==e&&(e?t.disable(t.CULL_FACE):t.enable(t.CULL_FACE),d=e)},this.setFlipSided=function(e){m!==e&&(e?t.frontFace(t.CW):t.frontFace(t.CCW),m=e)},this.setLineWidth=function(e){e!==v&&(t.lineWidth(e),v=e)},this.setPolygonOffset=function(e,n,r){g!==e&&(e?t.enable(t.POLYGON_OFFSET_FILL):t.disable(t.POLYGON_OFFSET_FILL),g=e),!e||E===n&&y===r||(t.polygonOffset(n,r),E=n,y=r)},this.reset=function(){for(var t=0;t0;var p;p=u?{vertexShader:["uniform lowp int renderType;","uniform vec3 screenPosition;","uniform vec2 scale;","uniform float rotation;","uniform sampler2D occlusionMap;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","varying float vVisibility;","void main() {","vUV = uv;","vec2 pos = position;","if( renderType == 2 ) {","vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );","vVisibility = visibility.r / 9.0;","vVisibility *= 1.0 - visibility.g / 9.0;","vVisibility *= visibility.b / 9.0;","vVisibility *= 1.0 - visibility.a / 9.0;","pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;","pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;","}","gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );","}"].join("\n"),fragmentShader:["uniform lowp int renderType;","uniform sampler2D map;","uniform float opacity;","uniform vec3 color;","varying vec2 vUV;","varying float vVisibility;","void main() {","if( renderType == 0 ) {","gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );","} else if( renderType == 1 ) {","gl_FragColor = texture2D( map, vUV );","} else {","vec4 texture = texture2D( map, vUV );","texture.a *= opacity * vVisibility;","gl_FragColor = texture;","gl_FragColor.rgb *= color;","}","}"].join("\n")}:{vertexShader:["uniform lowp int renderType;","uniform vec3 screenPosition;","uniform vec2 scale;","uniform float rotation;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","void main() {","vUV = uv;","vec2 pos = position;","if( renderType == 2 ) {","pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;","pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;","}","gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );","}"].join("\n"),fragmentShader:["precision mediump float;","uniform lowp int renderType;","uniform sampler2D map;","uniform sampler2D occlusionMap;","uniform float opacity;","uniform vec3 color;","varying vec2 vUV;","void main() {","if( renderType == 0 ) {","gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );","} else if( renderType == 1 ) {","gl_FragColor = texture2D( map, vUV );","} else {","float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;","visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;","visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;","visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;","visibility = ( 1.0 - visibility / 4.0 );","vec4 texture = texture2D( map, vUV );","texture.a *= opacity * visibility;","gl_FragColor = texture;","gl_FragColor.rgb *= color;","}","}"].join("\n")},o=n(p),s={vertex:c.getAttribLocation(o,"position"),uv:c.getAttribLocation(o,"uv")},a={renderType:c.getUniformLocation(o,"renderType"),map:c.getUniformLocation(o,"map"),occlusionMap:c.getUniformLocation(o,"occlusionMap"),opacity:c.getUniformLocation(o,"opacity"),color:c.getUniformLocation(o,"color"),scale:c.getUniformLocation(o,"scale"),rotation:c.getUniformLocation(o,"rotation"),screenPosition:c.getUniformLocation(o,"screenPosition")}};this.render=function(n,f,d,m){if(0!==e.length){var v=new THREE.Vector3,g=m/d,E=.5*d,y=.5*m,_=16/m,b=new THREE.Vector2(_*g,_),T=new THREE.Vector3(1,1,0),x=new THREE.Vector2(1,1);void 0===o&&p(),c.useProgram(o),c.enableVertexAttribArray(s.vertex),c.enableVertexAttribArray(s.uv),c.uniform1i(a.occlusionMap,0),c.uniform1i(a.map,1),c.bindBuffer(c.ARRAY_BUFFER,r),c.vertexAttribPointer(s.vertex,2,c.FLOAT,!1,16,0),c.vertexAttribPointer(s.uv,2,c.FLOAT,!1,16,8),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,i),c.disable(c.CULL_FACE),c.depthMask(!1);for(var w=0,R=e.length;R>w;w++){_=16/m,b.set(_*g,_);var H=e[w];if(v.set(H.matrixWorld.elements[12],H.matrixWorld.elements[13],H.matrixWorld.elements[14]),v.applyMatrix4(f.matrixWorldInverse),v.applyProjection(f.projectionMatrix),T.copy(v),x.x=T.x*E+E,x.y=T.y*y+y,u||x.x>0&&x.x0&&x.yM;M++){var k=H.lensFlares[M];k.opacity>.001&&k.scale>.001&&(T.x=k.x,T.y=k.y,T.z=k.z,_=k.size*k.scale/m,b.x=_*g,b.y=_,c.uniform3f(a.screenPosition,T.x,T.y,T.z),c.uniform2f(a.scale,b.x,b.y),c.uniform1f(a.rotation,k.rotation),c.uniform1f(a.opacity,k.opacity),c.uniform3f(a.color,k.color.r,k.color.g,k.color.b),t.state.setBlending(k.blending,k.blendEquation,k.blendSrc,k.blendDst),t.setTexture(k.texture,1),c.drawElements(c.TRIANGLES,6,c.UNSIGNED_SHORT,0))}}}c.enable(c.CULL_FACE),c.enable(c.DEPTH_TEST),c.depthMask(!0),t.resetGLState()}}},THREE.ShadowMapPlugin=function(t,e,n,r){function i(t,e,r){if(e.visible){var o=n[e.id];if(o&&e.castShadow&&(e.frustumCulled===!1||d.intersectsObject(e)===!0))for(var s=0,a=o.length;a>s;s++){var u=o[s];e._modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,e.matrixWorld),y.push(u)}for(var s=0,a=e.children.length;a>s;s++)i(t,e.children[s],r)}}function o(t,e){var n=new THREE.DirectionalLight;n.isVirtual=!0,n.onlyShadow=!0,n.castShadow=!0,n.shadowCameraNear=t.shadowCameraNear,n.shadowCameraFar=t.shadowCameraFar,n.shadowCameraLeft=t.shadowCameraLeft,n.shadowCameraRight=t.shadowCameraRight,n.shadowCameraBottom=t.shadowCameraBottom,n.shadowCameraTop=t.shadowCameraTop,n.shadowCameraVisible=t.shadowCameraVisible,n.shadowDarkness=t.shadowDarkness, +n.shadowBias=t.shadowCascadeBias[e],n.shadowMapWidth=t.shadowCascadeWidth[e],n.shadowMapHeight=t.shadowCascadeHeight[e],n.pointsWorld=[],n.pointsFrustum=[];for(var r=n.pointsWorld,i=n.pointsFrustum,o=0;8>o;o++)r[o]=new THREE.Vector3,i[o]=new THREE.Vector3;var s=t.shadowCascadeNearZ[e],a=t.shadowCascadeFarZ[e];return i[0].set(-1,-1,s),i[1].set(1,-1,s),i[2].set(-1,1,s),i[3].set(1,1,s),i[4].set(-1,-1,a),i[5].set(1,-1,a),i[6].set(-1,1,a),i[7].set(1,1,a),n}function s(t,e){var n=t.shadowCascadeArray[e];n.position.copy(t.position),n.target.position.copy(t.target.position),n.lookAt(n.target),n.shadowCameraVisible=t.shadowCameraVisible,n.shadowDarkness=t.shadowDarkness,n.shadowBias=t.shadowCascadeBias[e];var r=t.shadowCascadeNearZ[e],i=t.shadowCascadeFarZ[e],o=n.pointsFrustum;o[0].z=r,o[1].z=r,o[2].z=r,o[3].z=r,o[4].z=i,o[5].z=i,o[6].z=i,o[7].z=i}function a(t,e){var n=e.shadowCamera,r=e.pointsFrustum,i=e.pointsWorld;v.set(1/0,1/0,1/0),g.set(-(1/0),-(1/0),-(1/0));for(var o=0;8>o;o++){var s=i[o];s.copy(r[o]),s.unproject(t),s.applyMatrix4(n.matrixWorldInverse),s.xg.x&&(g.x=s.x),s.yg.y&&(g.y=s.y),s.zg.z&&(g.z=s.z)}n.left=v.x,n.right=g.x,n.top=g.y,n.bottom=v.y,n.updateProjectionMatrix()}function u(t){return t.material instanceof THREE.MeshFaceMaterial?t.material.materials[0]:t.material}var h,l,c,p,f=t.context,d=new THREE.Frustum,m=new THREE.Matrix4,v=new THREE.Vector3,g=new THREE.Vector3,E=new THREE.Vector3,y=[],_=THREE.ShaderLib.depthRGBA,b=THREE.UniformsUtils.clone(_.uniforms);h=new THREE.ShaderMaterial({uniforms:b,vertexShader:_.vertexShader,fragmentShader:_.fragmentShader}),l=new THREE.ShaderMaterial({uniforms:b,vertexShader:_.vertexShader,fragmentShader:_.fragmentShader,morphTargets:!0}),c=new THREE.ShaderMaterial({uniforms:b,vertexShader:_.vertexShader,fragmentShader:_.fragmentShader,skinning:!0}),p=new THREE.ShaderMaterial({uniforms:b,vertexShader:_.vertexShader,fragmentShader:_.fragmentShader,morphTargets:!0,skinning:!0}),h._shadowPass=!0,l._shadowPass=!0,c._shadowPass=!0,p._shadowPass=!0,this.render=function(n,v){if(t.shadowMapEnabled!==!1){var g,_,b,T,x,w,R,H,M,S,k,A,C,P=[],L=0,z=null;for(f.clearColor(1,1,1,1),f.disable(f.BLEND),f.enable(f.CULL_FACE),f.frontFace(f.CCW),t.shadowMapCullFace===THREE.CullFaceFront?f.cullFace(f.FRONT):f.cullFace(f.BACK),t.state.setDepthTest(!0),g=0,_=e.length;_>g;g++)if(C=e[g],C.castShadow)if(C instanceof THREE.DirectionalLight&&C.shadowCascade)for(x=0;xg;g++){if(C=P[g],!C.shadowMap){var F=THREE.LinearFilter;t.shadowMapType===THREE.PCFSoftShadowMap&&(F=THREE.NearestFilter);var U={minFilter:F,magFilter:F,format:THREE.RGBAFormat};C.shadowMap=new THREE.WebGLRenderTarget(C.shadowMapWidth,C.shadowMapHeight,U),C.shadowMapSize=new THREE.Vector2(C.shadowMapWidth,C.shadowMapHeight),C.shadowMatrix=new THREE.Matrix4}if(!C.shadowCamera){if(C instanceof THREE.SpotLight)C.shadowCamera=new THREE.PerspectiveCamera(C.shadowCameraFov,C.shadowMapWidth/C.shadowMapHeight,C.shadowCameraNear,C.shadowCameraFar);else{if(!(C instanceof THREE.DirectionalLight)){THREE.error("THREE.ShadowMapPlugin: Unsupported light type for shadow",C);continue}C.shadowCamera=new THREE.OrthographicCamera(C.shadowCameraLeft,C.shadowCameraRight,C.shadowCameraTop,C.shadowCameraBottom,C.shadowCameraNear,C.shadowCameraFar)}n.add(C.shadowCamera),n.autoUpdate===!0&&n.updateMatrixWorld()}C.shadowCameraVisible&&!C.cameraHelper&&(C.cameraHelper=new THREE.CameraHelper(C.shadowCamera),n.add(C.cameraHelper)),C.isVirtual&&O.originalCamera==v&&a(v,C),w=C.shadowMap,R=C.shadowMatrix,H=C.shadowCamera,H.position.setFromMatrixPosition(C.matrixWorld),E.setFromMatrixPosition(C.target.matrixWorld),H.lookAt(E),H.updateMatrixWorld(),H.matrixWorldInverse.getInverse(H.matrixWorld),C.cameraHelper&&(C.cameraHelper.visible=C.shadowCameraVisible),C.shadowCameraVisible&&C.cameraHelper.update(),R.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),R.multiply(H.projectionMatrix),R.multiply(H.matrixWorldInverse),m.multiplyMatrices(H.projectionMatrix,H.matrixWorldInverse),d.setFromMatrix(m),t.setRenderTarget(w),t.clear(),y.length=0,i(n,n,H);var B,N,V;for(b=0,T=y.length;T>b;b++)k=y[b],A=k.object,M=k.buffer,B=u(A),N=void 0!==A.geometry.morphTargets&&A.geometry.morphTargets.length>0&&B.morphTargets,V=A instanceof THREE.SkinnedMesh&&B.skinning,S=A.customDepthMaterial?A.customDepthMaterial:V?N?p:c:N?l:h,t.setMaterialFaces(B),M instanceof THREE.BufferGeometry?t.renderBufferDirect(H,e,z,S,M,A):t.renderBuffer(H,e,z,S,M,A);for(b=0,T=r.length;T>b;b++)k=r[b],A=k.object,A.visible&&A.castShadow&&(A._modelViewMatrix.multiplyMatrices(H.matrixWorldInverse,A.matrixWorld),t.renderImmediateObject(H,e,z,h,A))}var I=t.getClearColor(),j=t.getClearAlpha();f.clearColor(I.r,I.g,I.b,j),f.enable(f.BLEND),t.shadowMapCullFace===THREE.CullFaceFront&&f.cullFace(f.BACK),t.resetGLState()}}},THREE.SpritePlugin=function(t,e){function n(){var e=l.createProgram(),n=l.createShader(l.VERTEX_SHADER),r=l.createShader(l.FRAGMENT_SHADER);return l.shaderSource(n,["precision "+t.getPrecision()+" float;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform float rotation;","uniform vec2 scale;","uniform vec2 uvOffset;","uniform vec2 uvScale;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","void main() {","vUV = uvOffset + uv * uvScale;","vec2 alignedPosition = position * scale;","vec2 rotatedPosition;","rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;","rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;","vec4 finalPosition;","finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );","finalPosition.xy += rotatedPosition;","finalPosition = projectionMatrix * finalPosition;","gl_Position = finalPosition;","}"].join("\n")),l.shaderSource(r,["precision "+t.getPrecision()+" float;","uniform vec3 color;","uniform sampler2D map;","uniform float opacity;","uniform int fogType;","uniform vec3 fogColor;","uniform float fogDensity;","uniform float fogNear;","uniform float fogFar;","uniform float alphaTest;","varying vec2 vUV;","void main() {","vec4 texture = texture2D( map, vUV );","if ( texture.a < alphaTest ) discard;","gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );","if ( fogType > 0 ) {","float depth = gl_FragCoord.z / gl_FragCoord.w;","float fogFactor = 0.0;","if ( fogType == 1 ) {","fogFactor = smoothstep( fogNear, fogFar, depth );","} else {","const float LOG2 = 1.442695;","float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );","fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );","}","gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );","}","}"].join("\n")),l.compileShader(n),l.compileShader(r),l.attachShader(e,n),l.attachShader(e,r),l.linkProgram(e),e}function r(t,e){return t.z!==e.z?e.z-t.z:e.id-t.id}var i,o,s,a,u,h,l=t.context,c=new THREE.Vector3,p=new THREE.Quaternion,f=new THREE.Vector3,d=function(){var t=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),e=new Uint16Array([0,1,2,0,2,3]);i=l.createBuffer(),o=l.createBuffer(),l.bindBuffer(l.ARRAY_BUFFER,i),l.bufferData(l.ARRAY_BUFFER,t,l.STATIC_DRAW),l.bindBuffer(l.ELEMENT_ARRAY_BUFFER,o),l.bufferData(l.ELEMENT_ARRAY_BUFFER,e,l.STATIC_DRAW),s=n(),a={position:l.getAttribLocation(s,"position"),uv:l.getAttribLocation(s,"uv")},u={uvOffset:l.getUniformLocation(s,"uvOffset"),uvScale:l.getUniformLocation(s,"uvScale"),rotation:l.getUniformLocation(s,"rotation"),scale:l.getUniformLocation(s,"scale"),color:l.getUniformLocation(s,"color"),map:l.getUniformLocation(s,"map"),opacity:l.getUniformLocation(s,"opacity"),modelViewMatrix:l.getUniformLocation(s,"modelViewMatrix"),projectionMatrix:l.getUniformLocation(s,"projectionMatrix"),fogType:l.getUniformLocation(s,"fogType"),fogDensity:l.getUniformLocation(s,"fogDensity"),fogNear:l.getUniformLocation(s,"fogNear"),fogFar:l.getUniformLocation(s,"fogFar"),fogColor:l.getUniformLocation(s,"fogColor"),alphaTest:l.getUniformLocation(s,"alphaTest")};var r=document.createElement("canvas");r.width=8,r.height=8;var c=r.getContext("2d");c.fillStyle="white",c.fillRect(0,0,8,8),h=new THREE.Texture(r),h.needsUpdate=!0};this.render=function(n,m){if(0!==e.length){void 0===s&&d(),l.useProgram(s),l.enableVertexAttribArray(a.position),l.enableVertexAttribArray(a.uv),l.disable(l.CULL_FACE),l.enable(l.BLEND),l.bindBuffer(l.ARRAY_BUFFER,i),l.vertexAttribPointer(a.position,2,l.FLOAT,!1,16,0),l.vertexAttribPointer(a.uv,2,l.FLOAT,!1,16,8),l.bindBuffer(l.ELEMENT_ARRAY_BUFFER,o),l.uniformMatrix4fv(u.projectionMatrix,!1,m.projectionMatrix.elements),l.activeTexture(l.TEXTURE0),l.uniform1i(u.map,0);var v=0,g=0,E=n.fog;E?(l.uniform3f(u.fogColor,E.color.r,E.color.g,E.color.b),E instanceof THREE.Fog?(l.uniform1f(u.fogNear,E.near),l.uniform1f(u.fogFar,E.far),l.uniform1i(u.fogType,1),v=1,g=1):E instanceof THREE.FogExp2&&(l.uniform1f(u.fogDensity,E.density),l.uniform1i(u.fogType,2),v=2,g=2)):(l.uniform1i(u.fogType,0),v=0,g=0);for(var y=0,_=e.length;_>y;y++){var b=e[y];b._modelViewMatrix.multiplyMatrices(m.matrixWorldInverse,b.matrixWorld),b.z=-b._modelViewMatrix.elements[14]}e.sort(r);for(var T=[],y=0,_=e.length;_>y;y++){var b=e[y],x=b.material;l.uniform1f(u.alphaTest,x.alphaTest),l.uniformMatrix4fv(u.modelViewMatrix,!1,b._modelViewMatrix.elements),b.matrixWorld.decompose(c,p,f),T[0]=f.x,T[1]=f.y;var w=0;n.fog&&x.fog&&(w=g),v!==w&&(l.uniform1i(u.fogType,w),v=w),null!==x.map?(l.uniform2f(u.uvOffset,x.map.offset.x,x.map.offset.y),l.uniform2f(u.uvScale,x.map.repeat.x,x.map.repeat.y)):(l.uniform2f(u.uvOffset,0,0),l.uniform2f(u.uvScale,1,1)),l.uniform1f(u.opacity,x.opacity),l.uniform3f(u.color,x.color.r,x.color.g,x.color.b),l.uniform1f(u.rotation,x.rotation),l.uniform2fv(u.scale,T),t.state.setBlending(x.blending,x.blendEquation,x.blendSrc,x.blendDst),t.state.setDepthTest(x.depthTest),t.state.setDepthWrite(x.depthWrite),x.map&&x.map.image&&x.map.image.width?t.setTexture(x.map,0):t.setTexture(h,0),l.drawElements(l.TRIANGLES,6,l.UNSIGNED_SHORT,0)}l.enable(l.CULL_FACE),t.resetGLState()}}},THREE.GeometryUtils={merge:function(t,e,n){THREE.warn("THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.");var r;e instanceof THREE.Mesh&&(e.matrixAutoUpdate&&e.updateMatrix(),r=e.matrix,e=e.geometry),t.merge(e,r,n)},center:function(t){return THREE.warn("THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead."),t.center()}},THREE.ImageUtils={crossOrigin:void 0,loadTexture:function(t,e,n,r){var i=new THREE.ImageLoader;i.crossOrigin=this.crossOrigin;var o=new THREE.Texture(void 0,e);return i.load(t,function(t){o.image=t,o.needsUpdate=!0,n&&n(o)},void 0,function(t){r&&r(t)}),o.sourceFile=t,o},loadTextureCube:function(t,e,n,r){var i=[],o=new THREE.ImageLoader;o.crossOrigin=this.crossOrigin;var s=new THREE.CubeTexture(i,e);s.flipY=!1;for(var a=0,u=function(e){o.load(t[e],function(t){s.images[e]=t,a+=1,6===a&&(s.needsUpdate=!0,n&&n(s))},void 0,r)},h=0,l=t.length;l>h;++h)u(h);return s},loadCompressedTexture:function(){THREE.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.")},loadCompressedTextureCube:function(){THREE.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.")},getNormalMap:function(t,e){var n=function(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]},r=function(t,e){return[t[0]-e[0],t[1]-e[1],t[2]-e[2]]},i=function(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);return[t[0]/e,t[1]/e,t[2]/e]};e=1|e;var o=t.width,s=t.height,a=document.createElement("canvas");a.width=o,a.height=s;var u=a.getContext("2d");u.drawImage(t,0,0);for(var h=u.getImageData(0,0,o,s).data,l=u.createImageData(o,s),c=l.data,p=0;o>p;p++)for(var f=0;s>f;f++){var d=0>f-1?0:f-1,m=f+1>s-1?s-1:f+1,v=0>p-1?0:p-1,g=p+1>o-1?o-1:p+1,E=[],y=[0,0,h[4*(f*o+p)]/255*e];E.push([-1,0,h[4*(f*o+v)]/255*e]),E.push([-1,-1,h[4*(d*o+v)]/255*e]),E.push([0,-1,h[4*(d*o+p)]/255*e]),E.push([1,-1,h[4*(d*o+g)]/255*e]),E.push([1,0,h[4*(f*o+g)]/255*e]),E.push([1,1,h[4*(m*o+g)]/255*e]),E.push([0,1,h[4*(m*o+p)]/255*e]),E.push([-1,1,h[4*(m*o+v)]/255*e]);for(var _=[],b=E.length,T=0;b>T;T++){var x=E[T],w=E[(T+1)%b];x=r(x,y),w=r(w,y),_.push(i(n(x,w)))}for(var R=[0,0,0],T=0;T<_.length;T++)R[0]+=_[T][0],R[1]+=_[T][1],R[2]+=_[T][2];R[0]/=_.length,R[1]/=_.length,R[2]/=_.length;var H=4*(f*o+p);c[H]=(R[0]+1)/2*255|0,c[H+1]=(R[1]+1)/2*255|0,c[H+2]=255*R[2]|0,c[H+3]=255}return u.putImageData(l,0,0),a},generateDataTexture:function(t,e,n){for(var r=t*e,i=new Uint8Array(3*r),o=Math.floor(255*n.r),s=Math.floor(255*n.g),a=Math.floor(255*n.b),u=0;r>u;u++)i[3*u]=o,i[3*u+1]=s,i[3*u+2]=a;var h=new THREE.DataTexture(i,t,e,THREE.RGBFormat);return h.needsUpdate=!0,h}},THREE.SceneUtils={createMultiMaterialObject:function(t,e){for(var n=new THREE.Object3D,r=0,i=e.length;i>r;r++)n.add(new THREE.Mesh(t,e[r]));return n},detach:function(t,e,n){t.applyMatrix(e.matrixWorld),e.remove(t),n.add(t)},attach:function(t,e,n){var r=new THREE.Matrix4;r.getInverse(n.matrixWorld),t.applyMatrix(r),e.remove(t),n.add(t)}},THREE.FontUtils={faces:{},face:"helvetiker",weight:"normal",style:"normal",size:150,divisions:10,getFace:function(){try{return this.faces[this.face][this.weight][this.style]}catch(t){throw"The font "+this.face+" with "+this.weight+" weight and "+this.style+" style is missing."}},loadFace:function(t){var e=t.familyName.toLowerCase(),n=this;return n.faces[e]=n.faces[e]||{},n.faces[e][t.cssFontWeight]=n.faces[e][t.cssFontWeight]||{},n.faces[e][t.cssFontWeight][t.cssFontStyle]=t,n.faces[e][t.cssFontWeight][t.cssFontStyle]=t,t},drawText:function(t){var e,n=this.getFace(),r=this.size/n.resolution,i=0,o=String(t).split(""),s=o.length,a=[];for(e=0;s>e;e++){var u=new THREE.Path,h=this.extractGlyphPoints(o[e],n,r,i,u);i+=h.offset,a.push(h.path)}var l=i/2;return{paths:a,offset:l}},extractGlyphPoints:function(t,e,n,r,i){var o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w=[],R=e.glyphs[t]||e.glyphs["?"];if(R){if(R.o)for(u=R._cachedOutline||(R._cachedOutline=R.o.split(" ")),l=u.length,c=n,p=n,o=0;l>o;)switch(h=u[o++]){case"m":f=u[o++]*c+r,d=u[o++]*p,i.moveTo(f,d);break;case"l":f=u[o++]*c+r,d=u[o++]*p,i.lineTo(f,d);break;case"q":if(m=u[o++]*c+r,v=u[o++]*p,y=u[o++]*c+r,_=u[o++]*p,i.quadraticCurveTo(y,_,m,v),x=w[w.length-1])for(g=x.x,E=x.y,s=1,a=this.divisions;a>=s;s++){var H=s/a;THREE.Shape.Utils.b2(H,g,y,m),THREE.Shape.Utils.b2(H,E,_,v)}break;case"b":if(m=u[o++]*c+r,v=u[o++]*p,y=u[o++]*c+r,_=u[o++]*p,b=u[o++]*c+r,T=u[o++]*p,i.bezierCurveTo(y,_,b,T,m,v),x=w[w.length-1])for(g=x.x,E=x.y,s=1,a=this.divisions;a>=s;s++){var H=s/a;THREE.Shape.Utils.b3(H,g,y,b,m),THREE.Shape.Utils.b3(H,E,_,T,v)}}return{offset:R.ha*n,path:i}}}},THREE.FontUtils.generateShapes=function(t,e){e=e||{};var n=void 0!==e.size?e.size:100,r=void 0!==e.curveSegments?e.curveSegments:4,i=void 0!==e.font?e.font:"helvetiker",o=void 0!==e.weight?e.weight:"normal",s=void 0!==e.style?e.style:"normal";THREE.FontUtils.size=n,THREE.FontUtils.divisions=r,THREE.FontUtils.face=i,THREE.FontUtils.weight=o,THREE.FontUtils.style=s;for(var a=THREE.FontUtils.drawText(t),u=a.paths,h=[],l=0,c=u.length;c>l;l++)Array.prototype.push.apply(h,u[l].toShapes());return h},function(t){var e=1e-10,n=function(t,e){var n=t.length;if(3>n)return null;var o,s,a,u=[],h=[],l=[];if(r(t)>0)for(s=0;n>s;s++)h[s]=s;else for(s=0;n>s;s++)h[s]=n-1-s;var c=n,p=2*c;for(s=c-1;c>2;){if(p--<=0)return THREE.warn("THREE.FontUtils: Warning, unable to triangulate polygon! in Triangulate.process()"),e?l:u;if(o=s,o>=c&&(o=0),s=o+1,s>=c&&(s=0),a=s+1,a>=c&&(a=0),i(t,o,s,a,c,h)){var f,d,m,v,g;for(f=h[o],d=h[s],m=h[a],u.push([t[f],t[d],t[m]]),l.push([h[o],h[s],h[a]]),v=s,g=s+1;c>g;v++,g++)h[v]=h[g];c--,p=2*c}}return e?l:u},r=function(t){for(var e=t.length,n=0,r=e-1,i=0;e>i;r=i++)n+=t[r].x*t[i].y-t[i].x*t[r].y;return.5*n},i=function(t,n,r,i,o,s){var a,u,h,l,c,p,f,d,m;if(u=t[s[n]].x,h=t[s[n]].y,l=t[s[r]].x,c=t[s[r]].y,p=t[s[i]].x,f=t[s[i]].y,e>(l-u)*(f-h)-(c-h)*(p-u))return!1;var v,g,E,y,_,b,T,x,w,R,H,M,S,k,A;for(v=p-l,g=f-c,E=u-p,y=h-f,_=l-u,b=c-h,a=0;o>a;a++)if(d=t[s[a]].x,m=t[s[a]].y,!(d===u&&m===h||d===l&&m===c||d===p&&m===f)&&(T=d-u,x=m-h,w=d-l,R=m-c,H=d-p,M=m-f,A=v*R-g*w,S=_*x-b*T,k=E*M-y*H,A>=-e&&k>=-e&&S>=-e))return!1;return!0};return t.Triangulate=n,t.Triangulate.area=r,t}(THREE.FontUtils),self._typeface_js={faces:THREE.FontUtils.faces,loadFace:THREE.FontUtils.loadFace},THREE.typeface_js=self._typeface_js,THREE.Audio=function(t){THREE.Object3D.call(this),this.type="Audio",this.context=t.context,this.source=this.context.createBufferSource(),this.source.onended=this.onEnded.bind(this),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.panner=this.context.createPanner(),this.panner.connect(this.gain),this.autoplay=!1,this.startTime=0,this.isPlaying=!1},THREE.Audio.prototype=Object.create(THREE.Object3D.prototype),THREE.Audio.prototype.constructor=THREE.Audio,THREE.Audio.prototype.load=function(t){var e=this,n=new XMLHttpRequest;return n.open("GET",t,!0),n.responseType="arraybuffer",n.onload=function(t){e.context.decodeAudioData(this.response,function(t){e.source.buffer=t,e.autoplay&&e.play()})},n.send(),this},THREE.Audio.prototype.play=function(){if(this.isPlaying===!0)return void THREE.warn("THREE.Audio: Audio is already playing.");var t=this.context.createBufferSource();t.buffer=this.source.buffer,t.loop=this.source.loop,t.onended=this.source.onended,t.connect(this.panner),t.start(0,this.startTime),this.isPlaying=!0,this.source=t},THREE.Audio.prototype.pause=function(){this.source.stop(),this.startTime=this.context.currentTime},THREE.Audio.prototype.stop=function(){this.source.stop(),this.startTime=0},THREE.Audio.prototype.onEnded=function(){this.isPlaying=!1},THREE.Audio.prototype.setLoop=function(t){this.source.loop=t},THREE.Audio.prototype.setRefDistance=function(t){this.panner.refDistance=t},THREE.Audio.prototype.setRolloffFactor=function(t){this.panner.rolloffFactor=t},THREE.Audio.prototype.setVolume=function(t){this.gain.gain.value=t},THREE.Audio.prototype.updateMatrixWorld=function(){var t=new THREE.Vector3;return function(e){THREE.Object3D.prototype.updateMatrixWorld.call(this,e),t.setFromMatrixPosition(this.matrixWorld),this.panner.setPosition(t.x,t.y,t.z)}}(),THREE.AudioListener=function(){THREE.Object3D.call(this),this.type="AudioListener",this.context=new(window.AudioContext||window.webkitAudioContext)},THREE.AudioListener.prototype=Object.create(THREE.Object3D.prototype),THREE.AudioListener.prototype.constructor=THREE.AudioListener,THREE.AudioListener.prototype.updateMatrixWorld=function(){var t=new THREE.Vector3,e=new THREE.Quaternion,n=new THREE.Vector3,r=new THREE.Vector3,i=new THREE.Vector3,o=new THREE.Vector3;return function(s){THREE.Object3D.prototype.updateMatrixWorld.call(this,s);var a=this.context.listener,u=this.up;this.matrixWorld.decompose(t,e,n),r.set(0,0,-1).applyQuaternion(e),i.subVectors(t,o),a.setPosition(t.x,t.y,t.z),a.setOrientation(r.x,r.y,r.z,u.x,u.y,u.z),a.setVelocity(i.x,i.y,i.z),o.copy(t)}}(),THREE.Curve=function(){},THREE.Curve.prototype.getPoint=function(t){return THREE.warn("THREE.Curve: Warning, getPoint() not implemented!"),null},THREE.Curve.prototype.getPointAt=function(t){var e=this.getUtoTmapping(t);return this.getPoint(e)},THREE.Curve.prototype.getPoints=function(t){t||(t=5);var e,n=[];for(e=0;t>=e;e++)n.push(this.getPoint(e/t));return n},THREE.Curve.prototype.getSpacedPoints=function(t){t||(t=5);var e,n=[];for(e=0;t>=e;e++)n.push(this.getPointAt(e/t));return n},THREE.Curve.prototype.getLength=function(){var t=this.getLengths();return t[t.length-1]},THREE.Curve.prototype.getLengths=function(t){if(t||(t=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length==t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var e,n,r=[],i=this.getPoint(0),o=0;for(r.push(0),n=1;t>=n;n++)e=this.getPoint(n/t),o+=e.distanceTo(i),r.push(o),i=e;return this.cacheArcLengths=r,r},THREE.Curve.prototype.updateArcLengths=function(){this.needsUpdate=!0,this.getLengths()},THREE.Curve.prototype.getUtoTmapping=function(t,e){var n,r=this.getLengths(),i=0,o=r.length;n=e?e:t*r[o-1];for(var s,a=0,u=o-1;u>=a;)if(i=Math.floor(a+(u-a)/2),s=r[i]-n,0>s)a=i+1;else{if(!(s>0)){u=i;break}u=i-1}if(i=u,r[i]==n){var h=i/(o-1);return h}var l=r[i],c=r[i+1],p=c-l,f=(n-l)/p,h=(i+f)/(o-1);return h},THREE.Curve.prototype.getTangent=function(t){var e=1e-4,n=t-e,r=t+e;0>n&&(n=0),r>1&&(r=1);var i=this.getPoint(n),o=this.getPoint(r),s=o.clone().sub(i);return s.normalize()},THREE.Curve.prototype.getTangentAt=function(t){var e=this.getUtoTmapping(t);return this.getTangent(e)},THREE.Curve.Utils={tangentQuadraticBezier:function(t,e,n,r){return 2*(1-t)*(n-e)+2*t*(r-n)},tangentCubicBezier:function(t,e,n,r,i){return-3*e*(1-t)*(1-t)+3*n*(1-t)*(1-t)-6*t*n*(1-t)+6*t*r*(1-t)-3*t*t*r+3*t*t*i},tangentSpline:function(t,e,n,r,i){var o=6*t*t-6*t,s=3*t*t-4*t+1,a=-6*t*t+6*t,u=3*t*t-2*t;return o+s+a+u},interpolate:function(t,e,n,r,i){var o=.5*(n-t),s=.5*(r-e),a=i*i,u=i*a;return(2*e-2*n+o+s)*u+(-3*e+3*n-2*o-s)*a+o*i+e}},THREE.Curve.create=function(t,e){return t.prototype=Object.create(THREE.Curve.prototype),t.prototype.constructor=t,t.prototype.getPoint=e,t},THREE.CurvePath=function(){this.curves=[],this.bends=[],this.autoClose=!1},THREE.CurvePath.prototype=Object.create(THREE.Curve.prototype),THREE.CurvePath.prototype.constructor=THREE.CurvePath,THREE.CurvePath.prototype.add=function(t){this.curves.push(t)},THREE.CurvePath.prototype.checkConnection=function(){},THREE.CurvePath.prototype.closePath=function(){var t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);t.equals(e)||this.curves.push(new THREE.LineCurve(e,t))},THREE.CurvePath.prototype.getPoint=function(t){for(var e,n,r=t*this.getLength(),i=this.getCurveLengths(),o=0;o=r){e=i[o]-r,n=this.curves[o];var s=1-e/n.getLength();return n.getPointAt(s)}o++}return null},THREE.CurvePath.prototype.getLength=function(){var t=this.getCurveLengths();return t[t.length-1]},THREE.CurvePath.prototype.getCurveLengths=function(){if(this.cacheLengths&&this.cacheLengths.length==this.curves.length)return this.cacheLengths;var t,e=[],n=0,r=this.curves.length;for(t=0;r>t;t++)n+=this.curves[t].getLength(),e.push(n);return this.cacheLengths=e,e},THREE.CurvePath.prototype.getBoundingBox=function(){var t,e,n,r,i,o,s=this.getPoints();t=e=Number.NEGATIVE_INFINITY,r=i=Number.POSITIVE_INFINITY;var a,u,h,l,c=s[0]instanceof THREE.Vector3;for(l=c?new THREE.Vector3:new THREE.Vector2,u=0,h=s.length;h>u;u++)a=s[u],a.x>t?t=a.x:a.xe?e=a.y:a.yn?n=a.z:a.zn;n++)i=this.getWrapPoints(i,e[n]);return i},THREE.CurvePath.prototype.getTransformedSpacedPoints=function(t,e){var n,r,i=this.getSpacedPoints(t);for(e||(e=this.bends),n=0,r=e.length;r>n;n++)i=this.getWrapPoints(i,e[n]);return i},THREE.CurvePath.prototype.getWrapPoints=function(t,e){var n,r,i,o,s,a,u=this.getBoundingBox();for(n=0,r=t.length;r>n;n++){i=t[n],o=i.x,s=i.y,a=o/u.maxX,a=e.getUtoTmapping(a,o);var h=e.getPoint(a),l=e.getTangent(a);l.set(-l.y,l.x).multiplyScalar(s),i.x=h.x+l.x,i.y=h.y+l.y}return t},THREE.Gyroscope=function(){THREE.Object3D.call(this)},THREE.Gyroscope.prototype=Object.create(THREE.Object3D.prototype),THREE.Gyroscope.prototype.constructor=THREE.Gyroscope,THREE.Gyroscope.prototype.updateMatrixWorld=function(){var t=new THREE.Vector3,e=new THREE.Quaternion,n=new THREE.Vector3,r=new THREE.Vector3,i=new THREE.Quaternion,o=new THREE.Vector3;return function(s){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||s)&&(this.parent?(this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorld.decompose(r,i,o),this.matrix.decompose(t,e,n),this.matrixWorld.compose(r,e,o)):this.matrixWorld.copy(this.matrix),this.matrixWorldNeedsUpdate=!1,s=!0);for(var a=0,u=this.children.length;u>a;a++)this.children[a].updateMatrixWorld(s)}}(),THREE.Path=function(t){THREE.CurvePath.call(this),this.actions=[],t&&this.fromPoints(t)},THREE.Path.prototype=Object.create(THREE.CurvePath.prototype),THREE.Path.prototype.constructor=THREE.Path,THREE.PathActions={MOVE_TO:"moveTo",LINE_TO:"lineTo",QUADRATIC_CURVE_TO:"quadraticCurveTo",BEZIER_CURVE_TO:"bezierCurveTo",CSPLINE_THRU:"splineThru",ARC:"arc",ELLIPSE:"ellipse"},THREE.Path.prototype.fromPoints=function(t){this.moveTo(t[0].x,t[0].y);for(var e=1,n=t.length;n>e;e++)this.lineTo(t[e].x,t[e].y)},THREE.Path.prototype.moveTo=function(t,e){var n=Array.prototype.slice.call(arguments);this.actions.push({action:THREE.PathActions.MOVE_TO,args:n})},THREE.Path.prototype.lineTo=function(t,e){var n=Array.prototype.slice.call(arguments),r=this.actions[this.actions.length-1].args,i=r[r.length-2],o=r[r.length-1],s=new THREE.LineCurve(new THREE.Vector2(i,o),new THREE.Vector2(t,e));this.curves.push(s),this.actions.push({action:THREE.PathActions.LINE_TO,args:n})},THREE.Path.prototype.quadraticCurveTo=function(t,e,n,r){var i=Array.prototype.slice.call(arguments),o=this.actions[this.actions.length-1].args,s=o[o.length-2],a=o[o.length-1],u=new THREE.QuadraticBezierCurve(new THREE.Vector2(s,a),new THREE.Vector2(t,e),new THREE.Vector2(n,r));this.curves.push(u),this.actions.push({action:THREE.PathActions.QUADRATIC_CURVE_TO,args:i})},THREE.Path.prototype.bezierCurveTo=function(t,e,n,r,i,o){var s=Array.prototype.slice.call(arguments),a=this.actions[this.actions.length-1].args,u=a[a.length-2],h=a[a.length-1],l=new THREE.CubicBezierCurve(new THREE.Vector2(u,h),new THREE.Vector2(t,e),new THREE.Vector2(n,r),new THREE.Vector2(i,o));this.curves.push(l),this.actions.push({action:THREE.PathActions.BEZIER_CURVE_TO,args:s})},THREE.Path.prototype.splineThru=function(t){var e=Array.prototype.slice.call(arguments),n=this.actions[this.actions.length-1].args,r=n[n.length-2],i=n[n.length-1],o=[new THREE.Vector2(r,i)];Array.prototype.push.apply(o,t);var s=new THREE.SplineCurve(o);this.curves.push(s),this.actions.push({action:THREE.PathActions.CSPLINE_THRU,args:e})},THREE.Path.prototype.arc=function(t,e,n,r,i,o){var s=this.actions[this.actions.length-1].args,a=s[s.length-2],u=s[s.length-1];this.absarc(t+a,e+u,n,r,i,o)},THREE.Path.prototype.absarc=function(t,e,n,r,i,o){this.absellipse(t,e,n,n,r,i,o)},THREE.Path.prototype.ellipse=function(t,e,n,r,i,o,s){var a=this.actions[this.actions.length-1].args,u=a[a.length-2],h=a[a.length-1];this.absellipse(t+u,e+h,n,r,i,o,s)},THREE.Path.prototype.absellipse=function(t,e,n,r,i,o,s){var a=Array.prototype.slice.call(arguments),u=new THREE.EllipseCurve(t,e,n,r,i,o,s);this.curves.push(u);var h=u.getPoint(1);a.push(h.x),a.push(h.y),this.actions.push({action:THREE.PathActions.ELLIPSE,args:a})},THREE.Path.prototype.getSpacedPoints=function(t,e){t||(t=40);for(var n=[],r=0;t>r;r++)n.push(this.getPoint(r/t));return n},THREE.Path.prototype.getPoints=function(t,e){if(this.useSpacedPoints)return console.log("tata"),this.getSpacedPoints(t,e);t=t||12;var n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_=[];for(n=0,r=this.actions.length;r>n;n++)switch(i=this.actions[n],o=i.action,s=i.args,o){case THREE.PathActions.MOVE_TO:_.push(new THREE.Vector2(s[0],s[1]));break;case THREE.PathActions.LINE_TO:_.push(new THREE.Vector2(s[0],s[1]));break;case THREE.PathActions.QUADRATIC_CURVE_TO:for(a=s[2],u=s[3],c=s[0],p=s[1],_.length>0?(m=_[_.length-1],f=m.x,d=m.y):(m=this.actions[n-1].args,f=m[m.length-2],d=m[m.length-1]),v=1;t>=v;v++)g=v/t,E=THREE.Shape.Utils.b2(g,f,c,a),y=THREE.Shape.Utils.b2(g,d,p,u),_.push(new THREE.Vector2(E,y));break;case THREE.PathActions.BEZIER_CURVE_TO:for(a=s[4],u=s[5],c=s[0],p=s[1],h=s[2],l=s[3],_.length>0?(m=_[_.length-1],f=m.x,d=m.y):(m=this.actions[n-1].args,f=m[m.length-2],d=m[m.length-1]),v=1;t>=v;v++)g=v/t,E=THREE.Shape.Utils.b3(g,f,c,h,a),y=THREE.Shape.Utils.b3(g,d,p,l,u),_.push(new THREE.Vector2(E,y));break;case THREE.PathActions.CSPLINE_THRU:m=this.actions[n-1].args;var b=new THREE.Vector2(m[m.length-2],m[m.length-1]),T=[b],x=t*s[0].length;T=T.concat(s[0]);var w=new THREE.SplineCurve(T);for(v=1;x>=v;v++)_.push(w.getPointAt(v/x));break;case THREE.PathActions.ARC:var R,H=s[0],M=s[1],S=s[2],k=s[3],A=s[4],C=!!s[5],P=A-k,L=2*t;for(v=1;L>=v;v++)g=v/L,C||(g=1-g),R=k+g*P,E=H+S*Math.cos(R),y=M+S*Math.sin(R),_.push(new THREE.Vector2(E,y));break;case THREE.PathActions.ELLIPSE:var R,H=s[0],M=s[1],z=s[2],O=s[3],k=s[4],A=s[5],C=!!s[6],P=A-k,L=2*t;for(v=1;L>=v;v++)g=v/L,C||(g=1-g),R=k+g*P,E=H+z*Math.cos(R),y=M+O*Math.sin(R),_.push(new THREE.Vector2(E,y))}var D=_[_.length-1],F=1e-10;return Math.abs(D.x-_[0].x)e;e++)r=t[e],o=r.args,i=r.action,i==THREE.PathActions.MOVE_TO&&0!=a.actions.length&&(s.push(a),a=new THREE.Path),a[i].apply(a,o);return 0!=a.actions.length&&s.push(a),s}function r(t){for(var e=[],n=0,r=t.length;r>n;n++){var i=t[n],o=new THREE.Shape;o.actions=i.actions,o.curves=i.curves,e.push(o)}return e}function i(t,e){for(var n=1e-10,r=e.length,i=!1,o=r-1,s=0;r>s;o=s++){var a=e[o],u=e[s],h=u.x-a.x,l=u.y-a.y;if(Math.abs(l)>n){if(0>l&&(a=e[s],h=-h,u=e[o],l=-l),t.yu.y)continue;if(t.y==a.y){if(t.x==a.x)return!0}else{var c=l*(t.x-a.x)-h*(t.y-a.y);if(0==c)return!0;if(0>c)continue;i=!i}}else{if(t.y!=a.y)continue;if(u.x<=t.x&&t.x<=a.x||a.x<=t.x&&t.x<=u.x)return!0}}return i}var o=n(this.actions);if(0==o.length)return[];if(e===!0)return r(o);var s,a,u,h=[];if(1==o.length)return a=o[0],u=new THREE.Shape,u.actions=a.actions,u.curves=a.curves,h.push(u),h;var l=!THREE.Shape.Utils.isClockWise(o[0].getPoints());l=t?!l:l;var c,p=[],f=[],d=[],m=0;f[m]=void 0,d[m]=[];var v,g;for(v=0,g=o.length;g>v;v++)a=o[v],c=a.getPoints(),s=THREE.Shape.Utils.isClockWise(c),s=t?!s:s,s?(!l&&f[m]&&m++,f[m]={s:new THREE.Shape,p:c},f[m].s.actions=a.actions,f[m].s.curves=a.curves,l&&m++,d[m]=[]):d[m].push({h:a,p:c[0]});if(!f[0])return r(o);if(f.length>1){for(var E=!1,y=[],_=0,b=f.length;b>_;_++)p[_]=[];for(var _=0,b=f.length;b>_;_++)for(var T=d[_],x=0;x0&&(E||(d=p))}var M,S,k;for(v=0,g=f.length;g>v;v++)for(u=f[v].s,h.push(u),M=d[v],S=0,k=M.length;k>S;S++)u.holes.push(M[S].h);return h},THREE.Shape=function(){THREE.Path.apply(this,arguments),this.holes=[]},THREE.Shape.prototype=Object.create(THREE.Path.prototype),THREE.Shape.prototype.constructor=THREE.Shape,THREE.Shape.prototype.extrude=function(t){var e=new THREE.ExtrudeGeometry(this,t);return e},THREE.Shape.prototype.makeGeometry=function(t){var e=new THREE.ShapeGeometry(this,t);return e},THREE.Shape.prototype.getPointsHoles=function(t){var e,n=this.holes.length,r=[];for(e=0;n>e;e++)r[e]=this.holes[e].getTransformedPoints(t,this.bends);return r},THREE.Shape.prototype.getSpacedPointsHoles=function(t){ +var e,n=this.holes.length,r=[];for(e=0;n>e;e++)r[e]=this.holes[e].getTransformedSpacedPoints(t,this.bends);return r},THREE.Shape.prototype.extractAllPoints=function(t){return{shape:this.getTransformedPoints(t),holes:this.getPointsHoles(t)}},THREE.Shape.prototype.extractPoints=function(t){return this.useSpacedPoints?this.extractAllSpacedPoints(t):this.extractAllPoints(t)},THREE.Shape.prototype.extractAllSpacedPoints=function(t){return{shape:this.getTransformedSpacedPoints(t),holes:this.getSpacedPointsHoles(t)}},THREE.Shape.Utils={triangulateShape:function(t,e){function n(t,e,n){return t.x!=e.x?t.xs){var m;if(f>0){if(0>d||d>f)return[];if(m=l*c-h*p,0>m||m>f)return[]}else{if(d>0||f>d)return[];if(m=l*c-h*p,m>0||f>m)return[]}if(0==m)return!o||0!=d&&d!=f?[t]:[];if(m==f)return!o||0!=d&&d!=f?[e]:[];if(0==d)return[r];if(d==f)return[i];var v=m/f;return[{x:t.x+v*a,y:t.y+v*u}]}if(0!=d||l*c!=h*p)return[];var g=0==a&&0==u,E=0==h&&0==l;if(g&&E)return t.x!=r.x||t.y!=r.y?[]:[t];if(g)return n(r,i,t)?[t]:[];if(E)return n(t,e,r)?[r]:[];var y,_,b,T,x,w,R,H;return 0!=a?(t.x=b?R>T?[]:T==R?o?[]:[x]:H>=T?[x,_]:[x,w]:b>H?[]:b==H?o?[]:[y]:H>=T?[y,_]:[y,w]}function i(t,e,n,r){var i=1e-10,o=e.x-t.x,s=e.y-t.y,a=n.x-t.x,u=n.y-t.y,h=r.x-t.x,l=r.y-t.y,c=o*u-s*a,p=o*l-s*h;if(Math.abs(c)>i){var f=h*u-l*a;return c>0?p>=0&&f>=0:p>=0||f>=0}return p>0}function o(t,e){function n(t,e){var n=E.length-1,r=t-1;0>r&&(r=n);var o=t+1;o>n&&(o=0);var s=i(E[t],E[r],E[o],a[e]);if(!s)return!1;var u=a.length-1,h=e-1;0>h&&(h=u);var l=e+1;return l>u&&(l=0),s=i(a[e],a[h],a[l],E[t]),s?!0:!1}function o(t,e){var n,i,o;for(n=0;n0)return!0;return!1}function s(t,n){var i,o,s,a,u;for(i=0;i0)return!0;return!1}for(var a,u,h,l,c,p,f,d,m,v,g,E=t.concat(),y=[],_=[],b=0,T=e.length;T>b;b++)y.push(b);for(var x=0,w=2*y.length;y.length>0;){if(w--,0>w){console.log("Infinite Loop! Holes left:"+y.length+", Probably Hole outside Shape!");break}for(h=x;h=0)break;_[f]=!0}if(u>=0)break}}return E}for(var s,a,u,h,l,c,p={},f=t.concat(),d=0,m=e.length;m>d;d++)Array.prototype.push.apply(f,e[d]);for(s=0,a=f.length;a>s;s++)l=f[s].x+":"+f[s].y,void 0!==p[l]&&THREE.warn("THREE.Shape: Duplicate point",l),p[l]=s;var v=o(t,e),g=THREE.FontUtils.Triangulate(v,!1);for(s=0,a=g.length;a>s;s++)for(h=g[s],u=0;3>u;u++)l=h[u].x+":"+h[u].y,c=p[l],void 0!==c&&(h[u]=c);return g.concat()},isClockWise:function(t){return THREE.FontUtils.Triangulate.area(t)<0},b2p0:function(t,e){var n=1-t;return n*n*e},b2p1:function(t,e){return 2*(1-t)*t*e},b2p2:function(t,e){return t*t*e},b2:function(t,e,n,r){return this.b2p0(t,e)+this.b2p1(t,n)+this.b2p2(t,r)},b3p0:function(t,e){var n=1-t;return n*n*n*e},b3p1:function(t,e){var n=1-t;return 3*n*n*t*e},b3p2:function(t,e){var n=1-t;return 3*n*t*t*e},b3p3:function(t,e){return t*t*t*e},b3:function(t,e,n,r,i){return this.b3p0(t,e)+this.b3p1(t,n)+this.b3p2(t,r)+this.b3p3(t,i)}},THREE.LineCurve=function(t,e){this.v1=t,this.v2=e},THREE.LineCurve.prototype=Object.create(THREE.Curve.prototype),THREE.LineCurve.prototype.constructor=THREE.LineCurve,THREE.LineCurve.prototype.getPoint=function(t){var e=this.v2.clone().sub(this.v1);return e.multiplyScalar(t).add(this.v1),e},THREE.LineCurve.prototype.getPointAt=function(t){return this.getPoint(t)},THREE.LineCurve.prototype.getTangent=function(t){var e=this.v2.clone().sub(this.v1);return e.normalize()},THREE.QuadraticBezierCurve=function(t,e,n){this.v0=t,this.v1=e,this.v2=n},THREE.QuadraticBezierCurve.prototype=Object.create(THREE.Curve.prototype),THREE.QuadraticBezierCurve.prototype.constructor=THREE.QuadraticBezierCurve,THREE.QuadraticBezierCurve.prototype.getPoint=function(t){var e=new THREE.Vector2;return e.x=THREE.Shape.Utils.b2(t,this.v0.x,this.v1.x,this.v2.x),e.y=THREE.Shape.Utils.b2(t,this.v0.y,this.v1.y,this.v2.y),e},THREE.QuadraticBezierCurve.prototype.getTangent=function(t){var e=new THREE.Vector2;return e.x=THREE.Curve.Utils.tangentQuadraticBezier(t,this.v0.x,this.v1.x,this.v2.x),e.y=THREE.Curve.Utils.tangentQuadraticBezier(t,this.v0.y,this.v1.y,this.v2.y),e.normalize()},THREE.CubicBezierCurve=function(t,e,n,r){this.v0=t,this.v1=e,this.v2=n,this.v3=r},THREE.CubicBezierCurve.prototype=Object.create(THREE.Curve.prototype),THREE.CubicBezierCurve.prototype.constructor=THREE.CubicBezierCurve,THREE.CubicBezierCurve.prototype.getPoint=function(t){var e,n;return e=THREE.Shape.Utils.b3(t,this.v0.x,this.v1.x,this.v2.x,this.v3.x),n=THREE.Shape.Utils.b3(t,this.v0.y,this.v1.y,this.v2.y,this.v3.y),new THREE.Vector2(e,n)},THREE.CubicBezierCurve.prototype.getTangent=function(t){var e,n;e=THREE.Curve.Utils.tangentCubicBezier(t,this.v0.x,this.v1.x,this.v2.x,this.v3.x),n=THREE.Curve.Utils.tangentCubicBezier(t,this.v0.y,this.v1.y,this.v2.y,this.v3.y);var r=new THREE.Vector2(e,n);return r.normalize(),r},THREE.SplineCurve=function(t){this.points=void 0==t?[]:t},THREE.SplineCurve.prototype=Object.create(THREE.Curve.prototype),THREE.SplineCurve.prototype.constructor=THREE.SplineCurve,THREE.SplineCurve.prototype.getPoint=function(t){var e=this.points,n=(e.length-1)*t,r=Math.floor(n),i=n-r,o=e[0==r?r:r-1],s=e[r],a=e[r>e.length-2?e.length-1:r+1],u=e[r>e.length-3?e.length-1:r+2],h=new THREE.Vector2;return h.x=THREE.Curve.Utils.interpolate(o.x,s.x,a.x,u.x,i),h.y=THREE.Curve.Utils.interpolate(o.y,s.y,a.y,u.y,i),h},THREE.EllipseCurve=function(t,e,n,r,i,o,s){this.aX=t,this.aY=e,this.xRadius=n,this.yRadius=r,this.aStartAngle=i,this.aEndAngle=o,this.aClockwise=s},THREE.EllipseCurve.prototype=Object.create(THREE.Curve.prototype),THREE.EllipseCurve.prototype.constructor=THREE.EllipseCurve,THREE.EllipseCurve.prototype.getPoint=function(t){var e=this.aEndAngle-this.aStartAngle;0>e&&(e+=2*Math.PI),e>2*Math.PI&&(e-=2*Math.PI);var n;n=this.aClockwise===!0?this.aEndAngle+(1-t)*(2*Math.PI-e):this.aStartAngle+t*e;var r=new THREE.Vector2;return r.x=this.aX+this.xRadius*Math.cos(n),r.y=this.aY+this.yRadius*Math.sin(n),r},THREE.ArcCurve=function(t,e,n,r,i,o){THREE.EllipseCurve.call(this,t,e,n,n,r,i,o)},THREE.ArcCurve.prototype=Object.create(THREE.EllipseCurve.prototype),THREE.ArcCurve.prototype.constructor=THREE.ArcCurve,THREE.LineCurve3=THREE.Curve.create(function(t,e){this.v1=t,this.v2=e},function(t){var e=new THREE.Vector3;return e.subVectors(this.v2,this.v1),e.multiplyScalar(t),e.add(this.v1),e}),THREE.QuadraticBezierCurve3=THREE.Curve.create(function(t,e,n){this.v0=t,this.v1=e,this.v2=n},function(t){var e=new THREE.Vector3;return e.x=THREE.Shape.Utils.b2(t,this.v0.x,this.v1.x,this.v2.x),e.y=THREE.Shape.Utils.b2(t,this.v0.y,this.v1.y,this.v2.y),e.z=THREE.Shape.Utils.b2(t,this.v0.z,this.v1.z,this.v2.z),e}),THREE.CubicBezierCurve3=THREE.Curve.create(function(t,e,n,r){this.v0=t,this.v1=e,this.v2=n,this.v3=r},function(t){var e=new THREE.Vector3;return e.x=THREE.Shape.Utils.b3(t,this.v0.x,this.v1.x,this.v2.x,this.v3.x),e.y=THREE.Shape.Utils.b3(t,this.v0.y,this.v1.y,this.v2.y,this.v3.y),e.z=THREE.Shape.Utils.b3(t,this.v0.z,this.v1.z,this.v2.z,this.v3.z),e}),THREE.SplineCurve3=THREE.Curve.create(function(t){this.points=void 0==t?[]:t},function(t){var e=this.points,n=(e.length-1)*t,r=Math.floor(n),i=n-r,o=e[0==r?r:r-1],s=e[r],a=e[r>e.length-2?e.length-1:r+1],u=e[r>e.length-3?e.length-1:r+2],h=new THREE.Vector3;return h.x=THREE.Curve.Utils.interpolate(o.x,s.x,a.x,u.x,i),h.y=THREE.Curve.Utils.interpolate(o.y,s.y,a.y,u.y,i),h.z=THREE.Curve.Utils.interpolate(o.z,s.z,a.z,u.z,i),h}),THREE.ClosedSplineCurve3=THREE.Curve.create(function(t){this.points=void 0==t?[]:t},function(t){var e=this.points,n=(e.length-0)*t,r=Math.floor(n),i=n-r;r+=r>0?0:(Math.floor(Math.abs(r)/e.length)+1)*e.length;var o=e[(r-1)%e.length],s=e[r%e.length],a=e[(r+1)%e.length],u=e[(r+2)%e.length],h=new THREE.Vector3;return h.x=THREE.Curve.Utils.interpolate(o.x,s.x,a.x,u.x,i),h.y=THREE.Curve.Utils.interpolate(o.y,s.y,a.y,u.y,i),h.z=THREE.Curve.Utils.interpolate(o.z,s.z,a.z,u.z,i),h}),THREE.AnimationHandler={LINEAR:0,CATMULLROM:1,CATMULLROM_FORWARD:2,add:function(){THREE.warn("THREE.AnimationHandler.add() has been deprecated.")},get:function(){THREE.warn("THREE.AnimationHandler.get() has been deprecated.")},remove:function(){THREE.warn("THREE.AnimationHandler.remove() has been deprecated.")},animations:[],init:function(t){if(t.initialized===!0)return t;for(var e=0;et;t++){var n=this.hierarchy[t];void 0===n.animationCache&&(n.animationCache={animations:{},blending:{positionWeight:0,quaternionWeight:0,scaleWeight:0}});var r=this.data.name,i=n.animationCache.animations,o=i[r];void 0===o&&(o={prevKey:{pos:0,rot:0,scl:0},nextKey:{pos:0,rot:0,scl:0},originalMatrix:n.matrix},i[r]=o);for(var s=0;3>s;s++){for(var a=this.keyTypes[s],u=this.data.hierarchy[t].keys[0],h=this.getNextKeyWith(a,t,1);h.timeu.index;)u=h,h=this.getNextKeyWith(a,t,h.index+1);o.prevKey[a]=u,o.nextKey[a]=h}}},resetBlendWeights:function(){for(var t=0,e=this.hierarchy.length;e>t;t++){var n=this.hierarchy[t],r=n.animationCache;if(void 0!==r){var i=r.blending;i.positionWeight=0,i.quaternionWeight=0,i.scaleWeight=0}}},update:function(){var t=[],e=new THREE.Vector3,n=new THREE.Vector3,r=new THREE.Quaternion,i=function(t,e){var n,r,i,s,a,u,h,l,c,p=[],f=[];return n=(t.length-1)*e,r=Math.floor(n),i=n-r,p[0]=0===r?r:r-1,p[1]=r,p[2]=r>t.length-2?r:r+1,p[3]=r>t.length-3?r:r+2,u=t[p[0]],h=t[p[1]],l=t[p[2]],c=t[p[3]],s=i*i,a=i*s,f[0]=o(u[0],h[0],l[0],c[0],i,s,a),f[1]=o(u[1],h[1],l[1],c[1],i,s,a),f[2]=o(u[2],h[2],l[2],c[2],i,s,a),f},o=function(t,e,n,r,i,o,s){var a=.5*(n-t),u=.5*(r-e);return(2*(e-n)+a+u)*s+(-3*(e-n)-2*a-u)*o+a*i+e};return function(o){if(this.isPlaying!==!1&&(this.currentTime+=o*this.timeScale,0!==this.weight)){var s=this.data.length;(this.currentTime>s||this.currentTime<0)&&(this.loop?(this.currentTime%=s,this.currentTime<0&&(this.currentTime+=s),this.reset()):this.stop());for(var a=0,u=this.hierarchy.length;u>a;a++)for(var h=this.hierarchy[a],l=h.animationCache.animations[this.data.name],c=h.animationCache.blending,p=0;3>p;p++){var f=this.keyTypes[p],d=l.prevKey[f],m=l.nextKey[f];if(this.timeScale>0&&m.time<=this.currentTime||this.timeScale<0&&d.time>=this.currentTime){for(d=this.data.hierarchy[a].keys[0],m=this.getNextKeyWith(f,a,1);m.timed.index;)d=m,m=this.getNextKeyWith(f,a,m.index+1);l.prevKey[f]=d,l.nextKey[f]=m}var v=(this.currentTime-d.time)/(m.time-d.time),g=d[f],E=m[f];if(0>v&&(v=0),v>1&&(v=1),"pos"===f){if(this.interpolationType===THREE.AnimationHandler.LINEAR){n.x=g[0]+(E[0]-g[0])*v,n.y=g[1]+(E[1]-g[1])*v,n.z=g[2]+(E[2]-g[2])*v;var y=this.weight/(this.weight+c.positionWeight);h.position.lerp(n,y),c.positionWeight+=this.weight}else if(this.interpolationType===THREE.AnimationHandler.CATMULLROM||this.interpolationType===THREE.AnimationHandler.CATMULLROM_FORWARD){t[0]=this.getPrevKeyWith("pos",a,d.index-1).pos,t[1]=g,t[2]=E,t[3]=this.getNextKeyWith("pos",a,m.index+1).pos,v=.33*v+.33;var _=i(t,v),y=this.weight/(this.weight+c.positionWeight);c.positionWeight+=this.weight;var b=h.position;if(b.x=b.x+(_[0]-b.x)*y,b.y=b.y+(_[1]-b.y)*y,b.z=b.z+(_[2]-b.z)*y,this.interpolationType===THREE.AnimationHandler.CATMULLROM_FORWARD){var T=i(t,1.01*v);e.set(T[0],T[1],T[2]),e.sub(b),e.y=0,e.normalize();var x=Math.atan2(e.x,e.z);h.rotation.set(0,x,0)}}}else if("rot"===f)if(THREE.Quaternion.slerp(g,E,r,v),0===c.quaternionWeight)h.quaternion.copy(r),c.quaternionWeight=this.weight;else{var y=this.weight/(this.weight+c.quaternionWeight);THREE.Quaternion.slerp(h.quaternion,r,h.quaternion,y),c.quaternionWeight+=this.weight}else if("scl"===f){n.x=g[0]+(E[0]-g[0])*v,n.y=g[1]+(E[1]-g[1])*v,n.z=g[2]+(E[2]-g[2])*v;var y=this.weight/(this.weight+c.scaleWeight);h.scale.lerp(n,y),c.scaleWeight+=this.weight}}return!0}}}(),getNextKeyWith:function(t,e,n){var r=this.data.hierarchy[e].keys;for(this.interpolationType===THREE.AnimationHandler.CATMULLROM||this.interpolationType===THREE.AnimationHandler.CATMULLROM_FORWARD?n=n0?n:0:n>=0?n:n+r.length;n>=0;n--)if(void 0!==r[n][t])return r[n];return this.data.hierarchy[e].keys[r.length-1]}},THREE.KeyFrameAnimation=function(t){this.root=t.node,this.data=THREE.AnimationHandler.init(t),this.hierarchy=THREE.AnimationHandler.parse(this.root),this.currentTime=0,this.timeScale=.001,this.isPlaying=!1,this.isPaused=!0,this.loop=!0;for(var e=0,n=this.hierarchy.length;n>e;e++){var r=this.data.hierarchy[e].keys,i=this.data.hierarchy[e].sids,o=this.hierarchy[e];if(r.length&&i){for(var s=0;se;e++){n=this.hierarchy[e],r=this.data.hierarchy[e],void 0===r.animationCache&&(r.animationCache={},r.animationCache.prevKey=null,r.animationCache.nextKey=null,r.animationCache.originalMatrix=n.matrix);var o=this.data.hierarchy[e].keys;o.length&&(r.animationCache.prevKey=o[0],r.animationCache.nextKey=o[1],this.startTime=Math.min(o[0].time,this.startTime),this.endTime=Math.max(o[o.length-1].time,this.endTime))}this.update(0)}this.isPaused=!1,THREE.AnimationHandler.play(this)},stop:function(){this.isPlaying=!1,this.isPaused=!1,THREE.AnimationHandler.stop(this);for(var t=0;te&&(this.currentTime%=e),this.currentTime=Math.min(this.currentTime,e);for(var n=0,r=this.hierarchy.length;r>n;n++){var i=this.hierarchy[n],o=this.data.hierarchy[n],s=o.keys,a=o.animationCache;if(s.length){var u=a.prevKey,h=a.nextKey;if(h.time<=this.currentTime){for(;h.timeu.index;)u=h,h=s[u.index+1];a.prevKey=u,a.nextKey=h}h.time>=this.currentTime?u.interpolate(h,this.currentTime):u.interpolate(h,h.time),this.data.hierarchy[n].node.updateMatrix(),i.matrixWorldNeedsUpdate=!0}}}},getNextKeyWith:function(t,e,n){var r=this.data.hierarchy[e].keys;for(n%=r.length;n=0?n:n+r.length;n>=0;n--)if(r[n].hasTarget(t))return r[n];return r[r.length-1]}},THREE.MorphAnimation=function(t){this.mesh=t,this.frames=t.morphTargetInfluences.length,this.currentTime=0,this.duration=1e3,this.loop=!0,this.lastFrame=0,this.currentFrame=0,this.isPlaying=!1},THREE.MorphAnimation.prototype={constructor:THREE.MorphAnimation,play:function(){this.isPlaying=!0},pause:function(){this.isPlaying=!1},update:function(t){if(this.isPlaying!==!1){this.currentTime+=t,this.loop===!0&&this.currentTime>this.duration&&(this.currentTime%=this.duration),this.currentTime=Math.min(this.currentTime,this.duration);var e=this.duration/this.frames,n=Math.floor(this.currentTime/e),r=this.mesh.morphTargetInfluences;n!=this.currentFrame&&(r[this.lastFrame]=0,r[this.currentFrame]=1,r[n]=0,this.lastFrame=this.currentFrame,this.currentFrame=n),r[n]=this.currentTime%e/e,r[this.lastFrame]=1-r[n]}}},THREE.BoxGeometry=function(t,e,n,r,i,o){function s(t,e,n,r,i,o,s,u){var h,l,c,p=a.widthSegments,f=a.heightSegments,d=i/2,m=o/2,v=a.vertices.length;"x"===t&&"y"===e||"y"===t&&"x"===e?h="z":"x"===t&&"z"===e||"z"===t&&"x"===e?(h="y",f=a.depthSegments):("z"===t&&"y"===e||"y"===t&&"z"===e)&&(h="x",p=a.depthSegments);var g=p+1,E=f+1,y=i/p,_=o/f,b=new THREE.Vector3;for(b[h]=s>0?1:-1,c=0;E>c;c++)for(l=0;g>l;l++){var T=new THREE.Vector3;T[t]=(l*y-d)*n,T[e]=(c*_-m)*r,T[h]=s,a.vertices.push(T)}for(c=0;f>c;c++)for(l=0;p>l;l++){var x=l+g*c,w=l+g*(c+1),R=l+1+g*(c+1),H=l+1+g*c,M=new THREE.Vector2(l/p,1-c/f),S=new THREE.Vector2(l/p,1-(c+1)/f),k=new THREE.Vector2((l+1)/p,1-(c+1)/f),A=new THREE.Vector2((l+1)/p,1-c/f),C=new THREE.Face3(x+v,w+v,H+v);C.normal.copy(b),C.vertexNormals.push(b.clone(),b.clone(),b.clone()),C.materialIndex=u,a.faces.push(C),a.faceVertexUvs[0].push([M,S,A]),C=new THREE.Face3(w+v,R+v,H+v),C.normal.copy(b),C.vertexNormals.push(b.clone(),b.clone(),b.clone()),C.materialIndex=u,a.faces.push(C),a.faceVertexUvs[0].push([S.clone(),k,A.clone()])}}THREE.Geometry.call(this),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:r,heightSegments:i,depthSegments:o},this.widthSegments=r||1,this.heightSegments=i||1,this.depthSegments=o||1;var a=this,u=t/2,h=e/2,l=n/2;s("z","y",-1,-1,n,e,u,0),s("z","y",1,-1,n,e,-u,1),s("x","z",1,1,t,n,h,2),s("x","z",1,-1,t,n,-h,3),s("x","y",1,-1,t,e,l,4),s("x","y",-1,-1,t,e,-l,5),this.mergeVertices()},THREE.BoxGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.BoxGeometry.prototype.constructor=THREE.BoxGeometry,THREE.CircleGeometry=function(t,e,n,r){THREE.Geometry.call(this),this.type="CircleGeometry",this.parameters={radius:t,segments:e,thetaStart:n,thetaLength:r},t=t||50,e=void 0!==e?Math.max(3,e):8,n=void 0!==n?n:0,r=void 0!==r?r:2*Math.PI;var i,o=[],s=new THREE.Vector3,a=new THREE.Vector2(.5,.5);for(this.vertices.push(s),o.push(a),i=0;e>=i;i++){var u=new THREE.Vector3,h=n+i/e*r;u.x=t*Math.cos(h),u.y=t*Math.sin(h),this.vertices.push(u),o.push(new THREE.Vector2((u.x/t+1)/2,(u.y/t+1)/2))}var l=new THREE.Vector3(0,0,1);for(i=1;e>=i;i++)this.faces.push(new THREE.Face3(i,i+1,0,[l.clone(),l.clone(),l.clone()])),this.faceVertexUvs[0].push([o[i].clone(),o[i+1].clone(),a.clone()]);this.computeFaceNormals(),this.boundingSphere=new THREE.Sphere(new THREE.Vector3,t)},THREE.CircleGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.CircleGeometry.prototype.constructor=THREE.CircleGeometry,THREE.CubeGeometry=function(t,e,n,r,i,o){return THREE.warn("THREE.CubeGeometry has been renamed to THREE.BoxGeometry."),new THREE.BoxGeometry(t,e,n,r,i,o)},THREE.CylinderGeometry=function(t,e,n,r,i,o,s,a){THREE.Geometry.call(this),this.type="CylinderGeometry",this.parameters={radiusTop:t,radiusBottom:e,height:n,radialSegments:r,heightSegments:i,openEnded:o,thetaStart:s,thetaLength:a},t=void 0!==t?t:20,e=void 0!==e?e:20,n=void 0!==n?n:100,r=r||8,i=i||1,o=void 0!==o?o:!1,s=void 0!==s?s:0,a=void 0!==a?a:2*Math.PI;var u,h,l=n/2,c=[],p=[];for(h=0;i>=h;h++){var f=[],d=[],m=h/i,v=m*(e-t)+t;for(u=0;r>=u;u++){var g=u/r,E=new THREE.Vector3;E.x=v*Math.sin(g*a+s),E.y=-m*n+l,E.z=v*Math.cos(g*a+s),this.vertices.push(E),f.push(this.vertices.length-1),d.push(new THREE.Vector2(g,1-m))}c.push(f),p.push(d)}var y,_,b=(e-t)/n;for(u=0;r>u;u++)for(0!==t?(y=this.vertices[c[0][u]].clone(),_=this.vertices[c[0][u+1]].clone()):(y=this.vertices[c[1][u]].clone(),_=this.vertices[c[1][u+1]].clone()),y.setY(Math.sqrt(y.x*y.x+y.z*y.z)*b).normalize(),_.setY(Math.sqrt(_.x*_.x+_.z*_.z)*b).normalize(),h=0;i>h;h++){var T=c[h][u],x=c[h+1][u],w=c[h+1][u+1],R=c[h][u+1],H=y.clone(),M=y.clone(),S=_.clone(),k=_.clone(),A=p[h][u].clone(),C=p[h+1][u].clone(),P=p[h+1][u+1].clone(),L=p[h][u+1].clone();this.faces.push(new THREE.Face3(T,x,R,[H,M,k])),this.faceVertexUvs[0].push([A,C,L]),this.faces.push(new THREE.Face3(x,w,R,[M.clone(),S,k.clone()])),this.faceVertexUvs[0].push([C.clone(),P,L.clone()])}if(o===!1&&t>0)for(this.vertices.push(new THREE.Vector3(0,l,0)),u=0;r>u;u++){var T=c[0][u],x=c[0][u+1],w=this.vertices.length-1,H=new THREE.Vector3(0,1,0),M=new THREE.Vector3(0,1,0),S=new THREE.Vector3(0,1,0),A=p[0][u].clone(),C=p[0][u+1].clone(),P=new THREE.Vector2(C.x,0);this.faces.push(new THREE.Face3(T,x,w,[H,M,S])),this.faceVertexUvs[0].push([A,C,P])}if(o===!1&&e>0)for(this.vertices.push(new THREE.Vector3(0,-l,0)),u=0;r>u;u++){var T=c[i][u+1],x=c[i][u],w=this.vertices.length-1,H=new THREE.Vector3(0,-1,0),M=new THREE.Vector3(0,-1,0),S=new THREE.Vector3(0,-1,0),A=p[i][u+1].clone(),C=p[i][u].clone(),P=new THREE.Vector2(C.x,1);this.faces.push(new THREE.Face3(T,x,w,[H,M,S])),this.faceVertexUvs[0].push([A,C,P])}this.computeFaceNormals()},THREE.CylinderGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.CylinderGeometry.prototype.constructor=THREE.CylinderGeometry,THREE.ExtrudeGeometry=function(t,e){return"undefined"==typeof t?void(t=[]):(THREE.Geometry.call(this),this.type="ExtrudeGeometry",t=t instanceof Array?t:[t],this.addShapeList(t,e),void this.computeFaceNormals())},THREE.ExtrudeGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.ExtrudeGeometry.prototype.constructor=THREE.ExtrudeGeometry,THREE.ExtrudeGeometry.prototype.addShapeList=function(t,e){for(var n=t.length,r=0;n>r;r++){var i=t[r];this.addShape(i,e)}},THREE.ExtrudeGeometry.prototype.addShape=function(t,e){function n(t,e,n){return e||THREE.error("THREE.ExtrudeGeometry: vec does not exist"),e.clone().multiplyScalar(n).add(t)}function r(t,e,n){var r,i,o=1e-10,s=1,a=t.x-e.x,u=t.y-e.y,h=n.x-t.x,l=n.y-t.y,c=a*a+u*u,p=a*l-u*h;if(Math.abs(p)>o){var f=Math.sqrt(c),d=Math.sqrt(h*h+l*l),m=e.x-u/f,v=e.y+a/f,g=n.x-l/d,E=n.y+h/d,y=((g-m)*l-(E-v)*h)/(a*l-u*h);r=m+a*y-t.x,i=v+u*y-t.y;var _=r*r+i*i;if(2>=_)return new THREE.Vector2(r,i);s=Math.sqrt(_/2)}else{var b=!1;a>o?h>o&&(b=!0):-o>a?-o>h&&(b=!0):Math.sign(u)==Math.sign(l)&&(b=!0),b?(r=-u,i=a,s=Math.sqrt(c)):(r=a,i=u,s=Math.sqrt(c/2))}return new THREE.Vector2(r/s,i/s)}function i(){if(y){var t=0,e=G*t;for(X=0;W>X;X++)j=D[X],u(j[2]+e,j[1]+e,j[0]+e);for(t=b+2*E,e=G*t,X=0;W>X;X++)j=D[X],u(j[0]+e,j[1]+e,j[2]+e)}else{for(X=0;W>X;X++)j=D[X],u(j[2],j[1],j[0]);for(X=0;W>X;X++)j=D[X],u(j[0]+G*b,j[1]+G*b,j[2]+G*b)}}function o(){var t=0;for(s(F,t),t+=F.length,S=0,k=z.length;k>S;S++)M=z[S],s(M,t),t+=M.length}function s(t,e){var n,r;for(X=t.length;--X>=0;){n=X,r=X-1,0>r&&(r=t.length-1);var i=0,o=b+2*E;for(i=0;o>i;i++){var s=G*i,a=G*(i+1),u=e+n+s,l=e+r+s,c=e+r+a,p=e+n+a;h(u,l,c,p,t,i,o,n,r)}}}function a(t,e,n){A.vertices.push(new THREE.Vector3(t,e,n))}function u(t,e,n){t+=C,e+=C,n+=C,A.faces.push(new THREE.Face3(t,e,n,null,null,w));var r=H.generateTopUV(A,t,e,n);A.faceVertexUvs[0].push(r)}function h(t,e,n,r,i,o,s,a,u){t+=C,e+=C,n+=C,r+=C,A.faces.push(new THREE.Face3(t,e,r,null,null,R)),A.faces.push(new THREE.Face3(e,n,r,null,null,R));var h=H.generateSideWallUV(A,t,e,n,r);A.faceVertexUvs[0].push([h[0],h[1],h[3]]),A.faceVertexUvs[0].push([h[1],h[2],h[3]])}var l,c,p,f,d,m=void 0!==e.amount?e.amount:100,v=void 0!==e.bevelThickness?e.bevelThickness:6,g=void 0!==e.bevelSize?e.bevelSize:v-2,E=void 0!==e.bevelSegments?e.bevelSegments:3,y=void 0!==e.bevelEnabled?e.bevelEnabled:!0,_=void 0!==e.curveSegments?e.curveSegments:12,b=void 0!==e.steps?e.steps:1,T=e.extrudePath,x=!1,w=e.material,R=e.extrudeMaterial,H=void 0!==e.UVGenerator?e.UVGenerator:THREE.ExtrudeGeometry.WorldUVGenerator;T&&(l=T.getSpacedPoints(b),x=!0,y=!1,c=void 0!==e.frames?e.frames:new THREE.TubeGeometry.FrenetFrames(T,b,!1),p=new THREE.Vector3,f=new THREE.Vector3,d=new THREE.Vector3),y||(E=0,v=0,g=0);var M,S,k,A=this,C=this.vertices.length,P=t.extractPoints(_),L=P.shape,z=P.holes,O=!THREE.Shape.Utils.isClockWise(L);if(O){for(L=L.reverse(),S=0,k=z.length;k>S;S++)M=z[S],THREE.Shape.Utils.isClockWise(M)&&(z[S]=M.reverse());O=!1}var D=THREE.Shape.Utils.triangulateShape(L,z),F=L;for(S=0,k=z.length;k>S;S++)M=z[S],L=L.concat(M);for(var U,B,N,V,I,j,G=L.length,W=D.length,q=[],X=0,Y=F.length,Z=Y-1,K=X+1;Y>X;X++,Z++,K++)Z===Y&&(Z=0),K===Y&&(K=0),q[X]=r(F[X],F[Z],F[K]);var Q,J=[],$=q.concat();for(S=0,k=z.length;k>S;S++){for(M=z[S],Q=[],X=0,Y=M.length,Z=Y-1,K=X+1;Y>X;X++,Z++,K++)Z===Y&&(Z=0),K===Y&&(K=0),Q[X]=r(M[X],M[Z],M[K]);J.push(Q),$=$.concat(Q)}for(U=0;E>U;U++){for(N=U/E,V=v*(1-N),B=g*Math.sin(N*Math.PI/2),X=0,Y=F.length;Y>X;X++)I=n(F[X],q[X],B),a(I.x,I.y,-V);for(S=0,k=z.length;k>S;S++)for(M=z[S],Q=J[S],X=0,Y=M.length;Y>X;X++)I=n(M[X],Q[X],B),a(I.x,I.y,-V)}for(B=g,X=0;G>X;X++)I=y?n(L[X],$[X],B):L[X],x?(f.copy(c.normals[0]).multiplyScalar(I.x),p.copy(c.binormals[0]).multiplyScalar(I.y),d.copy(l[0]).add(f).add(p),a(d.x,d.y,d.z)):a(I.x,I.y,0);var tt;for(tt=1;b>=tt;tt++)for(X=0;G>X;X++)I=y?n(L[X],$[X],B):L[X],x?(f.copy(c.normals[tt]).multiplyScalar(I.x),p.copy(c.binormals[tt]).multiplyScalar(I.y),d.copy(l[tt]).add(f).add(p),a(d.x,d.y,d.z)):a(I.x,I.y,m/b*tt);for(U=E-1;U>=0;U--){for(N=U/E,V=v*(1-N),B=g*Math.sin(N*Math.PI/2),X=0,Y=F.length;Y>X;X++)I=n(F[X],q[X],B),a(I.x,I.y,m+V);for(S=0,k=z.length;k>S;S++)for(M=z[S],Q=J[S],X=0,Y=M.length;Y>X;X++)I=n(M[X],Q[X],B),x?a(I.x,I.y+l[b-1].y,l[b-1].x+V):a(I.x,I.y,m+V)}i(),o()},THREE.ExtrudeGeometry.WorldUVGenerator={generateTopUV:function(t,e,n,r){var i=t.vertices,o=i[e],s=i[n],a=i[r];return[new THREE.Vector2(o.x,o.y),new THREE.Vector2(s.x,s.y),new THREE.Vector2(a.x,a.y)]},generateSideWallUV:function(t,e,n,r,i){var o=t.vertices,s=o[e],a=o[n],u=o[r],h=o[i];return Math.abs(s.y-a.y)<.01?[new THREE.Vector2(s.x,1-s.z),new THREE.Vector2(a.x,1-a.z),new THREE.Vector2(u.x,1-u.z),new THREE.Vector2(h.x,1-h.z)]:[new THREE.Vector2(s.y,1-s.z),new THREE.Vector2(a.y,1-a.z),new THREE.Vector2(u.y,1-u.z),new THREE.Vector2(h.y,1-h.z)]}},THREE.ShapeGeometry=function(t,e){THREE.Geometry.call(this),this.type="ShapeGeometry",t instanceof Array==!1&&(t=[t]),this.addShapeList(t,e),this.computeFaceNormals()},THREE.ShapeGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.ShapeGeometry.prototype.constructor=THREE.ShapeGeometry,THREE.ShapeGeometry.prototype.addShapeList=function(t,e){for(var n=0,r=t.length;r>n;n++)this.addShape(t[n],e);return this},THREE.ShapeGeometry.prototype.addShape=function(t,e){void 0===e&&(e={});var n,r,i,o=void 0!==e.curveSegments?e.curveSegments:12,s=e.material,a=void 0===e.UVGenerator?THREE.ExtrudeGeometry.WorldUVGenerator:e.UVGenerator,u=this.vertices.length,h=t.extractPoints(o),l=h.shape,c=h.holes,p=!THREE.Shape.Utils.isClockWise(l);if(p){for(l=l.reverse(),n=0,r=c.length;r>n;n++)i=c[n],THREE.Shape.Utils.isClockWise(i)&&(c[n]=i.reverse());p=!1}var f=THREE.Shape.Utils.triangulateShape(l,c);for(n=0,r=c.length;r>n;n++)i=c[n],l=l.concat(i);var d,m,v=l.length,g=f.length;for(n=0;v>n;n++)d=l[n],this.vertices.push(new THREE.Vector3(d.x,d.y,0));for(n=0;g>n;n++){m=f[n];var E=m[0]+u,y=m[1]+u,_=m[2]+u;this.faces.push(new THREE.Face3(E,y,_,null,null,s)),this.faceVertexUvs[0].push(a.generateTopUV(this,E,y,_))}},THREE.LatheGeometry=function(t,e,n,r){THREE.Geometry.call(this),this.type="LatheGeometry",this.parameters={points:t,segments:e,phiStart:n,phiLength:r},e=e||12,n=n||0,r=r||2*Math.PI;for(var i=1/(t.length-1),o=1/e,s=0,a=e;a>=s;s++)for(var u=n+s*o*r,h=Math.cos(u),l=Math.sin(u),c=0,p=t.length;p>c;c++){var f=t[c],d=new THREE.Vector3;d.x=h*f.x-l*f.y,d.y=l*f.x+h*f.y,d.z=f.z,this.vertices.push(d)}for(var m=t.length,s=0,a=e;a>s;s++)for(var c=0,p=t.length-1;p>c;c++){var v=c+m*s,g=v,E=v+m,h=v+1+m,y=v+1,_=s*o,b=c*i,T=_+o,x=b+i;this.faces.push(new THREE.Face3(g,E,y)),this.faceVertexUvs[0].push([new THREE.Vector2(_,b),new THREE.Vector2(T,b),new THREE.Vector2(_,x)]),this.faces.push(new THREE.Face3(E,h,y)),this.faceVertexUvs[0].push([new THREE.Vector2(T,b),new THREE.Vector2(T,x),new THREE.Vector2(_,x)])}this.mergeVertices(),this.computeFaceNormals(),this.computeVertexNormals()},THREE.LatheGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.LatheGeometry.prototype.constructor=THREE.LatheGeometry,THREE.PlaneGeometry=function(t,e,n,r){console.info("THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint."),THREE.Geometry.call(this),this.type="PlaneGeometry",this.parameters={width:t,height:e,widthSegments:n,heightSegments:r},this.fromBufferGeometry(new THREE.PlaneBufferGeometry(t,e,n,r))},THREE.PlaneGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.PlaneGeometry.prototype.constructor=THREE.PlaneGeometry,THREE.PlaneBufferGeometry=function(t,e,n,r){THREE.BufferGeometry.call(this),this.type="PlaneBufferGeometry",this.parameters={width:t,height:e,widthSegments:n,heightSegments:r};for(var i=t/2,o=e/2,s=n||1,a=r||1,u=s+1,h=a+1,l=t/s,c=e/a,p=new Float32Array(u*h*3),f=new Float32Array(u*h*3),d=new Float32Array(u*h*2),m=0,v=0,g=0;h>g;g++)for(var E=g*c-o,y=0;u>y;y++){var _=y*l-i;p[m]=_,p[m+1]=-E,f[m+2]=1,d[v]=y/s,d[v+1]=1-g/a,m+=3,v+=2}m=0;for(var b=new(p.length/3>65535?Uint32Array:Uint16Array)(s*a*6),g=0;a>g;g++)for(var y=0;s>y;y++){var T=y+u*g,x=y+u*(g+1),w=y+1+u*(g+1),R=y+1+u*g;b[m]=T,b[m+1]=x,b[m+2]=R,b[m+3]=x,b[m+4]=w,b[m+5]=R,m+=6}this.addAttribute("index",new THREE.BufferAttribute(b,1)),this.addAttribute("position",new THREE.BufferAttribute(p,3)),this.addAttribute("normal",new THREE.BufferAttribute(f,3)), +this.addAttribute("uv",new THREE.BufferAttribute(d,2))},THREE.PlaneBufferGeometry.prototype=Object.create(THREE.BufferGeometry.prototype),THREE.PlaneBufferGeometry.prototype.constructor=THREE.PlaneBufferGeometry,THREE.RingGeometry=function(t,e,n,r,i,o){THREE.Geometry.call(this),this.type="RingGeometry",this.parameters={innerRadius:t,outerRadius:e,thetaSegments:n,phiSegments:r,thetaStart:i,thetaLength:o},t=t||0,e=e||50,i=void 0!==i?i:0,o=void 0!==o?o:2*Math.PI,n=void 0!==n?Math.max(3,n):8,r=void 0!==r?Math.max(1,r):8;var s,a,u=[],h=t,l=(e-t)/r;for(s=0;r+1>s;s++){for(a=0;n+1>a;a++){var c=new THREE.Vector3,p=i+a/n*o;c.x=h*Math.cos(p),c.y=h*Math.sin(p),this.vertices.push(c),u.push(new THREE.Vector2((c.x/e+1)/2,(c.y/e+1)/2))}h+=l}var f=new THREE.Vector3(0,0,1);for(s=0;r>s;s++){var d=s*(n+1);for(a=0;n>a;a++){var p=a+d,m=p,v=p+n+1,g=p+n+2;this.faces.push(new THREE.Face3(m,v,g,[f.clone(),f.clone(),f.clone()])),this.faceVertexUvs[0].push([u[m].clone(),u[v].clone(),u[g].clone()]),m=p,v=p+n+2,g=p+1,this.faces.push(new THREE.Face3(m,v,g,[f.clone(),f.clone(),f.clone()])),this.faceVertexUvs[0].push([u[m].clone(),u[v].clone(),u[g].clone()])}}this.computeFaceNormals(),this.boundingSphere=new THREE.Sphere(new THREE.Vector3,h)},THREE.RingGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.RingGeometry.prototype.constructor=THREE.RingGeometry,THREE.SphereGeometry=function(t,e,n,r,i,o,s){THREE.Geometry.call(this),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:n,phiStart:r,phiLength:i,thetaStart:o,thetaLength:s},t=t||50,e=Math.max(3,Math.floor(e)||8),n=Math.max(2,Math.floor(n)||6),r=void 0!==r?r:0,i=void 0!==i?i:2*Math.PI,o=void 0!==o?o:0,s=void 0!==s?s:Math.PI;var a,u,h=[],l=[];for(u=0;n>=u;u++){var c=[],p=[];for(a=0;e>=a;a++){var f=a/e,d=u/n,m=new THREE.Vector3;m.x=-t*Math.cos(r+f*i)*Math.sin(o+d*s),m.y=t*Math.cos(o+d*s),m.z=t*Math.sin(r+f*i)*Math.sin(o+d*s),this.vertices.push(m),c.push(this.vertices.length-1),p.push(new THREE.Vector2(f,1-d))}h.push(c),l.push(p)}for(u=0;n>u;u++)for(a=0;e>a;a++){var v=h[u][a+1],g=h[u][a],E=h[u+1][a],y=h[u+1][a+1],_=this.vertices[v].clone().normalize(),b=this.vertices[g].clone().normalize(),T=this.vertices[E].clone().normalize(),x=this.vertices[y].clone().normalize(),w=l[u][a+1].clone(),R=l[u][a].clone(),H=l[u+1][a].clone(),M=l[u+1][a+1].clone();Math.abs(this.vertices[v].y)===t?(w.x=(w.x+R.x)/2,this.faces.push(new THREE.Face3(v,E,y,[_,T,x])),this.faceVertexUvs[0].push([w,H,M])):Math.abs(this.vertices[E].y)===t?(H.x=(H.x+M.x)/2,this.faces.push(new THREE.Face3(v,g,E,[_,b,T])),this.faceVertexUvs[0].push([w,R,H])):(this.faces.push(new THREE.Face3(v,g,y,[_,b,x])),this.faceVertexUvs[0].push([w,R,M]),this.faces.push(new THREE.Face3(g,E,y,[b.clone(),T,x.clone()])),this.faceVertexUvs[0].push([R.clone(),H,M.clone()]))}this.computeFaceNormals(),this.boundingSphere=new THREE.Sphere(new THREE.Vector3,t)},THREE.SphereGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.SphereGeometry.prototype.constructor=THREE.SphereGeometry,THREE.TextGeometry=function(t,e){e=e||{};var n=THREE.FontUtils.generateShapes(t,e);e.amount=void 0!==e.height?e.height:50,void 0===e.bevelThickness&&(e.bevelThickness=10),void 0===e.bevelSize&&(e.bevelSize=8),void 0===e.bevelEnabled&&(e.bevelEnabled=!1),THREE.ExtrudeGeometry.call(this,n,e),this.type="TextGeometry"},THREE.TextGeometry.prototype=Object.create(THREE.ExtrudeGeometry.prototype),THREE.TextGeometry.prototype.constructor=THREE.TextGeometry,THREE.TorusGeometry=function(t,e,n,r,i){THREE.Geometry.call(this),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:n,tubularSegments:r,arc:i},t=t||100,e=e||40,n=n||8,r=r||6,i=i||2*Math.PI;for(var o=new THREE.Vector3,s=[],a=[],u=0;n>=u;u++)for(var h=0;r>=h;h++){var l=h/r*i,c=u/n*Math.PI*2;o.x=t*Math.cos(l),o.y=t*Math.sin(l);var p=new THREE.Vector3;p.x=(t+e*Math.cos(c))*Math.cos(l),p.y=(t+e*Math.cos(c))*Math.sin(l),p.z=e*Math.sin(c),this.vertices.push(p),s.push(new THREE.Vector2(h/r,u/n)),a.push(p.clone().sub(o).normalize())}for(var u=1;n>=u;u++)for(var h=1;r>=h;h++){var f=(r+1)*u+h-1,d=(r+1)*(u-1)+h-1,m=(r+1)*(u-1)+h,v=(r+1)*u+h,g=new THREE.Face3(f,d,v,[a[f].clone(),a[d].clone(),a[v].clone()]);this.faces.push(g),this.faceVertexUvs[0].push([s[f].clone(),s[d].clone(),s[v].clone()]),g=new THREE.Face3(d,m,v,[a[d].clone(),a[m].clone(),a[v].clone()]),this.faces.push(g),this.faceVertexUvs[0].push([s[d].clone(),s[m].clone(),s[v].clone()])}this.computeFaceNormals()},THREE.TorusGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.TorusGeometry.prototype.constructor=THREE.TorusGeometry,THREE.TorusKnotGeometry=function(t,e,n,r,i,o,s){function a(t,e,n,r,i){var o=Math.cos(t),s=Math.sin(t),a=e/n*t,u=Math.cos(a),h=r*(2+u)*.5*o,l=r*(2+u)*s*.5,c=i*r*Math.sin(a)*.5;return new THREE.Vector3(h,l,c)}THREE.Geometry.call(this),this.type="TorusKnotGeometry",this.parameters={radius:t,tube:e,radialSegments:n,tubularSegments:r,p:i,q:o,heightScale:s},t=t||100,e=e||40,n=n||64,r=r||8,i=i||2,o=o||3,s=s||1;for(var u=new Array(n),h=new THREE.Vector3,l=new THREE.Vector3,c=new THREE.Vector3,p=0;n>p;++p){u[p]=new Array(r);var f=p/n*2*i*Math.PI,d=a(f,o,i,t,s),m=a(f+.01,o,i,t,s);h.subVectors(m,d),l.addVectors(m,d),c.crossVectors(h,l),l.crossVectors(c,h),c.normalize(),l.normalize();for(var v=0;r>v;++v){var g=v/r*2*Math.PI,E=-e*Math.cos(g),y=e*Math.sin(g),_=new THREE.Vector3;_.x=d.x+E*l.x+y*c.x,_.y=d.y+E*l.y+y*c.y,_.z=d.z+E*l.z+y*c.z,u[p][v]=this.vertices.push(_)-1}}for(var p=0;n>p;++p)for(var v=0;r>v;++v){var b=(p+1)%n,T=(v+1)%r,x=u[p][v],w=u[b][v],R=u[b][T],H=u[p][T],M=new THREE.Vector2(p/n,v/r),S=new THREE.Vector2((p+1)/n,v/r),k=new THREE.Vector2((p+1)/n,(v+1)/r),A=new THREE.Vector2(p/n,(v+1)/r);this.faces.push(new THREE.Face3(x,w,H)),this.faceVertexUvs[0].push([M,S,A]),this.faces.push(new THREE.Face3(w,R,H)),this.faceVertexUvs[0].push([S.clone(),k,A.clone()])}this.computeFaceNormals(),this.computeVertexNormals()},THREE.TorusKnotGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.TorusKnotGeometry.prototype.constructor=THREE.TorusKnotGeometry,THREE.TubeGeometry=function(t,e,n,r,i,o){function s(t,e,n){return k.vertices.push(new THREE.Vector3(t,e,n))-1}THREE.Geometry.call(this),this.type="TubeGeometry",this.parameters={path:t,segments:e,radius:n,radialSegments:r,closed:i},e=e||64,n=n||1,r=r||8,i=i||!1,o=o||THREE.TubeGeometry.NoTaper;var a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S=[],k=this,A=e+1,C=new THREE.Vector3,P=new THREE.TubeGeometry.FrenetFrames(t,e,i),L=P.tangents,z=P.normals,O=P.binormals;for(this.tangents=L,this.normals=z,this.binormals=O,v=0;A>v;v++)for(S[v]=[],l=v/(A-1),m=t.getPointAt(l),a=L[v],u=z[v],h=O[v],p=n*o(l),g=0;r>g;g++)c=g/r*2*Math.PI,f=-p*Math.cos(c),d=p*Math.sin(c),C.copy(m),C.x+=f*u.x+d*h.x,C.y+=f*u.y+d*h.y,C.z+=f*u.z+d*h.z,S[v][g]=s(C.x,C.y,C.z);for(v=0;e>v;v++)for(g=0;r>g;g++)E=i?(v+1)%e:v+1,y=(g+1)%r,_=S[v][g],b=S[E][g],T=S[E][y],x=S[v][y],w=new THREE.Vector2(v/e,g/r),R=new THREE.Vector2((v+1)/e,g/r),H=new THREE.Vector2((v+1)/e,(g+1)/r),M=new THREE.Vector2(v/e,(g+1)/r),this.faces.push(new THREE.Face3(_,b,x)),this.faceVertexUvs[0].push([w,R,M]),this.faces.push(new THREE.Face3(b,T,x)),this.faceVertexUvs[0].push([R.clone(),H,M.clone()]);this.computeFaceNormals(),this.computeVertexNormals()},THREE.TubeGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.TubeGeometry.prototype.constructor=THREE.TubeGeometry,THREE.TubeGeometry.NoTaper=function(t){return 1},THREE.TubeGeometry.SinusoidalTaper=function(t){return Math.sin(Math.PI*t)},THREE.TubeGeometry.FrenetFrames=function(t,e,n){function r(){f[0]=new THREE.Vector3,d[0]=new THREE.Vector3,o=Number.MAX_VALUE,s=Math.abs(p[0].x),a=Math.abs(p[0].y),u=Math.abs(p[0].z),o>=s&&(o=s,c.set(1,0,0)),o>=a&&(o=a,c.set(0,1,0)),o>=u&&c.set(0,0,1),m.crossVectors(p[0],c).normalize(),f[0].crossVectors(p[0],m),d[0].crossVectors(p[0],f[0])}var i,o,s,a,u,h,l,c=new THREE.Vector3,p=[],f=[],d=[],m=new THREE.Vector3,v=new THREE.Matrix4,g=e+1,E=1e-4;for(this.tangents=p,this.normals=f,this.binormals=d,h=0;g>h;h++)l=h/(g-1),p[h]=t.getTangentAt(l),p[h].normalize();for(r(),h=1;g>h;h++)f[h]=f[h-1].clone(),d[h]=d[h-1].clone(),m.crossVectors(p[h-1],p[h]),m.length()>E&&(m.normalize(),i=Math.acos(THREE.Math.clamp(p[h-1].dot(p[h]),-1,1)),f[h].applyMatrix4(v.makeRotationAxis(m,i))),d[h].crossVectors(p[h],f[h]);if(n)for(i=Math.acos(THREE.Math.clamp(f[0].dot(f[g-1]),-1,1)),i/=g-1,p[0].dot(m.crossVectors(f[0],f[g-1]))>0&&(i=-i),h=1;g>h;h++)f[h].applyMatrix4(v.makeRotationAxis(p[h],i*h)),d[h].crossVectors(p[h],f[h])},THREE.PolyhedronGeometry=function(t,e,n,r){function i(t){var e=t.normalize().clone();e.index=l.vertices.push(e)-1;var n=a(t)/2/Math.PI+.5,r=u(t)/Math.PI+.5;return e.uv=new THREE.Vector2(n,1-r),e}function o(t,e,n){var r=new THREE.Face3(t.index,e.index,n.index,[t.clone(),e.clone(),n.clone()]);l.faces.push(r),y.copy(t).add(e).add(n).divideScalar(3);var i=a(y);l.faceVertexUvs[0].push([h(t.uv,t,i),h(e.uv,e,i),h(n.uv,n,i)])}function s(t,e){for(var n=Math.pow(2,e),r=i(l.vertices[t.a]),s=i(l.vertices[t.b]),a=i(l.vertices[t.c]),u=[],h=0;n>=h;h++){u[h]=[];for(var c=i(r.clone().lerp(a,h/n)),p=i(s.clone().lerp(a,h/n)),f=n-h,d=0;f>=d;d++)0==d&&h==n?u[h][d]=c:u[h][d]=i(c.clone().lerp(p,d/f))}for(var h=0;n>h;h++)for(var d=0;2*(n-h)-1>d;d++){var m=Math.floor(d/2);d%2==0?o(u[h][m+1],u[h+1][m],u[h][m]):o(u[h][m+1],u[h+1][m+1],u[h+1][m])}}function a(t){return Math.atan2(t.z,-t.x)}function u(t){return Math.atan2(-t.y,Math.sqrt(t.x*t.x+t.z*t.z))}function h(t,e,n){return 0>n&&1===t.x&&(t=new THREE.Vector2(t.x-1,t.y)),0===e.x&&0===e.z&&(t=new THREE.Vector2(n/2/Math.PI+.5,t.y)),t.clone()}THREE.Geometry.call(this),this.type="PolyhedronGeometry",this.parameters={vertices:t,indices:e,radius:n,detail:r},n=n||1,r=r||0;for(var l=this,c=0,p=t.length;p>c;c+=3)i(new THREE.Vector3(t[c],t[c+1],t[c+2]));for(var f=this.vertices,d=[],c=0,m=0,p=e.length;p>c;c+=3,m++){var v=f[e[c]],g=f[e[c+1]],E=f[e[c+2]];d[m]=new THREE.Face3(v.index,g.index,E.index,[v.clone(),g.clone(),E.clone()])}for(var y=new THREE.Vector3,c=0,p=d.length;p>c;c++)s(d[c],r);for(var c=0,p=this.faceVertexUvs[0].length;p>c;c++){var _=this.faceVertexUvs[0][c],b=_[0].x,T=_[1].x,x=_[2].x,w=Math.max(b,Math.max(T,x)),R=Math.min(b,Math.min(T,x));w>.9&&.1>R&&(.2>b&&(_[0].x+=1),.2>T&&(_[1].x+=1),.2>x&&(_[2].x+=1))}for(var c=0,p=this.vertices.length;p>c;c++)this.vertices[c].multiplyScalar(n);this.mergeVertices(),this.computeFaceNormals(),this.boundingSphere=new THREE.Sphere(new THREE.Vector3,n)},THREE.PolyhedronGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.PolyhedronGeometry.prototype.constructor=THREE.PolyhedronGeometry,THREE.DodecahedronGeometry=function(t,e){this.parameters={radius:t,detail:e};var n=(1+Math.sqrt(5))/2,r=1/n,i=[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-r,-n,0,-r,n,0,r,-n,0,r,n,-r,-n,0,-r,n,0,r,-n,0,r,n,0,-n,0,-r,n,0,-r,-n,0,r,n,0,r],o=[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9];THREE.PolyhedronGeometry.call(this,i,o,t,e)},THREE.DodecahedronGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.DodecahedronGeometry.prototype.constructor=THREE.DodecahedronGeometry,THREE.IcosahedronGeometry=function(t,e){var n=(1+Math.sqrt(5))/2,r=[-1,n,0,1,n,0,-1,-n,0,1,-n,0,0,-1,n,0,1,n,0,-1,-n,0,1,-n,n,0,-1,n,0,1,-n,0,-1,-n,0,1],i=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];THREE.PolyhedronGeometry.call(this,r,i,t,e),this.type="IcosahedronGeometry",this.parameters={radius:t,detail:e}},THREE.IcosahedronGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.IcosahedronGeometry.prototype.constructor=THREE.IcosahedronGeometry,THREE.OctahedronGeometry=function(t,e){this.parameters={radius:t,detail:e};var n=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],r=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2];THREE.PolyhedronGeometry.call(this,n,r,t,e),this.type="OctahedronGeometry",this.parameters={radius:t,detail:e}},THREE.OctahedronGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.OctahedronGeometry.prototype.constructor=THREE.OctahedronGeometry,THREE.TetrahedronGeometry=function(t,e){var n=[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],r=[2,1,0,0,3,2,1,3,0,2,3,1];THREE.PolyhedronGeometry.call(this,n,r,t,e),this.type="TetrahedronGeometry",this.parameters={radius:t,detail:e}},THREE.TetrahedronGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.TetrahedronGeometry.prototype.constructor=THREE.TetrahedronGeometry,THREE.ParametricGeometry=function(t,e,n){THREE.Geometry.call(this),this.type="ParametricGeometry",this.parameters={func:t,slices:e,stacks:n};var r,i,o,s,a,u=this.vertices,h=this.faces,l=this.faceVertexUvs[0],c=e+1;for(r=0;n>=r;r++)for(a=r/n,i=0;e>=i;i++)s=i/e,o=t(s,a),u.push(o);var p,f,d,m,v,g,E,y;for(r=0;n>r;r++)for(i=0;e>i;i++)p=r*c+i,f=r*c+i+1,d=(r+1)*c+i+1,m=(r+1)*c+i,v=new THREE.Vector2(i/e,r/n),g=new THREE.Vector2((i+1)/e,r/n),E=new THREE.Vector2((i+1)/e,(r+1)/n),y=new THREE.Vector2(i/e,(r+1)/n),h.push(new THREE.Face3(p,f,m)),l.push([v,g,y]),h.push(new THREE.Face3(f,d,m)),l.push([g.clone(),E,y.clone()]);this.computeFaceNormals(),this.computeVertexNormals()},THREE.ParametricGeometry.prototype=Object.create(THREE.Geometry.prototype),THREE.ParametricGeometry.prototype.constructor=THREE.ParametricGeometry,THREE.AxisHelper=function(t){t=t||1;var e=new Float32Array([0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t]),n=new Float32Array([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1]),r=new THREE.BufferGeometry;r.addAttribute("position",new THREE.BufferAttribute(e,3)),r.addAttribute("color",new THREE.BufferAttribute(n,3));var i=new THREE.LineBasicMaterial({vertexColors:THREE.VertexColors});THREE.Line.call(this,r,i,THREE.LinePieces)},THREE.AxisHelper.prototype=Object.create(THREE.Line.prototype),THREE.AxisHelper.prototype.constructor=THREE.AxisHelper,THREE.ArrowHelper=function(){var t=new THREE.Geometry;t.vertices.push(new THREE.Vector3(0,0,0),new THREE.Vector3(0,1,0));var e=new THREE.CylinderGeometry(0,.5,1,5,1);return e.applyMatrix((new THREE.Matrix4).makeTranslation(0,-.5,0)),function(n,r,i,o,s,a){THREE.Object3D.call(this),void 0===o&&(o=16776960),void 0===i&&(i=1),void 0===s&&(s=.2*i),void 0===a&&(a=.2*s),this.position.copy(r),this.line=new THREE.Line(t,new THREE.LineBasicMaterial({color:o})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new THREE.Mesh(e,new THREE.MeshBasicMaterial({color:o})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(n),this.setLength(i,s,a)}}(),THREE.ArrowHelper.prototype=Object.create(THREE.Object3D.prototype),THREE.ArrowHelper.prototype.constructor=THREE.ArrowHelper,THREE.ArrowHelper.prototype.setDirection=function(){var t,e=new THREE.Vector3;return function(n){n.y>.99999?this.quaternion.set(0,0,0,1):n.y<-.99999?this.quaternion.set(1,0,0,0):(e.set(n.z,0,-n.x).normalize(),t=Math.acos(n.y),this.quaternion.setFromAxisAngle(e,t))}}(),THREE.ArrowHelper.prototype.setLength=function(t,e,n){void 0===e&&(e=.2*t),void 0===n&&(n=.2*e),this.line.scale.set(1,t-e,1),this.line.updateMatrix(),this.cone.scale.set(n,e,n),this.cone.position.y=t,this.cone.updateMatrix()},THREE.ArrowHelper.prototype.setColor=function(t){this.line.material.color.set(t),this.cone.material.color.set(t)},THREE.BoxHelper=function(t){var e=new THREE.BufferGeometry;e.addAttribute("position",new THREE.BufferAttribute(new Float32Array(72),3)),THREE.Line.call(this,e,new THREE.LineBasicMaterial({color:16776960}),THREE.LinePieces),void 0!==t&&this.update(t)},THREE.BoxHelper.prototype=Object.create(THREE.Line.prototype),THREE.BoxHelper.prototype.constructor=THREE.BoxHelper,THREE.BoxHelper.prototype.update=function(t){var e=t.geometry;null===e.boundingBox&&e.computeBoundingBox();var n=e.boundingBox.min,r=e.boundingBox.max,i=this.geometry.attributes.position.array;i[0]=r.x,i[1]=r.y,i[2]=r.z,i[3]=n.x,i[4]=r.y,i[5]=r.z,i[6]=n.x,i[7]=r.y,i[8]=r.z,i[9]=n.x,i[10]=n.y,i[11]=r.z,i[12]=n.x,i[13]=n.y,i[14]=r.z,i[15]=r.x,i[16]=n.y,i[17]=r.z,i[18]=r.x,i[19]=n.y,i[20]=r.z,i[21]=r.x,i[22]=r.y,i[23]=r.z,i[24]=r.x,i[25]=r.y,i[26]=n.z,i[27]=n.x,i[28]=r.y,i[29]=n.z,i[30]=n.x,i[31]=r.y,i[32]=n.z,i[33]=n.x,i[34]=n.y,i[35]=n.z,i[36]=n.x,i[37]=n.y,i[38]=n.z,i[39]=r.x,i[40]=n.y,i[41]=n.z,i[42]=r.x,i[43]=n.y,i[44]=n.z,i[45]=r.x,i[46]=r.y,i[47]=n.z,i[48]=r.x,i[49]=r.y,i[50]=r.z,i[51]=r.x,i[52]=r.y,i[53]=n.z,i[54]=n.x,i[55]=r.y,i[56]=r.z,i[57]=n.x,i[58]=r.y,i[59]=n.z,i[60]=n.x,i[61]=n.y,i[62]=r.z,i[63]=n.x,i[64]=n.y,i[65]=n.z,i[66]=r.x,i[67]=n.y,i[68]=r.z,i[69]=r.x,i[70]=n.y,i[71]=n.z,this.geometry.attributes.position.needsUpdate=!0,this.geometry.computeBoundingSphere(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1},THREE.BoundingBoxHelper=function(t,e){var n=void 0!==e?e:8947848;this.object=t,this.box=new THREE.Box3,THREE.Mesh.call(this,new THREE.BoxGeometry(1,1,1),new THREE.MeshBasicMaterial({color:n,wireframe:!0}))},THREE.BoundingBoxHelper.prototype=Object.create(THREE.Mesh.prototype),THREE.BoundingBoxHelper.prototype.constructor=THREE.BoundingBoxHelper,THREE.BoundingBoxHelper.prototype.update=function(){this.box.setFromObject(this.object),this.box.size(this.scale),this.box.center(this.position)},THREE.CameraHelper=function(t){function e(t,e,r){n(t,r),n(e,r)}function n(t,e){r.vertices.push(new THREE.Vector3),r.colors.push(new THREE.Color(e)),void 0===o[t]&&(o[t]=[]),o[t].push(r.vertices.length-1)}var r=new THREE.Geometry,i=new THREE.LineBasicMaterial({color:16777215,vertexColors:THREE.FaceColors}),o={},s=16755200,a=16711680,u=43775,h=16777215,l=3355443;e("n1","n2",s),e("n2","n4",s),e("n4","n3",s),e("n3","n1",s),e("f1","f2",s),e("f2","f4",s),e("f4","f3",s),e("f3","f1",s),e("n1","f1",s),e("n2","f2",s),e("n3","f3",s),e("n4","f4",s),e("p","n1",a),e("p","n2",a),e("p","n3",a),e("p","n4",a),e("u1","u2",u),e("u2","u3",u),e("u3","u1",u),e("c","t",h),e("p","c",l),e("cn1","cn2",l),e("cn3","cn4",l),e("cf1","cf2",l),e("cf3","cf4",l),THREE.Line.call(this,r,i,THREE.LinePieces),this.camera=t,this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=o,this.update()},THREE.CameraHelper.prototype=Object.create(THREE.Line.prototype),THREE.CameraHelper.prototype.constructor=THREE.CameraHelper,THREE.CameraHelper.prototype.update=function(){var t,e,n=new THREE.Vector3,r=new THREE.Camera,i=function(i,o,s,a){n.set(o,s,a).unproject(r);var u=e[i];if(void 0!==u)for(var h=0,l=u.length;l>h;h++)t.vertices[u[h]].copy(n)};return function(){t=this.geometry,e=this.pointMap;var n=1,o=1;r.projectionMatrix.copy(this.camera.projectionMatrix),i("c",0,0,-1),i("t",0,0,1),i("n1",-n,-o,-1),i("n2",n,-o,-1),i("n3",-n,o,-1),i("n4",n,o,-1),i("f1",-n,-o,1),i("f2",n,-o,1),i("f3",-n,o,1),i("f4",n,o,1),i("u1",.7*n,1.1*o,-1),i("u2",.7*-n,1.1*o,-1),i("u3",0,2*o,-1),i("cf1",-n,0,1),i("cf2",n,0,1),i("cf3",0,-o,1),i("cf4",0,o,1),i("cn1",-n,0,-1),i("cn2",n,0,-1),i("cn3",0,-o,-1),i("cn4",0,o,-1),t.verticesNeedUpdate=!0}}(),THREE.DirectionalLightHelper=function(t,e){THREE.Object3D.call(this),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,e=e||1;var n=new THREE.Geometry;n.vertices.push(new THREE.Vector3(-e,e,0),new THREE.Vector3(e,e,0),new THREE.Vector3(e,-e,0),new THREE.Vector3(-e,-e,0),new THREE.Vector3(-e,e,0));var r=new THREE.LineBasicMaterial({fog:!1});r.color.copy(this.light.color).multiplyScalar(this.light.intensity),this.lightPlane=new THREE.Line(n,r),this.add(this.lightPlane),n=new THREE.Geometry,n.vertices.push(new THREE.Vector3,new THREE.Vector3),r=new THREE.LineBasicMaterial({fog:!1}),r.color.copy(this.light.color).multiplyScalar(this.light.intensity),this.targetLine=new THREE.Line(n,r),this.add(this.targetLine),this.update()},THREE.DirectionalLightHelper.prototype=Object.create(THREE.Object3D.prototype),THREE.DirectionalLightHelper.prototype.constructor=THREE.DirectionalLightHelper,THREE.DirectionalLightHelper.prototype.dispose=function(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose()},THREE.DirectionalLightHelper.prototype.update=function(){var t=new THREE.Vector3,e=new THREE.Vector3,n=new THREE.Vector3;return function(){t.setFromMatrixPosition(this.light.matrixWorld),e.setFromMatrixPosition(this.light.target.matrixWorld),n.subVectors(e,t),this.lightPlane.lookAt(n),this.lightPlane.material.color.copy(this.light.color).multiplyScalar(this.light.intensity),this.targetLine.geometry.vertices[1].copy(n),this.targetLine.geometry.verticesNeedUpdate=!0,this.targetLine.material.color.copy(this.lightPlane.material.color)}}(),THREE.EdgesHelper=function(t,e,n){var r=void 0!==e?e:16777215;n=void 0!==n?n:1;var i,o=Math.cos(THREE.Math.degToRad(n)),s=[0,0],a={},u=function(t,e){return t-e},h=["a","b","c"],l=new THREE.BufferGeometry;t.geometry instanceof THREE.BufferGeometry?(i=new THREE.Geometry,i.fromBufferGeometry(t.geometry)):i=t.geometry.clone(),i.mergeVertices(),i.computeFaceNormals();for(var c=i.vertices,p=i.faces,f=0,d=0,m=p.length;m>d;d++)for(var v=p[d],g=0;3>g;g++){s[0]=v[h[g]],s[1]=v[h[(g+1)%3]],s.sort(u);var E=s.toString();void 0===a[E]?(a[E]={vert1:s[0],vert2:s[1],face1:d,face2:void 0},f++):a[E].face2=d}var y=new Float32Array(2*f*3),_=0;for(var E in a){var b=a[E];if(void 0===b.face2||p[b.face1].normal.dot(p[b.face2].normal)<=o){var T=c[b.vert1];y[_++]=T.x,y[_++]=T.y,y[_++]=T.z,T=c[b.vert2],y[_++]=T.x,y[_++]=T.y,y[_++]=T.z}}l.addAttribute("position",new THREE.BufferAttribute(y,3)),THREE.Line.call(this,l,new THREE.LineBasicMaterial({color:r}),THREE.LinePieces),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1},THREE.EdgesHelper.prototype=Object.create(THREE.Line.prototype),THREE.EdgesHelper.prototype.constructor=THREE.EdgesHelper,THREE.FaceNormalsHelper=function(t,e,n,r){this.object=t,this.size=void 0!==e?e:1;for(var i=void 0!==n?n:16776960,o=void 0!==r?r:1,s=new THREE.Geometry,a=this.object.geometry.faces,u=0,h=a.length;h>u;u++)s.vertices.push(new THREE.Vector3,new THREE.Vector3);THREE.Line.call(this,s,new THREE.LineBasicMaterial({color:i,linewidth:o}),THREE.LinePieces),this.matrixAutoUpdate=!1,this.normalMatrix=new THREE.Matrix3,this.update()},THREE.FaceNormalsHelper.prototype=Object.create(THREE.Line.prototype),THREE.FaceNormalsHelper.prototype.constructor=THREE.FaceNormalsHelper,THREE.FaceNormalsHelper.prototype.update=function(){var t=this.geometry.vertices,e=this.object,n=e.geometry.vertices,r=e.geometry.faces,i=e.matrixWorld;e.updateMatrixWorld(!0),this.normalMatrix.getNormalMatrix(i);for(var o=0,s=0,a=r.length;a>o;o++,s+=2){var u=r[o];t[s].copy(n[u.a]).add(n[u.b]).add(n[u.c]).divideScalar(3).applyMatrix4(i),t[s+1].copy(u.normal).applyMatrix3(this.normalMatrix).normalize().multiplyScalar(this.size).add(t[s])}return this.geometry.verticesNeedUpdate=!0,this},THREE.GridHelper=function(t,e){var n=new THREE.Geometry,r=new THREE.LineBasicMaterial({vertexColors:THREE.VertexColors});this.color1=new THREE.Color(4473924),this.color2=new THREE.Color(8947848);for(var i=-t;t>=i;i+=e){n.vertices.push(new THREE.Vector3(-t,0,i),new THREE.Vector3(t,0,i),new THREE.Vector3(i,0,-t),new THREE.Vector3(i,0,t));var o=0===i?this.color1:this.color2;n.colors.push(o,o,o,o)}THREE.Line.call(this,n,r,THREE.LinePieces)},THREE.GridHelper.prototype=Object.create(THREE.Line.prototype),THREE.GridHelper.prototype.constructor=THREE.GridHelper,THREE.GridHelper.prototype.setColors=function(t,e){this.color1.set(t),this.color2.set(e),this.geometry.colorsNeedUpdate=!0},THREE.HemisphereLightHelper=function(t,e){THREE.Object3D.call(this),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.colors=[new THREE.Color,new THREE.Color];var n=new THREE.SphereGeometry(e,4,2);n.applyMatrix((new THREE.Matrix4).makeRotationX(-Math.PI/2));for(var r=0,i=8;i>r;r++)n.faces[r].color=this.colors[4>r?0:1];var o=new THREE.MeshBasicMaterial({vertexColors:THREE.FaceColors,wireframe:!0});this.lightSphere=new THREE.Mesh(n,o),this.add(this.lightSphere),this.update()},THREE.HemisphereLightHelper.prototype=Object.create(THREE.Object3D.prototype),THREE.HemisphereLightHelper.prototype.constructor=THREE.HemisphereLightHelper,THREE.HemisphereLightHelper.prototype.dispose=function(){this.lightSphere.geometry.dispose(),this.lightSphere.material.dispose()},THREE.HemisphereLightHelper.prototype.update=function(){var t=new THREE.Vector3;return function(){this.colors[0].copy(this.light.color).multiplyScalar(this.light.intensity),this.colors[1].copy(this.light.groundColor).multiplyScalar(this.light.intensity),this.lightSphere.lookAt(t.setFromMatrixPosition(this.light.matrixWorld).negate()),this.lightSphere.geometry.colorsNeedUpdate=!0}}(),THREE.PointLightHelper=function(t,e){this.light=t,this.light.updateMatrixWorld();var n=new THREE.SphereGeometry(e,4,2),r=new THREE.MeshBasicMaterial({wireframe:!0,fog:!1});r.color.copy(this.light.color).multiplyScalar(this.light.intensity),THREE.Mesh.call(this,n,r),this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1},THREE.PointLightHelper.prototype=Object.create(THREE.Mesh.prototype),THREE.PointLightHelper.prototype.constructor=THREE.PointLightHelper,THREE.PointLightHelper.prototype.dispose=function(){this.geometry.dispose(),this.material.dispose()},THREE.PointLightHelper.prototype.update=function(){this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)},THREE.SkeletonHelper=function(t){this.bones=this.getBoneList(t);for(var e=new THREE.Geometry,n=0;nu;u++)for(var l=a[u],c=0,p=l.vertexNormals.length;p>c;c++)s.vertices.push(new THREE.Vector3,new THREE.Vector3);THREE.Line.call(this,s,new THREE.LineBasicMaterial({color:i,linewidth:o}),THREE.LinePieces),this.matrixAutoUpdate=!1,this.normalMatrix=new THREE.Matrix3,this.update()},THREE.VertexNormalsHelper.prototype=Object.create(THREE.Line.prototype),THREE.VertexNormalsHelper.prototype.constructor=THREE.VertexNormalsHelper,THREE.VertexNormalsHelper.prototype.update=function(t){var e=new THREE.Vector3;return function(t){var n=["a","b","c","d"];this.object.updateMatrixWorld(!0),this.normalMatrix.getNormalMatrix(this.object.matrixWorld);for(var r=this.geometry.vertices,i=this.object.geometry.vertices,o=this.object.geometry.faces,s=this.object.matrixWorld,a=0,u=0,h=o.length;h>u;u++)for(var l=o[u],c=0,p=l.vertexNormals.length;p>c;c++){var f=l[n[c]],d=i[f],m=l.vertexNormals[c];r[a].copy(d).applyMatrix4(s),e.copy(m).applyMatrix3(this.normalMatrix).normalize().multiplyScalar(this.size),e.add(r[a]),a+=1,r[a].copy(e),a+=1}return this.geometry.verticesNeedUpdate=!0,this}}(),THREE.VertexTangentsHelper=function(t,e,n,r){this.object=t,this.size=void 0!==e?e:1;for(var i=void 0!==n?n:255,o=void 0!==r?r:1,s=new THREE.Geometry,a=t.geometry.faces,u=0,h=a.length;h>u;u++)for(var l=a[u],c=0,p=l.vertexTangents.length;p>c;c++)s.vertices.push(new THREE.Vector3),s.vertices.push(new THREE.Vector3);THREE.Line.call(this,s,new THREE.LineBasicMaterial({color:i,linewidth:o}),THREE.LinePieces),this.matrixAutoUpdate=!1,this.update()},THREE.VertexTangentsHelper.prototype=Object.create(THREE.Line.prototype),THREE.VertexTangentsHelper.prototype.constructor=THREE.VertexTangentsHelper,THREE.VertexTangentsHelper.prototype.update=function(t){var e=new THREE.Vector3;return function(t){var n=["a","b","c","d"];this.object.updateMatrixWorld(!0);for(var r=this.geometry.vertices,i=this.object.geometry.vertices,o=this.object.geometry.faces,s=this.object.matrixWorld,a=0,u=0,h=o.length;h>u;u++)for(var l=o[u],c=0,p=l.vertexTangents.length;p>c;c++){var f=l[n[c]],d=i[f],m=l.vertexTangents[c];r[a].copy(d).applyMatrix4(s),e.copy(m).transformDirection(s).multiplyScalar(this.size),e.add(r[a]),a+=1,r[a].copy(e),a+=1}return this.geometry.verticesNeedUpdate=!0,this}}(),THREE.WireframeHelper=function(t,e){var n=void 0!==e?e:16777215,r=[0,0],i={},o=function(t,e){return t-e},s=["a","b","c"],a=new THREE.BufferGeometry;if(t.geometry instanceof THREE.Geometry){for(var u=t.geometry.vertices,h=t.geometry.faces,l=0,c=new Uint32Array(6*h.length),p=0,f=h.length;f>p;p++)for(var d=h[p],m=0;3>m;m++){r[0]=d[s[m]],r[1]=d[s[(m+1)%3]],r.sort(o);var v=r.toString();void 0===i[v]&&(c[2*l]=r[0],c[2*l+1]=r[1],i[v]=!0,l++)}for(var g=new Float32Array(2*l*3),p=0,f=l;f>p;p++)for(var m=0;2>m;m++){var E=u[c[2*p+m]],y=6*p+3*m;g[y+0]=E.x,g[y+1]=E.y,g[y+2]=E.z}a.addAttribute("position",new THREE.BufferAttribute(g,3))}else if(t.geometry instanceof THREE.BufferGeometry)if(void 0!==t.geometry.attributes.index){var u=t.geometry.attributes.position.array,_=t.geometry.attributes.index.array,b=t.geometry.drawcalls,l=0;0===b.length&&(b=[{count:_.length,index:0,start:0}]);for(var c=new Uint32Array(2*_.length),T=0,x=b.length;x>T;++T)for(var w=b[T].start,R=b[T].count,y=b[T].index,p=w,H=w+R;H>p;p+=3)for(var m=0;3>m;m++){r[0]=y+_[p+m],r[1]=y+_[p+(m+1)%3],r.sort(o);var v=r.toString();void 0===i[v]&&(c[2*l]=r[0],c[2*l+1]=r[1],i[v]=!0,l++)}for(var g=new Float32Array(2*l*3),p=0,f=l;f>p;p++)for(var m=0;2>m;m++){var y=6*p+3*m,M=3*c[2*p+m];g[y+0]=u[M],g[y+1]=u[M+1],g[y+2]=u[M+2]}a.addAttribute("position",new THREE.BufferAttribute(g,3))}else{for(var u=t.geometry.attributes.position.array,l=u.length/3,S=l/3,g=new Float32Array(2*l*3),p=0,f=S;f>p;p++)for(var m=0;3>m;m++){var y=18*p+6*m,k=9*p+3*m;g[y+0]=u[k],g[y+1]=u[k+1],g[y+2]=u[k+2];var M=9*p+3*((m+1)%3);g[y+3]=u[M], +g[y+4]=u[M+1],g[y+5]=u[M+2]}a.addAttribute("position",new THREE.BufferAttribute(g,3))}THREE.Line.call(this,a,new THREE.LineBasicMaterial({color:n}),THREE.LinePieces),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1},THREE.WireframeHelper.prototype=Object.create(THREE.Line.prototype),THREE.WireframeHelper.prototype.constructor=THREE.WireframeHelper,THREE.ImmediateRenderObject=function(){THREE.Object3D.call(this),this.render=function(t){}},THREE.ImmediateRenderObject.prototype=Object.create(THREE.Object3D.prototype),THREE.ImmediateRenderObject.prototype.constructor=THREE.ImmediateRenderObject,THREE.MorphBlendMesh=function(t,e){THREE.Mesh.call(this,t,e),this.animationsMap={},this.animationsList=[];var n=this.geometry.morphTargets.length,r="__default",i=0,o=n-1,s=n/1;this.createAnimation(r,i,o,s),this.setAnimationWeight(r,1)},THREE.MorphBlendMesh.prototype=Object.create(THREE.Mesh.prototype),THREE.MorphBlendMesh.prototype.constructor=THREE.MorphBlendMesh,THREE.MorphBlendMesh.prototype.createAnimation=function(t,e,n,r){var i={startFrame:e,endFrame:n,length:n-e+1,fps:r,duration:(n-e)/r,lastFrame:0,currentFrame:0,active:!1,time:0,direction:1,weight:1,directionBackwards:!1,mirroredLoop:!1};this.animationsMap[t]=i,this.animationsList.push(i)},THREE.MorphBlendMesh.prototype.autoCreateAnimations=function(t){for(var e,n=/([a-z]+)_?(\d+)/,r={},i=this.geometry,o=0,s=i.morphTargets.length;s>o;o++){var a=i.morphTargets[o],u=a.name.match(n);if(u&&u.length>1){var h=u[1];r[h]||(r[h]={start:1/0,end:-(1/0)});var l=r[h];ol.end&&(l.end=o),e||(e=h)}}for(var h in r){var l=r[h];this.createAnimation(h,l.start,l.end,t)}this.firstAnimation=e},THREE.MorphBlendMesh.prototype.setAnimationDirectionForward=function(t){var e=this.animationsMap[t];e&&(e.direction=1,e.directionBackwards=!1)},THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward=function(t){var e=this.animationsMap[t];e&&(e.direction=-1,e.directionBackwards=!0)},THREE.MorphBlendMesh.prototype.setAnimationFPS=function(t,e){var n=this.animationsMap[t];n&&(n.fps=e,n.duration=(n.end-n.start)/n.fps)},THREE.MorphBlendMesh.prototype.setAnimationDuration=function(t,e){var n=this.animationsMap[t];n&&(n.duration=e,n.fps=(n.end-n.start)/n.duration)},THREE.MorphBlendMesh.prototype.setAnimationWeight=function(t,e){var n=this.animationsMap[t];n&&(n.weight=e)},THREE.MorphBlendMesh.prototype.setAnimationTime=function(t,e){var n=this.animationsMap[t];n&&(n.time=e)},THREE.MorphBlendMesh.prototype.getAnimationTime=function(t){var e=0,n=this.animationsMap[t];return n&&(e=n.time),e},THREE.MorphBlendMesh.prototype.getAnimationDuration=function(t){var e=-1,n=this.animationsMap[t];return n&&(e=n.duration),e},THREE.MorphBlendMesh.prototype.playAnimation=function(t){var e=this.animationsMap[t];e?(e.time=0,e.active=!0):THREE.warn("THREE.MorphBlendMesh: animation["+t+"] undefined in .playAnimation()")},THREE.MorphBlendMesh.prototype.stopAnimation=function(t){var e=this.animationsMap[t];e&&(e.active=!1)},THREE.MorphBlendMesh.prototype.update=function(t){for(var e=0,n=this.animationsList.length;n>e;e++){var r=this.animationsList[e];if(r.active){var i=r.duration/r.length;r.time+=r.direction*t,r.mirroredLoop?(r.time>r.duration||r.time<0)&&(r.direction*=-1,r.time>r.duration&&(r.time=r.duration,r.directionBackwards=!0),r.time<0&&(r.time=0,r.directionBackwards=!1)):(r.time=r.time%r.duration,r.time<0&&(r.time+=r.duration));var o=r.startFrame+THREE.Math.clamp(Math.floor(r.time/i),0,r.length-1),s=r.weight;o!==r.currentFrame&&(this.morphTargetInfluences[r.lastFrame]=0,this.morphTargetInfluences[r.currentFrame]=1*s,this.morphTargetInfluences[o]=0,r.lastFrame=r.currentFrame,r.currentFrame=o);var a=r.time%i/i;r.directionBackwards&&(a=1-a),this.morphTargetInfluences[r.currentFrame]=a*s,this.morphTargetInfluences[r.lastFrame]=(1-a)*s}}},function(){function t(t,e,n){for(var r=(n||0)-1,i=t?t.length:0;++r-1?0:-1:e?0:-1}function n(t){var e=this.cache,n=typeof t;if("boolean"==n||null==t)e[t]=!0;else{"number"!=n&&"string"!=n&&(n="object");var r="number"==n?t:g+t,i=e[n]||(e[n]={});"object"==n?(i[r]||(i[r]=[])).push(t):i[r]=!0}}function r(t){return t.charCodeAt(0)}function i(t,e){for(var n=t.criteria,r=e.criteria,i=-1,o=n.length;++ia||"undefined"==typeof s)return 1;if(a>s||"undefined"==typeof a)return-1}}return t.index-e.index}function o(t){var e=-1,r=t.length,i=t[0],o=t[r/2|0],s=t[r-1];if(i&&"object"==typeof i&&o&&"object"==typeof o&&s&&"object"==typeof s)return!1;var a=u();a["false"]=a["null"]=a["true"]=a.undefined=!1;var h=u();for(h.array=t,h.cache=a,h.push=n;++ei?0:i);++r=E&&s===t,h=[];if(u){var c=o(r);c?(s=e,r=c):u=!1}for(;++i-1:void 0});return i.pop(),o.pop(),E&&(h(i),h(o)),s}function nt(t,e,n,r,i){(Jn(e)?Kt:ur)(e,function(e,o){var s,a,u=e,h=t[o];if(e&&((a=Jn(e))||hr(e))){for(var l=r.length;l--;)if(s=r[l]==e){h=i[l];break}if(!s){var c;n&&(u=n(h,e),(c="undefined"!=typeof u)&&(h=u)),c||(h=a?Jn(h)?h:[]:hr(h)?h:{}),r.push(e),i.push(h),c||nt(h,e,n,r,i)}}else n&&(u=n(h,e),"undefined"==typeof u&&(u=e)),"undefined"!=typeof u&&(h=u);t[o]=h})}function rt(t,e){return t+Cn(Yn()*(e-t+1))}function it(n,r,i){var s=-1,u=ut(),c=n?n.length:0,p=[],f=!r&&c>=E&&u===t,d=i||f?a():p;if(f){var m=o(d);u=e,d=m}for(;++s3&&"function"==typeof e[n-2])var r=K(e[--n-1],e[n--],2);else n>2&&"function"==typeof e[n-1]&&(r=e[--n]);for(var i=c(arguments,1,n),o=-1,s=a(),u=a();++on?Wn(0,o+n):n)||0,Jn(t)?s=i(t,e,n)>-1:"number"==typeof o?s=(Ot(t)?t.indexOf(e,n):i(t,e,n))>-1:ur(t,function(t){return++r>=n?!(s=t===e):void 0}),s}function qt(t,e,n){var r=!0;e=d.createCallback(e,n,3);var i=-1,o=t?t.length:0;if("number"==typeof o)for(;++io&&(o=u)}else e=null==e&&Ot(t)?r:d.createCallback(e,n,3),Kt(t,function(t,n,r){var s=e(t,n,r);s>i&&(i=s,o=t)});return o}function ee(t,e,n){var i=1/0,o=i;if("function"!=typeof e&&n&&n[e]===t&&(e=null),null==e&&Jn(t))for(var s=-1,a=t.length;++su&&(o=u)}else e=null==e&&Ot(t)?r:d.createCallback(e,n,3),Kt(t,function(t,n,r){var s=e(t,n,r);i>s&&(i=s,o=t)});return o}function ne(t,e,n,r){if(!t)return n;var i=arguments.length<3;e=d.createCallback(e,r,4);var o=-1,s=t.length;if("number"==typeof s)for(i&&(n=t[++o]);++or?Wn(0,i+r):r||0}else if(r){var o=He(e,n);return e[o]===n?o:-1}return t(e,n,r)}function Ee(t,e,n){var r=0,i=t?t.length:0;if("number"!=typeof e&&null!=e){var o=i;for(e=d.createCallback(e,n,3);o--&&e(t[o],o,t);)r++}else r=null==e||n?1:e||r;return c(t,0,qn(Wn(0,i-r),i))}function ye(){for(var n=[],r=-1,i=arguments.length,s=a(),u=ut(),c=u===t,p=a();++r=E&&o(r?n[r]:p)))}var d=n[0],m=-1,v=d?d.length:0,g=[];t:for(;++mn?Wn(0,r+n):qn(n,r-1))+1);r--;)if(t[r]===e)return r;return-1}function Te(t){for(var e=arguments,n=0,r=e.length,i=t?t.length:0;++ni;){var s=i+o>>>1;n(t[s])1?arguments:arguments[0],e=-1,n=t?te(fr(t,"length")):0,r=dn(0>n?0:n);++e2?st(t,17,c(arguments,2),null,e):st(t,1,null,null,e)}function Oe(t){for(var e=arguments.length>1?tt(arguments,!0,!1,1):_t(t),n=-1,r=e.length;++n2?st(e,19,c(arguments,2),null,t):st(e,3,null,null,t)}function Fe(){for(var t=arguments,e=t.length;e--;)if(!kt(t[e]))throw new xn;return function(){for(var e=arguments,n=t.length;n--;)e=[t[n].apply(this,e)];return e[0]}}function Ue(t,e){return e="number"==typeof e?e:+e||t.length,st(t,4,null,null,null,e)}function Be(t,e,n){var r,i,o,s,a,u,h,l=0,c=!1,p=!0;if(!kt(t))throw new xn;if(e=Wn(0,e)||0,n===!0){var d=!0;p=!1}else At(n)&&(d=n.leading,c="maxWait"in n&&(Wn(e,n.maxWait)||0),p="trailing"in n?n.trailing:p);var m=function(){var n=e-(mr()-s);if(0>=n){i&&An(i);var c=h;i=u=h=f,c&&(l=mr(),o=t.apply(a,r),u||i||(r=a=null))}else u=Dn(m,n)},v=function(){u&&An(u),i=u=h=f,(p||c!==e)&&(l=mr(),o=t.apply(a,r),u||i||(r=a=null))};return function(){if(r=arguments,s=mr(),a=this,h=p&&(u||!d),c===!1)var n=d&&!u;else{i||d||(l=s);var f=c-(s-l),g=0>=f;g?(i&&(i=An(i)),l=s,o=t.apply(a,r)):i||(i=Dn(v,f))}return g&&u?u=An(u):u||e===c||(u=Dn(m,e)),n&&(g=!0,o=t.apply(a,r)),!g||u||i||(r=a=null),o}}function Ne(t){if(!kt(t))throw new xn;var e=c(arguments,1);return Dn(function(){t.apply(f,e)},1)}function Ve(t,e){if(!kt(t))throw new xn;var n=c(arguments,2);return Dn(function(){t.apply(f,n)},e)}function Ie(t,e){if(!kt(t))throw new xn;var n=function(){var r=n.cache,i=e?e.apply(this,arguments):g+arguments[0];return zn.call(r,i)?r[i]:r[i]=t.apply(this,arguments)};return n.cache={},n}function je(t){var e,n;if(!kt(t))throw new xn;return function(){return e?n:(e=!0,n=t.apply(this,arguments),t=null,n)}}function Ge(t){return st(t,16,c(arguments,1))}function We(t){return st(t,32,null,c(arguments,1))}function qe(t,e,n){var r=!0,i=!0;if(!kt(t))throw new xn;return n===!1?r=!1:At(n)&&(r="leading"in n?n.leading:r,i="trailing"in n?n.trailing:i),G.leading=r,G.maxWait=e,G.trailing=i,Be(t,e,G)}function Xe(t,e){return st(e,16,[t])}function Ye(t){return function(){return t}}function Ze(t,e,n){var r=typeof t;if(null==t||"function"==r)return K(t,e,n);if("object"!=r)return en(t);var i=tr(t),o=i[0],s=t[o];return 1!=i.length||s!==s||At(s)?function(e){for(var n=i.length,r=!1;n--&&(r=et(e[i[n]],t[i[n]],null,!0)););return r}:function(t){var e=t[o];return s===e&&(0!==s||1/s==1/e)}}function Ke(t){return null==t?"":Tn(t).replace(ir,at)}function Qe(t){return t}function Je(t,e,n){var r=!0,i=e&&_t(e);e&&(n||i.length)||(null==n&&(n=e),o=m,e=t,t=d,i=_t(e)),n===!1?r=!1:At(n)&&"chain"in n&&(r=n.chain);var o=t,s=kt(o);Kt(i,function(n){var i=t[n]=e[n];s&&(o.prototype[n]=function(){var e=this.__chain__,n=this.__wrapped__,s=[n];On.apply(s,arguments);var a=i.apply(t,s);if(r||e){if(n===a&&At(a))return this;a=new o(a),a.__chain__=e}return a})})}function $e(){return n._=Hn,this}function tn(){}function en(t){return function(e){return e[t]}}function nn(t,e,n){var r=null==t,i=null==e;if(null==n&&("boolean"==typeof t&&i?(n=t,t=1):i||"boolean"!=typeof e||(n=e,i=!0)),r&&i&&(e=1),t=+t||0,i?(e=t,t=0):e=+e||0,n||t%1||e%1){var o=Yn();return qn(t+o*(e-t+parseFloat("1e-"+((o+"").length-1))),e)}return rt(t,e)}function rn(t,e){if(t){var n=t[e];return kt(n)?t[e]():n}}function on(t,e,n){var r=d.templateSettings;t=Tn(t||""),n=sr({},n,r);var i,o=sr({},n.imports,r.imports),a=tr(o),u=jt(o),h=0,l=n.interpolate||k,c="__p += '",p=bn((n.escape||k).source+"|"+l.source+"|"+(l===M?w:k).source+"|"+(n.evaluate||k).source+"|$","g");t.replace(p,function(e,n,r,o,a,u){return r||(r=o),c+=t.slice(h,u).replace(C,s),n&&(c+="' +\n__e("+n+") +\n'"),a&&(i=!0,c+="';\n"+a+";\n__p += '"),r&&(c+="' +\n((__t = ("+r+")) == null ? '' : __t) +\n'"),h=u+e.length,e}),c+="';\n";var m=n.variable,v=m;v||(m="obj",c="with ("+m+") {\n"+c+"\n}\n"),c=(i?c.replace(b,""):c).replace(T,"$1").replace(x,"$1;"),c="function("+m+") {\n"+(v?"":m+" || ("+m+" = {});\n")+"var __t, __p = '', __e = _.escape"+(i?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+c+"return __p\n}";var g="\n/*\n//# sourceURL="+(n.sourceURL||"/lodash/template/source["+L++ +"]")+"\n*/";try{var E=gn(a,"return "+c+g).apply(f,u)}catch(y){throw y.source=c,y}return e?E(e):(E.source=c,E)}function sn(t,e,n){t=(t=+t)>-1?t:0;var r=-1,i=dn(t);for(e=K(e,n,1);++r/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:M,variable:"",imports:{_:d}},Nn||(Z=function(){function t(){}return function(e){if(At(e)){t.prototype=e;var r=new t;t.prototype=null}return r||n.Object()}}());var Qn=Bn?function(t,e){W.value=e,Bn(t,"__bindData__",W)}:tn,Jn=Vn||function(t){return t&&"object"==typeof t&&"number"==typeof t.length&&Mn.call(t)==O||!1},$n=function(t){var e,n=t,r=[];if(!n)return r;if(!q[typeof t])return r;for(e in n)zn.call(n,e)&&r.push(e);return r},tr=Gn?function(t){return At(t)?Gn(t):[]}:$n,er={"&":"&","<":"<",">":">",'"':""","'":"'"},nr=Tt(er),rr=bn("("+tr(nr).join("|")+")","g"),ir=bn("["+tr(er).join("")+"]","g"),or=function(t,e,n){var r,i=t,o=i;if(!i)return o;var s=arguments,a=0,u="number"==typeof n?2:s.length;if(u>3&&"function"==typeof s[u-2])var h=K(s[--u-1],s[u--],2);else u>2&&"function"==typeof s[u-1]&&(h=s[--u]);for(;++a/g,S=RegExp("^["+_+"]*0+(?=.$)"),k=/($^)/,A=/\bthis\b/,C=/['\n\r\t\u2028\u2029\\]/g,P=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"],L=0,z="[object Arguments]",O="[object Array]",D="[object Boolean]",F="[object Date]",U="[object Function]",B="[object Number]",N="[object Object]",V="[object RegExp]",I="[object String]",j={};j[U]=!1,j[z]=j[O]=j[D]=j[F]=j[B]=j[N]=j[V]=j[I]=!0;var G={leading:!1,maxWait:0,trailing:!1},W={configurable:!1,enumerable:!1,value:null,writable:!1},q={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},X={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"},Y=q[typeof window]&&window||this,Z=q[typeof exports]&&exports&&!exports.nodeType&&exports,K=q[typeof module]&&module&&!module.nodeType&&module,Q=K&&K.exports===Z&&Z,J=q[typeof global]&&global; +!J||J.global!==J&&J.window!==J||(Y=J);var $=p();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(Y._=$,define(function(){return $})):Z&&K?Q?(K.exports=$)._=$:Z._=$:Y._=$}.call(this),THREE.Binder={bind:function(t,e){return function(n,r){r.__binds||(r.__binds=[]);var i=t;_.isArray(n)&&(i=n[0],n=n[1]);for(var o=/^([^.:]*(?:\.[^.:]+)*)?(?:\:(.*))?$/.exec(n),s=o[1].split(/\./g),a=s.pop(),u=o[2]||a,h=s.shift(),l={"this":r}[h]||e[h]||t[h]||i;l&&(n=s.shift());)l=l[n];if(l&&(l.on||l.addEventListener)){var c=function(e){r[u]&&r[u](e,t)};THREE.Binder._polyfill(l,["addEventListener","on"],function(t){l[t](a,c)});var p={target:l,name:a,callback:c};return r.__binds.push(p),c}throw"Cannot bind '"+n+"' in "+this.__name}},unbind:function(){return function(t){t.__binds&&(t.__binds.forEach(function(t){THREE.Binder._polyfill(t.target,["removeEventListener","off"],function(e){t.target[e](t.name,t.callback)})}.bind(this)),t.__binds=[])}},apply:function(t){THREE.EventDispatcher.prototype.apply(t),t.trigger=THREE.Binder._trigger,t.triggerOnce=THREE.Binder._triggerOnce,t.on=t.addEventListener,t.off=t.removeEventListener,t.dispatchEvent=t.trigger},_triggerOnce:function(t){this.trigger(t),this._listeners&&delete this._listeners[t.type]},_trigger:function(t){if(void 0!==this._listeners){var e=t.type,n=this._listeners[e];if(void 0!==n){n=n.slice();var r=n.length;t.target=this;for(var i=0;r>i;i++)n[i].call(this,t,this)}}},_polyfill:function(t,e,n){e.map(function(e){return t.method}),e.length&&n(e[0])}},THREE.Api={apply:function(t){t.set=function(t){var e=this.options||{},n=_.reduce(t,function(t,n,r){return e[r]!==n&&(t[r]=n),t},{});this.options=_.extend(e,n),this.trigger({type:"change",options:t,changes:n})},t.get=function(){return this.options},t.api=function(t,e){return t=t||{},e&&_.each(t,function(t,n,r){_.isFunction(t)&&(r[n]=_.partialRight(t,e))}),t.set=this.set.bind(this),t.get=this.get.bind(this),t}}},THREE.Bootstrap=function(t){if(t){var e=[].slice.apply(arguments);t={},e[0]instanceof Node&&(node=e[0],e=e.slice(1),t.element=node),_.isString(e[0])&&(t.plugins=e),_.isArray(e[0])&&(t.plugins=e[0]),e[0]&&(t=_.defaults(t,e[0]))}if(!(this instanceof THREE.Bootstrap))return new THREE.Bootstrap(t);var n={init:!0,element:document.body,plugins:["core"],aliases:{},plugindb:THREE.Bootstrap.Plugins||{},aliasdb:THREE.Bootstrap.Aliases||{}};this.__options=_.defaults(t||{},n),this.__inited=!1,this.__destroyed=!1,this.__installed=[];var r=this.__options.element;r===""+r&&(r=document.querySelector(r)),this.plugins={},this.element=r,this.__options.init&&this.init()},THREE.Bootstrap.prototype={init:function(){return this.__inited?void 0:(this.__inited=!0,this.install(this.__options.plugins),this)},destroy:function(){return this.__inited&&!this.__destroyed?(this.__destroyed=!0,this.trigger({type:"destroy"}),this.uninstall(),this):void 0},resolve:function(t){function e(t,n,o){if(o>=256)throw"Plug-in alias recursion detected.";return t=_.filter(t,i),_.each(t,function(t){var i=r[t];i?n=n.concat(e(i,[],o+1)):n.push(t)}),n}t=_.isArray(t)?t:[t];var n=this.__options,r=_.extend({},n.aliasdb,n.aliases),i=function(t){var e=t.split(":");return e[1]?(r[e[0]]=[e[1]],!1):!0};return t=_.filter(t,i),_.each(r,function(t,e){r[e]=_.isArray(t)?t:[t]}),e(t,[],0)},install:function(t){t=_.isArray(t)?t:[t],t=this.resolve(t),_.each(t,this.__install,this),this.__ready()},uninstall:function(t){t&&(t=_.isArray(t)?t:[t],t=this.resolve(t)),_.eachRight(t||this.__installed,this.__uninstall,this)},__install:function(t){var e=this.__options.plugindb[t];if(!e)throw"[three.install] Cannot install. '"+t+"' is not registered.";if(this.plugins[t])return console.warn("[three.install] "+t+" is already installed.");var n=e,r=new n(this.__options[t]||{},t);return this.plugins[t]=r,flag=r.install(this),this.__installed.push(r),this.trigger({type:"install",plugin:r}),flag},__uninstall:function(t,e){return plugin=_.isString(t)?this.plugins[t]:t,plugin?(t=plugin.__name,plugin.uninstall(this),this.__installed=_.without(this.__installed,plugin),delete this.plugins[t],void this.trigger({type:"uninstall",plugin:plugin})):console.warn("[three.uninstall] "+t+"' is not installed.")},__ready:function(){this.triggerOnce({type:"ready"})}},THREE.Binder.apply(THREE.Bootstrap.prototype),THREE.Bootstrap.Plugins={},THREE.Bootstrap.Aliases={},THREE.Bootstrap.Plugin=function(t){this.options=_.defaults(t||{},this.defaults)},THREE.Bootstrap.Plugin.prototype={listen:[],defaults:{},install:function(t){},uninstall:function(t){}},THREE.Binder.apply(THREE.Bootstrap.Plugin.prototype),THREE.Api.apply(THREE.Bootstrap.Plugin.prototype),THREE.Bootstrap.registerPlugin=function(t,e){var n=function(e){THREE.Bootstrap.Plugin.call(this,e),this.__name=t};n.prototype=_.extend(new THREE.Bootstrap.Plugin,e),THREE.Bootstrap.Plugins[t]=n},THREE.Bootstrap.unregisterPlugin=function(t){delete THREE.Bootstrap.Plugins[t]},THREE.Bootstrap.registerAlias=function(t,e){THREE.Bootstrap.Aliases[t]=e},THREE.Bootstrap.unregisterAlias=function(t){delete THREE.Bootstrap.Aliases[t]},THREE.Bootstrap.registerAlias("empty",["fallback","bind","renderer","size","fill","loop","time"]),THREE.Bootstrap.registerAlias("core",["empty","scene","camera","render","warmup"]),THREE.Bootstrap.registerAlias("VR",["core","cursor","fullscreen","render:vr"]),THREE.Bootstrap.registerPlugin("fallback",{defaults:{force:!1,fill:!0,begin:'
',end:"
",message:'This example requires WebGL
Visit get.webgl.org for more info'},install:function(t){var e;try{if(e=document.createElement("canvas"),gl=e.getContext("webgl")||e.getContext("experimental-webgl"),!gl||this.options.force)throw"WebGL unavailable.";t.fallback=!1}catch(n){var r=this.options.message,i=this.options.begin,o=this.options.end,s=this.options.fill,a=document.createElement("div");for(a.innerHTML=i+r+o,this.children=[];a.childNodes.length>0;)this.children.push(a.firstChild),t.element.appendChild(a.firstChild);return s&&t.install("fill"),this.div=a,t.fallback=!0,!1}},uninstall:function(t){this.children&&(this.children.forEach(function(t){t.parentNode.removeChild(t)}),this.children=null),delete t.fallback}}),THREE.Bootstrap.registerPlugin("renderer",{defaults:{klass:THREE.WebGLRenderer,parameters:{depth:!0,stencil:!0,preserveDrawingBuffer:!0,antialias:!0}},listen:["resize"],install:function(t){var e=t.renderer=new this.options.klass(this.options.parameters);t.canvas=e.domElement,t.element.appendChild(e.domElement)},uninstall:function(t){t.element.removeChild(t.renderer.domElement),delete t.renderer,delete t.canvas},resize:function(t,e){var n=e.renderer,r=n.domElement;r&&"CANVAS"==r.tagName?n.setSize(t.renderWidth,t.renderHeight,!1):(n.setRenderSize&&n.setRenderSize(t.renderWidth,t.renderHeight),n.setSize(t.viewWidth,t.viewHeight,!1))}}),THREE.Bootstrap.registerPlugin("bind",{install:function(t){var e={three:t,window:window};t.bind=THREE.Binder.bind(t,e),t.unbind=THREE.Binder.unbind(t),t.bind("install:bind",this),t.bind("uninstall:unbind",this)},uninstall:function(t){t.unbind(this),delete t.bind,delete t.unbind},bind:function(t,e){var n=t.plugin,r=n.listen;r&&r.forEach(function(t){e.bind(t,n)})},unbind:function(t,e){e.unbind(t.plugin)}}),THREE.Bootstrap.registerPlugin("size",{defaults:{width:null,height:null,aspect:null,scale:1,maxRenderWidth:1/0,maxRenderHeight:1/0,devicePixelRatio:!0},listen:["window.resize:queue","element.resize:queue","this.change:queue","ready:resize","pre:pre"],install:function(t){t.Size=this.api({renderWidth:0,renderHeight:0,viewWidth:0,viewHeight:0}),this.resized=!1},uninstall:function(t){delete t.Size},queue:function(t,e){this.resized=!0},pre:function(t,e){this.resized&&(this.resized=!1,this.resize(t,e))},resize:function(t,e){var n,r,i,o,s,a,u,h,l,c=this.options,p=e.element,f=e.renderer,d=0,m=0;n=i=void 0===c.width||null==c.width?p.offsetWidth||p.innerWidth||0:c.width,r=o=void 0===c.height||null==c.height?p.offsetHeight||p.innerHeight||0:c.height,u=n/r,c.aspect&&(c.aspect>u?(r=Math.round(n/c.aspect),m=Math.floor((o-r)/2)):(n=Math.round(r*c.aspect),d=Math.floor((i-n)/2)),u=n/r),l=1,c.devicePixelRatio&&"undefined"!=typeof window&&(l=window.devicePixelRatio||1),s=Math.min(n*l*c.scale,c.maxRenderWidth),a=Math.min(r*l*c.scale,c.maxRenderHeight),raspect=s/a,raspect>u?s=Math.round(a*u):a=Math.round(s/u),l=a/r,h=f.domElement.style,h.width=n+"px",h.height=r+"px",h.marginLeft=d+"px",h.marginTop=m+"px",_.extend(e.Size,{renderWidth:s,renderHeight:a,viewWidth:n,viewHeight:r,aspect:u,pixelRatio:l}),e.trigger({type:"resize",renderWidth:s,renderHeight:a,viewWidth:n,viewHeight:r,aspect:u,pixelRatio:l})}}),THREE.Bootstrap.registerPlugin("fill",{defaults:{block:!0,body:!0,layout:!0},install:function(t){function e(t){var e=t.style.height;return"auto"==e||""==e}function n(t){return t.style.height="100%",t.style.margin=0,t.style.padding=0,t}if(this.options.body&&t.element==document.body&&(this.applied=[t.element,document.documentElement].filter(e).map(n)),this.options.block&&t.canvas&&(t.canvas.style.display="block",this.block=!0),this.options.layout&&t.element){var r=window.getComputedStyle(t.element);"static"==r.position&&(t.element.style.position="relative",this.layout=!0)}},uninstall:function(t){function e(t){return t.style.height="",t.style.margin="",t.style.padding="",t}this.applied&&(this.applied.map(e),delete this.applied),this.block&&t.canvas&&(t.canvas.style.display="",delete this.block),this.layout&&t.element&&(t.element.style.position="",delete this.layout)},change:function(t){this.uninstall(t),this.install(t)}}),THREE.Bootstrap.registerPlugin("loop",{defaults:{start:!0},listen:["ready"],install:function(t){this.running=!1,t.Loop=this.api({start:this.start.bind(this),stop:this.stop.bind(this),running:!1},t),this.events=["pre","update","render","post"].map(function(t){return{type:t}})},uninstall:function(t){this.stop(t)},ready:function(t,e){this.options.start&&this.start(e)},start:function(t){if(!this.running){t.Loop.running=this.running=!0;var e=t.trigger.bind(t),n=function(){this.running&&requestAnimationFrame(n),this.events.map(e)}.bind(this);requestAnimationFrame(n),t.trigger({type:"start"})}},stop:function(t){this.running&&(t.Loop.running=this.running=!1,t.trigger({type:"stop"}))}}),THREE.Bootstrap.registerPlugin("time",{defaults:{speed:1,warmup:0,timeout:1},listen:["pre:tick","this.change"],now:function(){return+new Date/1e3},install:function(t){t.Time=this.api({now:this.now(),clock:0,step:1/60,frames:0,time:0,delta:1/60,average:0,fps:0}),this.last=0,this.time=0,this.clock=0,this.wait=this.options.warmup,this.clockStart=0,this.timeStart=0},tick:function(t,e){var n=this.options.speed,r=this.options.timeout,i=e.Time,o=i.now=this.now(),s=this.last,a=this.time,u=this.clock;if(s){var h=i.delta=o-s,l=i.average||h;h>r&&(h=0);var c=h*n;a+=h,u+=c,i.frames>0&&(i.average=l+.1*(h-l),i.fps=1/l),i.step=c,i.clock=u-this.clockStart,i.time=a-this.timeStart,i.frames++,this.wait-->0&&(this.clockStart=u,this.timeStart=a,i.clock=0,i.step=1e-100)}this.last=o,this.clock=u,this.time=a},uninstall:function(t){delete t.Time}}),THREE.Bootstrap.registerPlugin("scene",{install:function(t){t.scene=new THREE.Scene},uninstall:function(t){delete t.scene}}),THREE.Bootstrap.registerPlugin("camera",{defaults:{near:.01,far:1e4,type:"perspective",fov:60,aspect:null,left:-1,right:1,bottom:-1,top:1,klass:null,parameters:null},listen:["resize","this.change"],install:function(t){t.Camera=this.api(),t.camera=null,this.aspect=1,this.change({},t)},uninstall:function(t){delete t.Camera,delete t.camera},change:function(t,e){var n=this.options,r=e.camera;if(!e.camera||t.changes.type||t.changes.klass){var i=n.klass||{perspective:THREE.PerspectiveCamera,orthographic:THREE.OrthographicCamera}[n.type]||THREE.Camera;e.camera=n.parameters?new i(n.parameters):new i}_.each(n,function(t,r){e.camera.hasOwnProperty(r)&&(e.camera[r]=n[r])}.bind(this)),this.update(e),r===e.camera||e.trigger({type:"camera",camera:e.camera})},resize:function(t,e){this.aspect=t.viewWidth/Math.max(1,t.viewHeight),this.update(e)},update:function(t){t.camera.aspect=this.options.aspect||this.aspect,t.camera.updateProjectionMatrix()}}),THREE.Bootstrap.registerPlugin("render",{listen:["render"],render:function(t,e){e.scene&&e.camera&&e.renderer.render(e.scene,e.camera)}}),THREE.Bootstrap.registerPlugin("warmup",{defaults:{delay:2},listen:["ready","post"],ready:function(t,e){e.renderer.domElement.style.visibility="hidden",this.frame=0,this.hidden=!0},post:function(t,e){this.hidden&&this.frame>=this.options.delay&&(e.renderer.domElement.style.visibility="visible",this.hidden=!1),this.frame++}}),THREE.Stats=function(){var t=Date.now(),e=t,n=0,r=1/0,i=0,o=0,s=1/0,a=0,u=0,h=0,l=document.createElement("div");l.id="stats",l.addEventListener("mousedown",function(t){t.preventDefault(),E(++h%2)},!1),l.style.cssText="width:80px;opacity:0.9;cursor:pointer";var c=document.createElement("div");c.id="fps",c.style.cssText="padding:0 0 3px 3px;text-align:left;background-color:#002",l.appendChild(c);var p=document.createElement("div");p.id="fpsText",p.style.cssText="color:#0ff;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px",p.innerHTML="FPS",c.appendChild(p);var f=document.createElement("div");for(f.id="fpsGraph",f.style.cssText="position:relative;width:74px;height:30px;background-color:#0ff",c.appendChild(f);74>f.children.length;){var d=document.createElement("span");d.style.cssText="width:1px;height:30px;float:left;background-color:#113",f.appendChild(d)}var m=document.createElement("div");m.id="ms",m.style.cssText="padding:0 0 3px 3px;text-align:left;background-color:#020;display:none",l.appendChild(m);var v=document.createElement("div");v.id="msText",v.style.cssText="color:#0f0;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px",v.innerHTML="MS",m.appendChild(v);var g=document.createElement("div");for(g.id="msGraph",g.style.cssText="position:relative;width:74px;height:30px;background-color:#0f0",m.appendChild(g);74>g.children.length;)d=document.createElement("span"),d.style.cssText="width:1px;height:30px;float:left;background-color:#131",g.appendChild(d);var E=function(t){switch(h=t){case 0:c.style.display="block",m.style.display="none";break;case 1:c.style.display="none",m.style.display="block"}};return{REVISION:11,domElement:l,setMode:E,begin:function(){t=Date.now()},end:function(){var h=Date.now();n=h-t,r=Math.min(r,n),i=Math.max(i,n),v.textContent=n+" MS ("+r+"-"+i+")";var l=Math.min(30,30-30*(n/200));return g.appendChild(g.firstChild).style.height=l+"px",u++,h>e+1e3&&(o=Math.round(1e3*u/(h-e)),s=Math.min(s,o),a=Math.max(a,o),p.textContent=o+" FPS ("+s+"-"+a+")",l=Math.min(30,30-30*(o/100)),f.appendChild(f.firstChild).style.height=l+"px",e=h,u=0),h},update:function(){t=this.end()}}},THREE.DeviceOrientationControls=function(t){var e=this;this.object=t,this.object.rotation.reorder("YXZ"),this.freeze=!0,this.deviceOrientation={},this.screenOrientation=0;var n=function(t){e.deviceOrientation=t},r=function(){e.screenOrientation=window.orientation||0},i=function(){var t=new THREE.Vector3(0,0,1),e=new THREE.Euler,n=new THREE.Quaternion,r=new THREE.Quaternion(-Math.sqrt(.5),0,0,Math.sqrt(.5));return function(i,o,s,a,u){e.set(s,o,-a,"YXZ"),i.setFromEuler(e),i.multiply(r),i.multiply(n.setFromAxisAngle(t,-u))}}();this.connect=function(){r(),window.addEventListener("orientationchange",r,!1),window.addEventListener("deviceorientation",n,!1),e.freeze=!1},this.disconnect=function(){e.freeze=!0,window.removeEventListener("orientationchange",r,!1),window.removeEventListener("deviceorientation",n,!1)},this.update=function(){if(!e.freeze){var t=e.deviceOrientation.gamma?THREE.Math.degToRad(e.deviceOrientation.alpha):0,n=e.deviceOrientation.beta?THREE.Math.degToRad(e.deviceOrientation.beta):0,r=e.deviceOrientation.gamma?THREE.Math.degToRad(e.deviceOrientation.gamma):0,o=e.screenOrientation?THREE.Math.degToRad(e.screenOrientation):0;i(e.object.quaternion,t,n,r,o)}}},THREE.FirstPersonControls=function(t,e){function n(t,e){return function(){e.apply(t,arguments)}}this.object=t,this.target=new THREE.Vector3(0,0,0),this.domElement=void 0!==e?e:document,this.movementSpeed=1,this.lookSpeed=.005,this.lookVertical=!0,this.autoForward=!1,this.activeLook=!0,this.heightSpeed=!1,this.heightCoef=1,this.heightMin=0,this.heightMax=1,this.constrainVertical=!1,this.verticalMin=0,this.verticalMax=Math.PI,this.autoSpeedFactor=0,this.mouseX=0,this.mouseY=0,this.lat=0,this.lon=0,this.phi=0,this.theta=0,this.moveForward=!1,this.moveBackward=!1,this.moveLeft=!1,this.moveRight=!1,this.freeze=!1,this.mouseDragOn=!1,this.viewHalfX=0,this.viewHalfY=0,this.domElement!==document&&this.domElement.setAttribute("tabindex",-1),this.handleResize=function(){this.domElement===document?(this.viewHalfX=window.innerWidth/2,this.viewHalfY=window.innerHeight/2):(this.viewHalfX=this.domElement.offsetWidth/2,this.viewHalfY=this.domElement.offsetHeight/2)},this.onMouseDown=function(t){if(this.domElement!==document&&this.domElement.focus(),t.preventDefault(),t.stopPropagation(),this.activeLook)switch(t.button){case 0:this.moveForward=!0;break;case 2:this.moveBackward=!0}this.mouseDragOn=!0},this.onMouseUp=function(t){if(t.preventDefault(),t.stopPropagation(),this.activeLook)switch(t.button){case 0:this.moveForward=!1;break;case 2:this.moveBackward=!1}this.mouseDragOn=!1},this.onMouseMove=function(t){this.domElement===document?(this.mouseX=t.pageX-this.viewHalfX,this.mouseY=t.pageY-this.viewHalfY):(this.mouseX=t.pageX-this.domElement.offsetLeft-this.viewHalfX,this.mouseY=t.pageY-this.domElement.offsetTop-this.viewHalfY)},this.onKeyDown=function(t){switch(t.keyCode){case 38:case 87:this.moveForward=!0;break;case 37:case 65:this.moveLeft=!0;break;case 40:case 83:this.moveBackward=!0;break;case 39:case 68:this.moveRight=!0;break;case 82:this.moveUp=!0;break;case 70:this.moveDown=!0;break;case 81:this.freeze=!this.freeze}},this.onKeyUp=function(t){switch(t.keyCode){case 38:case 87:this.moveForward=!1;break;case 37:case 65:this.moveLeft=!1;break;case 40:case 83:this.moveBackward=!1;break;case 39:case 68:this.moveRight=!1;break;case 82:this.moveUp=!1;break;case 70:this.moveDown=!1}},this.update=function(t){if(!this.freeze){if(this.heightSpeed){var e=THREE.Math.clamp(this.object.position.y,this.heightMin,this.heightMax),n=e-this.heightMin;this.autoSpeedFactor=t*(n*this.heightCoef)}else this.autoSpeedFactor=0;var r=t*this.movementSpeed;(this.moveForward||this.autoForward&&!this.moveBackward)&&this.object.translateZ(-(r+this.autoSpeedFactor)),this.moveBackward&&this.object.translateZ(r),this.moveLeft&&this.object.translateX(-r),this.moveRight&&this.object.translateX(r),this.moveUp&&this.object.translateY(r),this.moveDown&&this.object.translateY(-r);var i=t*this.lookSpeed;this.activeLook||(i=0);var o=1;this.constrainVertical&&(o=Math.PI/(this.verticalMax-this.verticalMin)),this.lon+=this.mouseX*i,this.lookVertical&&(this.lat-=this.mouseY*i*o),this.lat=Math.max(-85,Math.min(85,this.lat)),this.phi=THREE.Math.degToRad(90-this.lat),this.theta=THREE.Math.degToRad(this.lon),this.constrainVertical&&(this.phi=THREE.Math.mapLinear(this.phi,0,Math.PI,this.verticalMin,this.verticalMax));var s=this.target,a=this.object.position;s.x=a.x+100*Math.sin(this.phi)*Math.cos(this.theta),s.y=a.y+100*Math.cos(this.phi),s.z=a.z+100*Math.sin(this.phi)*Math.sin(this.theta),this.object.lookAt(s)}},this.domElement.addEventListener("contextmenu",function(t){t.preventDefault()},!1),this.domElement.addEventListener("mousemove",n(this,this.onMouseMove),!1),this.domElement.addEventListener("mousedown",n(this,this.onMouseDown),!1),this.domElement.addEventListener("mouseup",n(this,this.onMouseUp),!1),this.domElement.addEventListener("keydown",n(this,this.onKeyDown),!1),this.domElement.addEventListener("keyup",n(this,this.onKeyUp),!1),this.handleResize()},THREE.OrbitControls=function(t,e){function n(){return 2*Math.PI/60/60*p.autoRotateSpeed}function r(){return Math.pow(.95,p.zoomSpeed)}function i(t){if(p.enabled!==!1){if(t.preventDefault(),0===t.button){if(p.noRotate===!0)return;C=A.ROTATE,d.set(t.clientX,t.clientY)}else if(1===t.button){if(p.noZoom===!0)return;C=A.DOLLY,T.set(t.clientX,t.clientY)}else if(2===t.button){if(p.noPan===!0)return;C=A.PAN,g.set(t.clientX,t.clientY)}document.documentElement.addEventListener("mousemove",o,!1),document.documentElement.addEventListener("mouseup",s,!1),p.dispatchEvent(O)}}function o(t){if(p.enabled!==!1){t.preventDefault();var e=p.domElement===document?p.domElement.body:p.domElement;if(C===A.ROTATE){if(p.noRotate===!0)return;m.set(t.clientX,t.clientY),v.subVectors(m,d),p.rotateLeft(2*Math.PI*v.x/e.clientWidth*p.rotateSpeed),p.rotateUp(2*Math.PI*v.y/e.clientHeight*p.rotateSpeed),d.copy(m)}else if(C===A.DOLLY){if(p.noZoom===!0)return;x.set(t.clientX,t.clientY),w.subVectors(x,T),w.y>0?p.dollyIn():p.dollyOut(),T.copy(x)}else if(C===A.PAN){if(p.noPan===!0)return;E.set(t.clientX,t.clientY),y.subVectors(E,g),p.pan(y.x,y.y),g.copy(E)}p.update()}}function s(){p.enabled!==!1&&(document.documentElement.removeEventListener("mousemove",o,!1),document.documentElement.removeEventListener("mouseup",s,!1),p.dispatchEvent(D),C=A.NONE)}function a(t){if(p.enabled!==!1&&p.noZoom!==!0){t.preventDefault(),t.stopPropagation();var e=0;void 0!==t.wheelDelta?e=t.wheelDelta:void 0!==t.detail&&(e=-t.detail),e>0?p.dollyOut():p.dollyIn(),p.update(),p.dispatchEvent(O),p.dispatchEvent(D)}}function u(t){if(p.enabled!==!1&&p.noKeys!==!0&&p.noPan!==!0)switch(t.keyCode){case p.keys.UP:p.pan(0,p.keyPanSpeed),p.update();break;case p.keys.BOTTOM:p.pan(0,-p.keyPanSpeed),p.update();break;case p.keys.LEFT:p.pan(p.keyPanSpeed,0),p.update();break;case p.keys.RIGHT:p.pan(-p.keyPanSpeed,0),p.update()}}function h(t){if(p.enabled!==!1){switch(t.touches.length){case 1:if(p.noRotate===!0)return;C=A.TOUCH_ROTATE,d.set(t.touches[0].pageX,t.touches[0].pageY);break;case 2:if(p.noZoom===!0)return;C=A.TOUCH_DOLLY;var e=t.touches[0].pageX-t.touches[1].pageX,n=t.touches[0].pageY-t.touches[1].pageY,r=Math.sqrt(e*e+n*n);T.set(0,r);break;case 3:if(p.noPan===!0)return;C=A.TOUCH_PAN,g.set(t.touches[0].pageX,t.touches[0].pageY);break;default:C=A.NONE}p.dispatchEvent(O)}}function l(t){if(p.enabled!==!1){t.preventDefault(),t.stopPropagation();var e=p.domElement===document?p.domElement.body:p.domElement;switch(t.touches.length){case 1:if(p.noRotate===!0)return;if(C!==A.TOUCH_ROTATE)return;m.set(t.touches[0].pageX,t.touches[0].pageY),v.subVectors(m,d),p.rotateLeft(2*Math.PI*v.x/e.clientWidth*p.rotateSpeed),p.rotateUp(2*Math.PI*v.y/e.clientHeight*p.rotateSpeed),d.copy(m),p.update();break;case 2:if(p.noZoom===!0)return;if(C!==A.TOUCH_DOLLY)return;var n=t.touches[0].pageX-t.touches[1].pageX,r=t.touches[0].pageY-t.touches[1].pageY,i=Math.sqrt(n*n+r*r);x.set(0,i),w.subVectors(x,T),w.y>0?p.dollyOut():p.dollyIn(),T.copy(x),p.update();break;case 3:if(p.noPan===!0)return;if(C!==A.TOUCH_PAN)return;E.set(t.touches[0].pageX,t.touches[0].pageY),y.subVectors(E,g),p.pan(y.x,y.y),g.copy(E),p.update();break;default:C=A.NONE}}}function c(){p.enabled!==!1&&(p.dispatchEvent(D),C=A.NONE)}this.object=t,this.domElement=void 0!==e?e:document,this.enabled=!0,this.target=new THREE.Vector3,this.center=this.target,this.noZoom=!1,this.zoomSpeed=1,this.minDistance=0,this.maxDistance=1/0,this.noRotate=!1,this.rotateSpeed=1,this.noPan=!1,this.keyPanSpeed=7,this.autoRotate=!1,this.autoRotateSpeed=2,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.noKeys=!1,this.keys={LEFT:37,UP:38,RIGHT:39,BOTTOM:40};var p=this,f=1e-6,d=new THREE.Vector2,m=new THREE.Vector2,v=new THREE.Vector2,g=new THREE.Vector2,E=new THREE.Vector2,y=new THREE.Vector2,_=new THREE.Vector3,b=new THREE.Vector3,T=new THREE.Vector2,x=new THREE.Vector2,w=new THREE.Vector2,R=0,H=0,M=1,S=new THREE.Vector3,k=new THREE.Vector3,A={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_DOLLY:4,TOUCH_PAN:5},C=A.NONE;this.target0=this.target.clone(),this.position0=this.object.position.clone();var P=(new THREE.Quaternion).setFromUnitVectors(t.up,new THREE.Vector3(0,1,0)),L=P.clone().inverse(),z={type:"change"},O={type:"start"},D={type:"end"};this.rotateLeft=function(t){void 0===t&&(t=n()),H-=t},this.rotateUp=function(t){void 0===t&&(t=n()),R-=t},this.panLeft=function(t){var e=this.object.matrix.elements;_.set(e[0],e[1],e[2]),_.multiplyScalar(-t),S.add(_)},this.panUp=function(t){var e=this.object.matrix.elements;_.set(e[4],e[5],e[6]),_.multiplyScalar(t),S.add(_)},this.pan=function(t,e){var n=p.domElement===document?p.domElement.body:p.domElement;if(void 0!==p.object.fov){var r=p.object.position,i=r.clone().sub(p.target),o=i.length();o*=Math.tan(p.object.fov/2*Math.PI/180),p.panLeft(2*t*o/n.clientHeight),p.panUp(2*e*o/n.clientHeight)}else void 0!==p.object.top?(p.panLeft(t*(p.object.right-p.object.left)/n.clientWidth),p.panUp(e*(p.object.top-p.object.bottom)/n.clientHeight)):console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.")},this.dollyIn=function(t){void 0===t&&(t=r()),M/=t},this.dollyOut=function(t){void 0===t&&(t=r()),M*=t},this.update=function(){var t=this.object.position;b.copy(t).sub(this.target),b.applyQuaternion(P);var e=Math.atan2(b.x,b.z),r=Math.atan2(Math.sqrt(b.x*b.x+b.z*b.z),b.y);this.autoRotate&&this.rotateLeft(n()),e+=H,r+=R,r=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,r)),r=Math.max(f,Math.min(Math.PI-f,r));var i=b.length()*M;i=Math.max(this.minDistance,Math.min(this.maxDistance,i)),this.target.add(S),b.x=i*Math.sin(r)*Math.sin(e),b.y=i*Math.cos(r),b.z=i*Math.sin(r)*Math.cos(e),b.applyQuaternion(L),t.copy(this.target).add(b),this.object.lookAt(this.target),H=0,R=0,M=1,S.set(0,0,0),k.distanceToSquared(this.object.position)>f&&(this.dispatchEvent(z),k.copy(this.object.position))},this.reset=function(){C=A.NONE,this.target.copy(this.target0),this.object.position.copy(this.position0),this.update()},this.domElement.addEventListener("contextmenu",function(t){t.preventDefault()},!1),this.domElement.addEventListener("mousedown",i,!1),this.domElement.addEventListener("mousewheel",a,!1),this.domElement.addEventListener("DOMMouseScroll",a,!1),this.domElement.addEventListener("touchstart",h,!1),this.domElement.addEventListener("touchend",c,!1),this.domElement.addEventListener("touchmove",l,!1),window.addEventListener("keydown",u,!1),this.update()},THREE.OrbitControls.prototype=Object.create(THREE.EventDispatcher.prototype),THREE.TrackballControls=function(t,e){function n(t){c.enabled!==!1&&(window.removeEventListener("keydown",n),v=m,m===p.NONE&&(t.keyCode!==c.keys[p.ROTATE]||c.noRotate?t.keyCode!==c.keys[p.ZOOM]||c.noZoom?t.keyCode!==c.keys[p.PAN]||c.noPan||(m=p.PAN):m=p.ZOOM:m=p.ROTATE))}function r(t){c.enabled!==!1&&(m=v,window.addEventListener("keydown",n,!1))}function i(t){c.enabled!==!1&&(t.preventDefault(),t.stopPropagation(),m===p.NONE&&(m=t.button),m!==p.ROTATE||c.noRotate?m!==p.ZOOM||c.noZoom?m!==p.PAN||c.noPan||(H.copy(C(t.pageX,t.pageY)),M.copy(H)):(T.copy(C(t.pageX,t.pageY)),x.copy(T)):(y.copy(P(t.pageX,t.pageY)),E.copy(y)),document.addEventListener("mousemove",o,!1),document.addEventListener("mouseup",s,!1),c.dispatchEvent(k))}function o(t){c.enabled!==!1&&(t.preventDefault(),t.stopPropagation(),m!==p.ROTATE||c.noRotate?m!==p.ZOOM||c.noZoom?m!==p.PAN||c.noPan||M.copy(C(t.pageX,t.pageY)):x.copy(C(t.pageX,t.pageY)):(E.copy(y),y.copy(P(t.pageX,t.pageY))))}function s(t){c.enabled!==!1&&(t.preventDefault(),t.stopPropagation(),m=p.NONE,document.removeEventListener("mousemove",o),document.removeEventListener("mouseup",s),c.dispatchEvent(A))}function a(t){if(c.enabled!==!1&&!c.noZoom){t.preventDefault(),t.stopPropagation();var e=0;t.wheelDelta?e=t.wheelDelta/40:t.detail&&(e=-t.detail/3),T.y+=.01*e,c.dispatchEvent(k),c.dispatchEvent(A)}}function u(t){if(c.enabled!==!1){switch(t.touches.length){case 1:m=p.TOUCH_ROTATE,y.copy(P(t.touches[0].pageX,t.touches[0].pageY)),E.copy(y);break;case 2:m=p.TOUCH_ZOOM_PAN;var e=t.touches[0].pageX-t.touches[1].pageX,n=t.touches[0].pageY-t.touches[1].pageY;R=w=Math.sqrt(e*e+n*n);var r=(t.touches[0].pageX+t.touches[1].pageX)/2,i=(t.touches[0].pageY+t.touches[1].pageY)/2;H.copy(C(r,i)),M.copy(H);break;default:m=p.NONE}c.dispatchEvent(k)}}function h(t){if(c.enabled!==!1)switch(t.preventDefault(),t.stopPropagation(),t.touches.length){case 1:E.copy(y),y.copy(P(t.touches[0].pageX,t.touches[0].pageY));break;case 2:var e=t.touches[0].pageX-t.touches[1].pageX,n=t.touches[0].pageY-t.touches[1].pageY;R=Math.sqrt(e*e+n*n);var r=(t.touches[0].pageX+t.touches[1].pageX)/2,i=(t.touches[0].pageY+t.touches[1].pageY)/2;M.copy(C(r,i));break;default:m=p.NONE}}function l(t){if(c.enabled!==!1){switch(t.touches.length){case 1:E.copy(y),y.copy(P(t.touches[0].pageX,t.touches[0].pageY));break;case 2:w=R=0;var e=(t.touches[0].pageX+t.touches[1].pageX)/2,n=(t.touches[0].pageY+t.touches[1].pageY)/2;M.copy(C(e,n)),H.copy(M)}m=p.NONE,c.dispatchEvent(A)}}var c=this,p={NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM_PAN:4};this.object=t,this.domElement=void 0!==e?e:document,this.enabled=!0,this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.keys=[65,83,68],this.target=new THREE.Vector3;var f=1e-6,d=new THREE.Vector3,m=p.NONE,v=p.NONE,g=new THREE.Vector3,E=new THREE.Vector2,y=new THREE.Vector2,_=new THREE.Vector3,b=0,T=new THREE.Vector2,x=new THREE.Vector2,w=0,R=0,H=new THREE.Vector2,M=new THREE.Vector2;this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.up0=this.object.up.clone();var S={type:"change"},k={type:"start"},A={type:"end"};this.handleResize=function(){if(this.domElement===document)this.screen.left=0,this.screen.top=0,this.screen.width=window.innerWidth,this.screen.height=window.innerHeight;else{var t=this.domElement.getBoundingClientRect(),e=this.domElement.ownerDocument.documentElement;this.screen.left=t.left+window.pageXOffset-e.clientLeft,this.screen.top=t.top+window.pageYOffset-e.clientTop,this.screen.width=t.width,this.screen.height=t.height}},this.handleEvent=function(t){"function"==typeof this[t.type]&&this[t.type](t)};var C=function(){var t=new THREE.Vector2;return function(e,n){return t.set((e-c.screen.left)/c.screen.width,(n-c.screen.top)/c.screen.height),t}}(),P=function(){var t=new THREE.Vector2;return function(e,n){return t.set((e-.5*c.screen.width-c.screen.left)/(.5*c.screen.width),(c.screen.height+2*(c.screen.top-n))/c.screen.width),t}}();this.rotateCamera=function(){var t,e=new THREE.Vector3,n=new THREE.Quaternion,r=new THREE.Vector3,i=new THREE.Vector3,o=new THREE.Vector3,s=new THREE.Vector3;return function(){s.set(y.x-E.x,y.y-E.y,0),t=s.length(),t?(g.copy(c.object.position).sub(c.target),r.copy(g).normalize(),i.copy(c.object.up).normalize(),o.crossVectors(i,r).normalize(),i.setLength(y.y-E.y),o.setLength(y.x-E.x),s.copy(i.add(o)),e.crossVectors(s,g).normalize(),t*=c.rotateSpeed,n.setFromAxisAngle(e,t),g.applyQuaternion(n),c.object.up.applyQuaternion(n),_.copy(e),b=t):!c.staticMoving&&b&&(b*=Math.sqrt(1-c.dynamicDampingFactor),g.copy(c.object.position).sub(c.target),n.setFromAxisAngle(_,b),g.applyQuaternion(n),c.object.up.applyQuaternion(n)),E.copy(y)}}(),this.zoomCamera=function(){var t;m===p.TOUCH_ZOOM_PAN?(t=w/R,w=R,g.multiplyScalar(t)):(t=1+(x.y-T.y)*c.zoomSpeed,1!==t&&t>0&&(g.multiplyScalar(t),c.staticMoving?T.copy(x):T.y+=(x.y-T.y)*this.dynamicDampingFactor))},this.panCamera=function(){var t=new THREE.Vector2,e=new THREE.Vector3,n=new THREE.Vector3;return function(){t.copy(M).sub(H),t.lengthSq()&&(t.multiplyScalar(g.length()*c.panSpeed),n.copy(g).cross(c.object.up).setLength(t.x), +n.add(e.copy(c.object.up).setLength(t.y)),c.object.position.add(n),c.target.add(n),c.staticMoving?H.copy(M):H.add(t.subVectors(M,H).multiplyScalar(c.dynamicDampingFactor)))}}(),this.checkDistances=function(){c.noZoom&&c.noPan||(g.lengthSq()>c.maxDistance*c.maxDistance&&c.object.position.addVectors(c.target,g.setLength(c.maxDistance)),g.lengthSq()f&&(c.dispatchEvent(S),d.copy(c.object.position))},this.reset=function(){m=p.NONE,v=p.NONE,c.target.copy(c.target0),c.object.position.copy(c.position0),c.object.up.copy(c.up0),g.subVectors(c.object.position,c.target),c.object.lookAt(c.target),c.dispatchEvent(S),d.copy(c.object.position)},this.domElement.addEventListener("contextmenu",function(t){t.preventDefault()},!1),this.domElement.addEventListener("mousedown",i,!1),this.domElement.addEventListener("mousewheel",a,!1),this.domElement.addEventListener("DOMMouseScroll",a,!1),this.domElement.addEventListener("touchstart",u,!1),this.domElement.addEventListener("touchend",l,!1),this.domElement.addEventListener("touchmove",h,!1),window.addEventListener("keydown",n,!1),window.addEventListener("keyup",r,!1),this.handleResize(),this.update()},THREE.TrackballControls.prototype=Object.create(THREE.EventDispatcher.prototype),THREE.TrackballControls.prototype.constructor=THREE.TrackballControls,THREE.VRControls=function(t,e){var n=1e-5,r=this.dummy=new THREE.Object3D;this.object=t,this.device=new THREE.DeviceOrientationControls(r,e),this.orbit=new THREE.OrbitControls(r,e),this.orbit.target.copy(t.position),this.orbit.target.z+=n,this.orbit.rotateSpeed=-.25,this.supported=!1;var i=function(t){this.supported=t&&t.alpha==+t.alpha,window.removeEventListener("deviceorientation",i,!1)}.bind(this);window.addEventListener("deviceorientation",i,!1)},THREE.VRControls.prototype.vr=function(t){this.vrstate=t},THREE.VRControls.prototype.update=function(t){var e=!1;this.vrstate&&this.vrstate.orientation?(e=!0,this.object.quaternion.copy(this.vrstate.orientation),this.object.position.copy(this.vrstate.position),this.device.object=this.dummy,this.orbit.object=this.dummy):this.vrstate&&this.supported?(this.device.freeze&&this.device.connect(),this.device.object=this.object,this.orbit.object=this.dummy,this.device.update(t)):(e=!0,this.device.object=this.dummy,this.orbit.object=this.object,this.orbit.update(t)),e&&!this.device.freeze&&this.device.disconnect()},THREE.Bootstrap.registerPlugin("stats",{listen:["pre","post"],install:function(t){var e=this.stats=new THREE.Stats,n=e.domElement.style;n.position="absolute",n.top=n.left=0,t.element.appendChild(e.domElement),t.stats=e},uninstall:function(t){document.body.removeChild(this.stats.domElement),delete t.stats},pre:function(t,e){this.stats.begin()},post:function(t,e){this.stats.end()}}),THREE.Bootstrap.registerPlugin("controls",{listen:["update","resize","camera","this.change"],defaults:{klass:null,parameters:{}},install:function(t){if(!this.options.klass)throw"Must provide class for `controls.klass`";t.controls=null,this._camera=t.camera||new THREE.PerspectiveCamera,this.change(null,t)},uninstall:function(t){delete t.controls},change:function(t,e){this.options.klass?((!t||t.changes.klass)&&(e.controls=new this.options.klass(this._camera,e.renderer.domElement)),_.extend(e.controls,this.options.parameters)):e.controls=null},update:function(t,e){var n=e.Time&&e.Time.delta||1/60,r=e.VR&&e.VR.state;e.controls.vr&&e.controls.vr(r),e.controls.update(n)},camera:function(t,e){e.controls.object=this._camera=t.camera},resize:function(t,e){e.controls.handleResize&&e.controls.handleResize()}}),THREE.Bootstrap.registerPlugin("cursor",{listen:["update","this.change","install:change","uninstall:change","element.mousemove","vr"],defaults:{cursor:null,hide:!1,timeout:3},install:function(t){this.timeout=this.options.timeout,this.element=t.element,this.change(null,t)},uninstall:function(t){delete t.controls},change:function(t,e){this.applyCursor(e)},mousemove:function(t,e){this.options.hide&&(this.applyCursor(e),this.timeout=+this.options.timeout||0)},update:function(t,e){var n=e.Time&&e.Time.delta||1/60;this.options.hide&&(this.timeout-=n,this.timeout<0&&this.applyCursor(e,"none"))},vr:function(t,e){this.hide=t.active&&!t.hmd.fake,this.applyCursor(e)},applyCursor:function(t,e){var n=t.controls?"move":"";e=e||this.options.cursor||n,this.hide&&(e="none"),this.cursor!=e&&(this.element.style.cursor=e)}}),THREE.Bootstrap.registerPlugin("fullscreen",{defaults:{key:"f"},listen:["ready","update"],install:function(t){t.Fullscreen=this.api({active:!1,toggle:this.toggle.bind(this)},t)},uninstall:function(t){delete t.Fullscreen},ready:function(t,e){document.body.addEventListener("keypress",function(t){this.options.key&&t.charCode==this.options.key.charCodeAt(0)&&this.toggle(e)}.bind(this));var n=function(){var t=!!(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement);e.Fullscreen.active=this.active=t,e.trigger({type:"fullscreen",active:t})}.bind(this);document.addEventListener("fullscreenchange",n,!1),document.addEventListener("webkitfullscreenchange",n,!1),document.addEventListener("mozfullscreenchange",n,!1)},toggle:function(t){var e=t.canvas,n=t.VR&&t.VR.active?{vrDisplay:t.VR.hmd}:{};this.active?document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.webkitExitFullscreen?document.webkitExitFullscreen():document.mozCancelFullScreen&&document.mozCancelFullScreen():e.requestFullScreen?e.requestFullScreen(n):e.msRequestFullScreen?e.msRequestFullscreen(n):e.webkitRequestFullscreen?e.webkitRequestFullscreen(n):e.mozRequestFullScreen&&e.mozRequestFullScreen(n)}}),THREE.Bootstrap.registerPlugin("vr",{defaults:{mode:"auto",device:null,fov:80},listen:["window.load","pre","render","resize","this.change"],install:function(t){t.VR=this.api({active:!1,devices:[],hmd:null,sensor:null,renderer:null,state:null},t)},uninstall:function(t){delete t.VR},mocks:function(t,e,n){var r=.03,i=function(t){return{left:{x:-r,y:0,z:0},right:{x:r,y:0,z:0}}[t]},o=function(r){var i=t.camera,o=i&&i.aspect||16/9,s=(e||i&&i.fov||n)/2,a=180*Math.atan(Math.tan(s*Math.PI/180)*o/2)/Math.PI,u=s;return{left:{rightDegrees:a,leftDegrees:a,downDegrees:u,upDegrees:u},right:{rightDegrees:a,leftDegrees:a,downDegrees:u,upDegrees:u}}[r]},s=function(){return{}};return[{fake:!0,force:1,deviceId:"emu",deviceName:"Emulated",getEyeTranslation:i,getRecommendedEyeFieldOfView:o},{force:2,getState:s}]},load:function(t,e){var n=function(t){this.callback(t,e)}.bind(this);navigator.getVRDevices?navigator.getVRDevices().then(n):navigator.mozGetVRDevices?navigator.mozGetVRDevices(n):(console.warn("No native VR support detected."),n(this.mocks(e,this.options.fov,this.defaults.fov),e))},callback:function(t,e){var n,r,i=window.HMDVRDevice||function(){},o=window.PositionSensorVRDevice||function(){};t=e.VR.devices=t||e.VR.devices;for(var s=this.options.device,a=0;a'),t.VR&&i.push(''),'
'+i.join("\n")+"
"},install:function(t){var e=this.ui=document.createElement("div");e.innerHTML=this.markup(t,this.options.theme,this.options.style),document.body.appendChild(e);var n=this.ui.fullscreen=e.querySelector("button.fullscreen");n&&t.bind([n,"click:goFullscreen"],this);var r=this.ui.vr=e.querySelector("button.vr");r&&t.VR&&(t.VR.set({mode:"2d"}),t.bind([r,"click:goVR"],this))},uninstall:function(t){document.body.removeChild(ui)},fullscreen:function(t,e){this.ui.style.display=t.active?"none":"block",t.active||e.VR&&e.VR.set({mode:"2d"})},goFullscreen:function(t,e){e.Fullscreen&&e.Fullscreen.toggle()},goVR:function(t,e){e.VR&&(e.VR.set({mode:"auto"}),e.Fullscreen.toggle())},uninstall:function(t){document.body.removeChild(this.ui)}}),THREE.VRRenderer=function(t,e){var n=this;n.initialize=function(){var t=e.getEyeTranslation("left");n.halfIPD=new THREE.Vector3(t.x,t.y,t.z).length(),n.fovLeft=e.getRecommendedEyeFieldOfView("left"),n.fovRight=e.getRecommendedEyeFieldOfView("right")},n.FovToNDCScaleOffset=function(t){var e=2/(t.leftTan+t.rightTan),n=(t.leftTan-t.rightTan)*e*.5,r=2/(t.upTan+t.downTan),i=(t.upTan-t.downTan)*r*.5;return{scale:[e,r],offset:[n,i]}},n.FovPortToProjection=function(t,e,r,i,o){r=void 0===r?!0:r,i=void 0===i?.01:i,o=void 0===o?1e4:o;var s=r?-1:1,a=t.elements,u=n.FovToNDCScaleOffset(e);a[0]=u.scale[0],a[1]=0,a[2]=u.offset[0]*s,a[3]=0,a[4]=0,a[5]=u.scale[1],a[6]=-u.offset[1]*s,a[7]=0,a[8]=0,a[9]=0,a[10]=o/(i-o)*-s,a[11]=o*i/(i-o),a[12]=0,a[13]=0,a[14]=s,a[15]=0,t.transpose()},n.FovToProjection=function(t,e,r,i,o){var s={upTan:Math.tan(e.upDegrees*Math.PI/180),downTan:Math.tan(e.downDegrees*Math.PI/180),leftTan:Math.tan(e.leftDegrees*Math.PI/180),rightTan:Math.tan(e.rightDegrees*Math.PI/180)};return n.FovPortToProjection(t,s,r,i,o)};var r=new THREE.Vector3,i=new THREE.PerspectiveCamera,o=new THREE.PerspectiveCamera;n.render=function(e,s){n.FovToProjection(i.projectionMatrix,n.fovLeft,!0,s.near,s.far),n.FovToProjection(o.projectionMatrix,n.fovRight,!0,s.near,s.far),r.set(n.halfIPD,0,0),r.applyQuaternion(s.quaternion),i.position.copy(s.position).sub(r),o.position.copy(s.position).add(r),i.quaternion.copy(s.quaternion),o.quaternion.copy(s.quaternion);var a=t.devicePixelRatio||1,u=t.domElement.width/2/a,h=t.domElement.height/a;t.enableScissorTest(!0),t.setViewport(0,0,u,h),t.setScissor(0,0,u,h),t.render(e,i),t.setViewport(u,0,u,h),t.setScissor(u,0,u,h),t.render(e,o)},n.initialize()},THREE.VRControls=function(t,e){var n=1e-5,r=this.dummy=new THREE.Object3D;this.object=t,this.device=new THREE.DeviceOrientationControls(r,e),this.orbit=new THREE.OrbitControls(r,e),this.orbit.target.copy(t.position),this.orbit.target.z+=n,this.orbit.rotateSpeed=-.25,this.supported=!1;var i=function(t){this.supported=t&&t.alpha==+t.alpha,window.removeEventListener("deviceorientation",i,!1)}.bind(this);window.addEventListener("deviceorientation",i,!1)},THREE.VRControls.prototype.vr=function(t){this.vrstate=t},THREE.VRControls.prototype.update=function(t){var e=!1;this.vrstate&&this.vrstate.orientation?(e=!0,this.object.quaternion.copy(this.vrstate.orientation),this.object.position.copy(this.vrstate.position),this.device.object=this.dummy,this.orbit.object=this.dummy):this.vrstate&&this.supported?(this.device.freeze&&this.device.connect(),this.device.object=this.object,this.orbit.object=this.dummy,this.device.update(t)):(e=!0,this.device.object=this.dummy,this.orbit.object=this.object,this.orbit.update(t)),e&&!this.device.freeze&&this.device.disconnect()},THREE.OrbitControls=function(t,e){function n(){return 2*Math.PI/60/60*p.autoRotateSpeed}function r(){return Math.pow(.95,p.zoomSpeed)}function i(t){if(p.enabled!==!1){if(t.preventDefault(),0===t.button){if(p.noRotate===!0)return;C=A.ROTATE,d.set(t.clientX,t.clientY)}else if(1===t.button){if(p.noZoom===!0)return;C=A.DOLLY,T.set(t.clientX,t.clientY)}else if(2===t.button){if(p.noPan===!0)return;C=A.PAN,g.set(t.clientX,t.clientY)}document.documentElement.addEventListener("mousemove",o,!1),document.documentElement.addEventListener("mouseup",s,!1),p.dispatchEvent(O)}}function o(t){if(p.enabled!==!1){t.preventDefault();var e=p.domElement===document?p.domElement.body:p.domElement;if(C===A.ROTATE){if(p.noRotate===!0)return;m.set(t.clientX,t.clientY),v.subVectors(m,d),p.rotateLeft(2*Math.PI*v.x/e.clientWidth*p.rotateSpeed),p.rotateUp(2*Math.PI*v.y/e.clientHeight*p.rotateSpeed),d.copy(m)}else if(C===A.DOLLY){if(p.noZoom===!0)return;x.set(t.clientX,t.clientY),w.subVectors(x,T),w.y>0?p.dollyIn():p.dollyOut(),T.copy(x)}else if(C===A.PAN){if(p.noPan===!0)return;E.set(t.clientX,t.clientY),y.subVectors(E,g),p.pan(y.x,y.y),g.copy(E)}p.update()}}function s(){p.enabled!==!1&&(document.documentElement.removeEventListener("mousemove",o,!1),document.documentElement.removeEventListener("mouseup",s,!1),p.dispatchEvent(D),C=A.NONE)}function a(t){if(p.enabled!==!1&&p.noZoom!==!0){t.preventDefault(),t.stopPropagation();var e=0;void 0!==t.wheelDelta?e=t.wheelDelta:void 0!==t.detail&&(e=-t.detail),e>0?p.dollyOut():p.dollyIn(),p.update(),p.dispatchEvent(O),p.dispatchEvent(D)}}function u(t){if(p.enabled!==!1&&p.noKeys!==!0&&p.noPan!==!0)switch(t.keyCode){case p.keys.UP:p.pan(0,p.keyPanSpeed),p.update();break;case p.keys.BOTTOM:p.pan(0,-p.keyPanSpeed),p.update();break;case p.keys.LEFT:p.pan(p.keyPanSpeed,0),p.update();break;case p.keys.RIGHT:p.pan(-p.keyPanSpeed,0),p.update()}}function h(t){if(p.enabled!==!1){switch(t.touches.length){case 1:if(p.noRotate===!0)return;C=A.TOUCH_ROTATE,d.set(t.touches[0].pageX,t.touches[0].pageY);break;case 2:if(p.noZoom===!0)return;C=A.TOUCH_DOLLY;var e=t.touches[0].pageX-t.touches[1].pageX,n=t.touches[0].pageY-t.touches[1].pageY,r=Math.sqrt(e*e+n*n);T.set(0,r);break;case 3:if(p.noPan===!0)return;C=A.TOUCH_PAN,g.set(t.touches[0].pageX,t.touches[0].pageY);break;default:C=A.NONE}p.dispatchEvent(O)}}function l(t){if(p.enabled!==!1){t.preventDefault(),t.stopPropagation();var e=p.domElement===document?p.domElement.body:p.domElement;switch(t.touches.length){case 1:if(p.noRotate===!0)return;if(C!==A.TOUCH_ROTATE)return;m.set(t.touches[0].pageX,t.touches[0].pageY),v.subVectors(m,d),p.rotateLeft(2*Math.PI*v.x/e.clientWidth*p.rotateSpeed),p.rotateUp(2*Math.PI*v.y/e.clientHeight*p.rotateSpeed),d.copy(m),p.update();break;case 2:if(p.noZoom===!0)return;if(C!==A.TOUCH_DOLLY)return;var n=t.touches[0].pageX-t.touches[1].pageX,r=t.touches[0].pageY-t.touches[1].pageY,i=Math.sqrt(n*n+r*r);x.set(0,i),w.subVectors(x,T),w.y>0?p.dollyOut():p.dollyIn(),T.copy(x),p.update();break;case 3:if(p.noPan===!0)return;if(C!==A.TOUCH_PAN)return;E.set(t.touches[0].pageX,t.touches[0].pageY),y.subVectors(E,g),p.pan(y.x,y.y),g.copy(E),p.update();break;default:C=A.NONE}}}function c(){p.enabled!==!1&&(p.dispatchEvent(D),C=A.NONE)}this.object=t,this.domElement=void 0!==e?e:document,this.enabled=!0,this.target=new THREE.Vector3,this.center=this.target,this.noZoom=!1,this.zoomSpeed=1,this.minDistance=0,this.maxDistance=1/0,this.noRotate=!1,this.rotateSpeed=1,this.noPan=!1,this.keyPanSpeed=7,this.autoRotate=!1,this.autoRotateSpeed=2,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.noKeys=!1,this.keys={LEFT:37,UP:38,RIGHT:39,BOTTOM:40};var p=this,f=1e-6,d=new THREE.Vector2,m=new THREE.Vector2,v=new THREE.Vector2,g=new THREE.Vector2,E=new THREE.Vector2,y=new THREE.Vector2,_=new THREE.Vector3,b=new THREE.Vector3,T=new THREE.Vector2,x=new THREE.Vector2,w=new THREE.Vector2,R=0,H=0,M=1,S=new THREE.Vector3,k=new THREE.Vector3,A={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_DOLLY:4,TOUCH_PAN:5},C=A.NONE;this.target0=this.target.clone(),this.position0=this.object.position.clone();var P=(new THREE.Quaternion).setFromUnitVectors(t.up,new THREE.Vector3(0,1,0)),L=P.clone().inverse(),z={type:"change"},O={type:"start"},D={type:"end"};this.rotateLeft=function(t){void 0===t&&(t=n()),H-=t},this.rotateUp=function(t){void 0===t&&(t=n()),R-=t},this.panLeft=function(t){var e=this.object.matrix.elements;_.set(e[0],e[1],e[2]),_.multiplyScalar(-t),S.add(_)},this.panUp=function(t){var e=this.object.matrix.elements;_.set(e[4],e[5],e[6]),_.multiplyScalar(t),S.add(_)},this.pan=function(t,e){var n=p.domElement===document?p.domElement.body:p.domElement;if(void 0!==p.object.fov){var r=p.object.position,i=r.clone().sub(p.target),o=i.length();o*=Math.tan(p.object.fov/2*Math.PI/180),p.panLeft(2*t*o/n.clientHeight),p.panUp(2*e*o/n.clientHeight)}else void 0!==p.object.top?(p.panLeft(t*(p.object.right-p.object.left)/n.clientWidth),p.panUp(e*(p.object.top-p.object.bottom)/n.clientHeight)):console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.")},this.dollyIn=function(t){void 0===t&&(t=r()),M/=t},this.dollyOut=function(t){void 0===t&&(t=r()),M*=t},this.update=function(){var t=this.object.position;b.copy(t).sub(this.target),b.applyQuaternion(P);var e=Math.atan2(b.x,b.z),r=Math.atan2(Math.sqrt(b.x*b.x+b.z*b.z),b.y);this.autoRotate&&this.rotateLeft(n()),e+=H,r+=R,r=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,r)),r=Math.max(f,Math.min(Math.PI-f,r));var i=b.length()*M;i=Math.max(this.minDistance,Math.min(this.maxDistance,i)),this.target.add(S),b.x=i*Math.sin(r)*Math.sin(e),b.y=i*Math.cos(r),b.z=i*Math.sin(r)*Math.cos(e),b.applyQuaternion(L),t.copy(this.target).add(b),this.object.lookAt(this.target),H=0,R=0,M=1,S.set(0,0,0),k.distanceToSquared(this.object.position)>f&&(this.dispatchEvent(z),k.copy(this.object.position))},this.reset=function(){C=A.NONE,this.target.copy(this.target0),this.object.position.copy(this.position0),this.update()},this.domElement.addEventListener("contextmenu",function(t){t.preventDefault()},!1),this.domElement.addEventListener("mousedown",i,!1),this.domElement.addEventListener("mousewheel",a,!1),this.domElement.addEventListener("DOMMouseScroll",a,!1),this.domElement.addEventListener("touchstart",h,!1),this.domElement.addEventListener("touchend",c,!1),this.domElement.addEventListener("touchmove",l,!1),window.addEventListener("keydown",u,!1),this.update()},THREE.OrbitControls.prototype=Object.create(THREE.EventDispatcher.prototype),THREE.DeviceOrientationControls=function(t){var e=this;this.object=t,this.object.rotation.reorder("YXZ"),this.freeze=!0,this.deviceOrientation={},this.screenOrientation=0;var n=function(t){e.deviceOrientation=t},r=function(){e.screenOrientation=window.orientation||0},i=function(){var t=new THREE.Vector3(0,0,1),e=new THREE.Euler,n=new THREE.Quaternion,r=new THREE.Quaternion(-Math.sqrt(.5),0,0,Math.sqrt(.5));return function(i,o,s,a,u){e.set(s,o,-a,"YXZ"),i.setFromEuler(e),i.multiply(r),i.multiply(n.setFromAxisAngle(t,-u))}}();this.connect=function(){r(),window.addEventListener("orientationchange",r,!1),window.addEventListener("deviceorientation",n,!1),e.freeze=!1},this.disconnect=function(){e.freeze=!0,window.removeEventListener("orientationchange",r,!1),window.removeEventListener("deviceorientation",n,!1)},this.update=function(){if(!e.freeze){var t=e.deviceOrientation.gamma?THREE.Math.degToRad(e.deviceOrientation.alpha):0,n=e.deviceOrientation.beta?THREE.Math.degToRad(e.deviceOrientation.beta):0,r=e.deviceOrientation.gamma?THREE.Math.degToRad(e.deviceOrientation.gamma):0,o=e.screenOrientation?THREE.Math.degToRad(e.screenOrientation):0;i(e.object.quaternion,t,n,r,o)}}},THREE.TrackballControls=function(t,e){function n(t){c.enabled!==!1&&(window.removeEventListener("keydown",n),v=m,m===p.NONE&&(t.keyCode!==c.keys[p.ROTATE]||c.noRotate?t.keyCode!==c.keys[p.ZOOM]||c.noZoom?t.keyCode!==c.keys[p.PAN]||c.noPan||(m=p.PAN):m=p.ZOOM:m=p.ROTATE))}function r(t){c.enabled!==!1&&(m=v,window.addEventListener("keydown",n,!1))}function i(t){c.enabled!==!1&&(t.preventDefault(),t.stopPropagation(),m===p.NONE&&(m=t.button),m!==p.ROTATE||c.noRotate?m!==p.ZOOM||c.noZoom?m!==p.PAN||c.noPan||(H.copy(C(t.pageX,t.pageY)),M.copy(H)):(T.copy(C(t.pageX,t.pageY)),x.copy(T)):(y.copy(P(t.pageX,t.pageY)),E.copy(y)),document.addEventListener("mousemove",o,!1),document.addEventListener("mouseup",s,!1),c.dispatchEvent(k))}function o(t){c.enabled!==!1&&(t.preventDefault(),t.stopPropagation(),m!==p.ROTATE||c.noRotate?m!==p.ZOOM||c.noZoom?m!==p.PAN||c.noPan||M.copy(C(t.pageX,t.pageY)):x.copy(C(t.pageX,t.pageY)):(E.copy(y),y.copy(P(t.pageX,t.pageY))))}function s(t){c.enabled!==!1&&(t.preventDefault(),t.stopPropagation(),m=p.NONE,document.removeEventListener("mousemove",o),document.removeEventListener("mouseup",s),c.dispatchEvent(A))}function a(t){if(c.enabled!==!1&&!c.noZoom){t.preventDefault(),t.stopPropagation();var e=0;t.wheelDelta?e=t.wheelDelta/40:t.detail&&(e=-t.detail/3),T.y+=.01*e,c.dispatchEvent(k),c.dispatchEvent(A)}}function u(t){if(c.enabled!==!1){switch(t.touches.length){case 1:m=p.TOUCH_ROTATE,y.copy(P(t.touches[0].pageX,t.touches[0].pageY)),E.copy(y);break;case 2:m=p.TOUCH_ZOOM_PAN;var e=t.touches[0].pageX-t.touches[1].pageX,n=t.touches[0].pageY-t.touches[1].pageY;R=w=Math.sqrt(e*e+n*n);var r=(t.touches[0].pageX+t.touches[1].pageX)/2,i=(t.touches[0].pageY+t.touches[1].pageY)/2;H.copy(C(r,i)),M.copy(H);break;default:m=p.NONE}c.dispatchEvent(k)}}function h(t){if(c.enabled!==!1)switch(t.preventDefault(),t.stopPropagation(),t.touches.length){case 1:E.copy(y),y.copy(P(t.touches[0].pageX,t.touches[0].pageY));break;case 2:var e=t.touches[0].pageX-t.touches[1].pageX,n=t.touches[0].pageY-t.touches[1].pageY;R=Math.sqrt(e*e+n*n);var r=(t.touches[0].pageX+t.touches[1].pageX)/2,i=(t.touches[0].pageY+t.touches[1].pageY)/2;M.copy(C(r,i));break;default:m=p.NONE}}function l(t){if(c.enabled!==!1){switch(t.touches.length){case 1:E.copy(y),y.copy(P(t.touches[0].pageX,t.touches[0].pageY));break;case 2:w=R=0;var e=(t.touches[0].pageX+t.touches[1].pageX)/2,n=(t.touches[0].pageY+t.touches[1].pageY)/2;M.copy(C(e,n)),H.copy(M)}m=p.NONE,c.dispatchEvent(A)}}var c=this,p={NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM_PAN:4};this.object=t,this.domElement=void 0!==e?e:document,this.enabled=!0,this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.keys=[65,83,68],this.target=new THREE.Vector3;var f=1e-6,d=new THREE.Vector3,m=p.NONE,v=p.NONE,g=new THREE.Vector3,E=new THREE.Vector2,y=new THREE.Vector2,_=new THREE.Vector3,b=0,T=new THREE.Vector2,x=new THREE.Vector2,w=0,R=0,H=new THREE.Vector2,M=new THREE.Vector2;this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.up0=this.object.up.clone();var S={type:"change"},k={type:"start"},A={type:"end"};this.handleResize=function(){if(this.domElement===document)this.screen.left=0,this.screen.top=0,this.screen.width=window.innerWidth,this.screen.height=window.innerHeight;else{var t=this.domElement.getBoundingClientRect(),e=this.domElement.ownerDocument.documentElement;this.screen.left=t.left+window.pageXOffset-e.clientLeft,this.screen.top=t.top+window.pageYOffset-e.clientTop,this.screen.width=t.width,this.screen.height=t.height}},this.handleEvent=function(t){"function"==typeof this[t.type]&&this[t.type](t)};var C=function(){var t=new THREE.Vector2;return function(e,n){return t.set((e-c.screen.left)/c.screen.width,(n-c.screen.top)/c.screen.height),t}}(),P=function(){var t=new THREE.Vector2;return function(e,n){return t.set((e-.5*c.screen.width-c.screen.left)/(.5*c.screen.width),(c.screen.height+2*(c.screen.top-n))/c.screen.width),t}}();this.rotateCamera=function(){var t,e=new THREE.Vector3,n=new THREE.Quaternion,r=new THREE.Vector3,i=new THREE.Vector3,o=new THREE.Vector3,s=new THREE.Vector3;return function(){s.set(y.x-E.x,y.y-E.y,0),t=s.length(),t?(g.copy(c.object.position).sub(c.target),r.copy(g).normalize(),i.copy(c.object.up).normalize(),o.crossVectors(i,r).normalize(),i.setLength(y.y-E.y),o.setLength(y.x-E.x),s.copy(i.add(o)),e.crossVectors(s,g).normalize(),t*=c.rotateSpeed,n.setFromAxisAngle(e,t),g.applyQuaternion(n),c.object.up.applyQuaternion(n),_.copy(e),b=t):!c.staticMoving&&b&&(b*=Math.sqrt(1-c.dynamicDampingFactor),g.copy(c.object.position).sub(c.target),n.setFromAxisAngle(_,b),g.applyQuaternion(n),c.object.up.applyQuaternion(n)),E.copy(y)}}(),this.zoomCamera=function(){var t;m===p.TOUCH_ZOOM_PAN?(t=w/R,w=R,g.multiplyScalar(t)):(t=1+(x.y-T.y)*c.zoomSpeed,1!==t&&t>0&&(g.multiplyScalar(t),c.staticMoving?T.copy(x):T.y+=(x.y-T.y)*this.dynamicDampingFactor))},this.panCamera=function(){var t=new THREE.Vector2,e=new THREE.Vector3,n=new THREE.Vector3;return function(){t.copy(M).sub(H),t.lengthSq()&&(t.multiplyScalar(g.length()*c.panSpeed),n.copy(g).cross(c.object.up).setLength(t.x),n.add(e.copy(c.object.up).setLength(t.y)),c.object.position.add(n),c.target.add(n),c.staticMoving?H.copy(M):H.add(t.subVectors(M,H).multiplyScalar(c.dynamicDampingFactor)))}}(),this.checkDistances=function(){c.noZoom&&c.noPan||(g.lengthSq()>c.maxDistance*c.maxDistance&&c.object.position.addVectors(c.target,g.setLength(c.maxDistance)),g.lengthSq()f&&(c.dispatchEvent(S),d.copy(c.object.position))},this.reset=function(){m=p.NONE,v=p.NONE,c.target.copy(c.target0),c.object.position.copy(c.position0),c.object.up.copy(c.up0),g.subVectors(c.object.position,c.target),c.object.lookAt(c.target),c.dispatchEvent(S),d.copy(c.object.position)},this.domElement.addEventListener("contextmenu",function(t){t.preventDefault()},!1),this.domElement.addEventListener("mousedown",i,!1),this.domElement.addEventListener("mousewheel",a,!1),this.domElement.addEventListener("DOMMouseScroll",a,!1),this.domElement.addEventListener("touchstart",u,!1),this.domElement.addEventListener("touchend",l,!1),this.domElement.addEventListener("touchmove",h,!1),window.addEventListener("keydown",n,!1),window.addEventListener("keyup",r,!1),this.handleResize(),this.update()},THREE.TrackballControls.prototype=Object.create(THREE.EventDispatcher.prototype),THREE.TrackballControls.prototype.constructor=THREE.TrackballControls,function t(e,n,r){function i(s,a){if(!n[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);throw new Error("Cannot find module '"+s+"'")}var h=n[s]={exports:{}};e[s][0].call(h.exports,function(t){var n=e[s][1][t];return i(n?n:t)},h,h.exports,t,e,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s 0.0 ? 0.0 : 1.0; \n val = abs(val); \n float exponent = floor(log2(val)); \n float biased_exponent = exponent + 127.0; \n float fraction = ((val / exp2(exponent)) - 1.0) * 8388608.0; \n float t = biased_exponent / 2.0; \n float last_bit_of_biased_exponent = fract(t) * 2.0; \n float remaining_bits_of_biased_exponent = floor(t); \n float byte4 = extract_bits(fraction, 0.0, 8.0) / 255.0; \n float byte3 = extract_bits(fraction, 8.0, 16.0) / 255.0; \n float byte2 = (last_bit_of_biased_exponent * 128.0 + extract_bits(fraction, 16.0, 23.0)) / 255.0; \n float byte1 = (valuesign * 128.0 + remaining_bits_of_biased_exponent) / 255.0; \n return vec4(byte4, byte3, byte2, byte1); \n}\n","float.index.pack":"uniform vec4 indexModulus;\n\nvec4 getSample(vec4 xyzw);\nvec4 getIndex(vec4 xyzw);\n\nvec4 floatPackIndex(vec4 xyzw) {\n vec4 value = getSample(xyzw);\n vec4 index = getIndex(xyzw);\n\n vec4 offset = floor(index + .5) * indexModulus;\n vec2 sum2 = offset.xy + offset.zw;\n float sum = sum2.x + sum2.y;\n return vec4(value.xyz, sum);\n}","float.stretch":"vec4 getSample(vec4 xyzw);\n\nfloat floatStretch(vec4 xyzw, float channelIndex) {\n vec4 sample = getSample(xyzw);\n vec2 xy = channelIndex > 1.5 ? sample.zw : sample.xy;\n return mod(channelIndex, 2.0) > .5 ? xy.y : xy.x;\n}","fragment.clip.dashed":"varying float vClipStrokeWidth;\nvarying float vClipStrokeIndex;\nvarying vec3 vClipStrokeEven;\nvarying vec3 vClipStrokeOdd;\nvarying vec3 vClipStrokePosition;\n\nvoid clipStrokeFragment() {\n bool odd = mod(vClipStrokeIndex, 2.0) >= 1.0;\n\n vec3 tangent;\n if (odd) {\n tangent = vClipStrokeOdd;\n }\n else {\n tangent = vClipStrokeEven;\n }\n\n float travel = dot(vClipStrokePosition, normalize(tangent)) / vClipStrokeWidth;\n if (mod(travel, 16.0) > 8.0) {\n discard;\n }\n}\n","fragment.clip.dotted":"varying float vClipStrokeWidth;\nvarying float vClipStrokeIndex;\nvarying vec3 vClipStrokeEven;\nvarying vec3 vClipStrokeOdd;\nvarying vec3 vClipStrokePosition;\n\nvoid clipStrokeFragment() {\n bool odd = mod(vClipStrokeIndex, 2.0) >= 1.0;\n\n vec3 tangent;\n if (odd) {\n tangent = vClipStrokeOdd;\n }\n else {\n tangent = vClipStrokeEven;\n }\n\n float travel = dot(vClipStrokePosition, normalize(tangent)) / vClipStrokeWidth;\n if (mod(travel, 4.0) > 2.0) {\n discard;\n }\n}\n","fragment.clip.ends":"varying vec2 vClipEnds;\n\nvoid clipEndsFragment() {\n if (vClipEnds.x < 0.0 || vClipEnds.y < 0.0) discard;\n}\n","fragment.clip.proximity":"varying float vClipProximity;\n\nvoid clipProximityFragment() {\n if (vClipProximity >= 0.5) discard;\n}","fragment.color":"void setFragmentColor(vec4 color) {\n gl_FragColor = color;\n}","fragment.map.rgba":"vec4 fragmentRGBA(vec4 rgba, vec4 stpq) {\n return rgba;\n}","fragment.solid":"void setFragmentColor(vec4 color) {\n if (color.a < 1.0) discard;\n gl_FragColor = color;\n}","fragment.transparent":"void setFragmentColor(vec4 color) {\n if (color.a >= 1.0) discard;\n gl_FragColor = color;\n}","grid.position":"uniform vec4 gridPosition;\nuniform vec4 gridStep;\nuniform vec4 gridAxis;\n\nvec4 sampleData(vec2 xy);\n\nvec4 getGridPosition(vec4 xyzw) {\n vec4 onAxis = gridAxis * sampleData(vec2(xyzw.y, 0.0)).x;\n vec4 offAxis = gridStep * xyzw.x + gridPosition;\n return onAxis + offAxis;\n}\n","grow.position":"uniform float growScale;\nuniform vec4 growMask;\nuniform vec4 growAnchor;\n\nvec4 getSample(vec4 xyzw);\n\nvec4 getGrowSample(vec4 xyzw) {\n vec4 anchor = xyzw * growMask + growAnchor;\n\n vec4 position = getSample(xyzw);\n vec4 center = getSample(anchor);\n\n return mix(center, position, growScale);\n}","join.position":"uniform float joinStride;\nuniform float joinStrideInv;\n\nfloat getIndex(vec4 xyzw);\nvec4 getRest(vec4 xyzw);\nvec4 injectIndices(float a, float b);\n\nvec4 getJoinXYZW(vec4 xyzw) {\n\n float a = getIndex(xyzw);\n float b = a * joinStrideInv;\n\n float integer = floor(b);\n float fraction = b - integer;\n \n return injectIndices(fraction * joinStride, integer) + getRest(xyzw);\n}\n","label.alpha":"varying float vPixelSize;\n\nvec4 getLabelAlphaColor(vec4 color, vec4 sample) {\n float mask = clamp(sample.r * 1000.0, 0.0, 1.0);\n float alpha = (sample.r - .5) * vPixelSize + .5;\n float a = mask * alpha * color.a;\n if (a <= 0.0) discard;\n return vec4(color.xyz, a);\n}\n","label.map":"vec2 mapUV(vec4 uvwo, vec4 stpq) {\n return uvwo.xy;\n}\n","label.outline":"uniform float outlineExpand;\nuniform float outlineStep;\nuniform vec3 outlineColor;\n\nvarying float vPixelSize;\n\nconst float PIXEL_STEP = 255.0 / 16.0;\n\nvec4 getLabelOutlineColor(vec4 color, vec4 sample) {\n float ps = vPixelSize * PIXEL_STEP;\n float os = outlineStep;\n\n float sdf = sample.r - .5 + outlineExpand;\n vec2 sdfs = vec2(sdf, sdf + os);\n vec2 alpha = clamp(sdfs * ps + .5, 0.0, 1.0);\n\n if (alpha.y <= 0.0) {\n discard;\n }\n\n vec3 blend = color.xyz;\n if (alpha.y > alpha.x) {\n blend = sqrt(mix(outlineColor * outlineColor, blend * blend, alpha.x));\n }\n \n return vec4(blend, alpha.y * color.a);\n}\n","layer.position":"uniform vec4 layerScale;\nuniform vec4 layerBias;\n\nvec4 layerPosition(vec4 position, inout vec4 stpq) {\n return layerScale * position + layerBias;\n}\n","lerp.depth":"// External\nvec4 sampleData(vec4 xyzw);\n\nvec4 lerpDepth(vec4 xyzw) {\n float x = xyzw.z;\n float i = floor(x);\n float f = x - i;\n \n vec4 xyzw1 = vec4(xyzw.xy, i, xyzw.w);\n vec4 xyzw2 = vec4(xyzw.xy, i + 1.0, xyzw.w);\n \n vec4 a = sampleData(xyzw1);\n vec4 b = sampleData(xyzw2);\n\n return mix(a, b, f);\n}\n","lerp.height":"// External\nvec4 sampleData(vec4 xyzw);\n\nvec4 lerpHeight(vec4 xyzw) {\n float x = xyzw.y;\n float i = floor(x);\n float f = x - i;\n \n vec4 xyzw1 = vec4(xyzw.x, i, xyzw.zw);\n vec4 xyzw2 = vec4(xyzw.x, i + 1.0, xyzw.zw);\n \n vec4 a = sampleData(xyzw1);\n vec4 b = sampleData(xyzw2);\n\n return mix(a, b, f);\n}\n","lerp.items":"// External\nvec4 sampleData(vec4 xyzw);\n\nvec4 lerpItems(vec4 xyzw) {\n float x = xyzw.w;\n float i = floor(x);\n float f = x - i;\n \n vec4 xyzw1 = vec4(xyzw.xyz, i);\n vec4 xyzw2 = vec4(xyzw.xyz, i + 1.0);\n \n vec4 a = sampleData(xyzw1);\n vec4 b = sampleData(xyzw2);\n\n return mix(a, b, f);\n}\n","lerp.width":"// External\nvec4 sampleData(vec4 xyzw);\n\nvec4 lerpWidth(vec4 xyzw) {\n float x = xyzw.x;\n float i = floor(x);\n float f = x - i;\n \n vec4 xyzw1 = vec4(i, xyzw.yzw);\n vec4 xyzw2 = vec4(i + 1.0, xyzw.yzw);\n \n vec4 a = sampleData(xyzw1);\n vec4 b = sampleData(xyzw2);\n\n return mix(a, b, f);\n}\n","line.position":"// Units and calibration\nuniform float worldUnit;\nuniform float lineWidth;\nuniform float lineDepth;\nuniform float focusDepth;\n\n// General data index\nuniform vec4 geometryClip;\nattribute vec4 position4;\n\n// (Start/mid/end -1/0/1, top/bottom -1,1) \nattribute vec2 line;\n\n// 0...1 for round or bevel joins\n#ifdef LINE_JOIN_DETAIL\nattribute float joint;\n#else\nconst float joint = 0.0;\n#endif\n\n// Knock out excessively long line segments (e.g. for asymtpotes)\n#ifdef LINE_PROXIMITY\nuniform float lineProximity;\nvarying float vClipProximity;\n#endif\n\n// Ghetto line stroking (local only, not global)\n#ifdef LINE_STROKE\nvarying float vClipStrokeWidth;\nvarying float vClipStrokeIndex;\nvarying vec3 vClipStrokeEven;\nvarying vec3 vClipStrokeOdd;\nvarying vec3 vClipStrokePosition;\n#endif\n\n// External\nvec3 getPosition(vec4 xyzw, float canonical);\n\n// Clip line ends for arrows / decoration\n#ifdef LINE_CLIP\nuniform float clipRange;\nuniform vec2 clipStyle;\nuniform float clipSpace;\n\nattribute vec2 strip;\n\nvarying vec2 vClipEnds;\n\nvoid clipEnds(vec4 xyzw, vec3 center, vec3 pos) {\n\n // Sample end of line strip\n vec4 xyzwE = vec4(strip.y, xyzw.yzw);\n vec3 end = getPosition(xyzwE, 0.0);\n\n // Sample start of line strip\n vec4 xyzwS = vec4(strip.x, xyzw.yzw);\n vec3 start = getPosition(xyzwS, 0.0);\n\n // Measure length\n vec3 diff = end - start;\n float l = length(diff) * clipSpace;\n\n // Arrow length (=2.5x radius)\n float arrowSize = 1.25 * clipRange * lineWidth * worldUnit;\n\n vClipEnds = vec2(1.0);\n\n if (clipStyle.y > 0.0) {\n // Depth blend end\n float depth = focusDepth;\n if (lineDepth < 1.0) {\n float z = max(0.00001, -end.z);\n depth = mix(z, focusDepth, lineDepth);\n }\n \n // Absolute arrow length\n float size = arrowSize * depth;\n\n // Adjust clip range\n // Approach linear scaling with cubic ease the smaller we get\n float mini = clamp(1.0 - l / size * .333, 0.0, 1.0);\n float scale = 1.0 - mini * mini * mini; \n float invrange = 1.0 / (size * scale);\n \n // Clip end\n diff = normalize(end - center);\n float d = dot(end - pos, diff);\n vClipEnds.x = d * invrange - 1.0;\n }\n\n if (clipStyle.x > 0.0) {\n // Depth blend start\n float depth = focusDepth;\n if (lineDepth < 1.0) {\n float z = max(0.00001, -start.z);\n depth = mix(z, focusDepth, lineDepth);\n }\n \n // Absolute arrow length\n float size = arrowSize * depth;\n\n // Adjust clip range\n // Approach linear scaling with cubic ease the smaller we get\n float mini = clamp(1.0 - l / size * .333, 0.0, 1.0);\n float scale = 1.0 - mini * mini * mini; \n float invrange = 1.0 / (size * scale);\n \n // Clip start \n diff = normalize(center - start);\n float d = dot(pos - start, diff);\n vClipEnds.y = d * invrange - 1.0;\n }\n\n\n}\n#endif\n\n// Adjust left/center/right to be inside near/far z range\nconst float epsilon = 1e-5;\nvoid fixCenter(inout vec3 left, inout vec3 center, inout vec3 right) {\n if (center.z >= 0.0) {\n if (left.z < 0.0) {\n float d = (center.z + epsilon) / (center.z - left.z);\n center = mix(center, left, d);\n }\n else if (right.z < 0.0) {\n float d = (center.z + epsilon) / (center.z - right.z);\n center = mix(center, right, d);\n }\n }\n\n if (left.z >= 0.0) {\n if (center.z < 0.0) {\n float d = (left.z + epsilon) / (left.z - center.z);\n left = mix(left, center, d);\n }\n }\n\n if (right.z >= 0.0) {\n if (center.z < 0.0) {\n float d = (right.z + epsilon) / (right.z - center.z);\n right = mix(right, center, d);\n }\n }\n}\n\n// Sample the source data in an edge-aware manner\nvoid getLineGeometry(vec4 xyzw, float edge, out vec3 left, out vec3 center, out vec3 right) {\n vec4 delta = vec4(1.0, 0.0, 0.0, 0.0);\n\n center = getPosition(xyzw, 1.0);\n left = (edge > -0.5) ? getPosition(xyzw - delta, 0.0) : center;\n right = (edge < 0.5) ? getPosition(xyzw + delta, 0.0) : center;\n}\n\n// Calculate the position for a vertex along the line, including joins\nvec3 getLineJoin(float edge, bool odd, vec3 left, vec3 center, vec3 right, float width, float offset, float joint) {\n vec2 join = vec2(1.0, 0.0);\n\n fixCenter(left, center, right);\n\n vec4 a = vec4(left.xy, right.xy);\n vec4 b = a / vec4(left.zz, right.zz);\n\n vec2 l = b.xy;\n vec2 r = b.zw;\n vec2 c = center.xy / center.z;\n\n vec4 d = vec4(l, c) - vec4(c, r);\n float l1 = dot(d.xy, d.xy);\n float l2 = dot(d.zw, d.zw);\n\n if (l1 + l2 > 0.0) {\n \n if (edge > 0.5 || l2 == 0.0) {\n vec2 nl = normalize(d.xy);\n vec2 tl = vec2(nl.y, -nl.x);\n\n#ifdef LINE_PROXIMITY\n vClipProximity = 1.0;\n#endif\n\n#ifdef LINE_STROKE\n vClipStrokeEven = vClipStrokeOdd = normalize(left - center);\n#endif\n join = tl;\n }\n else if (edge < -0.5 || l1 == 0.0) {\n vec2 nr = normalize(d.zw);\n vec2 tr = vec2(nr.y, -nr.x);\n\n#ifdef LINE_PROXIMITY\n vClipProximity = 1.0;\n#endif\n\n#ifdef LINE_STROKE\n vClipStrokeEven = vClipStrokeOdd = normalize(center - right);\n#endif\n join = tr;\n }\n else {\n // Limit join stretch for tiny segments\n float lmin2 = min(l1, l2) / (width * width);\n\n // Hide line segment if ratio of leg lengths exceeds promixity threshold\n#ifdef LINE_PROXIMITY\n float lr = l1 / l2;\n float rl = l2 / l1;\n float ratio = max(lr, rl);\n float thresh = lineProximity + 1.0;\n vClipProximity = (ratio > thresh * thresh) ? 1.0 : 0.0;\n#endif\n\n // Calculate normals/tangents\n vec2 nl = normalize(d.xy);\n vec2 nr = normalize(d.zw);\n\n // Calculate tangents\n vec2 tl = vec2(nl.y, -nl.x);\n vec2 tr = vec2(nr.y, -nr.x);\n\n#ifdef LINE_PROXIMITY\n // Mix tangents according to leg lengths\n vec2 tc = normalize(mix(tl, tr, l1/(l1+l2)));\n#else\n // Average tangent\n vec2 tc = normalize(tl + tr);\n#endif\n \n // Miter join\n float cosA = dot(nl, tc);\n float sinA = max(0.1, abs(dot(tl, tc)));\n float factor = cosA / sinA;\n float scale = sqrt(1.0 + min(lmin2, factor * factor));\n\n // Stroke normals\n#ifdef LINE_STROKE\n vec3 stroke1 = normalize(left - center);\n vec3 stroke2 = normalize(center - right);\n\n if (odd) {\n vClipStrokeEven = stroke1;\n vClipStrokeOdd = stroke2;\n }\n else {\n vClipStrokeEven = stroke2;\n vClipStrokeOdd = stroke1;\n }\n#endif\n\n#ifdef LINE_JOIN_MITER\n // Apply straight up miter\n join = tc * scale;\n#endif\n\n#ifdef LINE_JOIN_ROUND\n // Slerp bevel join into circular arc\n float dotProduct = dot(nl, nr);\n float angle = acos(dotProduct);\n float sinT = sin(angle);\n join = (sin((1.0 - joint) * angle) * tl + sin(joint * angle) * tr) / sinT;\n#endif\n\n#ifdef LINE_JOIN_BEVEL\n // Direct bevel join between two flat ends\n float dotProduct = dot(nl, nr);\n join = mix(tl, tr, joint);\n#endif\n\n#ifdef LINE_JOIN_DETAIL\n // Check if on inside or outside of joint\n float crossProduct = nl.x * nr.y - nl.y * nr.x;\n if (offset * crossProduct < 0.0) {\n // For near-180-degree bends, correct back to a miter to avoid discontinuities\n float ratio = clamp(-dotProduct * 2.0 - 1.0, 0.0, 1.0);\n // Otherwise collapse the inside vertices into one.\n join = mix(tc * scale, join, ratio * ratio * ratio);\n }\n#endif\n\n }\n return vec3(join, 0.0);\n }\n else {\n return vec3(0.0);\n }\n\n}\n\n// Calculate final line position\nvec3 getLinePosition() {\n vec3 left, center, right, join;\n\n // left/center/right\n float edge = line.x;\n // up/down\n float offset = line.y;\n\n // Clip data\n vec4 p = min(geometryClip, position4);\n edge += max(0.0, position4.x - geometryClip.x);\n\n // Get position + adjacent neighbours\n getLineGeometry(p, edge, left, center, right);\n\n#ifdef LINE_STROKE\n // Set parameters for line stroke fragment shader\n vClipStrokePosition = center;\n vClipStrokeIndex = p.x;\n bool odd = mod(p.x, 2.0) >= 1.0;\n#else\n bool odd = true;\n#endif\n\n // Divide line width up/down\n float width = lineWidth * 0.5;\n\n float depth = focusDepth;\n if (lineDepth < 1.0) {\n // Depth blending\n float z = max(0.00001, -center.z);\n depth = mix(z, focusDepth, lineDepth);\n }\n width *= depth;\n\n // Convert to world units\n width *= worldUnit;\n\n // Calculate line join\n join = getLineJoin(edge, odd, left, center, right, width, offset, joint);\n vec3 pos = center + join * offset * width;\n\n#ifdef LINE_STROKE\n vClipStrokeWidth = width;\n#endif\n\n#ifdef LINE_CLIP\n clipEnds(p, center, pos);\n#endif\n\n return pos;\n}\n","map.2d.data":"uniform vec2 dataResolution;\nuniform vec2 dataPointer;\n\nvec2 map2DData(vec2 xy) {\n return (xy + dataPointer) * dataResolution;\n}\n","map.2d.data.wrap":"uniform vec2 dataResolution;\nuniform vec2 dataPointer;\n\nvec2 map2DData(vec2 xy) {\n return fract((xy + dataPointer) * dataResolution);\n}\n","map.xyzw.2dv":"void mapXyzw2DV(vec4 xyzw, out vec2 xy, out float z) {\n xy = xyzw.xy;\n z = xyzw.z;\n}\n\n","map.xyzw.align":"vec4 alignXYZW(vec4 xyzw) {\n return floor(xyzw + .5);\n}\n\n","map.xyzw.texture":"uniform float textureItems;\nuniform float textureHeight;\n\nvec2 mapXyzwTexture(vec4 xyzw) {\n \n float x = xyzw.x;\n float y = xyzw.y;\n float z = xyzw.z;\n float i = xyzw.w;\n \n return vec2(i, y) + vec2(x, z) * vec2(textureItems, textureHeight);\n}\n\n","mesh.fragment.color":"varying vec4 vColor;\n\nvec4 getColor() {\n return vColor;\n}\n","mesh.fragment.map":"#ifdef POSITION_STPQ\nvarying vec4 vSTPQ;\n#endif\n#ifdef POSITION_U\nvarying float vU;\n#endif\n#ifdef POSITION_UV\nvarying vec2 vUV;\n#endif\n#ifdef POSITION_UVW\nvarying vec3 vUVW;\n#endif\n#ifdef POSITION_UVWO\nvarying vec4 vUVWO;\n#endif\n\nvec4 getSample(vec4 uvwo, vec4 stpq);\n\nvec4 getMapColor() {\n #ifdef POSITION_STPQ\n vec4 stpq = vSTPQ;\n #else\n vec4 stpq = vec4(0.0);\n #endif\n\n #ifdef POSITION_U\n vec4 uvwo = vec4(vU, 0.0, 0.0, 0.0);\n #endif\n #ifdef POSITION_UV\n vec4 uvwo = vec4(vUV, 0.0, 0.0);\n #endif\n #ifdef POSITION_UVW\n vec4 uvwo = vec4(vUVW, 0.0);\n #endif\n #ifdef POSITION_UVWO\n vec4 uvwo = vec4(vUVWO);\n #endif\n\n return getSample(uvwo, stpq);\n}\n","mesh.fragment.mask":"varying float vMask;\n\nfloat ease(float t) {\n t = clamp(t, 0.0, 1.0);\n return t * t * (3.0 - 2.0 * t);\n}\n\nvec4 maskColor() {\n if (vMask <= 0.0) discard;\n return vec4(vec3(1.0), ease(vMask));\n}\n","mesh.fragment.material":"#ifdef POSITION_STPQ\nvarying vec4 vSTPQ;\n#endif\n#ifdef POSITION_U\nvarying float vU;\n#endif\n#ifdef POSITION_UV\nvarying vec2 vUV;\n#endif\n#ifdef POSITION_UVW\nvarying vec3 vUVW;\n#endif\n#ifdef POSITION_UVWO\nvarying vec4 vUVWO;\n#endif\n\nvec4 getSample(vec4 rgba, vec4 stpq);\n\nvec4 getMaterialColor(vec4 rgba) {\n vec4 stpq = vec4(0.0);\n\n #ifdef POSITION_U\n stpq.x = vU;\n #endif\n #ifdef POSITION_UV\n stpq.xy = vUV;\n #endif\n #ifdef POSITION_UVW\n stpq.xyz = vUVW;\n #endif\n #ifdef POSITION_UVWO\n stpq = vUVWO;\n #endif\n\n #ifdef POSITION_STPQ\n stpq = vSTPQ;\n #endif\n\n return getSample(rgba, stpq);\n}\n","mesh.fragment.shaded":"varying vec3 vNormal;\nvarying vec3 vLight;\nvarying vec3 vPosition;\n\nvec3 offSpecular(vec3 color) {\n vec3 c = 1.0 - color;\n return 1.0 - c * c;\n}\n\nvec4 getShadedColor(vec4 rgba) {\n \n vec3 color = rgba.xyz;\n vec3 color2 = offSpecular(rgba.xyz);\n\n vec3 normal = normalize(vNormal);\n vec3 light = normalize(vLight);\n vec3 position = normalize(vPosition);\n \n float side = gl_FrontFacing ? -1.0 : 1.0;\n float cosine = side * dot(normal, light);\n float diffuse = mix(max(0.0, cosine), .5 + .5 * cosine, .1);\n \n vec3 halfLight = normalize(light + position);\n float cosineHalf = max(0.0, side * dot(normal, halfLight));\n float specular = pow(cosineHalf, 16.0);\n \n return vec4(color * (diffuse * .9 + .05) + .25 * color2 * specular, rgba.a);\n}\n","mesh.fragment.texture":"","mesh.gamma.in":"vec4 getGammaInColor(vec4 rgba) {\n return vec4(rgba.rgb * rgba.rgb, rgba.a);\n}\n","mesh.gamma.out":"vec4 getGammaOutColor(vec4 rgba) {\n return vec4(sqrt(rgba.rgb), rgba.a);\n}\n","mesh.map.uvwo":"vec4 mapUVWO(vec4 uvwo, vec4 stpq) {\n return uvwo;\n}\n","mesh.position":"uniform vec4 geometryClip;\nattribute vec4 position4;\n\n// External\nvec3 getPosition(vec4 xyzw, float canonical);\n\nvec3 getMeshPosition() {\n vec4 p = min(geometryClip, position4);\n return getPosition(p, 1.0);\n}\n","mesh.vertex.color":"attribute vec4 position4;\nuniform vec4 geometryClip;\nvarying vec4 vColor;\n\n// External\nvec4 getSample(vec4 xyzw);\n\nvoid vertexColor() {\n vec4 p = min(geometryClip, position4);\n vColor = getSample(p);\n}\n","mesh.vertex.mask":"attribute vec4 position4;\nuniform vec4 geometryResolution;\nuniform vec4 geometryClip;\nvarying float vMask;\n\n// External\nfloat getSample(vec4 xyzw);\n\nvoid maskLevel() {\n vec4 p = min(geometryClip, position4);\n vMask = getSample(p * geometryResolution);\n}\n","mesh.vertex.position":"uniform vec4 geometryResolution;\n\n#ifdef POSITION_STPQ\nvarying vec4 vSTPQ;\n#endif\n#ifdef POSITION_U\nvarying float vU;\n#endif\n#ifdef POSITION_UV\nvarying vec2 vUV;\n#endif\n#ifdef POSITION_UVW\nvarying vec3 vUVW;\n#endif\n#ifdef POSITION_UVWO\nvarying vec4 vUVWO;\n#endif\n\n// External\nvec3 getPosition(vec4 xyzw, in vec4 stpqIn, out vec4 stpqOut);\n\nvec3 getMeshPosition(vec4 xyzw, float canonical) {\n vec4 stpqOut, stpqIn = xyzw * geometryResolution;\n vec3 xyz = getPosition(xyzw, stpqIn, stpqOut);\n\n #ifdef POSITION_MAP\n if (canonical > 0.5) {\n #ifdef POSITION_STPQ\n vSTPQ = stpqOut;\n #endif\n #ifdef POSITION_U\n vU = stpqOut.x;\n #endif\n #ifdef POSITION_UV\n vUV = stpqOut.xy;\n #endif\n #ifdef POSITION_UVW\n vUVW = stpqOut.xyz;\n #endif\n #ifdef POSITION_UVWO\n vUVWO = stpqOut;\n #endif\n }\n #endif\n return xyz;\n}\n","move.position":"uniform float transitionEnter;\nuniform float transitionExit;\nuniform vec4 transitionScale;\nuniform vec4 transitionBias;\nuniform float transitionSkew;\nuniform float transitionActive;\n\nuniform vec4 moveFrom;\nuniform vec4 moveTo;\n\nfloat ease(float t) {\n t = clamp(t, 0.0, 1.0);\n return 1.0 - (2.0 - t) * t;\n}\n\nvec4 getTransitionPosition(vec4 xyzw, inout vec4 stpq) {\n if (transitionActive < 0.5) return xyzw;\n\n float enter = transitionEnter;\n float exit = transitionExit;\n float skew = transitionSkew;\n vec4 scale = transitionScale;\n vec4 bias = transitionBias;\n\n float factor = 1.0 + skew;\n float offset = dot(vec4(1.0), stpq * scale + bias);\n\n float a1 = ease(enter * factor - offset);\n float a2 = ease(exit * factor + offset - skew);\n\n return xyzw + a1 * moveFrom + a2 * moveTo;\n}","object.mask.default":"vec4 getMask(vec4 xyzw) {\n return vec4(1.0);\n}","point.alpha.circle":"varying float vPixelSize;\n\nfloat getDiscAlpha(float mask) {\n // Approximation: 1 - x*x is approximately linear around x = 1 with slope 2\n return vPixelSize * (1.0 - mask);\n // return vPixelSize * 2.0 * (1.0 - sqrt(mask));\n}\n","point.alpha.circle.hollow":"varying float vPixelSize;\n\nfloat getDiscHollowAlpha(float mask) {\n return vPixelSize * (0.5 - 2.0 * abs(sqrt(mask) - .75));\n}\n","point.alpha.generic":"varying float vPixelSize;\n\nfloat getGenericAlpha(float mask) {\n return vPixelSize * 2.0 * (1.0 - mask);\n}\n","point.alpha.generic.hollow":"varying float vPixelSize;\n\nfloat getGenericHollowAlpha(float mask) {\n return vPixelSize * (0.5 - 2.0 * abs(mask - .75));\n}\n","point.edge":"varying vec2 vSprite;\n\nfloat getSpriteMask(vec2 xy);\nfloat getSpriteAlpha(float mask);\n\nvoid setFragmentColorFill(vec4 color) {\n float mask = getSpriteMask(vSprite);\n if (mask > 1.0) {\n discard;\n }\n float alpha = getSpriteAlpha(mask);\n if (alpha >= 1.0) {\n discard;\n }\n gl_FragColor = vec4(color.rgb, alpha * color.a);\n}\n","point.fill":"varying vec2 vSprite;\n\nfloat getSpriteMask(vec2 xy);\nfloat getSpriteAlpha(float mask);\n\nvoid setFragmentColorFill(vec4 color) {\n float mask = getSpriteMask(vSprite);\n if (mask > 1.0) {\n discard;\n }\n float alpha = getSpriteAlpha(mask);\n if (alpha < 1.0) {\n discard;\n }\n gl_FragColor = color;\n}\n\n","point.mask.circle":"varying float vPixelSize;\n\nfloat getCircleMask(vec2 uv) {\n return dot(uv, uv);\n}\n","point.mask.diamond":"varying float vPixelSize;\n\nfloat getDiamondMask(vec2 uv) {\n vec2 a = abs(uv);\n return a.x + a.y;\n}\n","point.mask.down":"varying float vPixelSize;\n\nfloat getTriangleDownMask(vec2 uv) {\n uv.y += .25;\n return max(uv.y, abs(uv.x) * .866 - uv.y * .5 + .6);\n}\n","point.mask.left":"varying float vPixelSize;\n\nfloat getTriangleLeftMask(vec2 uv) {\n uv.x += .25;\n return max(uv.x, abs(uv.y) * .866 - uv.x * .5 + .6);\n}\n","point.mask.right":"varying float vPixelSize;\n\nfloat getTriangleRightMask(vec2 uv) {\n uv.x -= .25;\n return max(-uv.x, abs(uv.y) * .866 + uv.x * .5 + .6);\n}\n","point.mask.square":"varying float vPixelSize;\n\nfloat getSquareMask(vec2 uv) {\n vec2 a = abs(uv);\n return max(a.x, a.y);\n}\n","point.mask.up":"varying float vPixelSize;\n\nfloat getTriangleUpMask(vec2 uv) {\n uv.y -= .25;\n return max(-uv.y, abs(uv.x) * .866 + uv.y * .5 + .6);\n}\n","point.position":"uniform float pointDepth;\n\nuniform float pixelUnit;\nuniform float renderScale;\nuniform float renderScaleInv;\nuniform float focusDepth;\n\nuniform vec4 geometryClip;\nattribute vec4 position4;\nattribute vec2 sprite;\n\nvarying vec2 vSprite;\nvarying float vPixelSize;\n\nconst float pointScale = POINT_SHAPE_SCALE;\n\n// External\nfloat getPointSize(vec4 xyzw);\nvec3 getPosition(vec4 xyzw, float canonical);\n\nvec3 getPointPosition() {\n vec4 p = min(geometryClip, position4);\n vec3 center = getPosition(p, 1.0);\n\n // Depth blending\n // TODO: orthographic camera\n // Workaround: set depth = 0\n float z = -center.z;\n float depth = mix(z, focusDepth, pointDepth);\n \n // Match device/unit mapping \n // Sprite goes from -1..1, width = 2.\n float pointSize = getPointSize(p);\n float size = pointScale * pointSize * pixelUnit * .5;\n float depthSize = depth * size;\n \n // Pad sprite by half a pixel to make the anti-aliasing straddle the pixel edge\n // Note: pixelsize measures radius\n float pixelSize = .5 * (pointDepth > 0.0 ? depthSize / z : size);\n float paddedSize = pixelSize + 0.5;\n float padFactor = paddedSize / pixelSize;\n\n vPixelSize = paddedSize;\n vSprite = sprite;\n\n return center + vec3(sprite * depthSize * renderScaleInv * padFactor, 0.0);\n}\n","point.size.uniform":"uniform float pointSize;\n\nfloat getPointSize(vec4 xyzw) {\n return pointSize;\n}","point.size.varying":"uniform float pointSize;\n\nvec4 getSample(vec4 xyzw);\n\nfloat getPointSize(vec4 xyzw) {\n return pointSize * getSample(xyzw).x;\n}","polar.position":"uniform float polarBend;\nuniform float polarFocus;\nuniform float polarAspect;\nuniform float polarHelix;\n\nuniform mat4 viewMatrix;\n\nvec4 getPolarPosition(vec4 position, inout vec4 stpq) {\n if (polarBend > 0.0) {\n\n if (polarBend < 0.001) {\n // Factor out large addition/subtraction of polarFocus\n // to avoid numerical error\n // sin(x) ~ x\n // cos(x) ~ 1 - x * x / 2\n vec2 pb = position.xy * polarBend;\n float ppbbx = pb.x * pb.x;\n return viewMatrix * vec4(\n position.x * (1.0 - polarBend + (pb.y * polarAspect)),\n position.y * (1.0 - .5 * ppbbx) - (.5 * ppbbx) * polarFocus / polarAspect,\n position.z + position.x * polarHelix * polarBend,\n 1.0\n );\n }\n else {\n vec2 xy = position.xy * vec2(polarBend, polarAspect);\n float radius = polarFocus + xy.y;\n return viewMatrix * vec4(\n sin(xy.x) * radius,\n (cos(xy.x) * radius - polarFocus) / polarAspect,\n position.z + position.x * polarHelix * polarBend,\n 1.0\n );\n }\n }\n else {\n return viewMatrix * vec4(position.xyz, 1.0);\n }\n}","project.position":"uniform float styleZBias;\nuniform float styleZIndex;\n\nvoid setPosition(vec3 position) {\n vec4 pos = projectionMatrix * vec4(position, 1.0);\n\n // Apply relative Z bias\n float bias = (1.0 - styleZBias / 32768.0);\n pos.z *= bias;\n \n // Apply large scale Z index changes\n if (styleZIndex > 0.0) {\n float z = pos.z / pos.w;\n pos.z = ((z + 1.0) / (styleZIndex + 1.0) - 1.0) * pos.w;\n }\n \n gl_Position = pos;\n}","project.readback":"// This is three.js' global uniform, missing from fragment shaders.\nuniform mat4 projectionMatrix;\n\nvec4 readbackPosition(vec3 position, vec4 stpq) {\n vec4 pos = projectionMatrix * vec4(position, 1.0);\n vec3 final = pos.xyz / pos.w;\n if (final.z < -1.0) {\n return vec4(0.0, 0.0, 0.0, -1.0);\n }\n else {\n return vec4(final, -position.z);\n }\n}\n","raw.position.scale":"uniform vec4 geometryScale;\nattribute vec4 position4;\n\nvec4 getRawPositionScale() {\n return geometryScale * position4;\n}\n","repeat.position":"uniform vec4 repeatModulus;\n\nvec4 getRepeatXYZW(vec4 xyzw) {\n return mod(xyzw + .5, repeatModulus) - .5;\n}\n","resample.padding":"uniform vec4 resampleBias;\n\nvec4 resamplePadding(vec4 xyzw) {\n return xyzw + resampleBias;\n}","resample.relative":"uniform vec4 resampleFactor;\n\nvec4 resampleRelative(vec4 xyzw) {\n return xyzw * resampleFactor;\n}","reveal.mask":"uniform float transitionEnter;\nuniform float transitionExit;\nuniform vec4 transitionScale;\nuniform vec4 transitionBias;\nuniform float transitionSkew;\nuniform float transitionActive;\n\nfloat getTransitionSDFMask(vec4 stpq) {\n if (transitionActive < 0.5) return 1.0;\n\n float enter = transitionEnter;\n float exit = transitionExit;\n float skew = transitionSkew;\n vec4 scale = transitionScale;\n vec4 bias = transitionBias;\n\n float factor = 1.0 + skew;\n float offset = dot(vec4(1.0), stpq * scale + bias);\n\n vec2 d = vec2(enter, exit) * factor + vec2(-offset, offset - skew);\n if (exit == 1.0) return d.x;\n if (enter == 1.0) return d.y;\n return min(d.x, d.y);\n}","root.position":"vec3 getRootPosition(vec4 position, in vec4 stpqIn, out vec4 stpqOut) {\n stpqOut = stpqIn; // avoid inout confusion\n return position.xyz;\n}","sample.2d":"uniform sampler2D dataTexture;\n\nvec4 sample2D(vec2 uv) {\n return texture2D(dataTexture, uv);\n}\n","scale.position":"uniform vec4 scaleAxis;\nuniform vec4 scaleOffset;\n\nvec4 sampleData(float x);\n\nvec4 getScalePosition(vec4 xyzw) {\n return scaleAxis * sampleData(xyzw.x).x + scaleOffset;\n}\n","screen.map.stpq":"uniform vec4 remapSTPQScale;\n\nvec4 screenMapSTPQ(vec4 xyzw, out vec4 stpq) {\n stpq = xyzw * remapSTPQScale;\n return xyzw;\n}\n","screen.map.xy":"uniform vec2 remapUVScale;\n\nvec4 screenMapXY(vec4 uvwo, vec4 stpq) {\n return vec4(floor(remapUVScale * uvwo.xy), 0.0, 0.0);\n}\n","screen.map.xyzw":"uniform vec2 remapUVScale;\nuniform vec2 remapModulus;\nuniform vec2 remapModulusInv;\n\nvec4 screenMapXYZW(vec4 uvwo, vec4 stpq) {\n vec2 st = floor(remapUVScale * uvwo.xy);\n vec2 xy = st * remapModulusInv;\n vec2 ixy = floor(xy);\n vec2 fxy = xy - ixy;\n vec2 zw = fxy * remapModulus;\n return vec4(ixy.x, zw.y, ixy.y, zw.x);\n}\n","screen.pass.uv":"vec2 screenPassUV(vec4 uvwo, vec4 stpq) {\n return uvwo.xy;\n}\n","screen.position":"void setScreenPosition(vec4 position) {\n gl_Position = vec4(position.xy * 2.0 - 1.0, 0.5, 1.0);\n}\n","slice.position":"uniform vec4 sliceOffset;\n\nvec4 getSliceOffset(vec4 xyzw) {\n return xyzw + sliceOffset;\n}\n","spherical.position":"uniform float sphericalBend;\nuniform float sphericalFocus;\nuniform float sphericalAspectX;\nuniform float sphericalAspectY;\nuniform float sphericalScaleY;\n\nuniform mat4 viewMatrix;\n\nvec4 getSphericalPosition(vec4 position, inout vec4 stpq) {\n if (sphericalBend > 0.0001) {\n\n vec3 xyz = position.xyz * vec3(sphericalBend, sphericalBend / sphericalAspectY * sphericalScaleY, sphericalAspectX);\n float radius = sphericalFocus + xyz.z;\n float cosine = cos(xyz.y) * radius;\n\n return viewMatrix * vec4(\n sin(xyz.x) * cosine,\n sin(xyz.y) * radius * sphericalAspectY,\n (cos(xyz.x) * cosine - sphericalFocus) / sphericalAspectX,\n 1.0\n );\n }\n else {\n return viewMatrix * vec4(position.xyz, 1.0);\n }\n}", +"split.position":"uniform float splitStride;\n\nvec2 getIndices(vec4 xyzw);\nvec4 getRest(vec4 xyzw);\nvec4 injectIndex(float v);\n\nvec4 getSplitXYZW(vec4 xyzw) {\n vec2 uv = getIndices(xyzw);\n float offset = uv.x + uv.y * splitStride;\n return injectIndex(offset) + getRest(xyzw);\n}\n","spread.position":"uniform vec4 spreadOffset;\nuniform mat4 spreadMatrix;\n\n// External\nvec4 getSample(vec4 xyzw);\n\nvec4 getSpreadSample(vec4 xyzw) {\n vec4 sample = getSample(xyzw);\n return sample + spreadMatrix * (spreadOffset + xyzw);\n}\n","sprite.fragment":"varying vec2 vSprite;\n\nvec4 getSample(vec2 xy);\n\nvec4 getSpriteColor() {\n return getSample(vSprite);\n}","sprite.position":"uniform vec2 spriteOffset;\nuniform float spriteScale;\nuniform float spriteDepth;\nuniform float spriteSnap;\n\nuniform vec2 renderOdd;\nuniform float renderScale;\nuniform float renderScaleInv;\nuniform float pixelUnit;\nuniform float focusDepth;\n\nuniform vec4 geometryClip;\nattribute vec4 position4;\nattribute vec2 sprite;\n\nvarying float vPixelSize;\n\n// External\nvec3 getPosition(vec4 xyzw, float canonical);\nvec4 getSprite(vec4 xyzw);\n\nvec3 getSpritePosition() {\n // Clip points\n vec4 p = min(geometryClip, position4);\n float diff = length(position4 - p);\n if (diff > 0.0) {\n return vec3(0.0, 0.0, 1000.0);\n }\n\n // Make sprites\n vec3 center = getPosition(p, 1.0);\n vec4 atlas = getSprite(p);\n\n // Sprite goes from -1..1, width = 2.\n // -1..1 -> -0.5..0.5\n vec2 halfSprite = sprite * .5;\n vec2 halfFlipSprite = vec2(halfSprite.x, -halfSprite.y);\n\n#ifdef POSITION_UV\n // Assign UVs\n vUV = atlas.xy + atlas.zw * (halfFlipSprite + .5);\n#endif\n\n // Depth blending\n // TODO: orthographic camera\n // Workaround: set depth = 0\n float depth = focusDepth, z;\n z = -center.z;\n if (spriteDepth < 1.0) {\n depth = mix(z, focusDepth, spriteDepth);\n }\n \n // Match device/unit mapping \n float size = pixelUnit * spriteScale;\n float depthSize = depth * size;\n\n // Calculate pixelSize for anti-aliasing\n float pixelSize = (spriteDepth > 0.0 ? depthSize / z : size);\n vPixelSize = pixelSize;\n\n // Position sprite\n vec2 atlasOdd = fract(atlas.zw / 2.0);\n vec2 offset = (spriteOffset + halfSprite * atlas.zw) * depthSize;\n if (spriteSnap > 0.5) {\n // Snap to pixel (w/ epsilon shift to avoid jitter)\n return vec3(((floor(center.xy / center.z * renderScale + 0.001) + renderOdd + atlasOdd) * center.z + offset) * renderScaleInv, center.z);\n }\n else {\n // Place directly\n return center + vec3(offset * renderScaleInv, 0.0);\n }\n\n}\n","stereographic.position":"uniform float stereoBend;\n\nuniform mat4 viewMatrix;\n\nvec4 getStereoPosition(vec4 position, inout vec4 stpq) {\n if (stereoBend > 0.0001) {\n\n vec3 pos = position.xyz;\n float r = length(pos);\n float z = r + pos.z;\n vec3 project = vec3(pos.xy / z, r);\n \n vec3 lerped = mix(pos, project, stereoBend);\n\n return viewMatrix * vec4(lerped, 1.0);\n }\n else {\n return viewMatrix * vec4(position.xyz, 1.0);\n }\n}","stereographic4.position":"uniform float stereoBend;\nuniform vec4 basisScale;\nuniform vec4 basisOffset;\nuniform mat4 viewMatrix;\nuniform vec2 view4D;\n\nvec4 getStereographic4Position(vec4 position, inout vec4 stpq) {\n \n vec4 transformed;\n if (stereoBend > 0.0001) {\n\n float r = length(position);\n float w = r + position.w;\n vec4 project = vec4(position.xyz / w, r);\n \n transformed = mix(position, project, stereoBend);\n }\n else {\n transformed = position;\n }\n\n vec4 pos4 = transformed * basisScale - basisOffset;\n vec3 xyz = (viewMatrix * vec4(pos4.xyz, 1.0)).xyz;\n return vec4(xyz, pos4.w * view4D.y + view4D.x);\n}\n","stpq.sample.2d":"varying vec2 vST;\n\nvec4 getSample(vec2 st);\n\nvec4 getSTSample() {\n return getSample(vST);\n}\n","stpq.xyzw.2d":"varying vec2 vUV;\n\nvoid setRawUV(vec4 xyzw) {\n vUV = xyzw.xy;\n}\n","strip.position.normal":"uniform vec4 geometryClip;\nattribute vec4 position4;\nattribute vec3 strip;\n\n// External\nvec3 getPosition(vec4 xyzw, float canonical);\n\nvarying vec3 vNormal;\nvarying vec3 vLight;\nvarying vec3 vPosition;\n\nvoid getStripGeometry(vec4 xyzw, vec3 strip, out vec3 pos, out vec3 normal) {\n vec3 a, b, c;\n\n a = getPosition(xyzw, 1.0);\n b = getPosition(vec4(xyzw.xyz, strip.x), 0.0);\n c = getPosition(vec4(xyzw.xyz, strip.y), 0.0);\n\n normal = normalize(cross(c - a, b - a)) * strip.z;\n \n pos = a;\n}\n\nvec3 getStripPositionNormal() {\n vec3 center, normal;\n\n vec4 p = min(geometryClip, position4);\n\n getStripGeometry(p, strip, center, normal);\n vNormal = normal;\n vLight = normalize((viewMatrix * vec4(1.0, 2.0, 2.0, 0.0)).xyz);\n vPosition = -center;\n\n return center;\n}\n","style.color":"uniform vec3 styleColor;\nuniform float styleOpacity;\n\nvec4 getStyleColor() {\n return vec4(styleColor, styleOpacity);\n}\n","subdivide.depth":"uniform float subdivideBevel;\n\n// External\nvec4 sampleData(vec4 xyzw);\n\nvec4 subdivideDepth(vec4 xyzw) {\n float x = xyzw.z;\n float i = floor(x);\n float f = x - i;\n\n float minf = subdivideBevel * min(f, 1.0 - f);\n float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5;\n\n return sampleData(vec4(xyzw.xy, i + g, xyzw.w));\n}\n","subdivide.depth.lerp":"uniform float subdivideBevel;\n\n// External\nvec4 sampleData(vec4 xyzw);\n\nvec4 subdivideDepthLerp(vec4 xyzw) {\n float x = xyzw.z;\n float i = floor(x);\n float f = x - i;\n\n float minf = subdivideBevel * min(f, 1.0 - f);\n float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5;\n\n vec4 xyzw1 = vec4(xyzw.xy, i, xyzw.w);\n vec4 xyzw2 = vec4(xyzw.xy, i + 1.0, xyzw.w);\n \n vec4 a = sampleData(xyzw1);\n vec4 b = sampleData(xyzw2);\n\n return mix(a, b, g);\n}\n","subdivide.height":"uniform float subdivideBevel;\n\n// External\nvec4 sampleData(vec4 xyzw);\n\nvec4 subdivideHeight(vec4 xyzw) {\n float x = xyzw.y;\n float i = floor(x);\n float f = x - i;\n\n float minf = subdivideBevel * min(f, 1.0 - f);\n float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5;\n\n return sampleData(vec4(xyzw.x, i + g, xyzw.zw));\n}\n","subdivide.height.lerp":"uniform float subdivideBevel;\n\n// External\nvec4 sampleData(vec4 xyzw);\n\nvec4 subdivideHeightLerp(vec4 xyzw) {\n float x = xyzw.y;\n float i = floor(x);\n float f = x - i;\n\n float minf = subdivideBevel * min(f, 1.0 - f);\n float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5;\n\n vec4 xyzw1 = vec4(xyzw.x, i, xyzw.zw);\n vec4 xyzw2 = vec4(xyzw.x, i + 1.0, xyzw.zw);\n \n vec4 a = sampleData(xyzw1);\n vec4 b = sampleData(xyzw2);\n\n return mix(a, b, g);\n}\n","subdivide.items":"uniform float subdivideBevel;\n\n// External\nvec4 sampleData(vec4 xyzw);\n\nvec4 subdivideItems(vec4 xyzw) {\n float x = xyzw.w;\n float i = floor(x);\n float f = x - i;\n\n float minf = subdivideBevel * min(f, 1.0 - f);\n float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5;\n\n return sampleData(vec4(xyzw.xyz, i + g));\n}\n","subdivide.items.lerp":"uniform float subdivideBevel;\n\n// External\nvec4 sampleData(vec4 xyzw);\n\nvec4 subdivideItemsLerp(vec4 xyzw) {\n float x = xyzw.w;\n float i = floor(x);\n float f = x - i;\n\n float minf = subdivideBevel * min(f, 1.0 - f);\n float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5;\n\n vec4 xyzw1 = vec4(xyzw.xyz, i);\n vec4 xyzw2 = vec4(xyzw.xyz, i + 1.0);\n \n vec4 a = sampleData(xyzw1);\n vec4 b = sampleData(xyzw2);\n\n return mix(a, b, g);\n}\n","subdivide.width":"uniform float subdivideBevel;\n\n// External\nvec4 sampleData(vec4 xyzw);\n\nvec4 subdivideWidth(vec4 xyzw) {\n float x = xyzw.x;\n float i = floor(x);\n float f = x - i;\n\n float minf = subdivideBevel * min(f, 1.0 - f);\n float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5;\n\n return sampleData(vec4(i + g, xyzw.yzw));\n}\n","subdivide.width.lerp":"uniform float subdivideBevel;\n\n// External\nvec4 sampleData(vec4 xyzw);\n\nvec4 subdivideWidthLerp(vec4 xyzw) {\n float x = xyzw.x;\n float i = floor(x);\n float f = x - i;\n\n float minf = subdivideBevel * min(f, 1.0 - f);\n float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5;\n\n vec4 xyzw1 = vec4(i, xyzw.yzw);\n vec4 xyzw2 = vec4(i + 1.0, xyzw.yzw);\n \n vec4 a = sampleData(xyzw1);\n vec4 b = sampleData(xyzw2);\n\n return mix(a, b, g);\n}\n","surface.mask.hollow":"attribute vec4 position4;\n\nfloat getSurfaceHollowMask(vec4 xyzw) {\n vec4 df = abs(fract(position4) - .5);\n vec2 df2 = min(df.xy, df.zw);\n float df3 = min(df2.x, df2.y);\n return df3;\n}","surface.position":"uniform vec4 geometryClip;\nuniform vec4 geometryResolution;\nuniform vec4 mapSize;\n\nattribute vec4 position4;\n\n// External\nvec3 getPosition(vec4 xyzw, float canonical);\n\nvec3 getSurfacePosition() {\n vec4 p = min(geometryClip, position4);\n vec3 xyz = getPosition(p, 1.0);\n\n // Overwrite UVs\n#ifdef POSITION_UV\n#ifdef POSITION_UV_INT\n vUV = -.5 + (position4.xy * geometryResolution.xy) * mapSize.xy;\n#else\n vUV = position4.xy * geometryResolution.xy;\n#endif\n#endif\n\n return xyz;\n}\n","surface.position.normal":"uniform vec4 mapSize;\nuniform vec4 geometryResolution;\nuniform vec4 geometryClip;\nattribute vec4 position4;\nattribute vec2 surface;\n\n// External\nvec3 getPosition(vec4 xyzw, float canonical);\n\nvoid getSurfaceGeometry(vec4 xyzw, float edgeX, float edgeY, out vec3 left, out vec3 center, out vec3 right, out vec3 up, out vec3 down) {\n vec4 deltaX = vec4(1.0, 0.0, 0.0, 0.0);\n vec4 deltaY = vec4(0.0, 1.0, 0.0, 0.0);\n\n /*\n // high quality, 5 tap\n center = getPosition(xyzw, 1.0);\n left = (edgeX > -0.5) ? getPosition(xyzw - deltaX, 0.0) : center;\n right = (edgeX < 0.5) ? getPosition(xyzw + deltaX, 0.0) : center;\n down = (edgeY > -0.5) ? getPosition(xyzw - deltaY, 0.0) : center;\n up = (edgeY < 0.5) ? getPosition(xyzw + deltaY, 0.0) : center;\n */\n \n // low quality, 3 tap\n center = getPosition(xyzw, 1.0);\n left = center;\n down = center;\n right = (edgeX < 0.5) ? getPosition(xyzw + deltaX, 0.0) : (2.0 * center - getPosition(xyzw - deltaX, 0.0));\n up = (edgeY < 0.5) ? getPosition(xyzw + deltaY, 0.0) : (2.0 * center - getPosition(xyzw - deltaY, 0.0));\n}\n\nvec3 getSurfaceNormal(vec3 left, vec3 center, vec3 right, vec3 up, vec3 down) {\n vec3 dx = right - left;\n vec3 dy = up - down;\n vec3 n = cross(dy, dx);\n if (length(n) > 0.0) {\n return normalize(n);\n }\n return vec3(0.0, 1.0, 0.0);\n}\n\nvarying vec3 vNormal;\nvarying vec3 vLight;\nvarying vec3 vPosition;\n\nvec3 getSurfacePositionNormal() {\n vec3 left, center, right, up, down;\n\n vec4 p = min(geometryClip, position4);\n\n getSurfaceGeometry(p, surface.x, surface.y, left, center, right, up, down);\n vNormal = getSurfaceNormal(left, center, right, up, down);\n vLight = normalize((viewMatrix * vec4(1.0, 2.0, 2.0, 0.0)).xyz); // hardcoded directional light\n vPosition = -center;\n\n#ifdef POSITION_UV\n#ifdef POSITION_UV_INT\n vUV = -.5 + (position4.xy * geometryResolution.xy) * mapSize.xy;\n#else\n vUV = position4.xy * geometryResolution.xy;\n#endif\n#endif\n \n return center;\n}\n","ticks.position":"uniform float worldUnit;\nuniform float focusDepth;\nuniform float tickSize;\nuniform float tickEpsilon;\nuniform vec3 tickNormal;\nuniform vec2 tickStrip;\n\nvec4 getSample(vec4 xyzw);\n\nvec3 transformPosition(vec4 position, in vec4 stpqIn, out vec4 stpqOut);\n\nvec3 getTickPosition(vec4 xyzw, in vec4 stpqIn, out vec4 stpqOut) {\n float epsilon = tickEpsilon;\n\n // determine tick direction\n float leftX = max(tickStrip.x, xyzw.y - 1.0);\n float rightX = min(tickStrip.y, xyzw.y + 1.0);\n \n vec4 left = getSample(vec4(leftX, xyzw.zw, 0.0));\n vec4 right = getSample(vec4(rightX, xyzw.zw, 0.0));\n vec4 diff = right - left;\n\n vec3 normal = cross(normalize(diff.xyz + vec3(diff.w)), tickNormal);\n float bias = max(0.0, 1.0 - length(normal) * 2.0);\n normal = mix(normal, tickNormal.yzx, bias * bias);\n \n // transform (point) and (point + delta)\n vec4 center = getSample(vec4(xyzw.yzw, 0.0));\n vec4 delta = vec4(normal, 0.0) * epsilon;\n\n vec4 a = center;\n vec4 b = center + delta;\n\n vec4 _;\n vec3 c = transformPosition(a, stpqIn, stpqOut);\n vec3 d = transformPosition(b, stpqIn, _);\n \n // sample on either side to create line\n float line = xyzw.x - .5;\n vec3 mid = c;\n vec3 side = normalize(d - c);\n\n return mid + side * line * tickSize * worldUnit * focusDepth;\n}\n","transform3.position":"uniform mat4 transformMatrix;\n\nvec4 transformPosition(vec4 position, inout vec4 stpq) {\n return transformMatrix * vec4(position.xyz, 1.0);\n}\n","transform4.position":"uniform mat4 transformMatrix;\nuniform vec4 transformOffset;\n\nvec4 transformPosition(vec4 position, inout vec4 stpq) {\n return transformMatrix * position + transformOffset;\n}\n","view.position":"// Implicit three.js uniform\n// uniform mat4 viewMatrix;\n\nvec4 getViewPosition(vec4 position, inout vec4 stpq) {\n return (viewMatrix * vec4(position.xyz, 1.0));\n}\n"}},{}],2:[function(t,e,n){function r(t){return function(e){return s(e,i(t))}}function i(t){for(var e in t)o(t,e)&&(t[e]=Function("return function(node, attr) { return node."+t[e]+" }"),t[e]=t[e]());return t}function o(t,e){return t.hasOwnProperty(e)&&"string"==typeof t[e]}function s(t,e){function n(t){var e;return"comma"===t.type?void y.unshift(g=[]):"op"===t.type||"any-child"===t.type?(g.unshift(v[t.data]),void g.unshift(i())):(g[0]=g[0]||i(),e=g[0],"!"===t.type?void(e.subject=y[0].subject=!0):void e.push("class"===t.type?o(t.type,t.data):"attr"===t.type?s(t):":"===t.type||"::"===t.type?m(t):"*"===t.type?Boolean:h(t.type,t.data)))}function r(t,e){function n(t){for(var e;t.length;)e=t.shift(),-1===u.indexOf(e)&&u.push(e)}var r,i,o,s,u;o=t,u=[];for(var h=0,l=y.length;l>h;++h){g=y[h],r=a,i=g.length,t=o,s=[];for(var c=0;i>c&&(t=r(t,g[c],s),t);c+=2)r=g[c+1];if(c>=i){if(e)return!0;n(g.subject?s:[o])}}return e?!1:u.length?1===u.length?u[0]:u:!1}function i(){function t(e,n){for(var r=0,i=t.bits.length;i>r;++r)if(!t.bits[r](e))return!1;return t.subject&&n.push(e),!0}return t.bits=[],t.subject=!1,t.push=function(e){t.bits.push(e)},t}function o(t,n){return function(r){var i=e[t](r);return i=Array.isArray(i)?i:i?i.toString().split(/\s+/):[],i.indexOf(n)>=0}}function s(t){return t.data.lhs?c(e.attr,t.data.lhs,t.data.cmp,t.data.rhs):c(e.attr,t.data)}function h(t,n){return function(r){return e[t](r)==n}}function l(t,n,r){do t=e.parent(t);while(t&&!n(t,r));return t}function p(t,n,r){return t=e.parent(t),t&&n(t,r)?t:null}function f(t,n,r){var i,o=e.parent(t),s=0;i=e.children(o);for(var a=0,u=i.length;u>a;++a)if(i[a]===t){s=a;break}return i[s-1]&&n(i[s-1],r)?i[s-1]:null}function d(t,n,r){var i,o=e.parent(t);i=e.children(o);for(var s=0,a=i.length;a>s;++s){if(i[s]===t)return null;if(n(i[s],r))return i[s]}return null}function m(t){return u(e,t.data)}var v,g,E=T(),y=[[]];return g=y[0],v={"":l,">":p,"+":f,"~":d},E.on("data",n).end(t),r}function a(t,e,n){return e(t,n)?t:null}function u(t,e){switch(e){case"empty":return d(t);case"first-child":return p(t);case"last-child":return f(t);case"root":return m(t)}return 0===e.indexOf("contains")?v(t,e.slice(9,-1)):0===e.indexOf("any")?l(t,e.slice(4,-1)):0===e.indexOf("not")?h(t,e.slice(4,-1)):function(){return!1}}function h(t,e){function n(t){return!r(t,!0)}var r=s(e,t);return n}function l(t,e){var n=s(e,t);return n}function c(t,e,n,r){return function(i){var o=t(i,e);return n?1===n.length?o==r:void 0===o||null===o?!1:x[n.charAt(0)](o,r):!!o}}function p(t){return function(e){return t.children(t.parent(e))[0]===e}}function f(t){return function(e){var n=t.children(t.parent(e));return n[n.length-1]===e}}function d(t){return function(e){return 0===t.children(e).length}}function m(t){return function(e){return!t.parent(e)}}function v(t,e){return function(n){return-1!==t.contents(n).indexOf(e)}}function g(t,e){return t.slice(t.length-e.length)===e}function E(t,e){return t.slice(0,e.length)===e}function y(t,e){return t.indexOf(e)>-1}function _(t,e){return t.split(/\s+/).indexOf(e)>-1}function b(t,e){return t.split("-").indexOf(e)>-1}e.exports=r;var T=t("./tokenizer"),x={$:g,"^":E,"*":y,"~":_,"|":b}},{"./tokenizer":4}],3:[function(t,e,n){(function(r){function i(t,e,n){function i(){for(;h.length&&!c.paused;){var t=h.shift();if(null===t)return c.emit("end");c.emit("data",t)}}function s(){c.writable=!1,e.call(c),!c.readable&&c.autoDestroy&&c.destroy()}t=t||function(t){this.queue(t)},e=e||function(){this.queue(null)};var a=!1,u=!1,h=[],l=!1,c=new o;return c.readable=c.writable=!0,c.paused=!1,c.autoDestroy=!(n&&n.autoDestroy===!1),c.write=function(e){return t.call(this,e),!c.paused},c.queue=c.push=function(t){return l?c:(null===t&&(l=!0),h.push(t),i(),c)},c.on("end",function(){c.readable=!1,!c.writable&&c.autoDestroy&&r.nextTick(function(){c.destroy()})}),c.end=function(t){return a?void 0:(a=!0,arguments.length&&c.write(t),s(),c)},c.destroy=function(){return u?void 0:(u=!0,a=!0,h.length=0,c.writable=c.readable=!1,c.emit("close"),c)},c.pause=function(){return c.paused?void 0:(c.paused=!0,c)},c.resume=function(){return c.paused&&(c.paused=!1,c.emit("resume")),i(),c.paused||c.emit("drain"),c},c}var o=t("stream");n=e.exports=i,i.through=i}).call(this,t("1YiZ5S"))},{"1YiZ5S":10,stream:12}],4:[function(t,e,n){function r(){function t(t){for(j=j.concat(t.split("")),L=j.length;L>G&&(B=j[G++]);)switch(I){case p:n();break;case a:w();break;case f:x();break;case s:M();break;case u:S();break;case h:k();break;case c:case l:R();break;case o:H();break;case _:case E:case d:A()}j=j.slice(G)}function e(e){arguments.length&&t(e),V.length&&P.queue(C())}function n(){switch(!0){case"#"===B:I=_;break;case"."===B:I=d;break;case":"===B:I=c;break;case"["===B:I=s;break;case"!"===B:r();break;case"*"===B:b();break;case","===B:T();break;case/[>\+~]/.test(B):I=f;break;case/\s/.test(B):I=a;break;case/[\w\d\-_]/.test(B):I=E,--G}}function r(){I=g,V=["!"],P.queue(C()),I=p}function b(){I=y,V=["*"],P.queue(C()),I=p}function T(){I=m,V=[","],P.queue(C()),I=p}function x(){return/[>\+~]/.test(B)?V.push(B):void(/\s/.test(B)||(P.queue(C()),I=p,--G))}function w(){if(!/\s/.test(B)){if(/[>\+~]/.test(B))return--G,I=f;P.queue(C()),I=p,--G}}function R(){if(F=I,A(!0),I===p){if("("===B)return D=V.join(""),I=o,V.length=0,O=1,void++G;I=c,P.queue(C()),I=p}}function H(){if(0!==V.length||z||!(z=/['"]/.test(B)?B:null)){if(z)return N||B!==z?"\\"===B?void(N?V.push(B):N=!0):(N=!1,void V.push(B)):void(z=null);V.push(B),"("===B?++O:")"===B&&--O,O||(V.pop(),P.queue({type:F,data:D+"("+V.join("")+")"}),I=p,D=F=U=null,V.length=0)}}function M(){if(A(!0),I===p){if("]"===B)return I=v,P.queue(C()),void(I=p);D=V.join(""),V.length=0,I=u}}function S(){return/[=~|$^*]/.test(B)&&V.push(B),2===V.length||"="===B?(U=V.join(""),V.length=0,I=h,void(z=null)):void 0}function k(){if(V.length||z||!(z=/['"]/.test(B)?B:null)){if(z)return N||B!==z?"\\"===B?(N&&V.push(B),void(N=!N)):(N=!1,void V.push(B)):void(z=null);A(!0),I===p&&(P.queue({type:v,data:{lhs:D,rhs:V.join(""),cmp:U}}),I=p,D=F=U=null,V.length=0)}}function A(t){return/[^\d\w\-_]/.test(B)&&!N?void("\\"===B?N=!0:(!t&&P.queue(C()),I=p,--G)):(N=!1,void V.push(B))}function C(){var t=V.join("");return V.length=0,{type:I,data:t}}var P,L,z,O,D,F,U,B,N=!1,V=[],I=p,j=[],G=0;return P=i(t,e)}e.exports=r;var i=t("through"),o="pseudo-start",s="attr-start",a="any-child",u="attr-comp",h="attr-end",l="::",c=":",p="(ready)",f="op",d="class",m="comma",v="attr",g="!",E="tag",y="*",_="id"},{through:3}],5:[function(t,e,n){function r(t,e,n){if(!(this instanceof r))return new r(t,e,n);var i=typeof t;if("base64"===e&&"string"===i)for(t=S(t);t.length%4!==0;)t+="=";var o;if("number"===i)o=A(t);else if("string"===i)o=r.byteLength(t,e);else{if("object"!==i)throw new Error("First argument needs to be a number, array or string.");o=A(t.length)}var s;r._useTypedArrays?s=r._augment(new Uint8Array(o)):(s=this,s.length=o,s._isBuffer=!0);var a;if(r._useTypedArrays&&"number"==typeof t.byteLength)s._set(t);else if(P(t))for(a=0;o>a;a++)r.isBuffer(t)?s[a]=t.readUInt8(a):s[a]=t[a];else if("string"===i)s.write(t,0,e);else if("number"===i&&!r._useTypedArrays&&!n)for(a=0;o>a;a++)s[a]=0;return s}function i(t,e,n,i){n=Number(n)||0;var o=t.length-n;i?(i=Number(i),i>o&&(i=o)):i=o;var s=e.length;j(s%2===0,"Invalid hex string"),i>s/2&&(i=s/2);for(var a=0;i>a;a++){var u=parseInt(e.substr(2*a,2),16);j(!isNaN(u),"Invalid hex string"),t[n+a]=u}return r._charsWritten=2*a,a}function o(t,e,n,i){var o=r._charsWritten=U(z(e),t,n,i);return o}function s(t,e,n,i){var o=r._charsWritten=U(O(e),t,n,i);return o}function a(t,e,n,r){return s(t,e,n,r)}function u(t,e,n,i){var o=r._charsWritten=U(F(e),t,n,i);return o}function h(t,e,n,i){var o=r._charsWritten=U(D(e),t,n,i);return o}function l(t,e,n){return 0===e&&n===t.length?G.fromByteArray(t):G.fromByteArray(t.slice(e,n))}function c(t,e,n){var r="",i="";n=Math.min(t.length,n);for(var o=e;n>o;o++)t[o]<=127?(r+=B(i)+String.fromCharCode(t[o]),i=""):i+="%"+t[o].toString(16);return r+B(i)}function p(t,e,n){var r="";n=Math.min(t.length,n);for(var i=e;n>i;i++)r+=String.fromCharCode(t[i]);return r}function f(t,e,n){return p(t,e,n)}function d(t,e,n){var r=t.length;(!e||0>e)&&(e=0),(!n||0>n||n>r)&&(n=r);for(var i="",o=e;n>o;o++)i+=L(t[o]);return i}function m(t,e,n){for(var r=t.slice(e,n),i="",o=0;o=i)){var o;return n?(o=t[e],i>e+1&&(o|=t[e+1]<<8)):(o=t[e]<<8,i>e+1&&(o|=t[e+1])),o}}function g(t,e,n,r){r||(j("boolean"==typeof n,"missing or invalid endian"),j(void 0!==e&&null!==e,"missing offset"),j(e+3=i)){var o;return n?(i>e+2&&(o=t[e+2]<<16),i>e+1&&(o|=t[e+1]<<8),o|=t[e],i>e+3&&(o+=t[e+3]<<24>>>0)):(i>e+1&&(o=t[e+1]<<16),i>e+2&&(o|=t[e+2]<<8),i>e+3&&(o|=t[e+3]),o+=t[e]<<24>>>0),o}}function E(t,e,n,r){r||(j("boolean"==typeof n,"missing or invalid endian"),j(void 0!==e&&null!==e,"missing offset"),j(e+1=i)){var o=v(t,e,n,!0),s=32768&o;return s?-1*(65535-o+1):o}}function y(t,e,n,r){r||(j("boolean"==typeof n,"missing or invalid endian"),j(void 0!==e&&null!==e,"missing offset"),j(e+3=i)){var o=g(t,e,n,!0),s=2147483648&o;return s?-1*(4294967295-o+1):o}}function _(t,e,n,r){return r||(j("boolean"==typeof n,"missing or invalid endian"),j(e+3=o))for(var s=0,a=Math.min(o-n,2);a>s;s++)t[n+s]=(e&255<<8*(r?s:1-s))>>>8*(r?s:1-s)}function x(t,e,n,r,i){i||(j(void 0!==e&&null!==e,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+3=o))for(var s=0,a=Math.min(o-n,4);a>s;s++)t[n+s]=e>>>8*(r?s:3-s)&255}function w(t,e,n,r,i){i||(j(void 0!==e&&null!==e,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+1=o||(e>=0?T(t,e,n,r,i):T(t,65535+e+1,n,r,i))}function R(t,e,n,r,i){i||(j(void 0!==e&&null!==e,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+3=o||(e>=0?x(t,e,n,r,i):x(t,4294967295+e+1,n,r,i))}function H(t,e,n,r,i){i||(j(void 0!==e&&null!==e,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+3=o||W.write(t,e,n,r,23,4)}function M(t,e,n,r,i){i||(j(void 0!==e&&null!==e,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+7=o||W.write(t,e,n,r,52,8)}function S(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function k(t,e,n){return"number"!=typeof t?n:(t=~~t,t>=e?e:t>=0?t:(t+=e,t>=0?t:0))}function A(t){return t=~~Math.ceil(+t),0>t?0:t}function C(t){return(Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)})(t)}function P(t){return C(t)||r.isBuffer(t)||t&&"object"==typeof t&&"number"==typeof t.length}function L(t){return 16>t?"0"+t.toString(16):t.toString(16)}function z(t){for(var e=[],n=0;n=r)e.push(t.charCodeAt(n));else{var i=n;r>=55296&&57343>=r&&n++;for(var o=encodeURIComponent(t.slice(i,n+1)).substr(1).split("%"),s=0;s>8,r=e%256,i.push(r),i.push(n);return i}function F(t){return G.toByteArray(t)}function U(t,e,n,r){for(var i=0;r>i&&!(i+n>=e.length||i>=t.length);i++)e[i+n]=t[i];return i}function B(t){try{return decodeURIComponent(t)}catch(e){return String.fromCharCode(65533)}}function N(t,e){j("number"==typeof t,"cannot write a non-number as a number"),j(t>=0,"specified a negative value for writing an unsigned value"),j(e>=t,"value is larger than maximum value for type"),j(Math.floor(t)===t,"value has a fractional component")}function V(t,e,n){j("number"==typeof t,"cannot write a non-number as a number"),j(e>=t,"value larger than maximum allowed value"),j(t>=n,"value smaller than minimum allowed value"),j(Math.floor(t)===t,"value has a fractional component")}function I(t,e,n){j("number"==typeof t,"cannot write a non-number as a number"),j(e>=t,"value larger than maximum allowed value"),j(t>=n,"value smaller than minimum allowed value")}function j(t,e){if(!t)throw new Error(e||"Failed assertion")}var G=t("base64-js"),W=t("ieee754");n.Buffer=r,n.SlowBuffer=r,n.INSPECT_MAX_BYTES=50,r.poolSize=8192,r._useTypedArrays=function(){try{var t=new ArrayBuffer(0),e=new Uint8Array(t);return e.foo=function(){return 42},42===e.foo()&&"function"==typeof e.subarray}catch(n){return!1}}(),r.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},r.isBuffer=function(t){return!(null===t||void 0===t||!t._isBuffer)},r.byteLength=function(t,e){var n;switch(t+="",e||"utf8"){case"hex":n=t.length/2;break;case"utf8":case"utf-8":n=z(t).length;break;case"ascii":case"binary":case"raw":n=t.length;break;case"base64":n=F(t).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":n=2*t.length;break;default:throw new Error("Unknown encoding")}return n},r.concat=function(t,e){if(j(C(t),"Usage: Buffer.concat(list, [totalLength])\nlist should be an Array."),0===t.length)return new r(0);if(1===t.length)return t[0];var n;if("number"!=typeof e)for(e=0,n=0;nc&&(n=c)):n=c,r=String(r||"utf8").toLowerCase();var p;switch(r){case"hex":p=i(this,t,e,n);break;case"utf8":case"utf-8":p=o(this,t,e,n);break;case"ascii":p=s(this,t,e,n);break;case"binary":p=a(this,t,e,n);break;case"base64":p=u(this,t,e,n);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":p=h(this,t,e,n);break;default:throw new Error("Unknown encoding")}return p},r.prototype.toString=function(t,e,n){var r=this;if(t=String(t||"utf8").toLowerCase(),e=Number(e)||0,n=void 0!==n?Number(n):n=r.length,n===e)return"";var i;switch(t){case"hex":i=d(r,e,n);break;case"utf8":case"utf-8":i=c(r,e,n);break;case"ascii":i=p(r,e,n);break;case"binary":i=f(r,e,n);break;case"base64":i=l(r,e,n);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":i=m(r,e,n);break;default:throw new Error("Unknown encoding")}return i},r.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},r.prototype.copy=function(t,e,n,i){var o=this;if(n||(n=0),i||0===i||(i=this.length),e||(e=0),i!==n&&0!==t.length&&0!==o.length){j(i>=n,"sourceEnd < sourceStart"),j(e>=0&&e=0&&n=0&&i<=o.length,"sourceEnd out of bounds"),i>this.length&&(i=this.length),t.length-es||!r._useTypedArrays)for(var a=0;s>a;a++)t[a+e]=this[a+n];else t._set(this.subarray(n,n+s),e)}},r.prototype.slice=function(t,e){var n=this.length;if(t=k(t,n,0),e=k(e,n,n),r._useTypedArrays)return r._augment(this.subarray(t,e));for(var i=e-t,o=new r(i,void 0,!0),s=0;i>s;s++)o[s]=this[s+t];return o},r.prototype.get=function(t){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(t)},r.prototype.set=function(t,e){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(t,e)},r.prototype.readUInt8=function(t,e){return e||(j(void 0!==t&&null!==t,"missing offset"),j(t=this.length?void 0:this[t]},r.prototype.readUInt16LE=function(t,e){return v(this,t,!0,e)},r.prototype.readUInt16BE=function(t,e){return v(this,t,!1,e)},r.prototype.readUInt32LE=function(t,e){return g(this,t,!0,e)},r.prototype.readUInt32BE=function(t,e){return g(this,t,!1,e)},r.prototype.readInt8=function(t,e){if(e||(j(void 0!==t&&null!==t,"missing offset"),j(t=this.length)){var n=128&this[t];return n?-1*(255-this[t]+1):this[t]}},r.prototype.readInt16LE=function(t,e){return E(this,t,!0,e)},r.prototype.readInt16BE=function(t,e){return E(this,t,!1,e)},r.prototype.readInt32LE=function(t,e){return y(this,t,!0,e)},r.prototype.readInt32BE=function(t,e){return y(this,t,!1,e)},r.prototype.readFloatLE=function(t,e){return _(this,t,!0,e)},r.prototype.readFloatBE=function(t,e){return _(this,t,!1,e)},r.prototype.readDoubleLE=function(t,e){return b(this,t,!0,e)},r.prototype.readDoubleBE=function(t,e){return b(this,t,!1,e)},r.prototype.writeUInt8=function(t,e,n){n||(j(void 0!==t&&null!==t,"missing value"),j(void 0!==e&&null!==e,"missing offset"),j(e=this.length||(this[e]=t)},r.prototype.writeUInt16LE=function(t,e,n){T(this,t,e,!0,n)},r.prototype.writeUInt16BE=function(t,e,n){T(this,t,e,!1,n)},r.prototype.writeUInt32LE=function(t,e,n){x(this,t,e,!0,n)},r.prototype.writeUInt32BE=function(t,e,n){x(this,t,e,!1,n)},r.prototype.writeInt8=function(t,e,n){n||(j(void 0!==t&&null!==t,"missing value"),j(void 0!==e&&null!==e,"missing offset"),j(e=this.length||(t>=0?this.writeUInt8(t,e,n):this.writeUInt8(255+t+1,e,n))},r.prototype.writeInt16LE=function(t,e,n){w(this,t,e,!0,n)},r.prototype.writeInt16BE=function(t,e,n){ +w(this,t,e,!1,n)},r.prototype.writeInt32LE=function(t,e,n){R(this,t,e,!0,n)},r.prototype.writeInt32BE=function(t,e,n){R(this,t,e,!1,n)},r.prototype.writeFloatLE=function(t,e,n){H(this,t,e,!0,n)},r.prototype.writeFloatBE=function(t,e,n){H(this,t,e,!1,n)},r.prototype.writeDoubleLE=function(t,e,n){M(this,t,e,!0,n)},r.prototype.writeDoubleBE=function(t,e,n){M(this,t,e,!1,n)},r.prototype.fill=function(t,e,n){if(t||(t=0),e||(e=0),n||(n=this.length),"string"==typeof t&&(t=t.charCodeAt(0)),j("number"==typeof t&&!isNaN(t),"value is not a number"),j(n>=e,"end < start"),n!==e&&0!==this.length){j(e>=0&&e=0&&n<=this.length,"end out of bounds");for(var r=e;n>r;r++)this[r]=t}},r.prototype.inspect=function(){for(var t=[],e=this.length,r=0;e>r;r++)if(t[r]=L(this[r]),r===n.INSPECT_MAX_BYTES){t[r+1]="...";break}return""},r.prototype.toArrayBuffer=function(){if("undefined"!=typeof Uint8Array){if(r._useTypedArrays)return new r(this).buffer;for(var t=new Uint8Array(this.length),e=0,n=t.length;n>e;e+=1)t[e]=this[e];return t.buffer}throw new Error("Buffer.toArrayBuffer not supported in this browser")};var q=r.prototype;r._augment=function(t){return t._isBuffer=!0,t._get=t.get,t._set=t.set,t.get=q.get,t.set=q.set,t.write=q.write,t.toString=q.toString,t.toLocaleString=q.toString,t.toJSON=q.toJSON,t.copy=q.copy,t.slice=q.slice,t.readUInt8=q.readUInt8,t.readUInt16LE=q.readUInt16LE,t.readUInt16BE=q.readUInt16BE,t.readUInt32LE=q.readUInt32LE,t.readUInt32BE=q.readUInt32BE,t.readInt8=q.readInt8,t.readInt16LE=q.readInt16LE,t.readInt16BE=q.readInt16BE,t.readInt32LE=q.readInt32LE,t.readInt32BE=q.readInt32BE,t.readFloatLE=q.readFloatLE,t.readFloatBE=q.readFloatBE,t.readDoubleLE=q.readDoubleLE,t.readDoubleBE=q.readDoubleBE,t.writeUInt8=q.writeUInt8,t.writeUInt16LE=q.writeUInt16LE,t.writeUInt16BE=q.writeUInt16BE,t.writeUInt32LE=q.writeUInt32LE,t.writeUInt32BE=q.writeUInt32BE,t.writeInt8=q.writeInt8,t.writeInt16LE=q.writeInt16LE,t.writeInt16BE=q.writeInt16BE,t.writeInt32LE=q.writeInt32LE,t.writeInt32BE=q.writeInt32BE,t.writeFloatLE=q.writeFloatLE,t.writeFloatBE=q.writeFloatBE,t.writeDoubleLE=q.writeDoubleLE,t.writeDoubleBE=q.writeDoubleBE,t.fill=q.fill,t.inspect=q.inspect,t.toArrayBuffer=q.toArrayBuffer,t}},{"base64-js":6,ieee754:7}],6:[function(t,e,n){var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(t){"use strict";function e(t){var e=t.charCodeAt(0);return e===s||e===c?62:e===a||e===p?63:u>e?-1:u+10>e?e-u+26+26:l+26>e?e-l:h+26>e?e-h+26:void 0}function n(t){function n(t){h[c++]=t}var r,i,s,a,u,h;if(t.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var l=t.length;u="="===t.charAt(l-2)?2:"="===t.charAt(l-1)?1:0,h=new o(3*t.length/4-u),s=u>0?t.length-4:t.length;var c=0;for(r=0,i=0;s>r;r+=4,i+=3)a=e(t.charAt(r))<<18|e(t.charAt(r+1))<<12|e(t.charAt(r+2))<<6|e(t.charAt(r+3)),n((16711680&a)>>16),n((65280&a)>>8),n(255&a);return 2===u?(a=e(t.charAt(r))<<2|e(t.charAt(r+1))>>4,n(255&a)):1===u&&(a=e(t.charAt(r))<<10|e(t.charAt(r+1))<<4|e(t.charAt(r+2))>>2,n(a>>8&255),n(255&a)),h}function i(t){function e(t){return r.charAt(t)}function n(t){return e(t>>18&63)+e(t>>12&63)+e(t>>6&63)+e(63&t)}var i,o,s,a=t.length%3,u="";for(i=0,s=t.length-a;s>i;i+=3)o=(t[i]<<16)+(t[i+1]<<8)+t[i+2],u+=n(o);switch(a){case 1:o=t[t.length-1],u+=e(o>>2),u+=e(o<<4&63),u+="==";break;case 2:o=(t[t.length-2]<<8)+t[t.length-1],u+=e(o>>10),u+=e(o>>4&63),u+=e(o<<2&63),u+="="}return u}var o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="+".charCodeAt(0),a="/".charCodeAt(0),u="0".charCodeAt(0),h="a".charCodeAt(0),l="A".charCodeAt(0),c="-".charCodeAt(0),p="_".charCodeAt(0);t.toByteArray=n,t.fromByteArray=i}("undefined"==typeof n?this.base64js={}:n)},{}],7:[function(t,e,n){n.read=function(t,e,n,r,i){var o,s,a=8*i-r-1,u=(1<>1,l=-7,c=n?i-1:0,p=n?-1:1,f=t[e+c];for(c+=p,o=f&(1<<-l)-1,f>>=-l,l+=a;l>0;o=256*o+t[e+c],c+=p,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=r;l>0;s=256*s+t[e+c],c+=p,l-=8);if(0===o)o=1-h;else{if(o===u)return s?NaN:(f?-1:1)*(1/0);s+=Math.pow(2,r),o-=h}return(f?-1:1)*s*Math.pow(2,o-r)},n.write=function(t,e,n,r,i,o){var s,a,u,h=8*o-i-1,l=(1<>1,p=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:o-1,d=r?1:-1,m=0>e||0===e&&0>1/e?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=l):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),e+=s+c>=1?p/u:p*Math.pow(2,1-c),e*u>=2&&(s++,u/=2),s+c>=l?(a=0,s=l):s+c>=1?(a=(e*u-1)*Math.pow(2,i),s+=c):(a=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[n+f]=255&a,f+=d,a/=256,i-=8);for(s=s<0;t[n+f]=255&s,f+=d,s/=256,h-=8);t[n+f-d]|=128*m}},{}],8:[function(t,e,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function o(t){return"number"==typeof t}function s(t){return"object"==typeof t&&null!==t}function a(t){return void 0===t}e.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(t){if(!o(t)||0>t||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},r.prototype.emit=function(t){var e,n,r,o,u,h;if(this._events||(this._events={}),"error"===t&&(!this._events.error||s(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}if(n=this._events[t],a(n))return!1;if(i(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:for(r=arguments.length,o=new Array(r-1),u=1;r>u;u++)o[u-1]=arguments[u];n.apply(this,o)}else if(s(n)){for(r=arguments.length,o=new Array(r-1),u=1;r>u;u++)o[u-1]=arguments[u];for(h=n.slice(),r=h.length,u=0;r>u;u++)h[u].apply(this,o)}return!0},r.prototype.addListener=function(t,e){var n;if(!i(e))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?s(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,s(this._events[t])&&!this._events[t].warned){var n;n=a(this._maxListeners)?r.defaultMaxListeners:this._maxListeners,n&&n>0&&this._events[t].length>n&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())}return this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var r=!1;return n.listener=e,this.on(t,n),this},r.prototype.removeListener=function(t,e){var n,r,o,a;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(n=this._events[t],o=n.length,r=-1,n===e||i(n.listener)&&n.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(s(n)){for(a=o;a-->0;)if(n[a]===e||n[a].listener&&n[a].listener===e){r=a;break}if(0>r)return this;1===n.length?(n.length=0,delete this._events[t]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[t],i(n))this.removeListener(t,n);else for(;n.length;)this.removeListener(t,n[n.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.listenerCount=function(t,e){var n;return n=t._events&&t._events[e]?i(t._events[e])?1:t._events[e].length:0}},{}],9:[function(t,e,n){"function"==typeof Object.create?e.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(t,e){t.super_=e;var n=function(){};n.prototype=e.prototype,t.prototype=new n,t.prototype.constructor=t}},{}],10:[function(t,e,n){function r(){}var i=e.exports={};i.nextTick=function(){var t="undefined"!=typeof window&&window.setImmediate,e="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(t)return function(t){return window.setImmediate(t)};if(e){var n=[];return window.addEventListener("message",function(t){var e=t.source;if((e===window||null===e)&&"process-tick"===t.data&&(t.stopPropagation(),n.length>0)){var r=n.shift();r()}},!0),function(t){n.push(t),window.postMessage("process-tick","*")}}return function(t){setTimeout(t,0)}}(),i.title="browser",i.browser=!0,i.env={},i.argv=[],i.on=r,i.addListener=r,i.once=r,i.off=r,i.removeListener=r,i.removeAllListeners=r,i.emit=r,i.binding=function(t){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(t){throw new Error("process.chdir is not supported")}},{}],11:[function(t,e,n){function r(t){return this instanceof r?(a.call(this,t),u.call(this,t),t&&t.readable===!1&&(this.readable=!1),t&&t.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,t&&t.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",i)):new r(t)}function i(){if(!this.allowHalfOpen&&!this._writableState.ended){var t=this;s(function(){t.end()})}}e.exports=r;var o=t("inherits"),s=t("process/browser.js").nextTick,a=t("./readable.js"),u=t("./writable.js");o(r,a),r.prototype.write=u.prototype.write,r.prototype.end=u.prototype.end,r.prototype._write=u.prototype._write},{"./readable.js":15,"./writable.js":17,inherits:9,"process/browser.js":13}],12:[function(t,e,n){function r(){i.call(this)}e.exports=r;var i=t("events").EventEmitter,o=t("inherits");o(r,i),r.Readable=t("./readable.js"),r.Writable=t("./writable.js"),r.Duplex=t("./duplex.js"),r.Transform=t("./transform.js"),r.PassThrough=t("./passthrough.js"),r.Stream=r,r.prototype.pipe=function(t,e){function n(e){t.writable&&!1===t.write(e)&&h.pause&&h.pause()}function r(){h.readable&&h.resume&&h.resume()}function o(){l||(l=!0,t.end())}function s(){l||(l=!0,"function"==typeof t.destroy&&t.destroy())}function a(t){if(u(),0===i.listenerCount(this,"error"))throw t}function u(){h.removeListener("data",n),t.removeListener("drain",r),h.removeListener("end",o),h.removeListener("close",s),h.removeListener("error",a),t.removeListener("error",a),h.removeListener("end",u),h.removeListener("close",u),t.removeListener("close",u)}var h=this;h.on("data",n),t.on("drain",r),t._isStdio||e&&e.end===!1||(h.on("end",o),h.on("close",s));var l=!1;return h.on("error",a),t.on("error",a),h.on("end",u),h.on("close",u),t.on("close",u),t.emit("pipe",h),t}},{"./duplex.js":11,"./passthrough.js":14,"./readable.js":15,"./transform.js":16,"./writable.js":17,events:8,inherits:9}],13:[function(t,e,n){var r=e.exports={};r.nextTick=function(){var t="undefined"!=typeof window&&window.setImmediate,e="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(t)return function(t){return window.setImmediate(t)};if(e){var n=[];return window.addEventListener("message",function(t){var e=t.source;if((e===window||null===e)&&"process-tick"===t.data&&(t.stopPropagation(),n.length>0)){var r=n.shift();r()}},!0),function(t){n.push(t),window.postMessage("process-tick","*")}}return function(t){setTimeout(t,0)}}(),r.title="browser",r.browser=!0,r.env={},r.argv=[],r.binding=function(t){throw new Error("process.binding is not supported")},r.cwd=function(){return"/"},r.chdir=function(t){throw new Error("process.chdir is not supported")}},{}],14:[function(t,e,n){function r(t){return this instanceof r?void i.call(this,t):new r(t)}e.exports=r;var i=t("./transform.js"),o=t("inherits");o(r,i),r.prototype._transform=function(t,e,n){n(null,t)}},{"./transform.js":16,inherits:9}],15:[function(t,e,n){(function(n){function r(e,n){e=e||{};var r=e.highWaterMark;this.highWaterMark=r||0===r?r:16384,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=!1,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.calledRead=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.objectMode=!!e.objectMode,this.defaultEncoding=e.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(x||(x=t("string_decoder").StringDecoder),this.decoder=new x(e.encoding),this.encoding=e.encoding)}function i(t){return this instanceof i?(this._readableState=new r(t,this),this.readable=!0,void R.call(this)):new i(t)}function o(t,e,n,r,i){var o=h(e,n);if(o)t.emit("error",o);else if(null===n||void 0===n)e.reading=!1,e.ended||l(t,e);else if(e.objectMode||n&&n.length>0)if(e.ended&&!i){var a=new Error("stream.push() after EOF");t.emit("error",a)}else if(e.endEmitted&&i){var a=new Error("stream.unshift() after end event");t.emit("error",a)}else!e.decoder||i||r||(n=e.decoder.write(n)),e.length+=e.objectMode?1:n.length,i?e.buffer.unshift(n):(e.reading=!1,e.buffer.push(n)),e.needReadable&&c(t),f(t,e);else i||(e.reading=!1);return s(e)}function s(t){return!t.ended&&(t.needReadable||t.length=k)t=k;else{t--;for(var e=1;32>e;e<<=1)t|=t>>e;t++}return t}function u(t,e){return 0===e.length&&e.ended?0:e.objectMode?0===t?0:1:isNaN(t)||null===t?e.flowing&&e.buffer.length?e.buffer[0].length:e.length:0>=t?0:(t>e.highWaterMark&&(e.highWaterMark=a(t)),t>e.length?e.ended?e.length:(e.needReadable=!0,0):t)}function h(t,e){var n=null;return H.isBuffer(e)||"string"==typeof e||null===e||void 0===e||t.objectMode||n||(n=new TypeError("Invalid non-string/buffer chunk")),n}function l(t,e){if(e.decoder&&!e.ended){var n=e.decoder.end();n&&n.length&&(e.buffer.push(n),e.length+=e.objectMode?1:n.length)}e.ended=!0,e.length>0?c(t):_(t)}function c(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(e.emittedReadable=!0,e.sync?M(function(){p(t)}):p(t))}function p(t){t.emit("readable")}function f(t,e){e.readingMore||(e.readingMore=!0,M(function(){d(t,e)}))}function d(t,e){for(var n=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length0)return;return 0===r.pipesCount?(r.flowing=!1,void(w.listenerCount(t,"data")>0&&E(t))):void(r.ranOut=!0)}function g(){this._readableState.ranOut&&(this._readableState.ranOut=!1,v(this))}function E(t,e){var n=t._readableState;if(n.flowing)throw new Error("Cannot switch to old mode now.");var r=e||!1,i=!1;t.readable=!0,t.pipe=R.prototype.pipe,t.on=t.addListener=R.prototype.on,t.on("readable",function(){i=!0;for(var e;!r&&null!==(e=t.read());)t.emit("data",e);null===e&&(i=!1,t._readableState.needReadable=!0)}),t.pause=function(){r=!0,this.emit("pause")},t.resume=function(){r=!1,i?M(function(){t.emit("readable")}):this.read(0),this.emit("resume")},t.emit("readable")}function y(t,e){var n,r=e.buffer,i=e.length,o=!!e.decoder,s=!!e.objectMode;if(0===r.length)return null;if(0===i)n=null;else if(s)n=r.shift();else if(!t||t>=i)n=o?r.join(""):H.concat(r,i),r.length=0;else if(th&&t>u;h++){var a=r[0],c=Math.min(t-u,a.length);o?n+=a.slice(0,c):a.copy(n,u,0,c),c0)throw new Error("endReadable called on non-empty stream");!e.endEmitted&&e.calledRead&&(e.ended=!0,M(function(){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}))}function b(t,e){for(var n=0,r=t.length;r>n;n++)e(t[n],n)}function T(t,e){for(var n=0,r=t.length;r>n;n++)if(t[n]===e)return n;return-1}e.exports=i,i.ReadableState=r;var x,w=t("events").EventEmitter,R=t("./index.js"),H=t("buffer").Buffer,M=t("process/browser.js").nextTick,S=t("inherits");S(i,R),i.prototype.push=function(t,e){var n=this._readableState;return"string"!=typeof t||n.objectMode||(e=e||n.defaultEncoding,e!==n.encoding&&(t=new H(t,e),e="")),o(this,n,t,e,!1)},i.prototype.unshift=function(t){var e=this._readableState;return o(this,e,t,"",!0)},i.prototype.setEncoding=function(e){x||(x=t("string_decoder").StringDecoder),this._readableState.decoder=new x(e),this._readableState.encoding=e};var k=8388608;i.prototype.read=function(t){var e=this._readableState;e.calledRead=!0;var n=t;if(("number"!=typeof t||t>0)&&(e.emittedReadable=!1),0===t&&e.needReadable&&(e.length>=e.highWaterMark||e.ended))return c(this),null;if(t=u(t,e),0===t&&e.ended)return 0===e.length&&_(this),null;var r=e.needReadable;e.length-t<=e.highWaterMark&&(r=!0),(e.ended||e.reading)&&(r=!1),r&&(e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1),r&&!e.reading&&(t=u(n,e));var i;return i=t>0?y(t,e):null,null===i&&(e.needReadable=!0,t=0),e.length-=t,0!==e.length||e.ended||(e.needReadable=!0),e.ended&&!e.endEmitted&&0===e.length&&_(this),i},i.prototype._read=function(t){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(t,e){function r(t){t===l&&o()}function i(){t.end()}function o(){t.removeListener("close",a),t.removeListener("finish",u),t.removeListener("drain",d),t.removeListener("error",s),t.removeListener("unpipe",r),l.removeListener("end",i),l.removeListener("end",o),(!t._writableState||t._writableState.needDrain)&&d()}function s(e){h(),0===E&&0===w.listenerCount(t,"error")&&t.emit("error",e)}function a(){t.removeListener("finish",u),h()}function u(){t.removeListener("close",a),h()}function h(){l.unpipe(t)}var l=this,c=this._readableState;switch(c.pipesCount){case 0:c.pipes=t;break;case 1:c.pipes=[c.pipes,t];break;default:c.pipes.push(t)}c.pipesCount+=1;var p=(!e||e.end!==!1)&&t!==n.stdout&&t!==n.stderr,f=p?i:o;c.endEmitted?M(f):l.once("end",f),t.on("unpipe",r);var d=m(l);t.on("drain",d);var E=w.listenerCount(t,"error");return t.once("error",s),t.once("close",a),t.once("finish",u),t.emit("pipe",l),c.flowing||(this.on("readable",g),c.flowing=!0,M(function(){v(l)})),t},i.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,this.removeListener("readable",g),e.flowing=!1,t&&t.emit("unpipe",this),this);if(!t){var n=e.pipes,r=e.pipesCount;e.pipes=null,e.pipesCount=0,this.removeListener("readable",g),e.flowing=!1;for(var i=0;r>i;i++)n[i].emit("unpipe",this);return this}var i=T(e.pipes,t);return-1===i?this:(e.pipes.splice(i,1),e.pipesCount-=1,1===e.pipesCount&&(e.pipes=e.pipes[0]),t.emit("unpipe",this),this)},i.prototype.on=function(t,e){var n=R.prototype.on.call(this,t,e);if("data"!==t||this._readableState.flowing||E(this),"readable"===t&&this.readable){var r=this._readableState;r.readableListening||(r.readableListening=!0,r.emittedReadable=!1,r.needReadable=!0,r.reading?r.length&&c(this,r):this.read(0))}return n},i.prototype.addListener=i.prototype.on,i.prototype.resume=function(){E(this),this.read(0),this.emit("resume")},i.prototype.pause=function(){E(this,!0),this.emit("pause")},i.prototype.wrap=function(t){var e=this._readableState,n=!1,r=this;t.on("end",function(){if(e.decoder&&!e.ended){var t=e.decoder.end();t&&t.length&&r.push(t)}r.push(null)}),t.on("data",function(i){if(e.decoder&&(i=e.decoder.write(i)),i&&(e.objectMode||i.length)){var o=r.push(i);o||(n=!0,t.pause())}});for(var i in t)"function"==typeof t[i]&&"undefined"==typeof this[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));var o=["error","close","destroy","pause","resume"];return b(o,function(e){t.on(e,function(t){return r.emit.apply(r,e,t)})}),r._read=function(e){n&&(n=!1,t.resume())},r},i._fromList=y}).call(this,t("1YiZ5S"))},{"./index.js":12,"1YiZ5S":10,buffer:5,events:8,inherits:9,"process/browser.js":13,string_decoder:18}],16:[function(t,e,n){function r(t,e){this.afterTransform=function(t,n){return i(e,t,n)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null}function i(t,e,n){var r=t._transformState;r.transforming=!1;var i=r.writecb;if(!i)return t.emit("error",new Error("no writecb in Transform class"));r.writechunk=null,r.writecb=null,null!==n&&void 0!==n&&t.push(n),i&&i(e);var o=t._readableState;o.reading=!1,(o.needReadable||o.length=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,n,r),this.charReceived+=r-n,n=r,this.charReceived=55296&&56319>=i)){if(this.charReceived=this.charLength=0,r==t.length)return e;t=t.slice(r,t.length);break}this.charLength+=this.surrogateSize,e=""}var o=this.detectIncompleteChar(t),s=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-o,s),this.charReceived=o,s-=o),e+=t.toString(this.encoding,0,s);var s=e.length-1,i=e.charCodeAt(s);if(i>=55296&&56319>=i){var a=this.surrogateSize;return this.charLength+=a,this.charReceived+=a,this.charBuffer.copy(this.charBuffer,a,0,a),this.charBuffer.write(e.charAt(e.length-1),this.encoding),e.substring(0,s)}return e},u.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var n=t[t.length-e];if(1==e&&n>>5==6){this.charLength=2;break}if(2>=e&&n>>4==14){this.charLength=3;break}if(3>=e&&n>>3==30){this.charLength=4;break}}return e},u.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var n=this.charReceived,r=this.charBuffer,i=this.encoding;e+=r.slice(0,n).toString(i)}return e}},{buffer:5}],19:[function(t,e,n){var r=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};n.setOrigin=function(t,e,n){var i,o,s,a;return+e===e&&(e=[e]),o=r.call(e,1)>=0?0:n.x,s=r.call(e,2)>=0?0:n.y,a=r.call(e,3)>=0?0:n.z,i=r.call(e,4)>=0?0:n.w,t.set(o,s,a,i)},n.addOrigin=function(){var t;return t=new THREE.Vector4,function(e,r,i){return n.setOrigin(t,r,i),e.add(t)}}(),n.setDimension=function(t,e){var n,r,i,o;return r=1===e?1:0,i=2===e?1:0,o=3===e?1:0,n=4===e?1:0,t.set(r,i,o,n)},n.setDimensionNormal=function(t,e){var n,r,i,o;return r=1===e?1:0,i=2===e?1:0,o=3===e?1:0,n=4===e?1:0,t.set(i,o+r,n,0)},n.recenterAxis=function(){var t;return t=[0,0],function(e,n,r,i){var o,s,a,u,h,l;return null==i&&(i=0),r>0&&(h=e,l=e+n,o=Math.max(Math.abs(h),Math.abs(l)),s=o*i,u=Math.min(h,l),a=Math.max(h,l),e=u+(-o+s-u)*r,n=a+(o+s-a)*r-e),t[0]=e,t[1]=n,t}}()},{}],20:[function(t,e,n){var r;n.getSizes=r=function(t){var e,n;for(n=[],e=t;"string"!=typeof e&&null!=(null!=e?e.length:void 0);)n.push(e.length),e=e[0];return n},n.getDimensions=function(t,e){var n,i,o,s,a,u,h,l,c,p,f,d,m,v,g;return null==e&&(e={}),a=e.items,n=e.channels,g=e.width,s=e.height,i=e.depth,o={},t&&t.length?(v=r(t),l=v.length,o.channels=1!==n&&v.length>1?v.pop():n,o.items=1!==a&&v.length>1?v.pop():a,o.width=1!==g&&v.length>1?v.pop():g,o.height=1!==s&&v.length>1?v.pop():s,o.depth=1!==i&&v.length>1?v.pop():i,u=l,1===n&&u++,1===a&&u>1&&u++,1===g&&u>2&&u++,1===s&&u>3&&u++,h=null!=(c=v.pop())?c:1,1>=u&&(h/=null!=(p=o.channels)?p:1),2>=u&&(h/=null!=(f=o.items)?f:1),3>=u&&(h/=null!=(d=o.width)?d:1),4>=u&&(h/=null!=(m=o.height)?m:1),h=Math.floor(h),null==o.width&&(o.width=h,h=1),null==o.height&&(o.height=h,h=1),null==o.depth&&(o.depth=h,h=1),o):{items:a,channels:n,width:null!=g?g:0,height:null!=s?s:0,depth:null!=i?i:0}},n.repeatCall=function(t,e){switch(e){case 0:return function(){return!0};case 1:return function(){return t()};case 2:return function(){return t(),t()};case 3:return function(){return t(),t(),t(),t()};case 4:return function(){return t(),t(),t(),t()};case 6:return function(){return t(),t(),t(),t(),t(),t()};case 8:return function(){return t(),t(),t(),t(),t(),t()}}},n.makeEmitter=function(t,e,n){var r,i,o,s;for(r=function(){switch(n){case 0:return function(){return!0};case 1:return function(e){return e(t())};case 2:return function(e){return e(t(),t())};case 3:return function(e){return e(t(),t(),t())};case 4:return function(e){return e(t(),t(),t(),t())};case 6:return function(e){return e(t(),t(),t(),t(),t(),t())};case 8:return function(e){return e(t(),t(),t(),t(),t(),t(),t(),t())}}}(),o=null;e>0;)i=Math.min(e,8),s=function(){switch(i){case 1:return function(t){return r(t)};case 2:return function(t){return r(t),r(t)};case 3:return function(t){return r(t),r(t),r(t)};case 4:return function(t){return r(t),r(t),r(t),r(t)};case 5:return function(t){return r(t),r(t),r(t),r(t),r(t)};case 6:return function(t){return r(t),r(t),r(t),r(t),r(t),r(t)};case 7:return function(t){return r(t),r(t),r(t),r(t),r(t),r(t),r(t)};case 8:return function(t){return r(t),r(t),r(t),r(t),r(t),r(t),r(t),r(t)}}}(),o=null!=o?function(t,e){return function(n){return t(n),e(n)}}(s,o):s,e-=i;return s=null!=o?o:function(){return!0},s.reset=t.reset,s.rebind=t.rebind,s},n.getThunk=function(t){var e,n,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S;switch(H=r(t),d=H.length,e=H.pop(),n=H.pop(),i=H.pop(),o=H.pop(),s=!1,d){case 0:S=function(){return 0},S.reset=function(){};break;case 1:h=0,S=function(){return t[h++]},S.reset=function(){return h=0};break;case 2:h=l=0,a=null!=(m=t[l])?m:[],S=function(){var n,r;return r=a[h++],h===e&&(h=0,l++,a=null!=(n=t[l])?n:[]),r},S.reset=function(){var e;h=l=0,a=null!=(e=t[l])?e:[]};break;case 3:h=l=c=0,R=null!=(v=t[c])?v:[],a=null!=(g=R[l])?g:[],S=function(){var r,i,o;return o=a[h++],h===e&&(h=0,l++,l===n&&(l=0,c++,R=null!=(r=t[c])?r:[]), +a=null!=(i=R[l])?i:[]),o},S.reset=function(){var e,n;h=l=c=0,R=null!=(e=t[c])?e:[],a=null!=(n=R[l])?n:[]};break;case 4:h=l=c=p=0,M=null!=(E=t[p])?E:[],R=null!=(y=M[c])?y:[],a=null!=(_=R[l])?_:[],S=function(){var r,o,s,u;return u=a[h++],h===e&&(h=0,l++,l===n&&(l=0,c++,c===i&&(c=0,p++,M=null!=(r=t[p])?r:[]),R=null!=(o=M[c])?o:[]),a=null!=(s=R[l])?s:[]),u},S.reset=function(){var e,n,r;h=l=c=p=0,M=null!=(e=t[p])?e:[],R=null!=(n=M[c])?n:[],a=null!=(r=R[l])?r:[]};break;case 5:h=l=c=p=f=0,u=null!=(b=t[f])?b:[],M=null!=(T=u[p])?T:[],R=null!=(x=M[c])?x:[],a=null!=(w=R[l])?w:[],S=function(){var r,s,d,m,v;return v=a[h++],h===e&&(h=0,l++,l===n&&(l=0,c++,c===i&&(c=0,p++,p===o&&(p=0,f++,u=null!=(r=t[f])?r:[]),M=null!=(s=u[p])?s:[]),R=null!=(d=M[c])?d:[]),a=null!=(m=R[l])?m:[]),v},S.reset=function(){var e,n,r,i;h=l=c=p=f=0,u=null!=(e=t[f])?e:[],M=null!=(n=u[p])?n:[],R=null!=(r=M[c])?r:[],a=null!=(i=R[l])?i:[]}}return S.rebind=function(o){return t=o,H=r(t),H.length&&(e=H.pop()),H.length&&(n=H.pop()),H.length&&(i=H.pop()),H.length?o=H.pop():void 0},S},n.getStreamer=function(t,e,n,r){var i,o,s,a,u,h,l,c,p;return l=u=h=0,c=function(){return l=e*n*r,u=h=0},o=function(){return h},s=function(){return 0>=l-u},p=function(){switch(n){case 1:return function(t){u+=t,h+=t};case 2:return function(t){u+=2*t,h+=t};case 3:return function(t){u+=3*t,h+=t};case 4:return function(t){u+=4*t,h+=t}}}(),i=function(){switch(n){case 1:return function(e){e(t[u++]),++h};case 2:return function(e){e(t[u++],t[u++]),++h};case 3:return function(e){e(t[u++],t[u++],t[u++]),++h};case 4:return function(e){e(t[u++],t[u++],t[u++],t[u++]),++h}}}(),a=function(){switch(n){case 1:return function(e){t[u++]=e,++h};case 2:return function(e,n){t[u++]=e,t[u++]=n,++h};case 3:return function(e,n,r){t[u++]=e,t[u++]=n,t[u++]=r,++h};case 4:return function(e,n,r,i){t[u++]=e,t[u++]=n,t[u++]=r,t[u++]=i,++h}}}(),i.reset=c,a.reset=c,c(),{emit:a,consume:i,skip:p,count:o,done:s,reset:c}},n.getLerpEmitter=function(t,e){var n,r,i,o,s,a,u,h,l,c,p;return p=new Float32Array(4096),s=a=.5,u=h=l=c=0,r=function(t,e,n,r){return l++,p[u++]=t*s,p[u++]=e*s,p[u++]=n*s,p[u++]=r*s},i=function(t,e,n,r){return c++,p[h++]+=t*a,p[h++]+=e*a,p[h++]+=n*a,p[h++]+=r*a},n=Math.max(t.length,e.length),o=3>=n?function(n,o,s){var a,f,d,m,v,g;for(u=h=l=c=0,t(r,o,s),e(i,o,s),d=Math.min(l,c),f=0,g=[],a=m=0,v=d;v>=0?v>m:m>v;a=v>=0?++m:--m)g.push(n(p[f++],p[f++],p[f++],p[f++]));return g}:5>=n?function(n,o,s,a,f){var d,m,v,g,E,y;for(u=h=l=c=0,t(r,o,s,a,f),e(i,o,s,a,f),v=Math.min(l,c),m=0,y=[],d=g=0,E=v;E>=0?E>g:g>E;d=E>=0?++g:--g)y.push(n(p[m++],p[m++],p[m++],p[m++]));return y}:7>=n?function(n,o,s,a,f,d,m){var v,g,E,y,_;for(u=h=l=c=0,t(r,o,s,a,f,d,m),e(i,o,s,a,f,d,m),g=Math.min(l,c),v=0,_=[],m=E=0,y=g;y>=0?y>E:E>y;m=y>=0?++E:--E)_.push(n(p[v++],p[v++],p[v++],p[v++]));return _}:9>=n?function(n,o,s,a,f,d,m,v,g){var E,y,_,b;for(u=h=l=c=0,t(r,o,s,a,f,d,m,v,g),e(i,o,s,a,f,d,m,v,g),E=Math.min(l,c),g=0,b=[],v=y=0,_=E;_>=0?_>y:y>_;v=_>=0?++y:--y)b.push(n(p[g++],p[g++],p[g++],p[g++]));return b}:function(n,o,s,a,f,d,m,v,g,E,y){var _,b,T,x;for(u=h=0,t(r,o,s,a,f,d,m,v,g,E,y),e(i,o,s,a,f,d,m,v,g,E,y),_=Math.min(l,c),g=0,x=[],v=b=0,T=_;T>=0?T>b:b>T;v=T>=0?++b:--b)x.push(n(p[g++],p[g++],p[g++],p[g++]));return x},o.lerp=function(t){var e;return e=[1-t,t],s=e[0],a=e[1],e},o},n.getLerpThunk=function(t,e){var r,i,o,s,a,u;return i=n.getSizes(t).reduce(function(t,e){return t*e}),o=n.getSizes(e).reduce(function(t,e){return t*e}),r=Math.min(i,o),a=n.getThunk(t),u=n.getThunk(e),s=new Float32Array(r),s.lerp=function(t){var e,n,i,o;for(a.reset(),u.reset(),i=0,o=[];r>i;)e=a(),n=u(),o.push(s[i++]=e+(n-e)*t);return o},s}},{}],21:[function(t,e,n){var r,i;i=Math.PI,r={clamp:function(t,e,n){return Math.max(e,Math.min(n,t))},cosine:function(t){return.5-.5*Math.cos(r.clamp(t,0,1)*i)},binary:function(t){return+(t>=.5)},hold:function(t){return+(t>=1)}},e.exports=r},{}],22:[function(t,e,n){var r,i,o,s,a,u=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};i="xyzw".split(""),r={0:-1,x:0,y:1,z:2,w:3},o=function(t){return t===""+t&&(t=t.split("")),t===+t&&(t=[t]),t},a=function(t){return t===+t&&(t="vec"+t),"vec1"===t&&(t="float"),t},s=function(t){return t=""+t,t.indexOf(".")<0?t+=".0":void 0},n.mapByte2FloatOffset=function(t){var e;return null==t&&(t=4),e=s(t),"vec4 float2ByteIndex(vec4 xyzw, out float channelIndex) {\n float relative = xyzw.w / "+e+";\n float w = floor(relative);\n channelIndex = (relative - w) * "+e+";\n return vec4(xyzw.xyz, w);\n}"},n.sample2DArray=function(t){var e,n;return n=function(t,e){var r,i;return t===e?i="return texture2D(dataTextures["+t+"], uv);":(r=Math.ceil(t+(e-t)/2),i="if (z < "+(r-.5)+") {\n "+n(t,r-1)+"\n}\nelse {\n "+n(r,e)+"\n}"),i=i.replace(/\n/g,"\n ")},e=n(0,t-1),"uniform sampler2D dataTextures["+t+"];\n\nvec4 sample2DArray(vec2 uv, float z) {\n "+e+"\n}"},n.binaryOperator=function(t,e,n){return t=a(t),null!=n?t+" binaryOperator("+t+" a) {\n return a "+e+" "+n+";\n}":t+" binaryOperator("+t+" a, "+t+" b) {\n return a "+e+" b;\n}"},n.extendVec=function(t,e,r){var i,o,u,h;return null==r&&(r=0),t>e?n.truncateVec(t,e):(o=e-t,t=a(t),e=a(e),r=s(r),u=function(){h=[];for(var t=0;o>=0?o>=t:t>=o;o>=0?t++:t--)h.push(t);return h}.apply(this).map(function(t){return t?r:"v"}),i=u.join(","),e+" extendVec("+t+" v) { return "+e+"("+i+"); }")},n.truncateVec=function(t,e){var r;return e>t?n.extendVec(t,e):(r="."+"xyzw".substr(0,e),t=a(t),e=a(e),e+" truncateVec("+t+" v) { return v"+r+"; }")},n.injectVec4=function(t){var e,n,i,s,a,u,h;for(h=["0.0","0.0","0.0","0.0"],t=o(t),t=t.map(function(t){return t===""+t?r[t]:t}),i=s=0,a=t.length;a>s;i=++s)n=t[i],h[n]=["a","b","c","d"][i];return u=h.slice(0,4).join(", "),e=["float a","float b","float c","float d"].slice(0,t.length),"vec4 inject("+e+") {\n return vec4("+u+");\n}"},n.swizzleVec4=function(t,e){var n,i;for(null==e&&(e=null),n=["0.0","xyzw.x","xyzw.y","xyzw.z","xyzw.w"],null==e&&(e=t.length),t=o(t),t=t.map(function(t){var e;return e=+t,u.call([0,1,2,3,4],e)>=0&&(t=+t),t===""+t&&(t=r[t]+1),n[t]});t.lengths;e=++s)u=t[e],l=i[e],n=r[u],c[n]="xyzw."+l;return h=c.join(", "),"vec4 invertSwizzle(vec4 xyzw) {\n return vec4("+h+");\n}"},n.identity=function(t){var e;return e=[].slice.call(arguments),e.length>1?(e=e.map(function(t,e){return["inout",t,String.fromCharCode(97+e)].join(" ")}),e=e.join(", "),"void identity("+e+") { }"):t+" identity("+t+" x) {\n return x;\n}"},n.constant=function(t,e){return t+" constant() {\n return "+e+";\n}"},n.toType=a},{}],23:[function(t,e,n){n.Axis=t("./axis"),n.Data=t("./data"),n.Ease=t("./ease"),n.GLSL=t("./glsl"),n.JS=t("./js"),n.Pretty=t("./pretty"),n.Three=t("./three"),n.Ticks=t("./ticks"),n.VDOM=t("./vdom")},{"./axis":19,"./data":20,"./ease":21,"./glsl":22,"./js":24,"./pretty":25,"./three":26,"./ticks":27,"./vdom":28}],24:[function(t,e,n){n.merge=function(){var t,e,n,r,i,o;for(o={},t=0,n=arguments.length;n>t;t++){r=arguments[t];for(e in r)i=r[e],o[e]=i}return o},n.clone=function(t){return JSON.parse(JSON.serialize(t))},n.parseQuoted=function(t){var e,n,r,i,o,s,a,u,h,l;for(e="",l=function(t){return t=t.replace(/\\/g,"")},a=function(t){return e.length&&s.push(l(e)),e=null!=t?t:""},t=t.split(/(?=(?:\\.|["' ,]))/g),u=!1,s=[],i=0,o=t.length;o>i;i++)switch(r=t[i],n=r[0],h=r.slice(1),n){case'"':case"'":if(u)u===n?(u=!1,a(h)):e+=r;else{if(""!==e)throw new Error("ParseError: String `"+t+"` does not contain comma-separated quoted tokens.");u=n,e+=h}break;case" ":case",":u?e+=r:a(h);break;default:e+=r}return a(),s}},{}],25:[function(t,e,n){var r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E;r=5,i=1e-4,o=function(t,e){return Math.abs(t/e-Math.round(t/e))i?"-":"",i+=n):"1"!==n&&(i+=r?""+n:"*"+n),i+"/"+e},u=[{1:1},{1:1,"τ":2*Math.PI},{1:1,"π":Math.PI},{1:1,"τ":2*Math.PI,"π":Math.PI},{1:1,e:Math.E},{1:1,"τ":2*Math.PI,e:Math.E},{1:1,"π":Math.PI,e:Math.E},{1:1,"τ":2*Math.PI,"π":Math.PI,e:Math.E}],c=[[420,[2,3,5,7]],[88200,[2,3,5,7]],[60060,[2,3,5,7,11,13]],[861764,[2,17,19,23,29]],[65536,[2]],[1e6,[2,5]]],g=function(t){var e,n,o,a,p,f,d,m,v,g;return t&&(e=t.cache,o=t.compact,v=t.tau,d=t.pi,a=t.e,g=t.threshold,m=t.precision),o=+!!(null!=o?o:!0),v=+!!(null!=v?v:!0),d=+!!(null!=d?d:!0),a=+!!(null!=a?a:!0),e=+!!(null!=e?e:!0),g=+(null!=g?g:i),m=+(null!=m?m:r),p=v+2*d+4*a,n=p+g+m,f=e?{}:null,function(t){var e,n,i,a,d,m,v,g,E,y,_,b,T,x,w,R,H,M;if(null!=f){if(null!=(n=f[t]))return n;if(t===Math.round(t))return f[t]=""+t}w=""+t,e=w.length+w.indexOf(".")+2,b=function(t){var n;return n=t.length,e>=n?(w=""+t,e=n):void 0},H=u[p];for(g in H)if(d=H[g],s(t/d))b(""+l(t/d,1,g,o));else for(m=0,E=c.length;E>m;m++)if(M=c[m],a=M[0],_=M[1],x=t/d*a,s(x)){for(v=0,y=_.length;y>v;v++)for(R=_[v];s(T=x/R)&&s(i=a/R);)x=T,a=i;b(""+h(t/d,a,g,o));break}return(""+t).length>r&&b(""+t.toPrecision(r)),null!=f&&(f[t]=w),w}},E=function(t,e){return null==e&&(e="info"),t=v(t),console[e].apply(console,t)},v=function(t){var e,n,r,i,o,s,a,u;return a="color:rgb(128,0,128)",n="color:rgb(144,64,0)",s="color:rgb(0,0,192)",i="color:rgb(0,70,156)",u="color:inherit",o=!1,r=0,e=[],t=t.replace(/(\\[<={}> "'])|(=>|[<={}> "'])/g,function(t,h,l){var c;return(null!=h?h.length:void 0)?h:o&&'"'!==l&&"'"!==l?l:r&&'"'!==l&&"'"!==l&&"{"!==l&&"}"!==l?l:c=function(){switch(l){case"<":return e.push(a),"%c<";case">":return e.push(a),e.push(u),"%c>%c";case" ":return e.push(n)," %c";case"=":case"=>":return e.push(a),"%c"+l;case'"':case"'":return o=!o,o?(e.push(r?n:s),l+"%c"):(e.push(r?i:a),"%c"+l);case"{":return 0===r++?(e.push(i),"%c"+l):l;case"}":return 0===--r?(e.push(a),l+"%c"):l;default:return l}}()}),[t].concat(e)},m=function(t,e){return d(t,e,"=")},f=function(t,e){return d(t,e,"=>")},d=function(){var t;return t=g({compact:!1}),function(e,n,r){var i,o,s;return i=function(t){return t===""+ +t||t.match(/^[A-Za-z_][A-Za-z0-9]*$/)?t:JSON.stringify(t)},s=function(t){return t.match('\n*"')?t:"{"+t+"}"},o=function(e){var n,r;if(e instanceof Array)return"["+e.map(o).join(", ")+"]";switch(typeof e){case"string":return e.match("\n")?'"\n'+e+'"\n':'"'+e+'"';case"function":return e=""+e,e.match("\n"),e=e.replace(/^function (\([^)]+\))/,"$1 =>"),e=e.replace(/^(\([^)]+\)) =>\s*{\s*return\s*([^}]+)\s*;\s*}/,"$1 => $2");case"number":return t(e);default:return null!=e&&e!==!!e?null!=e._up?o(e.map(function(t){return t})):e.toMarkup?e.toString():"{"+function(){var t;t=[];for(n in e)r=e[n],e.hasOwnProperty(n)&&t.push(i(n)+": "+o(r));return t}().join(", ")+"}":""+JSON.stringify(e)}},[e,r,s(o(n))].join("")}}(),a=function(t){return t=t.replace(/&/g,"&"),t=t.replace(/",t=a(t),r=0,i=n.length;i>r;r++)e=n[r],t=t.replace(/%([a-z])/,function(t,e){var r;switch(r=n.shift(),e){case"c":return'';default:return a(r)}});return o+=t,o+=""},e.exports={markup:v,number:g,print:E,format:p,JSX:{prop:m,bind:f}}},{}],26:[function(t,e,n){n.paramToGL=function(t,e){return e===THREE.RepeatWrapping?t.REPEAT:e===THREE.ClampToEdgeWrapping?t.CLAMP_TO_EDGE:e===THREE.MirroredRepeatWrapping?t.MIRRORED_REPEAT:e===THREE.NearestFilter?t.NEAREST:e===THREE.NearestMipMapNearestFilter?t.NEAREST_MIPMAP_NEAREST:e===THREE.NearestMipMapLinearFilter?t.NEAREST_MIPMAP_LINEAR:e===THREE.LinearFilter?t.LINEAR:e===THREE.LinearMipMapNearestFilter?t.LINEAR_MIPMAP_NEAREST:e===THREE.LinearMipMapLinearFilter?t.LINEAR_MIPMAP_LINEAR:e===THREE.UnsignedByteType?t.UNSIGNED_BYTE:e===THREE.UnsignedShort4444Type?t.UNSIGNED_SHORT_4_4_4_4:e===THREE.UnsignedShort5551Type?t.UNSIGNED_SHORT_5_5_5_1:e===THREE.UnsignedShort565Type?t.UNSIGNED_SHORT_5_6_5:e===THREE.ByteType?t.BYTE:e===THREE.ShortType?t.SHORT:e===THREE.UnsignedShortType?t.UNSIGNED_SHORT:e===THREE.IntType?t.INT:e===THREE.UnsignedIntType?t.UNSIGNED_INT:e===THREE.FloatType?t.FLOAT:e===THREE.AlphaFormat?t.ALPHA:e===THREE.RGBFormat?t.RGB:e===THREE.RGBAFormat?t.RGBA:e===THREE.LuminanceFormat?t.LUMINANCE:e===THREE.LuminanceAlphaFormat?t.LUMINANCE_ALPHA:e===THREE.AddEquation?t.FUNC_ADD:e===THREE.SubtractEquation?t.FUNC_SUBTRACT:e===THREE.ReverseSubtractEquation?t.FUNC_REVERSE_SUBTRACT:e===THREE.ZeroFactor?t.ZERO:e===THREE.OneFactor?t.ONE:e===THREE.SrcColorFactor?t.SRC_COLOR:e===THREE.OneMinusSrcColorFactor?t.ONE_MINUS_SRC_COLOR:e===THREE.SrcAlphaFactor?t.SRC_ALPHA:e===THREE.OneMinusSrcAlphaFactor?t.ONE_MINUS_SRC_ALPHA:e===THREE.DstAlphaFactor?t.DST_ALPHA:e===THREE.OneMinusDstAlphaFactor?t.ONE_MINUS_DST_ALPHA:e===THREE.DstColorFactor?t.DST_COLOR:e===THREE.OneMinusDstColorFactor?t.ONE_MINUS_DST_COLOR:e===THREE.SrcAlphaSaturateFactor?t.SRC_ALPHA_SATURATE:0},n.paramToArrayStorage=function(t){switch(t){case THREE.UnsignedByteType:return Uint8Array;case THREE.ByteType:return Int8Array;case THREE.ShortType:return Int16Array;case THREE.UnsignedShortType:return Uint16Array;case THREE.IntType:return Int32Array;case THREE.UnsignedIntType:return Uint32Array;case THREE.FloatType:return Float32Array}},n.swizzleToEulerOrder=function(t){return t.map(function(t){return["","X","Y","Z"][t]}).join("")},n.transformComposer=function(){var t,e,r,i,o;return t=new THREE.Euler,r=new THREE.Quaternion,e=new THREE.Vector3,i=new THREE.Vector3,o=new THREE.Matrix4,function(s,a,u,h,l,c){return null==c&&(c="XYZ"),null!=a?(c instanceof Array&&(c=n.swizzleToEulerOrder(c)),t.setFromVector3(a,c),r.setFromEuler(t)):r.set(0,0,0,1),null!=u&&r.multiply(u),null!=s?e.copy(s):e.set(0,0,0),null!=h?i.copy(h):i.set(1,1,1),o.compose(e,r,i),null!=l&&o.multiplyMatrices(o,l),o}}},{}],27:[function(t,e,n){var r,i,o,s,a;o=function(t,e,n,r,i,o,s,a,u,h){var l,c,p,f,d,m,v,g,E,y;return null==h&&(h=!0),n||(n=10),r||(r=1),i||(i=10),o||(o=1),v=e-t,d=v/n,h?(r||(r=1),i||(i=10),m=r*Math.pow(i,Math.floor(Math.log(d/r)/Math.log(i))),p=i%2===0?[i/2,1,.5]:i%3===0?[i/3,1,1/3]:[1],E=function(){var t,e,n;for(n=[],t=0,e=p.length;e>t;t++)c=p[t],n.push(m*c);return n}(),l=1/0,g=E.reduce(function(t,e){var n;return c=e/d,n=Math.max(c,1/c),l>n?(l=n,e):t},m),g*=o,t=Math.ceil(t/g+ +!s)*g,e=(Math.floor(e/g)-+!a)*g,n=Math.ceil((e-t)/g),y=function(){var e,r,i;for(i=[],f=e=0,r=n;r>=0?r>=e:e>=r;f=r>=0?++e:--e)i.push(t+f*g);return i}(),u||(y=y.filter(function(t){return 0!==t})),y):(y=function(){var e,r,i;for(i=[],f=e=0,r=n;r>=0?r>=e:e>=r;f=r>=0?++e:--e)i.push(t+f*d);return i}(),s||y.shift(),a||y.pop(),u||(y=y.filter(function(t){return 0!==t})),y)},s=function(t,e,n,r,i,o,s,a,u,h){throw new Error("Log ticks not yet implemented.")},r=0,i=1,a=function(t,e,n,a,u,h,l,c,p,f,d){switch(t){case r:return o(e,n,a,u,h,l,c,p,f,d);case i:return s(e,n,a,u,h,l,c,p,f,d)}},n.make=a,n.linear=o,n.log=s},{}],28:[function(t,e,n){var r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b;for(r=[],l=0,i={},a=function(){return{id:l++,type:null,props:null,children:null,rendered:null,instance:null}},h=function(t){var e,n,i,o;for(t*=2,t=Math.max(0,r.length-t),o=[],e=n=0,i=t;i>=0?i>n:n>i;e=i>=0?++n:--n)o.push(r.push(a()));return o},u=function(t,e,n){var i;return i=r.length?r.pop():a(),i.type=null!=t?t:"div",i.props=null!=e?e:null,i.children=null!=n?n:null,i},g=function(t){var e,n,i,o;if(t.type&&(n=t.children,t.type=t.props=t.children=t.instance=null,r.push(t),null!=n))for(i=0,o=n.length;o>i;i++)e=n[i],g(e)},o=function(t,e,n,r,s){var a,h,l,c,p,f,d,v,g,E,T,x,w,R,H,M,S,k,A,C,P,L,z,O,D,F,U,B,N,V;if(null!=t){if(null==e)return m(t,r,s);if(t instanceof Node){if(F=t===e)return}else F=typeof t==typeof e&&null!==e&&null!==t&&t.type===e.type;if(F){if(t.instance=e.instance,B=(null!=(P=t.type)?P.isComponentClass:void 0)?t.type:i[t.type],A=null!=e?e.props:void 0,H=t.props,c=null!=(L=null!=e?e.children:void 0)?L:null,R=t.children,null!=H&&(H.children=R),null!=B){if(f=n._COMPONENT_DIRTY,null!=A!=(null!=H)&&(f=!0),c!==R&&(f=!0),null!=A&&null!=H){if(!f)for(E in A)H.hasOwnProperty(E)||(f=!0);if(!f)for(E in H)V=H[E],(C=A[E])!==V&&(f=!0)}if(f){p=e.instance,null==t.props&&(t.props={}),z=p.defaultProps;for(g in z)N=z[g],null==(a=t.props)[g]&&(a[g]=N);t.props.children=t.children,"function"==typeof p.willReceiveProps&&p.willReceiveProps(t.props),U=n._COMPONENT_FORCE||(null!=(O="function"==typeof p.shouldUpdate?p.shouldUpdate(t.props):void 0)?O:!0),U&&(M=p.getNextState(),"function"==typeof p.willUpdate&&p.willUpdate(t.props,M)),S=p.props,k=p.applyNextState(),p.props=t.props,p.children=t.children,U&&(t=t.rendered="function"==typeof p.render?p.render(u,t.props,t.children):void 0,o(t,e.rendered,n,r,s),"function"==typeof p.didUpdate&&p.didUpdate(S,k))}return}if(null!=A)for(E in A)H.hasOwnProperty(E)||b(n,E,A[E]);if(null!=H)for(E in H)V=H[E],(C=A[E])!==V&&"children"!==E&&y(n,E,V,C);if(null!=R)if("string"==(D=typeof R)||"number"===D)R!==c&&(n.textContent=R);else if(null!=R.type)o(R,c,n.childNodes[0],n,0);else if(l=n.childNodes,null!=c)for(d=v=0,x=R.length;x>v;d=++v)h=R[d],o(h,c[d],l[d],n,d);else for(d=T=0,w=R.length;w>T;d=++T)h=R[d],o(h,null,l[d],n,d);else null!=c&&(_(null,n),n.innerHTML="");return}return _(e.instance,n),n.remove(),m(t,r,s)}return null!=e?(_(e.instance,n),e.node.remove()):void 0},m=function(t,e,n){var r,o,s,a,h,l,c,p,f,d,v,g,E,_,b,T,x,w,R,H;if(null==n&&(n=0),w=(null!=(g=t.type)?g.isComponentClass:void 0)?t.type:i[t.type],t instanceof Node)v=t;else{if(null!=w){if(h=(null!=(E=t.type)?E.isComponentClass:void 0)?t.type:i[t.type],!h)return t=t.rendered=u("noscript"),v=m(t,e,n);t.instance=a=new h(e),null==t.props&&(t.props={}),_=a.defaultProps;for(p in _)R=_[p],null==(r=t.props)[p]&&(r[p]=R);return t.props.children=t.children,a.props=t.props,a.children=t.children,a.setState("function"==typeof a.getInitialState?a.getInitialState():void 0),"function"==typeof a.willMount&&a.willMount(),t=t.rendered="function"==typeof a.render?a.render(u,t.props,t.children):void 0,v=m(t,e,n),"function"==typeof a.didMount&&a.didMount(t),v._COMPONENT=a,v}if("string"==(b=typeof t)||"number"===b)v=document.createTextNode(t);else{v=document.createElement(t.type),T=t.props;for(f in T)H=T[f],y(v,f,H)}if(s=t.children,null!=s)if("string"==(x=typeof s)||"number"===x)v.textContent=s;else if(null!=s.type)m(s,v,0);else for(l=c=0,d=s.length;d>c;l=++c)o=s[l],m(o,v,l)}return e.insertBefore(v,e.childNodes[n]),v},_=function(t,e){var n,r,i,o,s,a;if(t){"function"==typeof t.willUnmount&&t.willUnmount();for(i in t)delete t[i]}for(s=e.childNodes,a=[],r=0,o=s.length;o>r;r++)n=s[r],_(n._COMPONENT,n),a.push(delete n._COMPONENT);return a},v=function(t){var e,n,r,i;if("undefined"==typeof document)return!0;if(null!=document.documentElement.style[t])return t;for(t=t[0].toUpperCase()+t.slice(1),i=["webkit","moz","ms","o"],e=0,n=i.length;n>e;e++)if(r=i[e],null!=document.documentElement.style[r+t])return r+t},d={},E=["transform"],c=0,f=E.length;f>c;c++)p=E[c],d[p]=v(p);y=function(t,e,n,r){var i,o,s;{if("style"!==e)return null!=t[e]?void(t[e]=n):void(t instanceof Node&&t.setAttribute(e,n));for(i in n)s=n[i],(null!=r?r[i]:void 0)!==s&&(t.style[null!=(o=d[i])?o:i]=s)}},b=function(t,e,n){var r,i,o;if("style"!==e)null!=t[e]&&(t[e]=void 0),t instanceof Node&&t.removeAttribute(e);else for(r in n)o=n[r],t.style[null!=(i=d[r])?i:r]=""},s=function(t){var e,n,r,i,o;r={willMount:"componentWillMount",didMount:"componentDidMount",willReceiveProps:"componentWillReceiveProps",shouldUpdate:"shouldComponentUpdate",willUpdate:"componentWillUpdate",didUpdate:"componentDidUpdate",willUnmount:"componentWillUnmount"};for(n in r)i=r[n],null==t[n]&&(t[n]=t[i]);return e=function(){function e(e,n,r,i){var o,s,a,u;this.props=null!=n?n:{},this.state=null!=r?r:null,this.children=null!=i?i:null,o=function(t,e){return"function"==typeof t?t.bind(e):t};for(s in t)u=t[s],this[s]=o(u,this);a=null,this.setState=function(t){null==a&&(a=t?null!=a?a:{}:null);for(s in t)u=t[s],a[s]=u;e._COMPONENT_DIRTY=!0},this.forceUpdate=function(){var t,n;for(e._COMPONENT_FORCE=e._COMPONENT_DIRTY=!0,t=e,n=[];t=t.parentNode;)t._COMPONENT?n.push(t._COMPONENT_FORCE=!0):n.push(void 0);return n},this.getNextState=function(){return a},this.applyNextState=function(){var t,n;return e._COMPONENT_FORCE=e._COMPONENT_DIRTY=!1,t=this.state,n=[null,a],a=n[0],this.state=n[1],t}}return e}(),e.isComponentClass=!0,e.prototype.defaultProps=null!=(o="function"==typeof t.getDefaultProps?t.getDefaultProps():void 0)?o:{},e},e.exports={element:u,recycle:g,apply:o,hint:h,Types:i,createClass:s}},{}],29:[function(t,e,n){var r,i,o,s,a,u,h,l;i=t("./model"),o=t("./overlay"),s=t("./primitives"),a=t("./render"),u=t("./shaders"),h=t("./stage"),l=t("./util"),r=function(){function t(t,e,n){var r;null==e&&(e=null),null==n&&(n=null),this.canvas=r=t.domElement,this.element=null,this.shaders=new u.Factory(u.Snippets),this.renderables=new a.Factory(a.Classes,t,this.shaders),this.overlays=new o.Factory(o.Classes,r),this.scene=this.renderables.make("scene",{scene:e}),this.camera=this.defaultCamera=null!=n?n:new THREE.PerspectiveCamera,this.attributes=new i.Attributes(s.Types,this),this.primitives=new s.Factory(s.Types,this),this.root=this.primitives.make("root"),this.model=new i.Model(this.root),this.guard=new i.Guard,this.controller=new h.Controller(this.model,this.primitives),this.animator=new h.Animator(this),this.api=new h.API(this),this.speed=1,this.time={now:+new Date/1e3,time:0,delta:0,clock:0,step:0}}return t.Namespace={Model:i,Overlay:o,Primitives:s,Render:a,Shaders:u,Stage:h,Util:l,DOM:l.VDOM},t.prototype.init=function(){return this.scene.inject(),this.overlays.inject(),this},t.prototype.destroy=function(){return this.scene.unject(),this.overlays.unject(),this},t.prototype.resize=function(t){return null==t&&(t={}),null==t.renderWidth&&(t.renderWidth=null!=t.viewWidth?t.viewWidth:t.viewWidth=1280),null==t.renderHeight&&(t.renderHeight=null!=t.viewHeight?t.viewHeight:t.viewHeight=720),null==t.pixelRatio&&(t.pixelRatio=t.renderWidth/Math.max(1e-6,t.viewWidth)),null==t.aspect&&(t.aspect=t.viewWidth/Math.max(1e-6,t.viewHeight)),this.root.controller.resize(t),this},t.prototype.frame=function(t){return this.pre(t),this.update(),this.render(),this.post(),this},t.prototype.pre=function(t){var e;return t||(t={now:+new Date/1e3,time:0,delta:0,clock:0,step:0},t.delta=null!=this.time.now?t.now-this.time.now:0,t.delta>1&&(t.delta=1/60),t.step=t.delta*this.speed,t.time=this.time.time+t.delta,t.clock=this.time.clock+t.step),this.time=t,"function"==typeof(e=this.root.controller).pre&&e.pre(),this},t.prototype.update=function(){var t;return this.animator.update(),this.attributes.compute(),this.guard.iterate({step:function(t){return function(){var e;return e=t.attributes.digest(),e||(e=t.model.digest())}}(this),last:function(){return{attribute:this.attributes.getLastTrigger(),model:this.model.getLastTrigger()}}}),"function"==typeof(t=this.root.controller).update&&t.update(),this.camera=this.root.controller.getCamera(),this.speed=this.root.controller.getSpeed(),this},t.prototype.render=function(){var t;return"function"==typeof(t=this.root.controller).render&&t.render(),this.scene.render(),this},t.prototype.post=function(){var t;return"function"==typeof(t=this.root.controller).post&&t.post(),this},t.prototype.setWarmup=function(t){return this.scene.warmup(t),this},t.prototype.getPending=function(){return this.scene.pending.length},t}(),e.exports=r},{"./model":34,"./overlay":40,"./primitives":43,"./render":149,"./shaders":164,"./stage":169,"./util":175}],30:[function(t,e,n){var r,i,o,s,a;o=function(t){var e,n;return n=THREE.Bootstrap(t),n.fallback||(n.Time||n.install("time"),n.MathBox||n.install(["mathbox","splash"])),null!=(e=n.mathbox)?e:n},window.π=Math.PI,window.τ=2*π,window.e=Math.E,window.MathBox=n,window.mathBox=n.mathBox=o,n.version="0.0.5",n.Context=r=t("./context"),s=r.Namespace;for(i in s)a=s[i],n[i]=a;t("./splash"),THREE.Bootstrap.registerPlugin("mathbox",{defaults:{init:!0,warmup:2,inspect:!0,splash:!0},listen:["ready","pre","update","post","resize"],install:function(t){var e;return e=!1,this.first=!0,t.MathBox={init:function(n){return function(i){var o,s;if(!e)return e=!0,s=(null!=i?i.scene:void 0)||n.options.scene||t.scene,o=(null!=i?i.camera:void 0)||n.options.camera||t.camera,n.context=new r(t.renderer,s,o),n.context.api.three=t.three=t,n.context.api.mathbox=t.mathbox=n.context.api,n.context.api.start=function(){return t.Loop.start()},n.context.api.stop=function(){return t.Loop.stop()},n.context.init(),n.context.resize(t.Size),n.context.setWarmup(n.options.warmup),n.pending=0,n.warm=!n.options.warmup,console.log("MathBox²",MathBox.version),t.trigger({type:"mathbox/init",version:MathBox.version,context:n.context})}}(this),destroy:function(n){return function(){return e?(e=!1,t.trigger({type:"mathbox/destroy",context:n.context}),n.context.destroy(),delete t.mathbox,delete n.context.api.three,delete n.context):void 0}}(this),object:function(t){return function(){var e;return null!=(e=t.context)?e.scene.root:void 0}}(this)}},uninstall:function(t){return t.MathBox.destroy(),delete t.MathBox},ready:function(t,e){return this.options.init?(e.MathBox.init(),setTimeout(function(t){return function(){return t.options.inspect?t.inspect(e):void 0}}(this))):void 0},inspect:function(t){return this.context.api.inspect(),this.options.warmup?void 0:this.info(t)},info:function(t){var e,n;return e=function(t){var e;for(e=[];t>=1e3;)e.unshift(("000"+t%1e3).slice(-3)),t=Math.floor(t/1e3);return e.unshift(t),e.join(",")},n=t.renderer.info.render,console.log("Geometry ",e(n.faces)+" faces ",e(n.vertices)+" vertices ",e(n.calls)+" draw calls ")},resize:function(t,e){var n;return null!=(n=this.context)?n.resize(e.Size):void 0},pre:function(t,e){var n;return null!=(n=this.context)?n.pre(e.Time):void 0},update:function(t,e){var n,r,i,o;return null!=(r=this.context)&&r.update(),(n=null!=(i=this.context)?i.camera:void 0)&&n!==e.camera&&(e.camera=n),e.Time.set({speed:this.context.speed}),this.progress(this.context.getPending(),e),null!=(o=this.context)?o.render():void 0},post:function(t,e){var n;return null!=(n=this.context)?n.post():void 0},progress:function(t,e){var n,r,i;if(t||this.pending)return r=Math.max(t+this.options.warmup,this.pending),n=r-t,i=r,e.trigger({type:"mathbox/progress",current:r-t,total:r}),0===t&&(r=0),this.pending=r,n===i&&!this.warm&&(this.warm=!0,this.options.inspect)?this.info(e):void 0}})},{"./context":29,"./splash":165}],31:[function(t,e,n){var r,i,o;r=function(){function t(t,e){this.context=e,this.traits=t.Traits,this.types=t.Types,this.pending=[],this.bound=[],this.last=null}return t.prototype.make=function(t){return{"enum":"function"==typeof t["enum"]?t["enum"]():void 0,type:"function"==typeof t.uniform?t.uniform():void 0,value:t.make()}},t.prototype.apply=function(t,e){return new i(t,e,this)},t.prototype.bind=function(t){return this.bound.push(t)},t.prototype.unbind=function(t){var e;return this.bound=function(){var n,r,i,o;for(i=this.bound,o=[],n=0,r=i.length;r>n;n++)e=i[n],e!==t&&o.push(e);return o}.call(this)},t.prototype.queue=function(t,e,n,r){return this.lastObject=e,this.lastKey=n,this.lastValue=r,this.pending.push(t)},t.prototype.invoke=function(t){return t(this.context.time.clock,this.context.time.step)},t.prototype.compute=function(){var t,e,n,r;if(this.bound.length)for(r=this.bound,e=0,n=r.length;n>e;e++)t=r[e],this.invoke(t)},t.prototype.digest=function(){var t,e,n,r,i;if(!this.pending.length)return!1;for(i=[this.pending,[]],e=i[0],this.pending=i[1],n=0,r=e.length;r>n;n++)(t=e[n])();return!0},t.prototype.getTrait=function(t){return this.traits[t]},t.prototype.getLastTrigger=function(){return this.lastObject.toString()+" - "+this.lastKey+"=`"+this.lastValue+"`"},t}(),o=function(t){var e,n,r;n={};for(e in t)r=t[e],n[e]=r;return n},i=function(){function t(t,e,n){var r,i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k,A,C,P,L,z,O,D,F,U,B,N,V,I,j,G,W,q,X,Y,Z,K,Q,J,$,tt,et,nt,rt,it;for(J=e.traits,I=e.props,w=e.finals,H=e.freeform,m=this,null!=t.props&&null!=t.expr&&null!=t.orig&&null!=t.computed&&null!=t.attributes&&(N=o(t.props),U=o(t.expr),B=t.orig(),F=t.computed(),null!=(j=t.attributes)&&j.dispose()),R={},V={},z={},Y=function(t){var e;return null!=(e=z[t])?e:t},v=function(e,n){if(z[n])throw new Error(t.toString()+" - Duplicate property `"+n+"`");return z[n]=e},M=function(t){var e,n,r;return null!=(e=null!=(n=m[t])?n.value:void 0)?e:null!=(r=m[Y(t)])?r.value:void 0},W=function(e,n,r,o){var s,h,l,p,f;if(e=Y(e),null==(s=m[e])){if(!H)throw new Error(t.toString()+" - Setting unknown property `"+e+"={"+n+"}`");s=m[e]={"short":e,type:null,last:null,value:null},nt[e]=function(t){return t}}if(!r){if(a[e])throw new Error(t.toString()+" - Can't set bound property `"+e+"={"+n+"}`");if(i[e])throw new Error(t.toString()+" - Can't set computed property `"+e+"={"+n+"}`");if(u[e])throw new Error(t.toString()+" - Can't set final property `"+e+"={"+n+"}`")}return p=!0,f=et(e,n,s.last,function(){return p=!1,null}),p&&(h=[f,s.value],s.value=h[0],s.last=h[1],l=s["short"],R[l]=f,r||(V[l]=n),o||_(e,s.value,s.last)||c(e,n)),p},d=function(t,e,n){return t=Y(t),W(t,e,!0,n),u[t]=!0},x={},r={},s={},a={},i={},u={},l=function(e,o,h){var l,c;if(null==h&&(h=!1),e=Y(e),"function"!=typeof o)throw new Error(t.toString()+" - Expression `"+e+"=>{"+x+"}` is not a function");if(a[e])throw new Error(t.toString()+" - Property `"+e+"=>{"+x+"}` is already bound");if(i[e])throw new Error(t.toString()+" - Property `"+e+"` is computed");if(u[e])throw new Error(t.toString()+" - Property `"+e+"` is final");return l=h?i:a,l[e]=o,c=null!=m[e]?m[e]["short"]:e,h||(x[c]=o),s[e]=o,o=o.bind(t),r[e]=function(n,r){var i,s;return(i=null!=(s=t.clock)?s.getTime():void 0)&&(n=i.clock,r=i.step),t.set(e,o(n,r),!0)},n.bind(r[e])},$=function(t,e){var o;return null==e&&(e=!1),t=Y(t),o=e?i:a,o[t]?(n.unbind(r[t]),delete r[t],delete o[t],null!=m[t]&&(t=m[t]["short"]),delete x[t]):void 0},b=function(t,e){var n;return t=Y(t),null!=(n="function"==typeof s[t]?s[t](e,0):void 0)?n:m[t].value},t.expr=x,t.props=R,t.evaluate=function(t,e){var n;if(null!=t)return b(t,e);n={};for(t in I)n[t]=b(t,e);return n},t.get=function(t){return null!=t?M(t):R},t.set=function(t,e,n,r){var i;if("string"==typeof t)W(t,e,n,r);else{r=n,n=e,i=t;for(t in i)e=i[t],W(t,e,n,r)}},t.bind=function(t,e,n){var r;if("string"==typeof t)l(t,e,n);else{n=e,r=t;for(t in r)e=r[t],l(t,e,n)}},t.unbind=function(t,e){var n;if("string"==typeof t)$(t,e);else{e=x,n=t;for(t in n)$(t,e)}},t.attribute=function(t){return null!=t?m[Y(t)]:m},t.orig=function(t){return null!=t?V[Y(t)]:o(V)},t.computed=function(t){return null!=t?i[Y(t)]:o(i)},L={},nt={},y={},_=function(t,e,n){return y[t](e,n)},et=function(t,e,n,r){return nt[t](e,n,r)},t.validate=function(e,n){var r,i;return e=Y(e),r=L[e],null!=r&&(i=r()),i=et(e,n,i,function(){throw new Error(t.toString()+" - Invalid value `"+e+"={"+n+"}`")})},E=!1,f={},K={},p={},Z={},S=function(t){return t.split(".")[0]},c=function(e,r){var i;return E||(E=!0,n.queue(g,t,e,r)),i=S(e),f[e]=!0,K[i]=!0},T={type:"change",changed:null,touched:null},g=function(){var e,n,r;T.changed=f,T.touched=K,f=p,K=Z,p=T.changed,Z=T.touched,E=!1;for(e in f)f[e]=!1;for(e in K)K[e]=!1;T.type="change",t.trigger(T),n=[];for(r in T.touched)T.type="change:"+r,n.push(t.trigger(T));return n},q=function(t){var e,n;return e=t.split(/\./g),n=e.pop(),e.pop(),e.unshift(n),e.reduce(function(t,e){return t+e.charAt(0).toUpperCase()+e.substring(1)})},h=function(t,e){var n,r,i,o,s,a,u,h;s=[];for(r in e)u=e[r],r=[t,r].join("."),a=q(r),m[r]=n={T:u,ns:t,"short":a,"enum":"function"==typeof u["enum"]?u["enum"]():void 0,type:"function"==typeof u.uniform?u.uniform():void 0,last:u.make(),value:h=u.make()},v(r,a),R[a]=h,L[r]=u.make,nt[r]=null!=(i=u.validate)?i:function(t){return t; +},s.push(y[r]=null!=(o=u.equals)?o:function(t,e){return t===e});return s},P=[],it={},k=0,C=J.length;C>k;k++)Q=J[k],G=Q.split(":"),Q=G[0],D=G[1],O=D?[D,Q].join("."):Q,X=n.getTrait(Q),P.push(Q),null!=X&&h(O,X);if(null!=I)for(D in I)X=I[D],h(D,X);if(tt=P.filter(function(t,e){return P.indexOf(t)===e}),t.traits=tt,null!=N&&t.set(N,!0,!0),null!=w)for(A in w)rt=w[A],d(A,rt,!0);null!=B&&t.set(B,!1,!0),null!=F&&t.bind(F,!0),null!=U&&t.bind(U,!1),this.dispose=function(){for(A in i)$(A,!0);for(A in a)$(A,!1);return I={},delete t.attributes,delete t.get,delete t.set}}return t}(),e.exports=r},{}],32:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("./node"),r=function(t){function e(t,n,r,i,o,s){e.__super__.constructor.call(this,t,n,r,i,o,s),this.children=[],this.on("reindex",function(t){return function(e){var n,r,i,o,s;for(o=t.children,s=[],r=0,i=o.length;i>r;r++)n=o[r],s.push(n.trigger(e));return s}}(this))}return o(e,t),e.prototype.add=function(t){var e;return null!=(e=t.parent)&&e.remove(t),t._index(this.children.length,this),this.children.push(t),t._added(this)},e.prototype.remove=function(t){var e,n,r,i,o,s;if((null!=(o=t.children)?o.length:void 0)&&t.empty(),n=this.children.indexOf(t),-1!==n)for(this.children.splice(n,1),t._index(null),t._removed(this),s=this.children,e=r=0,i=s.length;i>r;e=++r)t=s[e],e>=n&&t._index(e)},e.prototype.empty=function(){var t,e,n,r;for(t=this.children.slice().reverse(),e=0,n=t.length;n>e;e++)r=t[e],this.remove(r)},e}(i),e.exports=r},{"./node":36}],33:[function(t,e,n){var r;r=function(){function t(t){this.limit=null!=t?t:10}return t.prototype.iterate=function(t){var e,n,r,i;for(i=t.step,e=t.last,n=this.limit;r=i();)if(!--n)throw console.warn("Last iteration","function"==typeof e?e():void 0),new Error("Exceeded iteration limit.");return null},t}(),e.exports=r},{}],34:[function(t,e,n){n.Attributes=t("./attributes"),n.Group=t("./group"),n.Guard=t("./guard"),n.Model=t("./model"),n.Node=t("./node")},{"./attributes":31,"./group":32,"./guard":33,"./model":35,"./node":36}],35:[function(t,e,n){var r,i,o,s,a,u,h,l,c,p=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};l=t("cssauron"),r="*",s=/^#([A-Za-z0-9_])$/,o=/^\.([A-Za-z0-9_]+)$/,u=/^\[([A-Za-z0-9_]+)\]$/,h=/^[A-Za-z0-9_]+$/,i=/^<([0-9]+|<*)$/,c=null,a=function(){function t(t){var e,n,r,i,o,s,a,u,h,p,f,d,m,v,g,E,y,_,b,T,x,w;this.root=t,this.root.model=this,this.root.root=this.root,this.ids={},this.classes={},this.traits={},this.types={},this.nodes=[],this.watchers=[],this.fire=!1,this.lastNode=null,this.event={type:"update"},null==c&&(c=l({tag:"type",id:"id","class":"classes.join(' ')",parent:"parent",children:"children",attr:"traits.hash[attr]"})),e=function(t){return function(t){return u(t.node)}}(this),v=function(t){return function(t){return p(t.node)}}(this),this.root.on("add",e),this.root.on("remove",v),u=function(t){return function(t){return i(t),a(t),s(t),t.on("change:node",w),w(null,t,!0),f(t)}}(this),p=function(t){return function(t){return y(t),T(t),b(t),E(t.id,t),g(t.classes,t),t.off("change:node",w),f(t)}}(this),m=function(t){return function(e){var n,r,i,o;for(i=t.watchers,n=0,r=i.length;r>n;n++)o=i[n],o.match=o.matcher(e);return null}}(this),h=function(t){return function(e){var n,r,i,o,s;for(o=t.watchers,r=0,i=o.length;i>r;r++)s=o[r],n=s.fire||(s.fire=s.match!==s.matcher(e)),n&&(t.lastNode=e),t.fire||(t.fire=n);return null}}(this),f=function(t){return function(e){var n,r,i,o,s;for(o=t.watchers,r=0,i=o.length;i>r;r++)s=o[r],n=s.fire||(s.fire=s.matcher(e)),n&&(t.lastNode=e),t.fire||(t.fire=n);return null}}(this),this.digest=function(t){return function(){var e,n,r,i;if(!t.fire)return!1;for(r=t.watchers.slice(),e=0,n=r.length;n>e;e++)i=r[e],i.fire&&(i.fire=!1,i.handler());return t.fire=!1,!0}}(this),w=function(t){return function(t,e,i){var o,s,a,u,l,c,p,f;return o=i||t.changed["node.id"],s=i||t.changed["node.classes"],c=!1,o&&(u=e.get("node.id"),u!==e.id&&(i||m(e),c=!0,null!=e.id&&E(e.id,e),r(u,e))),s&&(a=null!=(p=e.get("node.classes"))?p:[],l=a.join(","),l!==(null!=(f=e.classes)?f.klass:void 0)&&(a=a.slice(),i||c||m(e),c=!0,null!=e.classes&&g(e.classes,e),n(a,e),e.classes=a,e.classes.klass=l)),!i&&c&&h(e),null}}(this),o=function(t,e,n){var r,i,o,s,a;if(null!=e){for(r=0,o=e.length;o>r;r++)i=e[r],s=null!=(a=t[i])?a:[],s.push(n),t[i]=s;return null}},_=function(t,e,n){var r,i,o,s,a;if(null!=e){for(r=0,s=e.length;s>r;r++)o=e[r],a=t[o],i=a.indexOf(n),i>=0&&a.splice(i,1),0===a.length&&delete t[o];return null}},d=function(t){var e,n,r,i,o;if(t.length>0){for(e=t.hash={},o=[],n=0,i=t.length;i>n;n++)r=t[n],o.push(e[r]=!0);return o}},x=function(t){return delete t.hash},r=function(t){return function(e,n){if(t.ids[e])throw new Error("Duplicate node id `"+e+"`");return null!=e&&(t.ids[e]=[n]),n.id=null!=e?e:n._id}}(this),E=function(t){return function(e,n){return null!=e&&delete t.ids[e],n.id=n._id}}(this),n=function(t){return function(e,n){return o(t.classes,e,n),null!=e?d(e):void 0}}(this),g=function(t){return function(e,n){return _(t.classes,e,n),null!=e?x(e):void 0}}(this),i=function(t){return function(e){return t.nodes.push(e)}}(this),y=function(t){return function(e){return t.nodes.splice(t.nodes.indexOf(e),1)}}(this),a=function(t){return function(e){return o(t.types,[e.type],e)}}(this),T=function(t){return function(e){return _(t.types,[e.type],e)}}(this),s=function(t){return function(e){return o(t.traits,e.traits,e),d(e.traits)}}(this),b=function(t){return function(e){return _(t.traits,e.traits,e),x(e.traits)}}(this),u(this.root),this.root.trigger({type:"added"})}return t.prototype.filter=function(t,e){var n,r,i,o,s;for(i=this._matcher(e),s=[],n=0,r=t.length;r>n;n++)o=t[n],i(o)&&s.push(o);return s},t.prototype.ancestry=function(t,e){var n,r,i,o,s;for(o=[],n=0,r=t.length;r>n;n++)for(i=t[n],s=i.parent;null!=s;){if(p.call(e,s)>=0){o.push(i);break}s=s.parent}return o},t.prototype.select=function(t,e){var n;return n=this._select(t),null!=e&&(n=this.ancestry(n,e)),n.sort(function(t,e){return e.order-t.order}),n},t.prototype.watch=function(t,e){var n;return e.unwatch=function(t){return function(){return t.unwatch(e)}}(this),e.watcher=n={selector:t,handler:e,matcher:this._matcher(t),match:!1,fire:!1},this.watchers.push(n),this.select(t)},t.prototype.unwatch=function(t){var e;return e=t.watcher,null!=e?(this.watchers.splice(this.watchers.indexOf(e),1),delete t.unwatch,delete t.watcher):void 0},t.prototype._simplify=function(t){var e,n,a,l,c,p,f,d,m,v,g,E;return t=t.replace(/^\s+/,""),t=t.replace(/\s+$/,""),a=e=t===r,a||(a=l=null!=(p=t.match(s))?p[1]:void 0),a||(a=c=null!=(f=t.match(o))?f[1]:void 0),a||(a=g=null!=(d=t.match(u))?d[1]:void 0),a||(a=E=null!=(m=t.match(h))?m[0]:void 0),a||(a=n=null!=(v=t.match(i))?v[0]:void 0),[e,l,c,g,E,n]},t.prototype._matcher=function(t){var e,n,r,i,o,s,a;if(o=this._simplify(t),e=o[0],r=o[1],i=o[2],s=o[3],a=o[4],n=o[5],e)return function(t){return!0};if(r)return function(t){return t.id===r};if(i)return function(t){var e,n;return null!=(e=t.classes)&&null!=(n=e.hash)?n[i]:void 0};if(s)return function(t){var e,n;return null!=(e=t.traits)&&null!=(n=e.hash)?n[s]:void 0};if(a)return function(t){return t.type===a};if(n)throw"Auto-link matcher unsupported";return c(t)},t.prototype._select=function(t){var e,n,r,i,o,s,a,u,h,l;return i=this._simplify(t),e=i[0],n=i[1],r=i[2],h=i[3],l=i[4],e?this.nodes:n?null!=(o=this.ids[n])?o:[]:r?null!=(s=this.classes[r])?s:[]:h?null!=(a=this.traits[h])?a:[]:l?null!=(u=this.types[l])?u:[]:this.filter(this.nodes,t)},t.prototype.getRoot=function(){return this.root},t.prototype.getLastTrigger=function(){return this.lastNode.toString()},t}(),e.exports=a},{cssauron:2}],36:[function(t,e,n){var r,i,o,s;o=t("../util"),s=0,i=function(){function t(t,e,n,r,i,o){this.type=t,this._id=(++s).toString(),this.configure(i,o),this.parent=this.root=this.path=this.index=null,this.set(e,!0,!0),this.set(n,!1,!0),this.bind(r,!1)}return t.prototype.configure=function(t,e){var n,r,i,o,s,a,u,h,l,c,p,f;return f=t.traits,i=t.props,n=t.finals,r=t.freeform,null==f&&(f=null!=(o=null!=(s=this._config)?s.traits:void 0)?o:[]),null==i&&(i=null!=(a=null!=(u=this._config)?u.props:void 0)?a:{}),null==n&&(n=null!=(h=null!=(l=this._config)?l.finals:void 0)?h:{}),null==r&&(r=null!=(c=null!=(p=this._config)?p.freeform:void 0)?c:!1),this._config={traits:f,props:i,finals:n,freeform:r},this.attributes=e.apply(this,this._config)},t.prototype.dispose=function(){return this.attributes.dispose(),this.attributes=null},t.prototype._added=function(t){var e;return this.parent=t,this.root=t.root,e={type:"add",node:this,parent:this.parent},this.root&&this.root.trigger(e),e.type="added",this.trigger(e)},t.prototype._removed=function(){var t;return t={type:"remove",node:this},this.root&&this.root.trigger(t),t.type="removed",this.trigger(t),this.root=this.parent=null},t.prototype._index=function(t,e){var n,r;return null==e&&(e=this.parent),this.index=t,this.path=n=null!=t?(null!=(r=null!=e?e.path:void 0)?r:[]).concat([t]):null,this.order=null!=n?this._encode(n):1/0,null!=this.root?this.trigger({type:"reindex"}):void 0},t.prototype._encode=function(t){var e,n,r,i,o,s,a,u,h,l,c;for(a=3,l=function(t){return a/(t+a)},h=function(t){return n+(e-n)*t},e=1+1/a,n=0,o=0,u=t.length;u>o;o++)s=t[o],r=l(s+1),i=l(s+2),c=[h(r),h(i)],e=c[0],n=c[1];return e},t.prototype.toString=function(){var t,e,n,r,i,o,s;return t=null!=(r=this.id)?r:this._id,s=null!=(i=this.type)?i:"node",n=s,n+="#"+t,(null!=(o=this.classes)?o.length:void 0)&&(n+="."+this.classes.join(".")),null!=this.children?(e=this.children.length)?"<"+n+">…("+e+")…":"<"+n+">":"<"+n+" />"},t.prototype.toMarkup=function(t,e){var n,r,i,s,a,u,h,l,c,p,f,d,m,v,g,E;null==t&&(t=null),null==e&&(e=""),t&&"function"!=typeof t&&(t=null!=(f=null!=(d=this.root)?d.model._matcher(t):void 0)?f:function(){return!0}),g=null!=(m=this.type)?m:"node",a=this.expr,l={id:this._id},v="function"==typeof this.orig?this.orig():void 0;for(u in v)E=v[u],l[u]=E;return c=function(){var t;t=[];for(u in l)E=l[u],this.expr[u]||t.push(o.Pretty.JSX.prop(u,E));return t}.call(this),a=function(){var t;t=[];for(u in a)E=a[u],t.push(o.Pretty.JSX.bind(u,E));return t}(),n=[""],c.length&&(n=n.concat(c)),a.length&&(n=n.concat(a)),n=n.join(" "),r=e,p=function(e){return function(){var n,i;return(null!=(i=e.children)?i.length:void 0)?n=e.children.map(function(e){return e.toMarkup(t,r)}).filter(function(t){return null!=t&&t.length}).join("\n"):""}}(this),t&&!t(this)?p():null!=this.children?(h="<"+g+n+">",s="",r=e+" ",i=p(),i.length&&(i="\n"+i+"\n"+e),null==i&&(i=""),e+h+i+s):e+"<"+g+n+" />"},t.prototype.print=function(t,e){return o.Pretty.print(this.toMarkup(t),e)},t}(),r=t("../util/binder"),r.apply(i.prototype),e.exports=i},{"../util":175,"../util/binder":171}],37:[function(t,e,n){var r;r={dom:t("./dom")},e.exports=r},{"./dom":38}],38:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("./overlay"),o=t("../util").VDOM,r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.prototype.el=o.element,e.prototype.hint=o.hint,e.prototype.apply=o.apply,e.prototype.recycle=o.recycle,e.prototype.init=function(t){return this.last=null},e.prototype.dispose=function(){return this.unmount(),e.__super__.dispose.apply(this,arguments)},e.prototype.mount=function(){var t;return t=document.createElement("div"),t.classList.add("mathbox-overlay"),this.element.appendChild(t),this.overlay=t},e.prototype.unmount=function(t){return this.overlay.parentNode&&this.element.removeChild(this.overlay),this.overlay=null},e.prototype.render=function(t){var e,n,r,i,o,s;this.overlay||this.mount(),("string"==(s=typeof t)||"number"===s)&&(t=this.el("div",null,t)),t instanceof Array&&(t=this.el("div",null,t)),n="div"===t.type,e=this.last,i=this.overlay,r=n?i:i.childNodes[0],o=n?i.parentNode:i,!e&&r&&(e=this.el("div")),this.apply(t,e,r,o,0),this.last=t,null!=e&&this.recycle(e)},e}(i),e.exports=r},{"../util":175,"./overlay":41}],39:[function(t,e,n){var r;r=function(){function t(t,e){var n;this.classes=t,this.canvas=e,n=document.createElement("div"),n.classList.add("mathbox-overlays"),this.div=n}return t.prototype.inject=function(){var t;if(t=this.canvas.parentNode,!t)throw new Error("Canvas not inserted into document.");return t.insertBefore(this.div,this.canvas)},t.prototype.unject=function(){var t;return t=this.div.parentNode,t.removeChild(this.div)},t.prototype.getTypes=function(){return Object.keys(this.classes)},t.prototype.make=function(t,e){return new this.classes[t](this.div,e)},t}(),e.exports=r},{}],40:[function(t,e,n){n.Factory=t("./factory"),n.Classes=t("./classes"),n.Overlay=t("./overlay")},{"./classes":37,"./factory":39,"./overlay":41}],41:[function(t,e,n){var r;r=function(){function t(t,e){this.element=t,"function"==typeof this.init&&this.init(e)}return t.prototype.dispose=function(){},t}(),e.exports=r},{}],42:[function(t,e,n){var r,i;i=t("../util"),r=function(){function t(t,e){this.context=e,this.classes=t.Classes,this.helpers=t.Helpers}return t.prototype.getTypes=function(){return Object.keys(this.classes)},t.prototype.make=function(t,e,n){var r,i,o;if(null==e&&(e={}),null==n&&(n=null),r=this.classes[t],null==r)throw new Error("Unknown primitive class `"+t+"`");return i=new r.model(t,r.defaults,e,n,r,this.context.attributes),o=new r(i,this.context,this.helpers),i},t}(),e.exports=r},{"../util":175}],43:[function(t,e,n){n.Factory=t("./factory"),n.Primitive=t("./primitive"),n.Types=t("./types")},{"./factory":42,"./primitive":44,"./types":72}],44:[function(t,e,n){var r,i,o,s=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};i=t("../model"),o=function(){function t(t,e,n){this.node=t,this._context=e,this._renderables=this._context.renderables,this._attributes=this._context.attributes,this._shaders=this._context.shaders,this._overlays=this._context.overlays,this._animator=this._context.animator,this._types=this._attributes.types,this.node.controller=this,this.node.on("added",function(t){return function(e){return t._added()}}(this)),this.node.on("removed",function(t){return function(e){return t._removed()}}(this)),this.node.on("change",function(t){return function(e){return t._root?t.change(e.changed,e.touched):void 0}}(this)),this.reconfigure(),this._get=this.node.get.bind(this.node),this._helpers=n(this,this.node.traits),this._handlers={inherit:{},listen:[],watch:[],compute:[]},this._root=this._parent=null,this.init()}return t.Node=i.Node,t.Group=i.Group,t.model=t.Node,t.defaults=null,t.traits=null,t.props=null,t.finals=null,t.freeform=!1,t.prototype.is=function(t){return this.traits.hash[t]},t.prototype.init=function(){},t.prototype.make=function(){},t.prototype.made=function(){},t.prototype.unmake=function(t){},t.prototype.unmade=function(){},t.prototype.change=function(t,e,n){},t.prototype.refresh=function(){return this.change({},{},!0)},t.prototype.rebuild=function(){return this._root?(this._removed(!0),this._added()):void 0},t.prototype.reconfigure=function(t){return null!=t&&this.node.configure(t,this._attributes),this.traits=this.node.traits,this.props=this.node.props},t.prototype._added=function(){var t,e,n,r,i,o;this._parent=null!=(r=this.node.parent)?r.controller:void 0,this._root=null!=(i=this.node.root)?i.controller:void 0,this.node.clock=null!=(o=this._inherit("clock"))?o:this._root;try{try{return this.make(),this.refresh(),this.made()}catch(e){throw t=e,this.node.print("warn"),console.error(t),t}}catch(n){t=n;try{return this._removed()}catch(s){}}},t.prototype._removed=function(t){return null==t&&(t=!1),this.unmake(t),this._unlisten(),this._unattach(),this._uncompute(),this._root=null,this._parent=null,this.unmade(t)},t.prototype._listen=function(t,e,n,r){var i,o,s;if(null==r&&(r=this),t instanceof Array)for(i=0,o=t.length;o>i;i++)return s=t[i],this.__listen(s,e,n,r);return this.__listen(t,e,n,r)},t.prototype.__listen=function(t,e,n,r){var i;return null==r&&(r=this),"string"==typeof t&&(t=this._inherit(t)),null!=t&&(i=n.bind(r),i.node=this.node,t.on(e,i),this._handlers.listen.push([t,e,i])),t},t.prototype._unlisten=function(){var t,e,n,r,i,o,s;if(this._handlers.listen.length){for(i=this._handlers.listen,e=0,n=i.length;n>e;e++)o=i[e],r=o[0],s=o[1],t=o[2],r.off(s,t);return this._handlers.listen=[]}},t.prototype._inherit=function(t){var e,n;return e=this._handlers.inherit[t],void 0!==e?e:this._handlers.inherit[t]=null!=(n=this._parent)?n._find(null!=t?t:null):void 0},t.prototype._find=function(t){var e;return this.is(t)?this:null!=(e=this._parent)?e._find(t):void 0},t.prototype._uninherit=function(){return this._handlers.inherit={}},t.prototype._attach=function(t,e,n,r,o,a,u){var h,l,c,p,f;return null==r&&(r=this),null==o&&(o=this),null==a&&(a=!1),null==u&&(u=!1),h=function(t){return null!=t&&s.call(t.traits,e)>=0?t:void 0},c=function(t){return null!=t?t.controller:void 0},l=function(t){var e,n,r,i;if(null==t)return t;for(r=[],e=0,n=t.length;n>e;e++)i=t[e],i instanceof Array?r=r.concat(i):r.push(i);return r},f=function(t){return function(s){var c,p,d,m,v,g,E,y;if("object"==typeof s){if(d=s,null!=d?d._up:void 0)return s=u?d._targets:[d[0]];if(d instanceof Array)return s=u?l(d.map(f)):f(d[0]);if(d instanceof i.Node)return[d]}else if("string"==typeof s&&"<"===s[0]){for(c=0,(p=s.match(/^<([0-9])+$/))&&(c=+p[1]-1),s.match(/^<+$/)&&(c=+s.length-1),m=[],g=o.node;g&&(v=g.parent);)if(g=v.children[g.index-1],g||m.length||(g=v),d=null,h(g)&&(d=g),null!=d&&c--<=0&&m.push(d),!u&&m.length)return m;if(u&&m.length)return m}else if("string"==typeof s)if(y=n.bind(r),t._handlers.watch.push(y),E=t._root.watch(s,y),u){if(m=E.filter(h),m.length)return m}else if(h(E[0])&&(d=E[0]),null!=d)return[d];if(!a)throw console.warn(t.node.toMarkup()),new Error(t.node.toString()+" - Could not find "+e+" `"+s+"`");return u?[]:null}}(this),p=l(f(t)),u?null!=p?p.map(c):null:null!=p?c(p[0]):null},t.prototype._unattach=function(){var t,e,n,r;if(this._handlers.watch.length){for(n=this._handlers.watch,t=0,e=n.length;e>t;t++)r=n[t],null!=r&&r.unwatch();return this._handlers.watch=[]}},t.prototype._compute=function(t,e){return this._handlers.compute.push(t),this.node.bind(t,e,!0)},t.prototype._uncompute=function(){var t,e,n,r;if(this._handlers.compute.length){for(r=this._handlers.compute,t=0,n=r.length;n>t;t++)e=r[t],this.node.unbind(e,!0);return this._handlers.compute=[]}},t}(),r=t("../util/binder"),r.apply(o.prototype),e.exports=o},{"../model":34,"../util/binder":171}],45:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("./parent"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","object","entity","visible","active"],e.prototype.make=function(){return this._helpers.visible.make(),this._helpers.active.make()},e.prototype.unmake=function(){return this._helpers.visible.unmake(),this._helpers.active.unmake()},e}(i),e.exports=r},{"./parent":47}],46:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty,a=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};i=t("./parent"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","bind"],e.prototype.make=function(){return this._helpers.bind.make([{to:"inherit.source",trait:"node"}])},e.prototype.unmake=function(){return this._helpers.bind.unmake()},e.prototype._find=function(t){return this.bind.source&&a.call(this.props.traits,t)>=0?this.bind.source._inherit(t):e.__super__._find.apply(this,arguments)},e}(i),e.exports=r},{"./parent":47}],47:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("../../primitive"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.model=i.Group,e.traits=["node"],e}(i),e.exports=r},{"../../primitive":44}],48:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./parent"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","root","clock","scene","vertex","unit"],e.prototype.init=function(){return this.size=null,this.cameraEvent={type:"root.camera"},this.preEvent={type:"root.pre"},this.updateEvent={type:"root.update"},this.renderEvent={type:"root.render"},this.postEvent={type:"root.post"},this.clockEvent={type:"clock.tick"},this.camera=null},e.prototype.make=function(){return this._helpers.unit.make()},e.prototype.unmake=function(){return this._helpers.unit.unmake()},e.prototype.change=function(t,e,n){return t["root.camera"]||n?(this._unattach(),this._attach(this.props.camera,"camera",this.setCamera,this,this,!0),this.setCamera()):void 0},e.prototype.adopt=function(t){var e,n,r,i,o;for(i=t.renders,o=[],e=0,n=i.length;n>e;e++)r=i[e],o.push(this._context.scene.add(r));return o},e.prototype.unadopt=function(t){var e,n,r,i,o;for(i=t.renders,o=[],e=0,n=i.length;n>e;e++)r=i[e],o.push(this._context.scene.remove(r));return o},e.prototype.select=function(t){return this.node.model.select(t)},e.prototype.watch=function(t,e){return this.node.model.watch(t,e)},e.prototype.unwatch=function(t){return this.node.model.unwatch(t)},e.prototype.resize=function(t){return this.size=t,this.trigger({type:"root.resize",size:t})},e.prototype.getSize=function(){return this.size},e.prototype.getSpeed=function(){return this.props.speed},e.prototype.getUnit=function(){return this._helpers.unit.get()},e.prototype.getUnitUniforms=function(){return this._helpers.unit.uniforms()},e.prototype.pre=function(){return this.getCamera().updateProjectionMatrix(),this.trigger(this.clockEvent),this.trigger(this.preEvent)},e.prototype.update=function(){return this.trigger(this.updateEvent)},e.prototype.render=function(){return this.trigger(this.renderEvent)},e.prototype.post=function(){return this.trigger(this.postEvent)},e.prototype.setCamera=function(){var t,e;return t=null!=(e=this.select(this.props.camera)[0])?e.controller:void 0,this.camera!==t?(this.camera=t,this.trigger({type:"root.camera"})):void 0},e.prototype.getCamera=function(){var t,e;return null!=(t=null!=(e=this.camera)?e.getCamera():void 0)?t:this._context.defaultCamera},e.prototype.getTime=function(){return this._context.time},e.prototype.vertex=function(t,e){return 2===e?t.pipe("view.position"):3===e?t.pipe("root.position"):t},e}(r),e.exports=i},{"../../../util":175,"./parent":47}],49:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("../../primitive"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","source","index"],e.prototype.made=function(){return this.trigger({type:"source.rebuild"})},e.prototype.indexShader=function(t){return t.pipe(o.GLSL.identity("vec4"))},e.prototype.sourceShader=function(t){return t.pipe(o.GLSL.identity("vec4"))},e.prototype.getDimensions=function(){return{items:1,width:1,height:1,depth:1}},e.prototype.getActiveDimensions=function(){return this.getDimensions()},e.prototype.getIndexDimensions=function(){return this.getActiveDimensions()},e.prototype.getFutureDimensions=function(){return this.getActiveDimensions()},e}(r),e.exports=i},{"../../../util":175,"../../primitive":44}],50:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./parent"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","unit"],e.prototype.make=function(){return this._helpers.unit.make()},e.prototype.unmake=function(){return this._helpers.unit.unmake()},e.prototype.getUnit=function(){return this._helpers.unit.get()},e.prototype.getUnitUniforms=function(){return this._helpers.unit.uniforms()},e}(r),e.exports=i},{"../../../util":175,"./parent":47}],51:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../../primitive"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","camera"],e.prototype.init=function(){},e.prototype.make=function(){var t;return t=this._context.defaultCamera,this.camera=this.props.proxy?t:t.clone(),this.euler=new THREE.Euler,this.quat=new THREE.Quaternion},e.prototype.unmake=function(){},e.prototype.getCamera=function(){return this.camera},e.prototype.change=function(t,e,n){var r,i,s,a,u,h,l,c;return t["camera.position"]||t["camera.quaternion"]||t["camera.rotation"]||t["camera.lookAt"]||t["camera.up"]||t["camera.fov"]||n?(h=this.props,a=h.position,u=h.quaternion,l=h.rotation,s=h.lookAt,c=h.up,i=h.fov,r=h.aspect,null!=a&&this.camera.position.copy(a),(null!=u||null!=l||null!=s)&&(null!=s?this.camera.lookAt(s):this.camera.quaternion.set(0,0,0,1),null!=l&&(this.euler.setFromVector3(l,o.Three.swizzleToEulerOrder(this.props.eulerOrder)),this.quat.setFromEuler(this.euler),this.camera.quaternion.multiply(this.quat)),null!=u&&this.camera.quaternion.multiply(u)),null!=i&&null!=this.camera.fov&&(this.camera.fov=i),null!=c&&this.camera.up.copy(c),this.camera.updateMatrix()):void 0},e}(i),e.exports=r},{"../../../util":175,"../../primitive":44}],52:[function(t,e,n){var r;r={axis:t("./draw/axis"),face:t("./draw/face"),grid:t("./draw/grid"),line:t("./draw/line"),point:t("./draw/point"),strip:t("./draw/strip"),surface:t("./draw/surface"),ticks:t("./draw/ticks"),vector:t("./draw/vector"),view:t("./view/view"),cartesian:t("./view/cartesian"),cartesian4:t("./view/cartesian4"),polar:t("./view/polar"),spherical:t("./view/spherical"),stereographic:t("./view/stereographic"),stereographic4:t("./view/stereographic4"),transform:t("./transform/transform3"),transform4:t("./transform/transform4"),vertex:t("./transform/vertex"),fragment:t("./transform/fragment"),layer:t("./transform/layer"),mask:t("./transform/mask"),array:t("./data/array"),interval:t("./data/interval"),matrix:t("./data/matrix"),area:t("./data/area"),voxel:t("./data/voxel"),volume:t("./data/volume"),scale:t("./data/scale"),html:t("./overlay/html"),dom:t("./overlay/dom"),text:t("./text/text"),format:t("./text/format"),label:t("./text/label"),retext:t("./text/retext"),clamp:t("./operator/clamp"),grow:t("./operator/grow"),join:t("./operator/join"),lerp:t("./operator/lerp"),memo:t("./operator/memo"),readback:t("./operator/readback"),resample:t("./operator/resample"),repeat:t("./operator/repeat"),swizzle:t("./operator/swizzle"),spread:t("./operator/spread"),split:t("./operator/split"),slice:t("./operator/slice"),subdivide:t("./operator/subdivide"),transpose:t("./operator/transpose"),group:t("./base/group"),inherit:t("./base/inherit"),root:t("./base/root"),unit:t("./base/unit"),shader:t("./shader/shader"),camera:t("./camera/camera"),rtt:t("./rtt/rtt"),compose:t("./rtt/compose"),clock:t("./time/clock"),now:t("./time/now"),move:t("./present/move"),play:t("./present/play"),present:t("./present/present"),reveal:t("./present/reveal"),slide:t("./present/slide"),step:t("./present/step")},e.exports=r},{"./base/group":45,"./base/inherit":46,"./base/root":48,"./base/unit":50,"./camera/camera":51,"./data/area":53,"./data/array":54,"./data/interval":57,"./data/matrix":58,"./data/scale":59,"./data/volume":60,"./data/voxel":61,"./draw/axis":62,"./draw/face":63,"./draw/grid":64,"./draw/line":65,"./draw/point":66,"./draw/strip":67,"./draw/surface":68,"./draw/ticks":69,"./draw/vector":70,"./operator/clamp":73,"./operator/grow":74,"./operator/join":75,"./operator/lerp":76,"./operator/memo":77,"./operator/readback":79,"./operator/repeat":80,"./operator/resample":81,"./operator/slice":82,"./operator/split":83,"./operator/spread":84,"./operator/subdivide":85,"./operator/swizzle":86,"./operator/transpose":87,"./overlay/dom":88,"./overlay/html":89,"./present/move":90,"./present/play":91,"./present/present":92,"./present/reveal":93,"./present/slide":94,"./present/step":95,"./rtt/compose":98,"./rtt/rtt":99,"./shader/shader":100,"./text/format":101,"./text/label":102,"./text/retext":103,"./text/text":104,"./time/clock":105,"./time/now":106,"./transform/fragment":108,"./transform/layer":109,"./transform/mask":110,"./transform/transform3":112,"./transform/transform4":113,"./transform/vertex":114,"./view/cartesian":116,"./view/cartesian4":117,"./view/polar":118,"./view/spherical":119,"./view/stereographic":120,"./view/stereographic4":121,"./view/view":122}],53:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("./matrix"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","buffer","active","data","source","index","matrix","texture","raw","span:x","span:y","area","sampler:x","sampler:y"],e.prototype.updateSpan=function(){var t,e,n,r,i,o,s,a,u,h,l,c,p;return n=this.props.axes,p=this.props.width,r=this.props.height,t=this.props.centeredX,e=this.props.centeredY,s=this.props.paddingX,a=this.props.paddingY,u=this._helpers.span.get("x.",n[0]),h=this._helpers.span.get("y.",n[1]),this.aX=u.x,this.aY=h.x,l=u.y-u.x,c=h.y-h.x,p+=2*s,r+=2*a,t?(i=1/Math.max(1,p),this.aX+=l*i/2):i=1/Math.max(1,p-1),e?(o=1/Math.max(1,r),this.aY+=c*o/2):o=1/Math.max(1,r-1),this.bX=l*i,this.bY=c*o,this.aX+=s*this.bX,this.aY+=a*this.bY},e.prototype.callback=function(t){return this.updateSpan(),this.last===t?this._callback:(this.last=t,t.length<=5?this._callback=function(e){return function(n,r,i){var o,s;return o=e.aX+e.bX*r,s=e.aY+e.bY*i,t(n,o,s,r,i)}}(this):this._callback=function(e){return function(n,r,i){var o,s;return o=e.aX+e.bX*r,s=e.aY+e.bY*i,t(n,o,s,r,i,e.bufferClock,e.bufferStep)}}(this))},e.prototype.make=function(){return e.__super__.make.apply(this,arguments),this._helpers.span.make(),this._listen(this,"span.range",this.updateSpan)},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),this._helpers.span.unmake()},e}(i),e.exports=r},{"../../../util":175,"./matrix":58}],54:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("./buffer"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","buffer","active","data","source","index","array","texture","raw"],e.prototype.init=function(){return this.buffer=this.spec=null,this.space={width:0,history:0},this.used={width:0},this.storage="arrayBuffer",this.passthrough=function(t,e){return t(e,0,0,0)},e.__super__.init.apply(this,arguments)},e.prototype.sourceShader=function(t){ +var e;return e=this.getDimensions(),this.alignShader(e,t),this.buffer.shader(t)},e.prototype.getDimensions=function(){return{items:this.items,width:this.space.width,height:this.space.history,depth:1}},e.prototype.getActiveDimensions=function(){return{items:this.items,width:this.used.width,height:this.buffer.getFilled(),depth:1}},e.prototype.getFutureDimensions=function(){return{items:this.items,width:this.used.width,height:this.space.history,depth:1}},e.prototype.getRawDimensions=function(){return{items:this.items,width:space.width,height:1,depth:1}},e.prototype.make=function(){var t,n,r,i,s,a,u,h,l,c,p,f,d,m;return e.__super__.make.apply(this,arguments),u=null!=(h=this.minFilter)?h:this.props.minFilter,a=null!=(l=this.magFilter)?l:this.props.magFilter,d=null!=(c=this.type)?c:this.props.type,m=this.props.width,i=this.props.history,p=this.props.bufferWidth,t=this.props.channels,s=this.props.items,r=this.spec={channels:t,items:s,width:m},this.items=r.items,this.channels=r.channels,n=this.props.data,r=o.Data.getDimensions(n,r),f=this.space,f.width=Math.max(p,r.width||1),f.history=i,this.buffer=this._renderables.make(this.storage,{width:f.width,history:f.history,channels:t,items:s,minFilter:u,magFilter:a,type:d})},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),this.buffer?(this.buffer.dispose(),this.buffer=this.spec=null):void 0},e.prototype.change=function(t,e,n){var r;if(e.texture||t["history.history"]||t["buffer.channels"]||t["buffer.items"]||t["array.bufferWidth"])return this.rebuild();if(this.buffer)return t["array.width"]&&(r=this.props.width,r>this.space.width)?this.rebuild():t["data.map"]||t["data.data"]||t["data.resolve"]||t["data.expr"]||n?this.buffer.setCallback(this.emitter()):void 0},e.prototype.callback=function(t){return t.length<=2?t:function(e){return function(n,r){return t(n,r,e.bufferClock,e.bufferStep)}}(this)},e.prototype.update=function(){var t,e,n,r,i;if(this.buffer)return t=this.props.data,r=this.space,i=this.used,n=i.width,e=this.buffer.getFilled(),this.syncBuffer(function(e){return function(n){var s,a,u;return null!=t?(a=o.Data.getDimensions(t,e.spec),a.width>r.width?(n(),e.rebuild()):(i.width=a.width,e.buffer.setActive(i.width),"function"==typeof(s=e.buffer.callback).rebind&&s.rebind(t),e.buffer.update())):(u=e.spec.width||1,e.buffer.setActive(u),u=e.buffer.update(),i.width=u)}}(this)),i.width!==n||e!==this.buffer.getFilled()?this.trigger({type:"source.resize"}):void 0},e}(i),e.exports=r},{"../../../util":175,"./buffer":55}],55:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("./data"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","buffer","active","data","source","index","texture"],e.prototype.init=function(){return this.bufferSlack=0,this.bufferFrames=0,this.bufferTime=0,this.bufferDelta=0,this.bufferClock=0,this.bufferStep=0,e.__super__.init.apply(this,arguments)},e.prototype.make=function(){return e.__super__.make.apply(this,arguments),this.clockParent=this._inherit("clock")},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments)},e.prototype.rawBuffer=function(){return this.buffer},e.prototype.emitter=function(){var t,n,r;return r=this.props,t=r.channels,n=r.items,e.__super__.emitter.call(this,t,n)},e.prototype.change=function(t,e,n){var r;return t["buffer.fps"]||n?(r=this.props.fps,this.bufferSlack=r?.5/r:0):void 0},e.prototype.syncBuffer=function(t){var e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b;if(this.buffer&&(d=this.props,c=d.live,i=d.fps,a=d.hurry,l=d.limit,f=d.realtime,p=d.observe,r=this.buffer.getFilled(),!r||c)){if(b=this.clockParent.getTime(),null!=i){for(g=this.bufferSlack,E=b.step/b.delta,n=f?b.delta:b.step,o=1/i,y=f&&p?E*o:o,this.bufferSlack=Math.min(l/i,g+n),this.bufferDelta=n,this.bufferStep=y,s=Math.min(a,Math.floor(g*i)),r||(s=Math.max(1,s)),_=!1,e=function(){return _=!0},v=[],u=h=0,m=s;(m>=0?m>h:h>m)&&(this.bufferTime+=n,this.bufferClock+=y,!_);u=m>=0?++h:--h)t(e,this.bufferFrames++,u,s),v.push(this.bufferSlack-=o);return v}return this.bufferTime=b.time,this.bufferDelta=b.delta,this.bufferClock=b.clock,this.bufferStep=b.step,t(function(){},this.bufferFrames++,0,1)}},e.prototype.alignShader=function(t,e){var n,r,i,o,s,a;return a=this.props,i=a.minFilter,r=a.magFilter,n=a.aligned,o=t.items>1&&t.width>1||t.height>1&&t.depth>1,!n&&o?(s=i===this.node.attributes["texture.minFilter"]["enum"].nearest&&r===this.node.attributes["texture.magFilter"]["enum"].nearest,s||console.warn(this.node.toString()+" - Cannot use linear min/magFilter with 3D/4D sampling"),e.pipe("map.xyzw.align")):void 0},e}(i),e.exports=r},{"../../../util":175,"./data":56}],56:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../base/source"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","data","source","index","entity","active"],e.prototype.init=function(){return this.dataEmitter=null,this.dataSizes=null},e.prototype.emitter=function(t,e){var n,r,i,s,a,u,h,l;return r=this.props.data,n=this.props.bind,s=this.props.expr,null!=r?(a=this.dataSizes,h=o.Data.getSizes(r),a&&a.length===h.length||(l=o.Data.getThunk(r),this.dataEmitter=this.callback(o.Data.makeEmitter(l,e,t)),this.dataSizes=h),i=this.dataEmitter):"undefined"!=typeof u&&null!==u?(u=this._inherit("resolve"),i=this.callback(u.callback(n))):i=null!=s?this.callback(s):this.callback(this.passthrough),i},e.prototype.callback=function(t){return null!=t?t:function(){}},e.prototype.update=function(){},e.prototype.make=function(){return this._helpers.active.make(),this.first=!0,this._listen("root","root.update",function(t){return function(){return(t.isActive||t.first)&&t.update(),t.first=!1}}(this))},e.prototype.unmake=function(){return this._helpers.active.unmake(),this.dataEmitter=null,this.dataSizes=null},e}(i),e.exports=r},{"../../../util":175,"../base/source":49}],57:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;o=t("./array"),i=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","buffer","active","data","source","index","texture","array","span","interval","sampler","raw"],e.prototype.updateSpan=function(){var t,e,n,r,i,o,s;return e=this.props.axis,s=this.props.width,t=this.props.centered,r=this.props.padding,i=this._helpers.span.get("",e),s+=2*r,this.a=i.x,o=i.y-i.x,t?(n=1/Math.max(1,s),this.a+=o*n/2):n=1/Math.max(1,s-1),this.b=o*n,this.a+=r*this.b},e.prototype.callback=function(t){return this.updateSpan(),this.last===t?this._callback:(this.last=t,t.length<=3?this._callback=function(e){return function(n,r){var i;return i=e.a+e.b*r,t(n,i,r)}}(this):this._callback=function(e){return function(n,r){var i;return i=e.a+e.b*r,t(n,i,r,e.bufferClock,e.bufferStep)}}(this))},e.prototype.make=function(){return e.__super__.make.apply(this,arguments),this._helpers.span.make(),this._listen(this,"span.range",this.updateSpan)},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),this._helpers.span.unmake()},e}(o),e.exports=r},{"../../../util":175,"./array":54}],58:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./buffer"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","buffer","active","data","source","index","texture","matrix","raw"],e.prototype.init=function(){return this.buffer=this.spec=null,this.space={width:0,height:0,history:0},this.used={width:0,height:0},this.storage="matrixBuffer",this.passthrough=function(t,e,n){return t(e,n,0,0)},e.__super__.init.apply(this,arguments)},e.prototype.sourceShader=function(t){var e;return e=this.getDimensions(),this.alignShader(e,t),this.buffer.shader(t)},e.prototype.getDimensions=function(){return{items:this.items,width:this.space.width,height:this.space.height,depth:this.space.history}},e.prototype.getActiveDimensions=function(){return{items:this.items,width:this.used.width,height:this.used.height,depth:this.buffer.getFilled()}},e.prototype.getFutureDimensions=function(){return{items:this.items,width:this.used.width,height:this.used.height,depth:this.space.history}},e.prototype.getRawDimensions=function(){return{items:this.items,width:this.space.width,height:this.space.height,depth:1}},e.prototype.make=function(){var t,n,r,i,s,a,u,h,l,c,p,f,d,m,v,g;return e.__super__.make.apply(this,arguments),h=null!=(l=this.minFilter)?l:this.props.minFilter,u=null!=(c=this.magFilter)?c:this.props.magFilter,v=null!=(p=this.type)?p:this.props.type,g=this.props.width,i=this.props.height,s=this.props.history,f=this.props.bufferWidth,d=this.props.bufferHeight,t=this.props.channels,a=this.props.items,r=this.spec={channels:t,items:a,width:g,height:i},this.items=r.items,this.channels=r.channels,n=this.props.data,r=o.Data.getDimensions(n,r),m=this.space,m.width=Math.max(f,r.width||1),m.height=Math.max(d,r.height||1),m.history=s,this.buffer=this._renderables.make(this.storage,{width:m.width,height:m.height,history:m.history,channels:t,items:a,minFilter:h,magFilter:u,type:v})},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),this.buffer?(this.buffer.dispose(),this.buffer=this.spec=null):void 0},e.prototype.change=function(t,e,n){var r,i;if(e.texture||t["matrix.history"]||t["buffer.channels"]||t["buffer.items"]||t["matrix.bufferWidth"]||t["matrix.bufferHeight"])return this.rebuild();if(this.buffer)return t["matrix.width"]&&(i=this.props.width,i>this.space.width)?this.rebuild():t["matrix.height"]&&(r=this.props.height,r>this.space.height)?this.rebuild():t["data.map"]||t["data.data"]||t["data.resolve"]||t["data.expr"]||n?this.buffer.setCallback(this.emitter()):void 0},e.prototype.callback=function(t){return t.length<=3?t:function(e){return function(n,r,i){return t(n,r,i,e.bufferClock,e.bufferStep)}}(this)},e.prototype.update=function(){var t,e,n,r,i,s;if(this.buffer)return t=this.props.data,r=this.space,i=this.used,s=i.width,n=i.height,e=this.buffer.getFilled(),this.syncBuffer(function(e){return function(n){var s,a,u,h,l,c;return null!=t?(u=o.Data.getDimensions(t,e.spec),u.width>r.width||u.height>r.height?(n(),e.rebuild()):(i.width=u.width,i.height=u.height,e.buffer.setActive(i.width,i.height),"function"==typeof(a=e.buffer.callback).rebind&&a.rebind(t),e.buffer.update())):(c=e.spec.width||1,h=e.spec.height||1,e.buffer.setActive(c,h),l=e.buffer.update(),i.width=s=c,i.height=Math.ceil(l/s),1===i.height?i.width=l:void 0)}}(this)),i.width!==s||i.height!==n||e!==this.buffer.getFilled()?this.trigger({type:"source.resize"}):void 0},e}(r),e.exports=i},{"../../../util":175,"./buffer":55}],59:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../base/source"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","source","index","interval","span","scale","raw","origin"],e.prototype.init=function(){return this.used=this.space=this.scaleAxis=this.sampler=null},e.prototype.rawBuffer=function(){return this.buffer},e.prototype.sourceShader=function(t){return t.pipe(this.sampler)},e.prototype.getDimensions=function(){return{items:1,width:this.space,height:1,depth:1}},e.prototype.getActiveDimensions=function(){return{items:1,width:this.used,height:this.buffer.getFilled(),depth:1}},e.prototype.getRawDimensions=function(){return this.getDimensions()},e.prototype.make=function(){var t,e,n;return this.space=n=this._helpers.scale.divide(""),this.buffer=this._renderables.make("dataBuffer",{width:n,channels:1,items:1}),e={scaleAxis:this._attributes.make(this._types.vec4()),scaleOffset:this._attributes.make(this._types.vec4())},this.scaleAxis=e.scaleAxis.value,this.scaleOffset=e.scaleOffset.value,t=this.sampler=this._shaders.shader(),t.require(this.buffer.shader(this._shaders.shader(),1)),t.pipe("scale.position",e),this._helpers.span.make(),this._listen(this,"span.range",this.updateRanges)},e.prototype.unmake=function(){return this.scaleAxis=null,this._helpers.span.unmake()},e.prototype.change=function(t,e,n){return t["scale.divide"]?this.rebuild():e.view||e.interval||e.span||e.scale||n?this.updateRanges():void 0},e.prototype.updateRanges=function(){var t,e,n,r,i,s,a,u;return u=this.used,s=this.props,t=s.axis,r=s.origin,i=this._helpers.span.get("",t),n=i.x,e=i.y,a=this._helpers.scale.generate("",this.buffer,n,e),o.Axis.setDimension(this.scaleAxis,t),o.Axis.setOrigin(this.scaleOffset,t,r),this.used=a.length,this.used!==u?this.trigger({type:"source.resize"}):void 0},e}(i),e.exports=r},{"../../../util":175,"../base/source":49}],60:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;o=t("./voxel"),r=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","buffer","active","data","source","index","texture","voxel","span:x","span:y","span:z","volume","sampler:x","sampler:y","sampler:z","raw"],e.prototype.updateSpan=function(){var t,e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E;return i=this.props.axes,E=this.props.width,o=this.props.height,r=this.props.depth,t=this.props.centeredX,e=this.props.centeredY,n=this.props.centeredZ,h=this.props.paddingX,l=this.props.paddingY,c=this.props.paddingZ,p=this._helpers.span.get("x.",i[0]),f=this._helpers.span.get("y.",i[1]),d=this._helpers.span.get("z.",i[2]),this.aX=p.x,this.aY=f.x,this.aZ=d.x,m=p.y-p.x,v=f.y-f.x,g=d.y-d.x,E+=2*h,o+=2*l,r+=2*c,t?(s=1/Math.max(1,E),this.aX+=m*s/2):s=1/Math.max(1,E-1),e?(a=1/Math.max(1,o),this.aY+=v*a/2):a=1/Math.max(1,o-1),n?(u=1/Math.max(1,r),this.aZ+=g*u/2):u=1/Math.max(1,r-1),this.bX=m*s,this.bY=v*a,this.bZ=g*u,this.aX+=this.bX*h,this.aY+=this.bY*l,this.aZ+=this.bZ*l},e.prototype.callback=function(t){return this.updateSpan(),this.last===t?this._callback:(this.last=t,t.length<=7?this._callback=function(e){return function(n,r,i,o){var s,a,u;return s=e.aX+e.bX*r,a=e.aY+e.bY*i,u=e.aZ+e.bZ*o,t(n,s,a,u,r,i,o)}}(this):this._callback=function(e){return function(n,r,i,o){var s,a,u;return s=e.aX+e.bX*r,a=e.aY+e.bY*i,u=e.aZ+e.bZ*o,t(n,s,a,u,r,i,o,e.bufferClock,e.bufferStep)}}(this))},e.prototype.make=function(){return e.__super__.make.apply(this,arguments),this._helpers.span.make(),this._listen(this,"span.range",this.updateSpan)},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),this._helpers.span.unmake()},e}(o),e.exports=i},{"../../../util":175,"./voxel":61}],61:[function(t,e,n){var r,i,o,s=function(t,e){return function(){return t.apply(e,arguments)}},a=function(t,e){function n(){this.constructor=t}for(var r in e)u.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},u={}.hasOwnProperty;r=t("./buffer"),i=t("../../../util"),o=function(t){function e(){return this.update=s(this.update,this),e.__super__.constructor.apply(this,arguments)}return a(e,t),e.traits=["node","buffer","active","data","source","index","texture","voxel","raw"],e.prototype.init=function(){return this.buffer=this.spec=null,this.space={width:0,height:0,depth:0},this.used={width:0,height:0,depth:0},this.storage="voxelBuffer",this.passthrough=function(t,e,n,r){return t(e,n,r,0)},e.__super__.init.apply(this,arguments)},e.prototype.sourceShader=function(t){var e;return e=this.getDimensions(),this.alignShader(e,t),this.buffer.shader(t)},e.prototype.getDimensions=function(){return{items:this.items,width:this.space.width,height:this.space.height,depth:this.space.depth}},e.prototype.getActiveDimensions=function(){return{items:this.items,width:this.used.width,height:this.used.height,depth:this.used.depth*this.buffer.getFilled()}},e.prototype.getRawDimensions=function(){return this.getDimensions()},e.prototype.make=function(){var t,n,r,o,s,a,u,h,l,c,p,f,d,m,v,g,E;return e.__super__.make.apply(this,arguments),h=null!=(l=this.minFilter)?l:this.props.minFilter,u=null!=(c=this.magFilter)?c:this.props.magFilter,g=null!=(p=this.type)?p:this.props.type,E=this.props.width,s=this.props.height,r=this.props.depth,f=this.props.bufferWidth,d=this.props.bufferHeight,m=this.props.bufferDepth,t=this.props.channels,a=this.props.items,o=this.spec={channels:t,items:a,width:E,height:s,depth:r},this.items=o.items,this.channels=o.channels,n=this.props.data,o=i.Data.getDimensions(n,o),v=this.space,v.width=Math.max(f,o.width||1),v.height=Math.max(d,o.height||1),v.depth=Math.max(m,o.depth||1),this.buffer=this._renderables.make(this.storage,{width:v.width,height:v.height,depth:v.depth,channels:t,items:a,minFilter:h,magFilter:u,type:g})},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),this.buffer?(this.buffer.dispose(),this.buffer=this.spec=null):void 0},e.prototype.change=function(t,e,n){var r,i,o;if(e.texture||t["buffer.channels"]||t["buffer.items"]||t["voxel.bufferWidth"]||t["voxel.bufferHeight"]||t["voxel.bufferDepth"])return this.rebuild();if(this.buffer)return t["voxel.width"]&&(o=this.props.width,o>this.space.width)?this.rebuild():t["voxel.height"]&&(i=this.props.height,i>this.space.height)?this.rebuild():t["voxel.depth"]&&(r=this.props.depth,r>this.space.depth)?this.rebuild():t["data.map"]||t["data.data"]||t["data.resolve"]||t["data.expr"]||n?this.buffer.setCallback(this.emitter()):void 0},e.prototype.callback=function(t){return t.length<=4?t:function(e){return function(n,r,i,o){return t(n,r,i,o,e.bufferClock,e.bufferStep)}}(this)},e.prototype.update=function(){var t,e,n,r,o,s,a;if(this.buffer)return e=this.props.data,o=this.space,s=this.used,a=s.width,r=s.height,t=s.depth,n=this.buffer.getFilled(),this.syncBuffer(function(t){return function(n){var r,a,u,h,l,c,p,f;return null!=e?(l=i.Data.getDimensions(e,t.spec),l.width>o.width||l.height>o.height||l.depth>o.depth?(n(),t.rebuild()):(s.width=l.width,s.height=l.height,s.depth=l.depth,t.buffer.setActive(s.width,s.height,s.depth),"function"==typeof(u=t.buffer.callback).rebind&&u.rebind(e),t.buffer.update())):(f=t.spec.width||1,c=t.spec.height||1,h=t.spec.depth||1,t.buffer.setActive(f,c,h),p=t.buffer.update(),s.width=a=f,s.height=r=c,s.depth=Math.ceil(p/a/r),1===s.depth&&(s.height=Math.ceil(p/a),1===s.height)?s.width=p:void 0)}}(this)),s.width!==a||s.height!==r||s.depth!==t||n!==this.buffer.getFilled()?this.trigger({type:"source.resize"}):void 0},e}(r),e.exports=o},{"../../../util":175,"./buffer":55}],62:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../../primitive"),o=t("../../../util"),r=function(t){function e(t,n,r){e.__super__.constructor.call(this,t,n,r),this.axisPosition=this.axisStep=this.resolution=this.line=this.arrows=null}return s(e,t),e.traits=["node","object","visible","style","line","axis","span","interval","arrow","position","origin","shade"],e.defaults={end:!0,zBias:-1},e.prototype.make=function(){var t,e,n,r,i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b;return c={axisPosition:this._attributes.make(this._types.vec4()),axisStep:this._attributes.make(this._types.vec4())},this.axisPosition=c.axisPosition.value,this.axisStep=c.axisStep.value,l=this._shaders.shader(),l.pipe("axis.position",c),l=this._helpers.position.pipeline(l),E=this._helpers.style.uniforms(),a=this._helpers.line.uniforms(),t=this._helpers.arrow.uniforms(),b=this._inherit("unit").getUnitUniforms(),r=this.props.detail,m=r+1,this.resolution=1/r,p=this.props,v=p.start,i=p.end,f=this.props,g=f.stroke,s=f.join,u=this._helpers.object.mask(),h=this._helpers.shade.pipeline()||!1,d=this.props,n=d.crossed,e=d.axis,!n&&null!=u&&e>1&&(y=["x000","y000","z000","w000"][e],u=this._helpers.position.swizzle(u,y)),_=o.JS.merge(t,a,E,b),this.line=this._renderables.make("line",{uniforms:_,samples:m,position:l,clip:v||i,stroke:g,join:s,mask:u,material:h}),this.arrows=[],v&&this.arrows.push(this._renderables.make("arrow",{uniforms:_,flip:!0,samples:m,position:l,mask:u,material:h})),i&&this.arrows.push(this._renderables.make("arrow",{uniforms:_,samples:m,position:l,mask:u,material:h})),this._helpers.visible.make(),this._helpers.object.make(this.arrows.concat([this.line])),this._helpers.span.make(),this._listen(this,"span.range",this.updateRanges)},e.prototype.unmake=function(){return this._helpers.visible.unmake(),this._helpers.object.unmake(),this._helpers.span.unmake()},e.prototype.change=function(t,e,n){return t["axis.detail"]||t["line.stroke"]||t["line.join"]||t["axis.crossed"]||t["interval.axis"]&&this.props.crossed?this.rebuild():e.interval||e.span||e.view||n?this.updateRanges():void 0},e.prototype.updateRanges=function(){var t,e,n,r,i,s;return s=this.props,t=s.axis,r=s.origin,i=this._helpers.span.get("",t),n=i.x,e=i.y,o.Axis.setDimension(this.axisPosition,t).multiplyScalar(n),o.Axis.setDimension(this.axisStep,t).multiplyScalar((e-n)*this.resolution),o.Axis.addOrigin(this.axisPosition,t,r)},e}(i),e.exports=r},{"../../../util":175,"../../primitive":44}],63:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../../primitive"),o=t("../../../util"),r=function(t){function e(t,n,r){e.__super__.constructor.call(this,t,n,r),this.face=null}return s(e,t),e.traits=["node","object","visible","style","line","mesh","face","geometry","position","bind","shade"],e.prototype.resize=function(){var t,e,n,r,i,o;if(null!=this.bind.points)return e=this.bind.points.getActiveDimensions(),r=e.items,o=e.width,n=e.height,t=e.depth,this.face&&this.face.geometry.clip(o,n,t,r),this.line&&this.line.geometry.clip(r,o,n,t),null!=this.bind.map&&(i=this.bind.map.getActiveDimensions(),this.face)?this.face.geometry.map(i.width,i.height,i.depth,i.items):void 0},e.prototype.make=function(){var t,e,n,r,i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H;return this._helpers.bind.make([{to:"geometry.points",trait:"source"},{to:"geometry.colors",trait:"source"},{to:"mesh.map",trait:"source"}]),null!=this.bind.points?(v=this.bind.points.sourceShader(this._shaders.shader()),v=this._helpers.position.pipeline(v),b=this._helpers.style.uniforms(),c=this._helpers.line.uniforms(),w=this._inherit("unit").getUnitUniforms(),H={},H.styleZBias=this._attributes.make(this._types.number()),this.wireZBias=H.styleZBias,n=this.bind.points.getDimensions(),a=n.items,R=n.width,s=n.height,e=n.depth,g=this.props,h=g.line,y=g.shaded,i=g.fill,_=g.stroke,u=g.join,this.bind.colors&&(t=this._shaders.shader(),this.bind.colors.sourceShader(t)),f=this._helpers.object.mask(),p=this._helpers.shade.map(null!=(E=this.bind.map)?E.sourceShader(this._shaders.shader()):void 0),d=this._helpers.shade.pipeline(),r=d||y,l=d||!1,m=[],h&&(T=this._shaders.shader(),T.pipe(o.GLSL.swizzleVec4("yzwx")),T.pipe(v),x=o.JS.merge(w,c,b,H),this.line=this._renderables.make("line",{uniforms:x,samples:a,strips:R,ribbons:s,layers:e,position:T,color:t,stroke:_,join:u,material:l,mask:f,closed:!0}),m.push(this.line)),i&&(x=o.JS.merge(w,b,{}),this.face=this._renderables.make("face",{uniforms:x,width:R,height:s,depth:e,items:a,position:v,color:t,material:r,mask:f,map:p}),m.push(this.face)),this._helpers.visible.make(),this._helpers.object.make(m)):void 0},e.prototype.made=function(){return this.resize()},e.prototype.unmake=function(){return this._helpers.bind.unmake(),this._helpers.visible.unmake(),this._helpers.object.unmake(),this.face=this.line=null},e.prototype.change=function(t,e,n){var r,i,o,s;return t["geometry.points"]||e.mesh?this.rebuild():t["style.zBias"]||t["mesh.lineBias"]||n?(o=this.props,r=o.fill,s=o.zBias,i=o.lineBias,this.wireZBias.value=s+(r?i:0)):void 0},e}(i),e.exports=r},{"../../../util":175,"../../primitive":44}],64:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../../primitive"),o=t("../../../util"),r=function(t){function e(t,n,r){e.__super__.constructor.call(this,t,n,r),this.axes=null}return s(e,t),e.traits=["node","object","visible","style","line","grid","area","position","origin","shade","axis:x","axis:y","scale:x","scale:y","span:x","span:y"],e.defaults={width:1,zBias:-2},e.prototype.make=function(){var t,e,n,r,i,s,a,u,h,l,c,p,f;return u=this._helpers.object.mask(),h=this._helpers.shade.pipeline()||!1,e=function(t){return function(e,n,i){var s,a,l,c,f,d,m,v,g,E,y,_,b,T;return a=t._get(e+"axis.detail"),g=a+1,v=1/a,E=t._helpers.scale.divide(n),s=t._renderables.make("dataBuffer",{width:E,channels:1}),m={gridPosition:t._attributes.make(t._types.vec4()),gridStep:t._attributes.make(t._types.vec4()),gridAxis:t._attributes.make(t._types.vec4())},T={gridPosition:m.gridPosition.value,gridStep:m.gridStep.value,gridAxis:m.gridAxis.value},f=d=t._shaders.shader(),null!=i&&null!=u&&(u=t._helpers.position.swizzle(u,i)),f.require(s.shader(t._shaders.shader(),2)),f.pipe("grid.position",m),d=t._helpers.position.pipeline(f),y=t._helpers.style.uniforms(),c=t._helpers.line.uniforms(),b=t._inherit("unit").getUnitUniforms(),_=o.JS.merge(c,y,b),l=t._renderables.make("line",{uniforms:_,samples:g,strips:E,position:d,stroke:p,join:r,mask:u,material:h}),{first:e,second:n,resolution:v,samples:g,line:l,buffer:s,values:T}}}(this),l=this.props,i=l.lineX,s=l.lineY,n=l.crossed,t=l.axes,f=["0000","x000","y000","z000","w000"][t[1]],c=this.props,p=c.stroke,r=c.join,this.axes=[],i&&this.axes.push(e("x.","y.",null)),s&&this.axes.push(e("y.","x.",n?null:f)),a=function(){var t,n,r,i;for(r=this.axes,i=[],t=0,n=r.length;n>t;t++)e=r[t],i.push(e.line);return i}.call(this),this._helpers.visible.make(),this._helpers.object.make(a),this._helpers.span.make(),this._listen(this,"span.range",this.updateRanges)},e.prototype.unmake=function(){var t,e,n,r;for(this._helpers.visible.unmake(),this._helpers.object.unmake(),this._helpers.span.unmake(),r=this.axes,e=0,n=r.length;n>e;e++)t=r[e],t.buffer.dispose();return this.axes=null},e.prototype.change=function(t,e,n){return t["x.axis.detail"]||t["y.axis.detail"]||t["x.axis.factor"]||t["y.axis.factor"]||t["grid.lineX"]||t["grid.lineY"]||t["line.stroke"]||t["line.join"]||t["grid.crossed"]||t["grid.axes"]&&this.props.crossed?this.rebuild():e.x||e.y||e.area||e.grid||e.view||n?this.updateRanges():void 0},e.prototype.updateRanges=function(){var t,e,n,r,i,s,a,u,h;return e=function(e){return function(n,r,s,a,u){var h,l,c,p,f,d,m,v,g,E,y;return l=u.first,g=u.second,m=u.resolution,v=u.samples,c=u.line,h=u.buffer,y=u.values,f=s.x,p=s.y,o.Axis.setDimension(y.gridPosition,n).multiplyScalar(f),o.Axis.setDimension(y.gridStep,n).multiplyScalar((p-f)*m),o.Axis.addOrigin(y.gridPosition,t,i),f=a.x,p=a.y,E=e._helpers.scale.generate(g,h,f,p),o.Axis.setDimension(y.gridAxis,r),d=E.length,c.geometry.clip(v,d,1,1)}}(this),u=this.props,t=u.axes,i=u.origin,s=this._helpers.span.get("x.",t[0]),a=this._helpers.span.get("y.",t[1]),h=this.props,n=h.lineX,r=h.lineY,n&&e(t[0],t[1],s,a,this.axes[0]),r?e(t[1],t[0],a,s,this.axes[+n]):void 0},e}(i),e.exports=r},{"../../../util":175,"../../primitive":44}],65:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../../primitive"),o=t("../../../util"),r=function(t){function e(t,n,r){e.__super__.constructor.call(this,t,n,r),this.line=this.arrows=null}return s(e,t),e.traits=["node","object","visible","style","line","arrow","geometry","position","bind","shade"],e.prototype.resize=function(){var t,e,n,r,i,o,s,a,u,h;if(null!=this.bind.points){for(e=this.bind.points.getActiveDimensions(),u=e.width,h=e.height,a=e.depth,r=e.items,this.line.geometry.clip(u,h,a,r),o=this.arrows,s=[],n=0,i=o.length;i>n;n++)t=o[n],s.push(t.geometry.clip(u,h,a,r));return s}},e.prototype.make=function(){var t,e,n,r,i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b;return this._helpers.bind.make([{to:"geometry.points",trait:"source"},{to:"geometry.colors",trait:"source"}]),null!=this.bind.points?(l=this._shaders.shader(),l=this.bind.points.sourceShader(l),l=this._helpers.position.pipeline(l),y=this._helpers.style.uniforms(),a=this._helpers.line.uniforms(),t=this._helpers.arrow.uniforms(),b=this._inherit("unit").getUnitUniforms(),p=this.props,v=p.start,r=p.end,f=this.props,E=f.stroke,i=f.join,c=f.proximity,this.proximity=c,n=this.bind.points.getDimensions(),m=n.width,g=n.height,d=n.depth,s=n.items,this.bind.colors&&(e=this._shaders.shader(),this.bind.colors.sourceShader(e)),u=this._helpers.object.mask(),h=this._helpers.shade.pipeline()||!1,_=o.JS.merge(t,a,y,b),this.line=this._renderables.make("line",{uniforms:_,samples:m,strips:g,ribbons:d,layers:s,position:l,color:e,clip:v||r,stroke:E,join:i,proximity:c,mask:u,material:h}),this.arrows=[],v&&this.arrows.push(this._renderables.make("arrow",{uniforms:_,flip:!0,samples:m,strips:g,ribbons:d,layers:s,position:l,color:e,mask:u,material:h})),r&&this.arrows.push(this._renderables.make("arrow",{uniforms:_,samples:m,strips:g,ribbons:d,layers:s,position:l,color:e,mask:u,material:h})),this._helpers.visible.make(),this._helpers.object.make(this.arrows.concat([this.line]))):void 0},e.prototype.made=function(){return this.resize()},e.prototype.unmake=function(){return this._helpers.bind.unmake(),this._helpers.visible.unmake(),this._helpers.object.unmake(),this.line=this.arrows=null},e.prototype.change=function(t,e,n){return t["geometry.points"]||t["line.stroke"]||t["line.join"]||t["arrow.start"]||t["arrow.end"]?this.rebuild():t["line.proximity"]&&null!=this.proximity!=(null!=this.props.proximity)?this.rebuild():void 0},e}(i),e.exports=r},{"../../../util":175,"../../primitive":44}],66:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../../primitive"),o=t("../../../util"),r=function(t){function e(t,n,r){e.__super__.constructor.call(this,t,n,r),this.point=null}return s(e,t),e.traits=["node","object","visible","style","point","geometry","position","bind","shade"],e.prototype.resize=function(){var t,e,n,r,i;if(null!=this.bind.points)return e=this.bind.points.getActiveDimensions(),r=e.items,i=e.width,n=e.height,t=e.depth,this.point.geometry.clip(i,n,t,r)},e.prototype.make=function(){var t,e,n,r,i,s,a,u,h,l,c,p,f,d,m,v,g;return this._helpers.bind.make([{to:"geometry.points",trait:"source"},{to:"geometry.colors",trait:"source"},{to:"point.sizes",trait:"source"}]),null!=this.bind.points?(c=this._shaders.shader(),c=this.bind.points.sourceShader(c),c=this._helpers.position.pipeline(c),n=this.bind.points.getDimensions(),s=n.items,g=n.width,i=n.height,e=n.depth,d=this._helpers.style.uniforms(),l=this._helpers.point.uniforms(),v=this._inherit("unit").getUnitUniforms(),this.bind.colors&&(t=this._shaders.shader(),this.bind.colors.sourceShader(t)),this.bind.sizes&&(f=this._shaders.shader(),this.bind.sizes.sourceShader(f)), +a=this._helpers.object.mask(),u=this._helpers.shade.pipeline()||!1,p=this.props.shape,r=this.props.fill,h=this.props.optical,m=o.JS.merge(v,l,d),this.point=this._renderables.make("point",{uniforms:m,width:g,height:i,depth:e,items:s,position:c,color:t,size:f,shape:p,optical:h,fill:r,mask:a,material:u}),this._helpers.visible.make(),this._helpers.object.make([this.point])):void 0},e.prototype.made=function(){return this.resize()},e.prototype.unmake=function(){return this._helpers.bind.unmake(),this._helpers.visible.unmake(),this._helpers.object.unmake(),this.point=null},e.prototype.change=function(t,e,n){return t["geometry.points"]||t["point.shape"]||t["point.fill"]?this.rebuild():void 0},e}(i),e.exports=r},{"../../../util":175,"../../primitive":44}],67:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("../../primitive"),o=t("../../../util"),i=function(t){function e(t,n,r){e.__super__.constructor.call(this,t,n,r),this.strip=null}return s(e,t),e.traits=["node","object","visible","style","line","mesh","strip","geometry","position","bind","shade"],e.prototype.resize=function(){var t,e,n,r,i,o;if(null!=this.bind.points)return e=this.bind.points.getActiveDimensions(),r=e.items,o=e.width,n=e.height,t=e.depth,this.strip&&this.strip.geometry.clip(o,n,t,r),this.line&&this.line.geometry.clip(r,o,n,t),null!=this.bind.map&&(i=this.bind.map.getActiveDimensions(),this.strip)?this.strip.geometry.map(i.width,i.height,i.depth,i.items):void 0},e.prototype.make=function(){var t,e,n,r,i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H;return this._helpers.bind.make([{to:"geometry.points",trait:"source"},{to:"geometry.colors",trait:"source"},{to:"mesh.map",trait:"source"}]),null!=this.bind.points?(v=this._shaders.shader(),v=this.bind.points.sourceShader(v),v=this._helpers.position.pipeline(v),b=this._helpers.style.uniforms(),c=this._helpers.line.uniforms(),w=this._inherit("unit").getUnitUniforms(),h=this.props.line,y=this.props.shaded,i=this.props.fill,H={},H.styleZBias=this._attributes.make(this._types.number()),this.wireZBias=H.styleZBias,n=this.bind.points.getDimensions(),a=n.items,R=n.width,s=n.height,e=n.depth,g=this.props,h=g.line,y=g.shaded,i=g.fill,_=g.stroke,u=g.join,this.bind.colors&&(t=this._shaders.shader(),t=this.bind.colors.sourceShader(t)),f=this._helpers.object.mask(),p=this._helpers.shade.map(null!=(E=this.bind.map)?E.sourceShader(this._shaders.shader()):void 0),d=this._helpers.shade.pipeline(),r=d||y,l=d||!1,m=[],h&&(T=this._shaders.shader(),T.pipe(o.GLSL.swizzleVec4("yzwx")),T.pipe(v),x=o.JS.merge(w,c,b,H),this.line=this._renderables.make("line",{uniforms:x,samples:a,strips:R,ribbons:s,layers:e,position:T,color:t,stroke:_,join:u,mask:f,material:l}),m.push(this.line)),i&&(x=o.JS.merge(b,{}),this.strip=this._renderables.make("strip",{uniforms:x,width:R,height:s,depth:e,items:a,position:v,color:t,material:r}),m.push(this.strip)),this._helpers.visible.make(),this._helpers.object.make(m)):void 0},e.prototype.made=function(){return this.resize()},e.prototype.unmake=function(){return this._helpers.bind.unmake(),this._helpers.visible.unmake(),this._helpers.object.unmake(),this.strip=null},e.prototype.change=function(t,e,n){var r,i,o,s;return t["geometry.points"]||e.mesh?this.rebuild():t["style.zBias"]||t["mesh.lineBias"]||n?(o=this.props,r=o.fill,s=o.zBias,i=o.lineBias,this.wireZBias.value=s+(r?i:0)):void 0},e}(r),e.exports=i},{"../../../util":175,"../../primitive":44}],68:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("../../primitive"),o=t("../../../util"),i=function(t){function e(t,n,r){e.__super__.constructor.call(this,t,n,r),this.lineX=this.lineY=this.surface=null}return s(e,t),e.traits=["node","object","visible","style","line","mesh","geometry","surface","position","grid","bind","shade"],e.defaults={lineX:!1,lineY:!1},e.prototype.resize=function(){var t,e,n,r,i,o;if(null!=this.bind.points)return e=this.bind.points.getActiveDimensions(),o=e.width,n=e.height,t=e.depth,r=e.items,this.surface&&this.surface.geometry.clip(o,n,t,r),this.lineX&&this.lineX.geometry.clip(o,n,t,r),this.lineY&&this.lineY.geometry.clip(n,o,t,r),null!=this.bind.map&&(i=this.bind.map.getActiveDimensions(),this.surface)?this.surface.geometry.map(i.width,i.height,i.depth,i.items):void 0},e.prototype.make=function(){var t,e,n,r,i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k,A,C,P,L,z,O;return this._helpers.bind.make([{to:"geometry.points",trait:"source"},{to:"geometry.colors",trait:"source"},{to:"mesh.map",trait:"source"}]),null!=this.bind.points?(_=this._shaders.shader(),_=this.bind.points.sourceShader(_),_=this._helpers.position.pipeline(_),M=this._helpers.style.uniforms(),z=this._helpers.style.uniforms(),f=this._helpers.line.uniforms(),S=this._helpers.surface.uniforms(),P=this._inherit("unit").getUnitUniforms(),z.styleColor=this._attributes.make(this._types.color()),z.styleZBias=this._attributes.make(this._types.number()),this.wireColor=z.styleColor.value,this.wireZBias=z.styleZBias,this.wireScratch=new THREE.Color,s=this.bind.points.getDimensions(),L=s.width,h=s.height,i=s.depth,l=s.items,T=this.props,R=T.shaded,u=T.fill,d=T.lineX,m=T.lineY,t=T.closedX,e=T.closedY,H=T.stroke,c=T.join,b=T.proximity,r=T.crossed,y=[],this.proximity=b,this.bind.colors&&(n=this._shaders.shader(),this.bind.colors.sourceShader(n)),g=this._helpers.object.mask(),v=this._helpers.shade.map(null!=(x=this.bind.map)?x.sourceShader(this._shaders.shader()):void 0),E=this._helpers.shade.pipeline(),a=E||R,p=E||!1,w=this._helpers.position,k=w.swizzle,A=w.swizzle2,C=o.JS.merge(P,f,M,z),O=d||m?-50:0,d&&(this.lineX=this._renderables.make("line",{uniforms:C,samples:L,strips:h,ribbons:i,layers:l,position:_,color:n,zUnits:-O,stroke:H,join:c,mask:g,material:p,proximity:b,closed:t||closed}),y.push(this.lineX)),m&&(this.lineY=this._renderables.make("line",{uniforms:C,samples:h,strips:L,ribbons:i,layers:l,position:A(_,"yxzw","yxzw"),color:k(n,"yxzw"),zUnits:-O,stroke:H,join:c,mask:k(g,r?"xyzw":"yxzw"),material:p,proximity:b,closed:e||closed}),y.push(this.lineY)),u&&(C=o.JS.merge(P,S,M),this.surface=this._renderables.make("surface",{uniforms:C,width:L,height:h,surfaces:i,layers:l,position:_,color:n,zUnits:O,stroke:H,material:a,mask:g,map:v,intUV:!0,closedX:t||closed,closedY:e||closed}),y.push(this.surface)),this._helpers.visible.make(),this._helpers.object.make(y)):void 0},e.prototype.made=function(){return this.resize()},e.prototype.unmake=function(){return this._helpers.bind.unmake(),this._helpers.visible.unmake(),this._helpers.object.unmake(),this.lineX=this.lineY=this.surface=null},e.prototype.change=function(t,e,n){var r,i,o,s,a,u;return t["geometry.points"]||t["mesh.shaded"]||t["mesh.fill"]||t["line.stroke"]||t["line.join"]||e.grid?this.rebuild():((t["style.color"]||t["style.zBias"]||t["mesh.fill"]||t["mesh.lineBias"]||n)&&(a=this.props,o=a.fill,i=a.color,u=a.zBias,s=a.lineBias,this.wireZBias.value=u+(o?s:0),this.wireColor.copy(i),o&&(r=this.wireScratch,r.setRGB(i.x,i.y,i.z),r.convertGammaToLinear().multiplyScalar(.75).convertLinearToGamma(),this.wireColor.x=r.r,this.wireColor.y=r.g,this.wireColor.z=r.b)),t["line.proximity"]&&null!=this.proximity!=(null!=this.props.proximity)?this.rebuild():void 0)},e}(r),e.exports=i},{"../../../util":175,"../../primitive":44}],69:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("../../primitive"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","object","visible","style","line","ticks","geometry","position","bind","shade"],e.prototype.init=function(){return this.tickStrip=this.line=null},e.prototype.resize=function(){var t,e,n,r,i;if(null!=this.bind.points)return e=this.bind.points.getActiveDimensions(),t=+(e.items>0),i=e.width*t,r=e.height*t,n=e.depth*t,this.line.geometry.clip(2,i,r,n),this.tickStrip.set(0,i-1)},e.prototype.make=function(){var t,e,n,r,i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_;return this._helpers.bind.make([{to:"geometry.points",trait:"source"},{to:"geometry.colors",trait:"source"}]),null!=this.bind.points?(v=this._helpers.style.uniforms(),i=this._helpers.line.uniforms(),_=this._inherit("unit").getUnitUniforms(),y=o.JS.merge(i,v,_),l={tickEpsilon:this.node.attributes["ticks.epsilon"],tickSize:this.node.attributes["ticks.size"],tickNormal:this.node.attributes["ticks.normal"],tickStrip:this._attributes.make(this._types.vec2(0,0)),worldUnit:y.worldUnit,focusDepth:y.focusDepth},this.tickStrip=l.tickStrip.value,u=h=this._shaders.shader(),u.require(this.bind.points.sourceShader(this._shaders.shader())),u.require(this._helpers.position.pipeline(this._shaders.shader())),u.pipe("ticks.position",l),c=this.props,m=c.stroke,n=c.join,e=this.bind.points.getDimensions(),d=e.width,f=e.height,r=e.depth,this.bind.colors&&(t=this._shaders.shader(),this.bind.colors.sourceShader(t)),s=this._helpers.object.mask(),a=this._helpers.shade.pipeline()||!1,p=this._helpers.position,g=p.swizzle,E=p.swizzle2,this.line=this._renderables.make("line",{uniforms:y,samples:2,strips:d,ribbons:f,layers:r,position:h,color:t,stroke:m,join:n,mask:g(s,"yzwx"),material:a}),this._helpers.visible.make(),this._helpers.object.make([this.line])):void 0},e.prototype.made=function(){return this.resize()},e.prototype.unmake=function(){return this.line=null,this._helpers.visible.unmake(),this._helpers.object.unmake()},e.prototype.change=function(t,e,n){return t["geometry.points"]||t["line.stroke"]||t["line.join"]?this.rebuild():void 0},e}(r),e.exports=i},{"../../../util":175,"../../primitive":44}],70:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("../../primitive"),i=t("../../../util"),o=function(t){function e(t,n,r){e.__super__.constructor.call(this,t,n,r),this.line=this.arrows=null}return s(e,t),e.traits=["node","object","visible","style","line","arrow","geometry","position","bind","shade"],e.prototype.resize=function(){var t,e,n,r,i,o,s,a,u,h;if(null!=this.bind.points){for(e=this.bind.points.getActiveDimensions(),u=e.items,h=e.width,a=e.height,r=e.depth,this.line.geometry.clip(u,h,a,r),o=this.arrows,s=[],n=0,i=o.length;i>n;n++)t=o[n],s.push(t.geometry.clip(u,h,a,r));return s}},e.prototype.make=function(){var t,e,n,r,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w;return this._helpers.bind.make([{to:"geometry.points",trait:"source"},{to:"geometry.colors",trait:"source"}]),null!=this.bind.points?(l=this._shaders.shader(),this.bind.points.sourceShader(l),this._helpers.position.pipeline(l),_=this._helpers.style.uniforms(),a=this._helpers.line.uniforms(),t=this._helpers.arrow.uniforms(),w=this._inherit("unit").getUnitUniforms(),p=this.props,g=p.start,r=p.end,f=this.props,y=f.stroke,o=f.join,c=f.proximity,this.proximity=c,n=this.bind.points.getDimensions(),v=n.items,E=n.width,m=n.height,s=n.depth,this.bind.colors&&(e=this._shaders.shader(),this.bind.colors.sourceShader(e)),u=this._helpers.object.mask(),h=this._helpers.shade.pipeline()||!1,d=this._helpers.position,b=d.swizzle,T=d.swizzle2,l=T(l,"yzwx","yzwx"),e=b(e,"yzwx"),u=b(u,"yzwx"),h=b(h,"yzwx"),x=i.JS.merge(t,a,_,w),this.line=this._renderables.make("line",{uniforms:x,samples:v,ribbons:m,strips:E,layers:s,position:l,color:e,clip:g||r,stroke:y,join:o,proximity:c,mask:u,material:h}),this.arrows=[],g&&this.arrows.push(this._renderables.make("arrow",{uniforms:x,flip:!0,samples:v,ribbons:m,strips:E,layers:s,position:l,color:e,mask:u,material:h})),r&&this.arrows.push(this._renderables.make("arrow",{uniforms:x,samples:v,ribbons:m,strips:E,layers:s,position:l,color:e,mask:u,material:h})),this._helpers.visible.make(),this._helpers.object.make(this.arrows.concat([this.line]))):void 0},e.prototype.made=function(){return this.resize()},e.prototype.unmake=function(){return this._helpers.bind.unmake(),this._helpers.visible.unmake(),this._helpers.object.unmake(),this.line=this.arrows=null},e.prototype.change=function(t,e,n){return t["geometry.points"]||t["line.stroke"]||t["line.join"]||t["arrow.start"]||t["arrow.end"]?this.rebuild():t["line.proximity"]&&null!=this.proximity!=(null!=this.props.proximity)?this.rebuild():void 0},e}(r),e.exports=o},{"../../../util":175,"../../primitive":44}],71:[function(t,e,n){var r,i,o,s=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};r=t("../../util"),i=t("./view/view"),o={bind:{make:function(t){var e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E;for(null==this.bind&&(this.bind={}),null==this.bound&&(this.bound=[]),r=0,s=t.length;s>r;r++){if(f=t[r],v=f.to,g=f.trait,l=f.optional,E=f.unique,u=f.multiple,e=f.callback,null==e&&(e=this.rebuild),h=v.split(/\./g).pop(),p=this._get(v),d=null,null!=p)for(m=this,n=!1;!n;)m=d=this._attach(p,g,e,this,m,l,u),i=E&&(null==d||this.bound.indexOf(d)<0),n=u||l||!E||i;if(null!=d)if(null!=this.resize&&this._listen(d,"source.resize",this.resize),e&&this._listen(d,"source.rebuild",e),u)for(o=0,a=d.length;a>o;o++)c=d[o],this.bound.push(c);else this.bound.push(d);this.bind[h]=d}return null},unmake:function(){return this.bind?(delete this.bind,delete this.bound):void 0}},span:{make:function(){return this.spanView=this._inherit("view"),this._listen("view","view.range",function(t){return function(){return t.trigger({type:"span.range"})}}(this))},unmake:function(){return delete this.spanView},get:function(){var t;return t=new THREE.Vector2(-1,1),function(e,n){var r,i,o;return r=this._get(e+"span.range"),null!=r?r:null!=(i=null!=(o=this.spanView)?o.axis(n):void 0)?i:t}}()},scale:{divide:function(t){var e,n;return e=this._get(t+"scale.divide"),n=this._get(t+"scale.factor"),Math.round(2.5*e/n)},generate:function(t,e,n,i){var o,s,a,u,h,l,c,p,f,d;return h=this._get(t+"scale.mode"),s=this._get(t+"scale.divide"),f=this._get(t+"scale.unit"),o=this._get(t+"scale.base"),u=this._get(t+"scale.factor"),c=this._get(t+"scale.start"),a=this._get(t+"scale.end"),d=this._get(t+"scale.zero"),l=this._get(t+"scale.nice"),p=r.Ticks.make(h,n,i,s,f,o,u,c,a,d,l),e.copy(p),p}},style:{uniforms:function(){return{styleColor:this.node.attributes["style.color"],styleOpacity:this.node.attributes["style.opacity"],styleZBias:this.node.attributes["style.zBias"],styleZIndex:this.node.attributes["style.zIndex"]}}},arrow:{uniforms:function(){var t,e,n,r,i;return r=this.props.start,t=this.props.end,n=this._attributes.make(this._types.number(1.25/(r+t))),i=this._attributes.make(this._types.vec2(+r,+t)),e=this.node.attributes["arrow.size"],{clipStyle:i,clipRange:e,clipSpace:n,arrowSpace:n,arrowSize:e}}},point:{uniforms:function(){return{pointSize:this.node.attributes["point.size"],pointDepth:this.node.attributes["point.depth"]}}},line:{uniforms:function(){return{lineWidth:this.node.attributes["line.width"],lineDepth:this.node.attributes["line.depth"],lineProximity:this.node.attributes["line.proximity"]}}},surface:{uniforms:function(){return{}}},shade:{pipeline:function(t){var e,n,r;if(!this._inherit("fragment"))return t;for(null==t&&(t=this._shaders.shader()),n=e=0;2>=e;n=++e)t=null!=(r=this._inherit("fragment"))?r.fragment(t,n):void 0;return t.pipe("fragment.map.rgba"),t},map:function(t){return t?t=this._shaders.shader().pipe("mesh.map.uvwo").pipe(t):t}},position:{pipeline:function(t){var e,n,r;if(!this._inherit("vertex"))return t;for(null==t&&(t=this._shaders.shader()),n=e=0;3>=e;n=++e)t=null!=(r=this._inherit("vertex"))?r.vertex(t,n):void 0;return t},swizzle:function(t,e){return t?this._shaders.shader().pipe(r.GLSL.swizzleVec4(e)).pipe(t):void 0},swizzle2:function(t,e,n){return t?this._shaders.shader().split().pipe(r.GLSL.swizzleVec4(e)).next().pipe(r.GLSL.swizzleVec4(n)).join().pipe(t):void 0}},visible:{make:function(){var t,e,n,r;return t={type:"visible.change"},n=null,this.setVisible=function(t){return null!=t&&(n=t),e()},e=function(e){return function(){var i,o,s;return i=e.isVisible,s=null!=(o=null!=n?n:e._get("object.visible"))?o:!0,"undefined"!=typeof r&&null!==r&&s&&(s=r.isVisible),e.isVisible=s,i!==e.isVisible?e.trigger(t):void 0}}(this),r=this._inherit("visible"),r&&this._listen(r,"visible.change",e),this.is("object")&&this._listen(this.node,"change:object",e),e()},unmake:function(){return delete this.isVisible}},active:{make:function(){var t,e,n,r;return n={type:"active.change"},t=null,this.setActive=function(e){return null!=e&&(t=e),r()},r=function(r){return function(){var i,o,s;return i=r.isActive,s=null!=(o=null!=t?t:r._get("entity.active"))?o:!0,"undefined"!=typeof e&&null!==e&&s&&(s=e.isActive),r.isActive=s,i!==r.isActive?r.trigger(n):void 0}}(this),e=this._inherit("active"),e&&this._listen(e,"active.change",r),this.is("entity")&&this._listen(this.node,"change:entity",r),r()},unmake:function(){return delete this.isActive}},object:{make:function(t){var e,n,r,i,o,a,u,h,l,c,p,f,d,m;for(this.objects=null!=t?t:[],this.renders=this.objects.reduce(function(t,e){return t.concat(e.renders)},[]),u=this._inherit("scene"),c=e=f=null,n=s.call(this.traits,"style")>=0,c=1,e=THREE.NormalBlending,m=!0,d=!0,n&&(c=this.props.opacity,e=this.props.blending,f=this.props.zOrder,m=this.props.zWrite,d=this.props.zTest),h=function(t){return function(n){var r,i;return r=n.changed,i=null,r["style.opacity"]&&(i=c=t.props.opacity),r["style.blending"]&&(i=e=t.props.blending),r["style.zOrder"]&&(i=f=t.props.zOrder),r["style.zWrite"]&&(i=m=t.props.zWrite),r["style.zTest"]&&(i=d=t.props.zTest),null!=i?l():void 0}}(this),i=null,l=function(t){return function(){var r,i,o,s,a,u,h,l,p,v,g,E,y,_,b,T;if(l=null!=f?-f:t.node.order,T=(null!=(p=t.isVisible)?p:!0)&&c>0){if(n){for(v=t.objects,y=[],r=0,s=v.length;s>r;r++)h=v[r],h.show(1>c,e,l),y.push(h.depth(m,d));return y}for(g=t.objects,_=[],i=0,a=g.length;a>i;i++)h=g[i],_.push(h.show(!0,e,l));return _}for(E=t.objects,b=[],o=0,u=E.length;u>o;o++)h=E[o],b.push(h.hide());return b}}(this),this._listen(this.node,"change:style",h),this._listen(this.node,"reindex",l),this._listen(this,"visible.change",l),p=this.objects,r=0,o=p.length;o>r;r++)a=p[r],u.adopt(a);return l()},unmake:function(t){var e,n,r,i,o,s,a,u,h;if(null==t&&(t=!0),this.objects){for(s=this._inherit("scene"),a=this.objects,e=0,r=a.length;r>e;e++)o=a[e],s.unadopt(o);if(t){for(u=this.objects,h=[],n=0,i=u.length;i>n;n++)o=u[n],h.push(o.dispose());return h}}},mask:function(){var t,e;if(t=this._inherit("mask"))return e=t.mask(e)}},unit:{make:function(){var t,e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v;return v=Math.PI,this.unitUniforms={renderScaleInv:h=this._attributes.make(this._types.number(1)),renderScale:u=this._attributes.make(this._types.number(1)),renderAspect:o=this._attributes.make(this._types.number(1)),renderWidth:l=this._attributes.make(this._types.number(0)),renderHeight:s=this._attributes.make(this._types.number(0)),viewWidth:d=this._attributes.make(this._types.number(0)),viewHeight:f=this._attributes.make(this._types.number(0)),pixelRatio:r=this._attributes.make(this._types.number(1)),pixelUnit:i=this._attributes.make(this._types.number(1)),worldUnit:m=this._attributes.make(this._types.number(1)),focusDepth:e=this._attributes.make(this._types.number(1)),renderOdd:a=this._attributes.make(this._types.vec2())},p=new THREE.Vector3,t=new THREE.Vector3,n=function(n){return function(){var g,E,y,_,b,T,x,w,R,H,M,S,k,A;if(null!=(k="undefined"!=typeof c&&null!==c?c.getSize():void 0))return v=Math.PI,S=n.props.scale,_=n.props.fov,y=null!=(H=n.props.focus)?H:n.inherit("unit").props.focus,T=null===S,w=1,(g="undefined"!=typeof c&&null!==c?c.getCamera():void 0)&&(x=g.projectionMatrix,p.set(0,-.5,1).applyProjection(x),t.set(0,.5,1).applyProjection(x),p.sub(t),w=p.y),E=k.renderHeight/k.viewHeight,b=null!=_?w*Math.tan(_*v/360):1,R=T?E:k.renderHeight/S*b,M=k.renderHeight*w/2,A=R/M,d.value=k.viewWidth,f.value=k.viewHeight,l.value=k.renderWidth,s.value=k.renderHeight,o.value=k.aspect,u.value=M,h.value=1/M,r.value=E,i.value=R,m.value=A,e.value=y,a.value.set(k.renderWidth%2,k.renderHeight%2).multiplyScalar(.5)}}(this),c=this.is("root")?this:this._inherit("root"),this._listen(c,"root.update",n),n()},unmake:function(){return delete this.unitUniforms},get:function(){var t,e,n,r;n={},e=this.unitUniforms;for(t in e)r=e[t],n[t]=r.value;return n},uniforms:function(){return this.unitUniforms}}},e.exports=function(t,e){var n,r,i,s,a,u,h;for(n={},r=0,s=e.length;s>r;r++)if(h=e[r],u=o[h]){n[h]={};for(i in u)a=u[i],n[h][i]=a.bind(t)}return n}},{"../../util":175,"./view/view":122}],72:[function(t,e,n){var r;r=t("../../model"),n.Classes=t("./classes"),n.Types=t("./types"),n.Traits=t("./traits"),n.Helpers=t("./helpers")},{"../../model":34,"./classes":52,"./helpers":71,"./traits":107,"./types":115}],73:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("./operator"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","bind","operator","source","index","clamp"],e.prototype.indexShader=function(t){return t.pipe(this.operator),e.__super__.indexShader.call(this,t)},e.prototype.sourceShader=function(t){return t.pipe(this.operator),e.__super__.sourceShader.call(this,t)},e.prototype.make=function(){var t,n;return e.__super__.make.apply(this,arguments),null!=this.bind.source?(n={clampLimit:this._attributes.make(this._types.vec4())},this.clampLimit=n.clampLimit,t=this._shaders.shader(),t.pipe("clamp.position",n),this.operator=t):void 0},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments)},e.prototype.resize=function(){var t;return null!=this.bind.source&&(t=this.bind.source.getActiveDimensions(),this.clampLimit.value.set(t.width-1,t.height-1,t.depth-1,t.items-1)),e.__super__.resize.apply(this,arguments)},e.prototype.change=function(t,e,n){return e.operator||e.clamp?this.rebuild():void 0},e}(i),e.exports=r},{"./operator":78}],74:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("./operator"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","bind","operator","source","index","grow"],e.prototype.sourceShader=function(t){return t.pipe(this.operator)},e.prototype.make=function(){var t,n;return e.__super__.make.apply(this,arguments),null!=this.bind.source?(n={growScale:this.node.attributes["grow.scale"],growMask:this._attributes.make(this._types.vec4()),growAnchor:this._attributes.make(this._types.vec4())},this.growMask=n.growMask.value,this.growAnchor=n.growAnchor.value,t=this._shaders.shader(),t.require(this.bind.source.sourceShader(this._shaders.shader())),t.pipe("grow.position",n),this.operator=t):void 0},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments)},e.prototype.resize=function(){return this.update(),e.__super__.resize.apply(this,arguments)},e.prototype.update=function(){var t,e,n,r,i,o,s,a,u;for(e=this.bind.source.getFutureDimensions(),a=["width","height","depth","items"],s=function(t,e){return((t||1)-1)*(.5-.5*e)},u=[],n=r=0,o=a.length;o>r;n=++r)i=a[n],t=this.props[i],this.growMask.setComponent(n,+(null==t)),u.push(this.growAnchor.setComponent(n,null!=t?s(e[i],t):0));return u},e.prototype.change=function(t,e,n){return e.operator?this.rebuild():e.grow?this.update():void 0},e}(i),e.exports=r},{"./operator":78}],75:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("./operator"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","operator","source","index","join"],e.prototype.indexShader=function(t){return t.pipe(this.operator),e.__super__.indexShader.call(this,t)},e.prototype.sourceShader=function(t){return t.pipe(this.operator),e.__super__.sourceShader.call(this,t)},e.prototype.getDimensions=function(){return this._resample(this.bind.source.getDimensions())},e.prototype.getActiveDimensions=function(){return this._resample(this.bind.source.getActiveDimensions())},e.prototype.getFutureDimensions=function(){return this._resample(this.bind.source.getFutureDimensions())},e.prototype.getIndexDimensions=function(){return this._resample(this.bind.source.getIndexDimensions())},e.prototype._resample=function(t){var e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v;for(l=this.order,e=this.axis,p=this.overlap,u=this.length,v=this.stride,s=["width","height","depth","items"],h=l.map(function(t){return s[t-1]}),i=l.indexOf(e),m=function(){var e,r,i;for(i=[],e=0,r=h.length;r>e;e++)n=h[e],i.push(t[n]);return i}(),f=(null!=(d=m[i+1])?d:1)*v,m.splice(i,2,f),m=m.slice(0,3),m.push(1),c={},r=o=0,a=h.length;a>o;r=++o)n=h[r],c[n]=m[r];return c},e.prototype.make=function(){var t,n,r,i,s,a,u,h,l,c,p,f,d;return e.__super__.make.apply(this,arguments),null!=this.bind.source?(u=this.props.order,t=this.props.axis,h=this.props.overlap,l=u.join(""),null==t&&(t=u[0]),r=l.indexOf(t),c=l.replace(t,"00").substring(0,4),i=[null,"width","height","depth","items"],a=i[t],n=this.bind.source.getDimensions(),s=n[a],h=Math.min(s-1,h),p=s-h,d={joinStride:this._attributes.make(this._types.number(p)),joinStrideInv:this._attributes.make(this._types.number(1/p))},f=this._shaders.shader(),f.require(o.GLSL.swizzleVec4(t,1)),f.require(o.GLSL.swizzleVec4(c,4)),f.require(o.GLSL.injectVec4([r,r+1])),f.pipe("join.position",d),f.pipe(o.GLSL.invertSwizzleVec4(u)),this.operator=f,this.order=u,this.axis=t,this.overlap=h,this.length=s,this.stride=p):void 0},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments)},e.prototype.change=function(t,e,n){return e.join||e.operator?this.rebuild():void 0},e}(i),e.exports=r},{"../../../util":175,"./operator":78}],76:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("./operator"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","operator","source","index","lerp","sampler:x","sampler:y","sampler:z","sampler:w"],e.prototype.indexShader=function(t){return t.pipe(this.indexer),e.__super__.indexShader.call(this,t)},e.prototype.sourceShader=function(t){return t.pipe(this.operator)},e.prototype.getDimensions=function(){return this._resample(this.bind.source.getDimensions())},e.prototype.getActiveDimensions=function(){return this._resample(this.bind.source.getActiveDimensions())},e.prototype.getFutureDimensions=function(){return this._resample(this.bind.source.getFutureDimensions())},e.prototype.getIndexDimensions=function(){return this._resample(this.bind.source.getIndexDimensions())},e.prototype._resample=function(t){var e,n,r;return r=this.resampled,e=this.centered,n=this.padding,this.relativeSize?(e.items||t.items--,e.width||t.width--,e.height||t.height--,e.depth||t.depth--,null!=r.items&&(t.items*=r.items),null!=r.width&&(t.width*=r.width),null!=r.height&&(t.height*=r.height),null!=r.depth&&(t.depth*=r.depth),e.items||t.items++,e.width||t.width++,e.height||t.height++,e.depth||t.depth++,t.items-=2*n.items,t.width-=2*n.width,t.height-=2*n.height,t.depth-=2*n.depth):(null!=r.items&&(t.items=r.items),null!=r.width&&(t.width=r.width),null!=r.height&&(t.height=r.height),null!=r.depth&&(t.depth=r.depth)),t.items=Math.max(0,Math.floor(t.items)),t.width=Math.max(0,Math.floor(t.width)),t.height=Math.max(0,Math.floor(t.height)),t.depth=Math.max(0,Math.floor(t.depth)),t},e.prototype.make=function(){var t,n,r,i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R;if(e.__super__.make.apply(this,arguments),null!=this.bind.source){for(v=this.props,T=v.size,h=v.items,R=v.width,i=v.height,r=v.depth,y=T===this.node.attributes["lerp.size"]["enum"].relative,this.resampled={},null!=h&&(this.resampled.items=h),null!=R&&(this.resampled.width=R),null!=i&&(this.resampled.height=i),null!=r&&(this.resampled.depth=r),this.centered={},this.centered.items=this.props.centeredW,this.centered.width=this.props.centeredX,this.centered.height=this.props.centeredY,this.centered.depth=this.props.centeredZ,this.padding={},this.padding.items=this.props.paddingW,this.padding.width=this.props.paddingX,this.padding.height=this.props.paddingY,this.padding.depth=this.props.paddingZ,m=this._shaders.shader(),u=this._shaders.shader(),x={resampleFactor:this._attributes.make(this._types.vec4(0,0,0,0)),resampleBias:this._attributes.make(this._types.vec4(0,0,0,0))},this.resampleFactor=x.resampleFactor,this.resampleBias=x.resampleBias,_=null!=h||null!=R||null!=i||null!=r,m.pipe("resample.padding",x),w=[],t=!1,g=["width","height","depth","items"],s=l=0,f=g.length;f>l;s=++l)p=g[s],n=this.centered[p],t||(t=n),w[s]=n?"0.5":"0.0";for(t&&_&&(w="vec4("+w+")",m.pipe(o.GLSL.binaryOperator(4,"+",vec4)),u.pipe(o.GLSL.binaryOperator(4,"+",vec4))),_?(m.pipe("resample.relative",x),u.pipe("resample.relative",x)):(m.pipe(o.GLSL.identity("vec4")),u.pipe(o.GLSL.identity("vec4"))),t&&_&&(m.pipe(o.GLSL.binaryOperator(4,"-",w)),u.pipe(o.GLSL.binaryOperator(4,"-",w))),b=this.bind.source.sourceShader(this._shaders.shader()),E=["width","height","depth","items"],s=c=0,d=E.length;d>c;s=++c)p=E[s],a="lerp."+p,null!=this.props[p]&&(b=this._shaders.shader().require(b),b.pipe(a,x));return m.pipe(b),this.operator=m,this.indexer=u,this.relativeSize=y}},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),this.operator=null},e.prototype.resize=function(){var t,n,r,i,o,s,a,u,h,l,c,p,f,d,m;if(null!=this.bind.source)return s=this.bind.source.getActiveDimensions(),m=this.getActiveDimensions(),t=function(t){return function(e){var n,r,i;return n=t.centered[e],r=t.padding[e],m[e]+=2*r,i=n?s[e]/Math.max(1,m[e]):Math.max(1,s[e]-1)/Math.max(1,m[e]-1),[i,r]}}(this),u=t("width"),d=u[0],o=u[1],h=t("height"),p=h[0],r=h[1],l=t("depth"),a=l[0],n=l[1],c=t("items"),f=c[0],i=c[1],this.resampleFactor.value.set(d,p,a,f),this.resampleBias.value.set(o,r,n,i),e.__super__.resize.apply(this,arguments)},e.prototype.change=function(t,e,n){return e.operator||e.lerp||e.sampler?this.rebuild():void 0},e}(i),e.exports=r},{"../../../util":175,"./operator":78}],77:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("./operator"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","active","operator","source","index","texture","memo"],e.prototype.sourceShader=function(t){return this.memo.shaderAbsolute(t,1)},e.prototype.make=function(){var t,n,r,i,o,s,a,u,h,l;return e.__super__.make.apply(this,arguments),null!=this.bind.source?(this._helpers.active.make(),this._listen("root","root.update",function(t){return function(){return t.isActive?t.update():void 0}}(this)),u=this.props,s=u.minFilter,o=u.magFilter,h=u.type,n=this.bind.source.getDimensions(),i=n.items,l=n.width,r=n.height,t=n.depth,this.memo=this._renderables.make("memo",{items:i,width:l,height:r,depth:t,minFilter:s,magFilter:o,type:h}),a=this._shaders.shader(),this.bind.source.sourceShader(a),this.compose=this._renderables.make("memoScreen",{map:a,items:i,width:l, +height:r,depth:t}),this.memo.adopt(this.compose),this.objects=[this.compose],this.renders=this.compose.renders):void 0},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),null!=this.bind.source?(this._helpers.active.unmake(),this.memo.unadopt(this.compose),this.memo.dispose(),this.memo=this.compose=null):void 0},e.prototype.update=function(){var t;return null!=(t=this.memo)?t.render():void 0},e.prototype.resize=function(){var t,n,r,i;if(null!=this.bind.source)return n=this.bind.source.getActiveDimensions(),i=n.width,r=n.height,t=n.depth,this.compose.cover(i,r,t),e.__super__.resize.apply(this,arguments)},e.prototype.change=function(t,e,n){return e.texture||e.operator?this.rebuild():void 0},e}(i),e.exports=r},{"../../../util":175,"./operator":78}],78:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("../base/source"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","bind","operator","source","index"],e.prototype.indexShader=function(t){var e;return null!=(e=this.bind.source)&&"function"==typeof e.indexShader?e.indexShader(t):void 0},e.prototype.sourceShader=function(t){var e;return null!=(e=this.bind.source)&&"function"==typeof e.sourceShader?e.sourceShader(t):void 0},e.prototype.getDimensions=function(){return this.bind.source.getDimensions()},e.prototype.getFutureDimensions=function(){return this.bind.source.getFutureDimensions()},e.prototype.getActiveDimensions=function(){return this.bind.source.getActiveDimensions()},e.prototype.getIndexDimensions=function(){return this.bind.source.getIndexDimensions()},e.prototype.init=function(){return this.sourceSpec=[{to:"operator.source",trait:"source"}]},e.prototype.make=function(){return e.__super__.make.apply(this,arguments),this._helpers.bind.make(this.sourceSpec)},e.prototype.made=function(){return this.resize(),e.__super__.made.apply(this,arguments)},e.prototype.unmake=function(){return this._helpers.bind.unmake()},e.prototype.resize=function(t){return this.trigger({type:"source.resize"})},e}(i),e.exports=r},{"../base/source":49}],79:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("../../primitive"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","operator","readback","entity","active"],e.finals={channels:4},e.prototype.init=function(){return this.emitter=this.root=null,this.active={}},e.prototype.make=function(){var t,n,r,i,o,s,a,u,h,l;return e.__super__.make.apply(this,arguments),this._compute("readback.data",function(t){return function(){var e;return null!=(e=t.readback)?e.data:void 0}}(this)),this._compute("readback.items",function(t){return function(){var e;return null!=(e=t.readback)?e.items:void 0}}(this)),this._compute("readback.width",function(t){return function(){var e;return null!=(e=t.readback)?e.width:void 0}}(this)),this._compute("readback.height",function(t){return function(){var e;return null!=(e=t.readback)?e.height:void 0}}(this)),this._compute("readback.depth",function(t){return function(){var e;return null!=(e=t.readback)?e.depth:void 0}}(this)),this._helpers.bind.make([{to:"operator.source",trait:"source"}]),null!=this.bind.source?(s=this.props,h=s.type,t=s.channels,r=s.expr,this.root=this._inherit("root"),this._listen("root","root.update",this.update),a=this.bind.source.getDimensions(),o=a.items,l=a.width,i=a.height,n=a.depth,u=this.bind.source.sourceShader(this._shaders.shader()),this.readback=this._renderables.make("readback",{map:u,items:o,width:l,height:i,depth:n,channels:t,type:h}),null!=r&&this.readback.setCallback(r),this._helpers.active.make()):void 0},e.prototype.unmake=function(){return null!=this.readback&&(this.readback.dispose(),this.readback=null,this.root=null,this.emitter=null,this.active={}),this._helpers.active.unmake(),this._helpers.bind.unmake()},e.prototype.update=function(){var t;if(null!=this.readback)return this.isActive&&(this.readback.update(null!=(t=this.root)?t.getCamera():void 0),this.readback.post(),null!=this.props.expr)?this.readback.iterate():void 0},e.prototype.resize=function(){var t,e,n,r,i,o,s,a;if(null!=this.readback)return r=this.bind.source.getActiveDimensions(),n=r.items,a=r.width,e=r.height,t=r.depth,this.readback.setActive(n,a,e,t),this.strideI=i=n,this.strideJ=o=i*a,this.strideK=s=o*e},e.prototype.change=function(t,e,n){return t["readback.type"]?this.rebuild():t["readback.expr"]&&this.readback?this.readback.setCallback(this.props.expr):void 0},e}(r),e.exports=i},{"../../../util":175,"../../primitive":44}],80:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("./operator"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","bind","operator","source","index","repeat"],e.prototype.indexShader=function(t){return t.pipe(this.operator),e.__super__.indexShader.call(this,t)},e.prototype.sourceShader=function(t){return t.pipe(this.operator),e.__super__.sourceShader.call(this,t)},e.prototype.getDimensions=function(){return this._resample(this.bind.source.getDimensions())},e.prototype.getActiveDimensions=function(){return this._resample(this.bind.source.getActiveDimensions())},e.prototype.getFutureDimensions=function(){return this._resample(this.bind.source.getFutureDimensions())},e.prototype.getIndexDimensions=function(){return this._resample(this.bind.source.getIndexDimensions())},e.prototype._resample=function(t){var e;return e=this.resample,{items:e.items*t.items,width:e.width*t.width,height:e.height*t.height,depth:e.depth*t.depth}},e.prototype.make=function(){var t,n;return e.__super__.make.apply(this,arguments),null!=this.bind.source?(this.resample={},n={repeatModulus:this._attributes.make(this._types.vec4())},this.repeatModulus=n.repeatModulus,t=this._shaders.shader(),t.pipe("repeat.position",n),this.operator=t):void 0},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments)},e.prototype.resize=function(){var t;return null!=this.bind.source&&(t=this.bind.source.getActiveDimensions(),this.repeatModulus.value.set(t.width,t.height,t.depth,t.items)),e.__super__.resize.apply(this,arguments)},e.prototype.change=function(t,e,n){var r,i,o,s,a;if(e.operator||e.repeat)return this.rebuild();if(n){for(s=["items","width","height","depth"],a=[],r=0,o=s.length;o>r;r++)i=s[r],a.push(this.resample[i]=this.props[i]);return a}},e}(r),e.exports=i},{"./operator":78}],81:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./operator"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","operator","source","index","resample","sampler:x","sampler:y","sampler:z","sampler:w","include"],e.prototype.indexShader=function(t){return t.pipe(this.indexer),e.__super__.indexShader.call(this,t)},e.prototype.sourceShader=function(t){return t.pipe(this.operator)},e.prototype.getDimensions=function(){return this._resample(this.bind.source.getDimensions())},e.prototype.getActiveDimensions=function(){return this._resample(this.bind.source.getActiveDimensions())},e.prototype.getFutureDimensions=function(){return this._resample(this.bind.source.getFutureDimensions())},e.prototype.getIndexDimensions=function(){return this._resample(this.bind.source.getIndexDimensions())},e.prototype._resample=function(t){var e,n,r;return r=this.resampled,e=this.centered,n=this.padding,this.relativeSize?(e.items||t.items--,e.width||t.width--,e.height||t.height--,e.depth||t.depth--,null!=r.items&&(t.items*=r.items),null!=r.width&&(t.width*=r.width),null!=r.height&&(t.height*=r.height),null!=r.depth&&(t.depth*=r.depth),e.items||t.items++,e.width||t.width++,e.height||t.height++,e.depth||t.depth++,t.items-=2*n.items,t.width-=2*n.width,t.height-=2*n.height,t.depth-=2*n.depth):(null!=r.items&&(t.items=r.items),null!=r.width&&(t.width=r.width),null!=r.height&&(t.height=r.height),null!=r.depth&&(t.depth=r.depth)),t.items=Math.max(0,Math.floor(t.items)),t.width=Math.max(0,Math.floor(t.width)),t.height=Math.max(0,Math.floor(t.height)),t.depth=Math.max(0,Math.floor(t.depth)),t},e.prototype.make=function(){var t,n,r,i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M;if(e.__super__.make.apply(this,arguments),null!=this.bind.source){for(this._helpers.bind.make([{to:"include.shader",trait:"shader",optional:!0}]),m=this.props,h=m.indices,r=m.channels,T=this.bind.shader,v=this.props,b=v.sample,x=v.size,l=v.items,M=v.width,s=v.height,i=v.depth,E=b===this.node.attributes["resample.sample"]["enum"].relative,y=x===this.node.attributes["resample.size"]["enum"].relative,this.resampled={},null!=l&&(this.resampled.items=l),null!=M&&(this.resampled.width=M),null!=s&&(this.resampled.height=s),null!=i&&(this.resampled.depth=i),this.centered={},this.centered.items=this.props.centeredW,this.centered.width=this.props.centeredX,this.centered.height=this.props.centeredY,this.centered.depth=this.props.centeredZ,this.padding={},this.padding.items=this.props.paddingW,this.padding.width=this.props.paddingX,this.padding.height=this.props.paddingY,this.padding.depth=this.props.paddingZ,d=this._shaders.shader(),u=this._shaders.shader(),w=[null,this._types.number,this._types.vec2,this._types.vec3,this._types.vec4][h],R={dataSize:this._attributes.make(w(0,0,0,0)),dataResolution:this._attributes.make(w(0,0,0,0)),targetSize:this._attributes.make(w(0,0,0,0)),targetResolution:this._attributes.make(w(0,0,0,0)),resampleFactor:this._attributes.make(this._types.vec4(0,0,0,0)),resampleBias:this._attributes.make(this._types.vec4(0,0,0,0))},this.dataResolution=R.dataResolution,this.dataSize=R.dataSize,this.targetResolution=R.targetResolution,this.targetSize=R.targetSize,this.resampleFactor=R.resampleFactor,this.resampleBias=R.resampleBias,_=null!=l||null!=M||null!=s||null!=i,d.pipe("resample.padding",R),H=[],t=!1,g=["width","height","depth","items"],a=c=0,f=g.length;f>c;a=++c)p=g[a],n=this.centered[p],t||(t=n),H[a]=n?"0.5":"0.0";return t&&(H="vec4("+H+")",d.pipe(o.GLSL.binaryOperator(4,"+",vec4)),_&&u.pipe(o.GLSL.binaryOperator(4,"+",vec4))),E&&(_?(d.pipe("resample.relative",R),u.pipe("resample.relative",R)):u.pipe(o.GLSL.identity("vec4"))),null!=T?(4!==h&&d.pipe(o.GLSL.truncateVec(4,h)),d.callback(),4!==h&&d.pipe(o.GLSL.extendVec(h,4)),t&&d.pipe(o.GLSL.binaryOperator(4,"-",H)),d.pipe(this.bind.source.sourceShader(this._shaders.shader())),4!==r&&d.pipe(o.GLSL.truncateVec(4,r)),d.join(),null!=this.bind.shader&&d.pipe(this.bind.shader.shaderBind(R)),4!==r&&d.pipe(o.GLSL.extendVec(r,4))):(t&&d.pipe(o.GLSL.binaryOperator(4,"-",H)),d.pipe(this.bind.source.sourceShader(this._shaders.shader()))),t&&_&&u.pipe(o.GLSL.binaryOperator(4,"-",H)),this.operator=d,this.indexer=u,this.indices=h,this.relativeSample=E,this.relativeSize=y}},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),this.operator=null},e.prototype.resize=function(){var t,n,r,i,o,s,a,u,h,l,c,p,f,d,m;if(null!=this.bind.source)return s=this.bind.source.getActiveDimensions(),m=this.getActiveDimensions(),t=function(t){return function(e){var n,r,i;return n=t.centered[e],r=t.padding[e],m[e]+=2*r,i=n?s[e]/Math.max(1,m[e]):Math.max(1,s[e]-1)/Math.max(1,m[e]-1),[i,r]}}(this),u=t("width"),d=u[0],o=u[1],h=t("height"),p=h[0],r=h[1],l=t("depth"),a=l[0],n=l[1],c=t("items"),f=c[0],i=c[1],1===this.indices?(this.dataResolution.value=1/s.width,this.targetResolution.value=1/m.width,this.dataSize.value=s.width,this.targetSize.value=m.width):(this.dataResolution.value.set(1/s.width,1/s.height,1/s.depth,1/s.items),this.targetResolution.value.set(1/m.width,1/m.height,1/m.depth,1/m.items),this.dataSize.value.set(s.width,s.height,s.depth,s.items),this.targetSize.value.set(m.width,m.height,m.depth,m.items)),this.resampleFactor.value.set(d,p,a,f),this.resampleBias.value.set(o,r,n,i),e.__super__.resize.apply(this,arguments)},e.prototype.change=function(t,e,n){return e.operator||e.resample||e.sampler||e.include?this.rebuild():void 0},e}(r),e.exports=i},{"../../../util":175,"./operator":78}],82:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./operator"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","operator","source","index","slice"],e.prototype.getDimensions=function(){return this._resample(this.bind.source.getDimensions())},e.prototype.getActiveDimensions=function(){return this._resample(this.bind.source.getActiveDimensions())},e.prototype.getFutureDimensions=function(){return this._resample(this.bind.source.getFutureDimensions())},e.prototype.getIndexDimensions=function(){return this._resample(this.bind.source.getIndexDimensions())},e.prototype.sourceShader=function(t){return t.pipe("slice.position",this.uniforms),this.bind.source.sourceShader(t)},e.prototype._resolve=function(t,e){var n,r,i,o,s;return o=this.props[t],n=e[t],null==o?[0,n]:(i=function(t,e){return 0>t?e+t:t},s=i(Math.round(o.x),n),r=i(Math.round(o.y),n),r=Math.max(s,r),[s,r-s])},e.prototype._resample=function(t){return t.width=this._resolve("width",t)[1],t.height=this._resolve("height",t)[1],t.depth=this._resolve("depth",t)[1],t.items=this._resolve("items",t)[1],t},e.prototype.make=function(){return e.__super__.make.apply(this,arguments),null!=this.bind.source?this.uniforms={sliceOffset:this._attributes.make(this._types.vec4())}:void 0},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments)},e.prototype.resize=function(){var t;if(null!=this.bind.source)return t=this.bind.source.getActiveDimensions(),this.uniforms.sliceOffset.value.set(this._resolve("width",t)[0],this._resolve("height",t)[0],this._resolve("depth",t)[0],this._resolve("items",t)[0]),e.__super__.resize.apply(this,arguments)},e.prototype.change=function(t,e,n){return e.operator?this.rebuild():e.slice?this.resize():void 0},e}(r),e.exports=i},{"../../../util":175,"./operator":78}],83:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./operator"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","operator","source","index","split"],e.prototype.indexShader=function(t){return t.pipe(this.operator),e.__super__.indexShader.call(this,t)},e.prototype.sourceShader=function(t){return t.pipe(this.operator),e.__super__.sourceShader.call(this,t)},e.prototype.getDimensions=function(){return this._resample(this.bind.source.getDimensions())},e.prototype.getActiveDimensions=function(){return this._resample(this.bind.source.getActiveDimensions())},e.prototype.getFutureDimensions=function(){return this._resample(this.bind.source.getFutureDimensions())},e.prototype.getIndexDimensions=function(){return this._resample(this.bind.source.getIndexDimensions())},e.prototype._resample=function(t){var e,n,r,i,o,s,a,u,h,l,c,p,f,d,m;for(l=this.order,e=this.axis,p=this.overlap,u=this.length,m=this.stride,s=["width","height","depth","items"],h=l.map(function(t){return s[t-1]}),i=l.indexOf(e),d=function(){var e,r,i;for(i=[],e=0,r=h.length;r>e;e++)n=h[e],i.push(t[n]);return i}(),f=Math.floor((d[i]-p)/m),d.splice(i,1,u,f),d=d.slice(0,4),c={},r=o=0,a=h.length;a>o;r=++o)n=h[r],c[n]=d[r];return c},e.prototype.make=function(){var t,n,r,i,s,a,u,h,l,c,p,f;return e.__super__.make.apply(this,arguments),null!=this.bind.source?(i=this.props.order,t=this.props.axis,s=this.props.overlap,r=this.props.length,a=i.join(""),null==t&&(t=i[0]),n=a.indexOf(t),l=a[n]+(null!=(u=a[n+1])?u:0),h=a.replace(l[1],"").replace(l[0],"0")+"0",s=Math.min(r-1,s),c=r-s,f={splitStride:this._attributes.make(this._types.number(c))},p=this._shaders.shader(),p.require(o.GLSL.swizzleVec4(l,2)),p.require(o.GLSL.swizzleVec4(h,4)),p.require(o.GLSL.injectVec4(n)),p.pipe("split.position",f),p.pipe(o.GLSL.invertSwizzleVec4(i)),this.operator=p,this.order=i,this.axis=t,this.overlap=s,this.length=r,this.stride=c):void 0},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments)},e.prototype.change=function(t,e,n){return t["split.axis"]||t["split.order"]||e.operator?this.rebuild():void 0},e}(r),e.exports=i},{"../../../util":175,"./operator":78}],84:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("./operator"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","bind","operator","source","index","spread"],e.prototype.sourceShader=function(t){return t.pipe(this.operator)},e.prototype.make=function(){var t,n;return e.__super__.make.apply(this,arguments),null!=this.bind.source?(n={spreadMatrix:this._attributes.make(this._types.mat4()),spreadOffset:this._attributes.make(this._types.vec4())},this.spreadMatrix=n.spreadMatrix,this.spreadOffset=n.spreadOffset,t=this._shaders.shader(),t.require(this.bind.source.sourceShader(this._shaders.shader())),t.pipe("spread.position",n),this.operator=t):void 0},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments)},e.prototype.resize=function(){return this.update(),e.__super__.resize.apply(this,arguments)},e.prototype.update=function(){var t,e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y;for(r=this.bind.source.getFutureDimensions(),c=this.spreadMatrix.value,i=c.elements,f=["width","height","depth","items"],t=["alignWidth","alignHeight","alignDepth","alignItems"],g=this.props.unit,E=this.node.attributes["spread.unit"]["enum"],l=function(){switch(g){case E.relative:return function(t,e,n,o){return i[4*e+n]=o/Math.max(1,r[t]-1)};case E.absolute:return function(t,e,n,r){return i[4*e+n]=r}}}(),m=[],o=s=0,h=f.length;h>s;o=++s)u=f[o],v=this.props[u],e=this.props[t[o]],null!=v?(n=null!=(d=r[u])?d:1,p=-(n-1)*(.5-.5*e)):p=0,this.spreadOffset.value.setComponent(o,p),m.push(function(){var t,e,n;for(n=[],a=t=0;3>=t;a=++t)y=null!=(e=null!=v?v.getComponent(a):void 0)?e:0,n.push(i[4*o+a]=l(u,o,a,y));return n}());return m},e.prototype.change=function(t,e,n){return e.operator?this.rebuild():e.spread?this.update():void 0},e}(r),e.exports=i},{"./operator":78}],85:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./operator"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","operator","source","index","subdivide"],e.prototype.indexShader=function(t){return t.pipe(this.indexer),e.__super__.indexShader.call(this,t)},e.prototype.sourceShader=function(t){return t.pipe(this.operator)},e.prototype.getDimensions=function(){return this._resample(this.bind.source.getDimensions())},e.prototype.getActiveDimensions=function(){return this._resample(this.bind.source.getActiveDimensions())},e.prototype.getFutureDimensions=function(){return this._resample(this.bind.source.getFutureDimensions())},e.prototype.getIndexDimensions=function(){return this._resample(this.bind.source.getIndexDimensions())},e.prototype._resample=function(t){var e;return e=this.resampled,t.items--,t.width--,t.height--,t.depth--,null!=e.items&&(t.items*=e.items),null!=e.width&&(t.width*=e.width),null!=e.height&&(t.height*=e.height),null!=e.depth&&(t.depth*=e.depth),t.items++,t.width++,t.height++,t.depth++,t},e.prototype.make=function(){var t,n,r,i,s,a,u,h,l,c,p,f,d,m,v,g,E,y;if(e.__super__.make.apply(this,arguments),null!=this.bind.source){for(f=this.props,g=f.size,a=f.items,y=f.width,n=f.height,t=f.depth,c=f.lerp,this.resampled={},null!=a&&(this.resampled.items=a),null!=y&&(this.resampled.width=y),null!=n&&(this.resampled.height=n),null!=t&&(this.resampled.depth=t),p=this._shaders.shader(),s=this._shaders.shader(),E={resampleFactor:this._attributes.make(this._types.vec4(0,0,0,0)),subdivideBevel:this.node.attributes["subdivide.bevel"]},this.resampleFactor=E.resampleFactor,this.resampleBias=E.resampleBias,m=null!=a||null!=y||null!=n||null!=t,m?(p.pipe("resample.relative",E),s.pipe("resample.relative",E)):(p.pipe(o.GLSL.identity("vec4")),s.pipe(o.GLSL.identity("vec4"))),v=this.bind.source.sourceShader(this._shaders.shader()),c=c?".lerp":"",d=["width","height","depth","items"],r=u=0,l=d.length;l>u;r=++u)h=d[r],i="subdivide."+h+c,null!=this.props[h]&&(v=this._shaders.shader().require(v),v.pipe(i,E));return p.pipe(v),this.operator=p,this.indexer=s}},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),this.operator=null},e.prototype.resize=function(){var t,n,r,i,o,s,a;if(null!=this.bind.source)return n=this.bind.source.getActiveDimensions(),a=this.getActiveDimensions(),t=function(t){return Math.max(1,n[t]-1)/Math.max(1,a[t]-1)},s=t("width"),i=t("height"),r=t("depth"),o=t("items"),this.resampleFactor.value.set(s,i,r,o),e.__super__.resize.apply(this,arguments)},e.prototype.change=function(t,e,n){return e.operator||e.subdivide?this.rebuild():void 0},e}(r),e.exports=i},{"../../../util":175,"./operator":78}],86:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./operator"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","operator","source","index","swizzle"],e.prototype.sourceShader=function(t){return t=e.__super__.sourceShader.call(this,t),this.swizzler&&t.pipe(this.swizzler),t},e.prototype.make=function(){var t;return e.__super__.make.apply(this,arguments),null!=this.bind.source?(t=this.props.order,"1234"!==t.join()?this.swizzler=o.GLSL.swizzleVec4(t,4):void 0):void 0},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),this.swizzler=null},e.prototype.change=function(t,e,n){return e.swizzle||e.operator?this.rebuild():void 0},e}(r),e.exports=i},{"../../../util":175,"./operator":78}],87:[function(t,e,n){var r,i,o,s,a=function(t,e){function n(){this.constructor=t}for(var r in e)u.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},u={}.hasOwnProperty;r=t("./operator"),o=t("../../../util"),s={1:"width",2:"height",3:"depth",4:"items"},i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return a(e,t),e.traits=["node","bind","operator","source","index","transpose"],e.prototype.indexShader=function(t){return this.swizzler&&t.pipe(this.swizzler),e.__super__.indexShader.call(this,t)},e.prototype.sourceShader=function(t){return this.swizzler&&t.pipe(this.swizzler),e.__super__.sourceShader.call(this,t)},e.prototype.getDimensions=function(){return this._remap(this.transpose,this.bind.source.getDimensions())},e.prototype.getActiveDimensions=function(){return this._remap(this.transpose,this.bind.source.getActiveDimensions())},e.prototype.getFutureDimensions=function(){return this._remap(this.transpose,this.bind.source.getFutureDimensions())},e.prototype.getIndexDimensions=function(){return this._remap(this.transpose,this.bind.source.getIndexDimensions())},e.prototype._remap=function(t,e){var n,r,i,o,a,u;for(o={},r=i=0;3>=i;r=++i)n=s[r+1],u=s[t[r]],o[n]=null!=(a=e[u])?a:1;return o},e.prototype.make=function(){var t;return e.__super__.make.apply(this,arguments),null!=this.bind.source?(t=this.props.order,"1234"!==t.join()&&(this.swizzler=o.GLSL.invertSwizzleVec4(t)),this.transpose=t,this.trigger({type:"source.rebuild"})):void 0},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),this.swizzler=null},e.prototype.change=function(t,e,n){return e.transpose||e.operator?this.rebuild():void 0},e}(r),e.exports=i},{"../../../util":175,"./operator":78}],88:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../../primitive"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","object","visible","overlay","dom","attach","position"],e.prototype.init=function(){return this.emitter=this.root=null,this.active={}},e.prototype.make=function(){var t,n,r,i,o,s,a,u,h;return e.__super__.make.apply(this,arguments),this._helpers.bind.make([{to:"dom.html",trait:"html"},{to:"dom.points",trait:"source"}]),null!=this.bind.points&&null!=this.bind.html?(this.root=this._inherit("root"),this._listen("root","root.update",this.update),this._listen("root","root.post",this.post),s=this.bind.points.getDimensions(),r=this.bind.html.getDimensions(),o=Math.min(s.items,r.items),h=Math.min(s.width,r.width),n=Math.min(s.height,r.height),t=Math.min(s.depth,r.depth),a=this.bind.points.sourceShader(this._shaders.shader()),a=this._helpers.position.pipeline(a),u=this._shaders.shader({globals:["projectionMatrix"]}),u.pipe("project.readback"),a.pipe(u),i=this._shaders.shader(),this.readback=this._renderables.make("readback",{map:a,indexer:i,items:o,width:h,height:n,depth:t,channels:4,stpq:!0}),this.dom=this._overlays.make("dom"),this.dom.hint(o*h*n*t*2),this.readback.setCallback(this.emitter=this.callback(this.bind.html.nodes())),this._helpers.visible.make()):void 0},e.prototype.unmake=function(){return null!=this.readback&&(this.readback.dispose(),this.dom.dispose(),this.readback=this.dom=null,this.root=null,this.emitter=null,this.active={}),this._helpers.bind.unmake(),this._helpers.visible.unmake()},e.prototype.update=function(){var t;if(null!=this.readback)return this.props.visible?(this.readback.update(null!=(t=this.root)?t.getCamera():void 0),this.readback.post(),this.readback.iterate()):void 0},e.prototype.post=function(){return null!=this.readback?this.dom.render(this.isVisible?this.emitter.nodes():[]):void 0},e.prototype.callback=function(t){var e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x;return _=this._inherit("unit").getUnitUniforms(),b=_.viewWidth,u=_.viewHeight,e=this.node.attributes["dom.attributes"],d=this.node.attributes["dom.size"],x=this.node.attributes["dom.zoom"],r=this.node.attributes["dom.color"],p=this.node.attributes["dom.outline"],f=this.node.attributes["dom.pointerEvents"],c=this.node.attributes["overlay.opacity"],T=this.node.attributes["overlay.zIndex"],l=this.node.attributes["attach.offset"],o=this.node.attributes["attach.depth"],m=this.node.attributes["attach.snap"],s=this.dom.el,h=[],y=null,n=null,v=g=E=0,i="",a=function(r,i,a,p,f,d,_,T){var w,R,H,M,S,k,A,C,P,L,z,O,D,F,U,B;k=T+v*f+g*d+E*_,H=t[k],M=0>p,A=1/p,S=1+(A-1)*o.value,D=M?0:S,C=+l.value.x*D,P=+l.value.y*D,U=(r+1)*b.value*.5+C,B=(i-1)*u.value*.5+P,U/=x.value,B/=x.value,m.value&&(U=Math.round(U),B=Math.round(B)),R=Math.min(.999,M?0:c.value),L={className:n,style:{transform:"translate3d("+U+"px, "+-B+"px, "+(1-p)+"px) translate(-50%, -50%) scale("+D+","+D+")",opacity:R}};for(_ in y)F=y[_],L.style[_]=F;if(w=e.value,null!=w){O=w.style;for(_ in w)F=w[_],"style"!==_&&"className"!==_&&(L[_]=F);if(null!=O)for(_ in O)F=O[_],L.style[_]=F}return L.className+=" "+(null!=(z=null!=w?w.className:void 0)?z:"mathbox-label"),h.push(s("div",L,H))},a.reset=function(t){return function(){var e,o,s;return h=[],s=[t.strideI,t.strideJ,t.strideK],v=s[0],g=s[1],E=s[2],e=r.value,o=function(t){return Math.floor(255*t)},i=e?"rgb("+[o(e.x),o(e.y),o(e.z)]+")":"",n="mathbox-outline-"+Math.round(p.value),y={},e&&(y.color=i),y.fontSize=d.value+"px",1!==x.value&&(y.zoom=x.value),T.value>0&&(y.zIndex=T.value),f.value?y.pointerEvents="auto":void 0}}(this),a.nodes=function(){return h},a},e.prototype.resize=function(){var t,e,n,r,i,o,s,a,u;if(null!=this.readback)return i=this.bind.points.getActiveDimensions(),n=this.bind.html.getActiveDimensions(),r=Math.min(i.items,n.items),u=Math.min(i.width,n.width),e=Math.min(i.height,n.height),t=Math.min(i.depth,n.depth),this.readback.setActive(r,u,e,t),this.strideI=o=n.items,this.strideJ=s=o*n.width,this.strideK=a=s*n.height},e.prototype.change=function(t,e,n){return t["dom.html"]||t["dom.points"]?this.rebuild():void 0},e}(i),e.exports=r},{"../../../util":175,"../../primitive":44}],89:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;o=t("../data/voxel"),i=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","buffer","active","data","voxel","html"],e.finals={channels:1},e.prototype.init=function(){return e.__super__.init.apply(this,arguments),this.storage="pushBuffer"},e.prototype.make=function(){var t,n,r,i,o;return e.__super__.make.apply(this,arguments),i=this.getDimensions(),r=i.items,o=i.width,n=i.height,t=i.depth,this.dom=this._overlays.make("dom"),this.dom.hint(r*o*n*t)},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),null!=this.dom?(this.dom.dispose(),this.dom=null):void 0},e.prototype.update=function(){return e.__super__.update.apply(this,arguments)},e.prototype.change=function(t,n,r){return n.html?this.rebuild():e.__super__.change.call(this,t,n,r)},e.prototype.nodes=function(){return this.buffer.read()},e.prototype.callback=function(t){var e;return e=this.dom.el,t.length<=6?function(n,r,i,o,s){return t(n,e,r,i,o,s)}:function(n){return function(r,i,o,s,a){return t(r,e,i,o,s,a,n.bufferClock,n.bufferStep)}}(this)},e}(o),e.exports=r},{"../../../util":175,"../data/voxel":61}],90:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("./transition"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","transition","vertex","move","visible","active"],e.prototype.make=function(){var t,n,r;e.__super__.make.apply(this,arguments),n={moveFrom:this.node.attributes["move.from"],moveTo:this.node.attributes["move.to"]};for(t in n)r=n[t],this.uniforms[t]=r},e.prototype.vertex=function(t,e){var n,r;return e===this.props.pass&&t.pipe("move.position",this.uniforms),null!=(n=null!=(r=this._inherit("vertex"))?r.vertex(t,e):void 0)?n:t},e}(i),e.exports=r},{"./transition":97}],91:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("./track"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","track","trigger","play","bind"],e.prototype.init=function(){return e.__super__.init.apply(this,arguments),this.skew=null,this.start=null},e.prototype.reset=function(t){return null==t&&(t=!0),this.skew=t?0:null,this.start=null},e.prototype.make=function(){var t;return e.__super__.make.apply(this,arguments), +this._listen("slide","slide.step",function(t){return function(e){var n;return n=t.props.trigger,null!=n&&e.index===n?t.reset():null!=n&&0===e.index?t.reset(!1):void 0}}(this)),this.props.trigger&&null!=this._inherit("slide")||this.reset(),t=this._inherit("clock"),this._listen(t,"clock.tick",function(e){return function(){var n,r,i,o,s,a,u,h,l,c,p,f;return l=e.props,i=l.from,f=l.to,c=l.speed,a=l.pace,n=l.delay,h=l.realtime,p=t.getTime(),null!=e.skew?(o=h?p.time:p.clock,r=h?p.delta:p.step,u=c/a,null==e.start&&(e.start=o),e.skew+=r*(u-1),s=Math.max(0,o-e.start+e.skew-n*u),e.props.loop&&(s%=f-i),e.playhead=Math.min(f,i+s)):e.playhead=0,e.update()}}(this))},e.prototype.update=function(){return e.__super__.update.apply(this,arguments)},e.prototype.change=function(t,n,r){return t["trigger.trigger"]||t["play.realtime"]?this.rebuild():e.__super__.change.call(this,t,n,r)},e}(i),e.exports=r},{"./track":96}],92:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("../base/parent"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","present"],e.prototype.init=function(){},e.prototype.make=function(){return this.nodes=[],this.steps=[],this.length=0,this.last=[],this.index=0,this.dirty=[],this._listen("root","root.update",this.update),this._compute("present.length",function(t){return function(){return t.length}}(this))},e.prototype.adopt=function(t){var e;return e=t.node,this.nodes.indexOf(t)<0&&this.nodes.push(e),this.dirty.push(t)},e.prototype.unadopt=function(t){var e;return e=t.node,this.nodes=this.nodes.filter(function(e){return e!==t}),this.dirty.push(t)},e.prototype.update=function(){var t,e,n,r,i;if(this.dirty.length){for(r=this.dirty,e=0,n=r.length;n>e;e++)t=r[e],this.slideReset(t);return i=this.process(this.nodes),this.steps=i[0],this.indices=i[1],this.length=this.steps.length,this.index=null,this.go(this.props.index),this.dirty=[]}},e.prototype.slideLatch=function(t,e,n){return t.slideLatch(e,n)},e.prototype.slideStep=function(t,e,n){return t.slideStep(this.mapIndex(t,e),n)},e.prototype.slideRelease=function(t,e){return t.slideRelease()},e.prototype.slideReset=function(t){return t.slideReset()},e.prototype.mapIndex=function(t,e){return e-this.indices[t.node._id]},e.prototype.process=function(t){var e,n,r,i,o,s,a,u,h,l,c,p;return h=function(t){var e,n,r,i;for(i=[],n=0,r=t.length;r>n;n++)e=t[n],i.push(a(e).filter(o));return i},p=function(t){return function(e){var n,r,i;for(i=[];e&&(r=[t(e),e],e=r[0],n=r[1],r);)i.push(n);return i}},a=p(function(t){return t.parent.traits.hash.present?null:t.parent}),o=function(e){return t.indexOf(e)>=0},i=function(t,e){var n,r,i,o,s,a;if(n=t.length,r=e.length,i=n-r,0!==i)return!1;for(i=Math.min(n,r),o=s=a=i-1;0>=a?0>s:s>0;o=0>=a?++s:--s)if(t[o]!==e[o])return!1;return!0},s=function(t){return t.sort(function(t,e){var n,r,i,o,s,a,u,h,l,c;for(n=t.length,r=e.length,i=Math.min(n,r),a=u=1,c=i;c>=1?c>=u:u>=c;a=c>=1?++u:--u){if(h=t[n-a],l=e[r-a],o=h.props.order,s=l.props.order,null!=o||null!=s){if(null!=o&&null!=s&&0!==(i=o-s))return i;if(null!=o)return-1;if(null!=s)return 1}if(l.order!==h.order)return l.order-h.order}return i=n-r,0!==i?i:0})},l=function(t){var e,n,r,i,o,s;for(o=[],e=[],n=0,r=t.length;r>n;n++)s=t[n],(null!=(i=s[0]).props.steps?o:e).push(s);return[o,e]},n=function(t){var n,i,o,s,a,u,h,l,c,p,f,d;for(c=t[0],n=t[1],l=100,o={},d=[],p=function(t,e){var n,r,i,s,a,u,h,c,p,f,m,v;for(p=(u=t[0]).props,h=t[1],c=null!=h?o[h._id]:0,n=e,r=null!=p.from?c+p.from:n-p.early,v=null!=p.to?c+p.to:n+p.steps+p.late,r=Math.max(0,r),v=Math.min(l,v),null==o[a=u._id]&&(o[a]=r),i=s=f=r,m=v;m>=f?m>s:s>m;i=m>=f?++s:--s)d[i]=(null!=d[i]?d[i]:d[i]=[]).concat(t);return p.steps},i=0,s=0,u=c.length;u>s;s++)f=c[s],i+=p(f,i);for(a=0,h=n.length;h>a;a++)f=n[a],p(f,0);return d=function(){var t,n,i;for(i=[],t=0,n=d.length;n>t;t++)f=d[t],i.push(r(e(f)));return i}(),[d,o]},e=function(t){var e,n,r,i,o;if(t){for(o=[],e=n=0,r=t.length;r>n;e=++n)i=t[e],t.indexOf(i)===e&&o.push(i);return o}return[]},r=function(t){return t.sort(function(t,e){return t.order-e.order})},u=h(t),c=s(u),n(l(c))},e.prototype.go=function(t){var e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k,A,C,P,L,z,O;for(t=Math.max(0,Math.min(this.length+1,+t||0)),h=this.last,e=null!=(H=this.steps[t-1])?H:[],z=this.props.directed?t-this.index:1,this.index=t,i=function(){var t,n,r;for(r=[],t=0,n=e.length;n>t;t++)b=e[t],this.last.indexOf(b)<0&&r.push(b);return r}.call(this),o=function(){var t,n,r,i;for(r=this.last,i=[],t=0,n=r.length;n>t;t++)b=r[t],e.indexOf(b)<0&&i.push(b);return i}.call(this),L=function(){var t,n,r;for(r=[],t=0,n=e.length;n>t;t++)b=e[t],i.indexOf(b)<0&&o.indexOf(b)<0&&r.push(b);return r}(),n=function(t){return t.sort(function(t,e){return t.order-e.order})},r=function(t){return t.sort(function(t,e){return e.order-t.order})},O=function(t){return t.toString()},M=n(i),s=0,l=M.length;l>s;s++)b=M[s],this.slideLatch(b.controller,!0,z);for(S=n(L),a=0,c=S.length;c>a;a++)b=S[a],this.slideLatch(b.controller,null,z);for(k=n(o),u=0,p=k.length;p>u;u++)b=k[u],this.slideLatch(b.controller,!1,z);for(y=0,f=i.length;f>y;y++)b=i[y],this.slideStep(b.controller,t,z);for(_=0,d=L.length;d>_;_++)b=L[_],this.slideStep(b.controller,t,z);for(T=0,m=o.length;m>T;T++)b=o[T],this.slideStep(b.controller,t,z);for(A=r(i),x=0,v=A.length;v>x;x++)b=A[x],this.slideRelease(b.controller);for(C=r(L),w=0,g=C.length;g>w;w++)b=C[w],this.slideRelease(b.controller);for(P=r(o),R=0,E=P.length;E>R;R++)b=P[R],this.slideRelease(b.controller);this.last=e},e.prototype.change=function(t,e,n){return t["present.index"]||n?this.go(this.props.index):void 0},e}(r),e.exports=i},{"../../../util":175,"../base/parent":47}],93:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("./transition"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","transition","mask","visible","active"],e.prototype.mask=function(t){var e,n,r;return t?(r=this._shaders.shader(),r.pipe(o.GLSL.identity("vec4")),r.fan(),r.pipe(t,this.uniforms),r.next(),r.pipe("reveal.mask",this.uniforms),r.end(),r.pipe("float combine(float a, float b) { return min(a, b); }")):(r=this._shaders.shader(),r.pipe("reveal.mask",this.uniforms)),null!=(e=null!=(n=this._inherit("mask"))?n.mask(r):void 0)?e:r},e}(i),e.exports=r},{"../../../util":175,"./transition":97}],94:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("../base/parent"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","slide","visible","active"],e.prototype.make=function(){if(this._helpers.visible.make(),this._helpers.active.make(),!this._inherit("present"))throw new Error(this.node.toString()+" must be placed inside ");return this._inherit("present").adopt(this)},e.prototype.unmake=function(){return this._helpers.visible.unmake(),this._helpers.active.unmake(),this._inherit("present")(unadopt(this))},e.prototype.change=function(t,e,n){return t["slide.early"]||t["slide.late"]||t["slide.steps"]||t["slide.from"]||t["slide.to"]?this.rebuild():void 0},e.prototype.slideLatch=function(t,e){return this.trigger({type:"transition.latch",step:e}),null!=t?this._instant(t):void 0},e.prototype.slideStep=function(t,e){return this.trigger({type:"slide.step",index:t,step:e})},e.prototype.slideRelease=function(){return this.trigger({type:"transition.release"})},e.prototype.slideReset=function(){return this._instant(!1),this.trigger({type:"slide.reset"})},e.prototype._instant=function(t){return this.setVisible(t),this.setActive(t)},e}(r),e.exports=i},{"../base/parent":47}],95:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("./track"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","track","step","trigger","bind"],e.prototype.make=function(){var t,n,r;return e.__super__.make.apply(this,arguments),t=this._inherit("clock"),null==this.actualIndex&&(this.actualIndex=null),this.animateIndex=this._animator.make(this._types.number(0),{clock:t,realtime:this.props.realtime,step:function(t){return function(e){return t.actualIndex=e}}(this)}),null==this.lastIndex&&(this.lastIndex=null),this.animateStep=this._animator.make(this._types.number(0),{clock:t,realtime:this.props.realtime,step:function(t){return function(e){return t.playhead=e,t.update()}}(this)}),this.stops=null!=(n=this.props.stops)?n:function(){r=[];for(var t=0,e=this.script.length;e>=0?e>t:t>e;e>=0?t++:t--)r.push(t);return r}.apply(this),this._listen("slide","slide.reset",function(t){return function(e){return t.lastIndex=null}}(this)),this._listen("slide","slide.step",function(t){return function(e){var n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x;if(f=t.props,n=f.delay,r=f.duration,c=f.pace,y=f.speed,p=f.playback,v=f.rewind,g=f.skip,x=f.trigger,a=Math.max(0,Math.min(t.stops.length-1,e.index-x)),s=t.playhead,T=t.stops[a],null==t.lastIndex&&x)return t.lastIndex=a,t.animateStep.set(T),void t.animateIndex.set(a);for(h=null!=(d=null!=(m=t.actualIndex)?m:t.lastIndex)?d:0,_=a-h,E=t.stops.slice(Math.min(h,a),Math.max(h,a)),o=0,h=E.shift(),u=0,l=E.length;l>u;u++)b=E[u],h===b&&o++,h=b;return t.lastIndex=a,i=y*(e.step>=0?1:v),i*=g?Math.max(1,Math.abs(_)-o):1,r+=Math.abs(T-s)*c/i,s!==T?(t.animateIndex.immediate(a,{delay:n,duration:r,ease:p}),t.animateStep.immediate(T,{delay:n,duration:r,ease:p})):void 0}}(this))},e.prototype.made=function(){return this.update()},e.prototype.unmake=function(){return this.animateIndex.dispose(),this.animateStep.dispose(),this.animateIndex=this.animateStep=null,e.__super__.unmake.apply(this,arguments)},e.prototype.change=function(t,n,r){return t["step.stops"]||t["step.realtime"]?this.rebuild():e.__super__.change.call(this,t,n,r)},e}(i),e.exports=r},{"./track":96}],96:[function(t,e,n){var r,i,o,s,a=function(t,e){function n(){this.constructor=t}for(var r in e)u.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},u={}.hasOwnProperty;i=t("../../primitive"),r=t("../../../util").Ease,s=function(t){var e,n,r;n={};for(e in t)r=t[e],r instanceof Array?n[e]=r.slice():null!=r&&"object"==typeof r?n[e]=s(r):n[e]=r;return n},o=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return a(e,t),e.traits=["node","track","seek","bind"],e.prototype.init=function(){return this.handlers={},this.script=null,this.values=null,this.playhead=0,this.velocity=null,this.section=null,this.expr=null},e.prototype.make=function(){var t,e,n;return this._helpers.bind.make([{to:"track.target",trait:"node",callback:null}]),n=this.props.script,t=this.bind.target.node,this.targetNode=t,e=this._process(t,n),this.script=e[0],this.values=e[1],this.start=e[2],this.end=e[3],e},e.prototype.unmake=function(){return this.unbindExpr(),this._helpers.bind.unmake(),this.script=this.values=this.start=this.end=this.section=this.expr=null,this.playhead=0},e.prototype.bindExpr=function(t){var e;return this.unbindExpr(),this.expr=t,this.targetNode.bind(t,!0),e=this.targetNode.clock,this._attributes.bind(this.measure=function(){var t;return t=null,function(n){return function(){var r;return r=e.getTime().step,null!=t&&(n.velocity=(n.playhead-t)/r),t=n.playhead}}(this)}())},e.prototype.unbindExpr=function(){return null!=this.expr&&this.targetNode.unbind(this.expr,!0),null!=this.measure&&this._attributes.unbind(this.measure),this.expr=this.measure=null},e.prototype._process=function(t,e){var n,r,i,o,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T;if(e instanceof Array){for(E={},r=i=0,l=e.length;l>i;r=++i)_=e[r],E[r]=_;e=E}E=[];for(a in e)_=e[a],null==_&&(_=[]),_ instanceof Array?_={key:+a,props:null!=_[0]?s(_[0]):{},expr:null!=_[1]?s(_[1]):{}}:(_=null!=_.key||_.props||_.expr?s(_):{props:s(_)},_.key=null!=_.key?+_.key:+a,null==_.props&&(_.props={}),null==_.expr&&(_.expr={})),E.push(_);if(e=E,!e.length)return[[],{},0,0];e.sort(function(t,e){return t.key-e.key}),y=e[0].key,n=e[e.length-1].key;for(a in e)_=e[a],"undefined"!=typeof h&&null!==h&&(h.next=_),h=_;h.next=h,e=E,f={},T={};for(a in e){_=e[a],d=_.props;for(o in d)b=d[o],f[o]=!0}for(a in e){_=e[a],m=_.expr;for(o in m)b=m[o],f[o]=!0}for(o in f)f[o]=t.get(o);try{for(o in f)T[o]=[t.attribute(o).T.make(),t.attribute(o).T.make(),t.attribute(o).T.make()]}catch(x){throw console.warn(this.node.toMarkup()),p=this.node.toString()+" - Target "+t+" has no `"+o+"` property",new Error(p)}for(g=[],u=0,c=e.length;c>u;u++){_=e[u];for(o in f)if(b=f[o],b=t.validate(o,null!=(v=_.props[o])?v:b),f[o]=_.props[o]=b,null!=_.expr[o]&&"function"!=typeof _.expr[o])throw console.warn(this.node.toMarkup()),p=this.node.toString()+" - Expression `"+_.expr[o]+"` on property `"+o+"` is not a function",new Error(p);g.push(_)}return[g,T,y,n]},e.prototype.update=function(){var t,e,n,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y;if(f=this.playhead,m=this.script,d=this.props,e=d.ease,g=d.seek,p=this.targetNode,null!=g&&(f=g),m.length){if(s=function(){var t,e,n,r,i;for(n=m[0],t=e=0,r=m.length;r>e&&(i=m[t],!(i.key>f));t=++e)n=i;return n},v=this.section,(!v||fv.next.key)&&(v=s(m,f)),v===this.section)return;this.section=v,a=v,y=v.next,E=a.key,i=y.key,n=function(){switch(e){case"linear":case 0:return r.clamp;case"cosine":case 1:return r.cosine;case"binary":case 2:return r.binary;case"hold":case 3:return r.hold;default:return r.cosine}}(),t=p.clock,h=function(e){return function(n){var r;return null==e.velocity?e.playhead:(r=t.getTime(),e.playhead+e.velocity*(n-r.time))}}(this),u=function(){var t;return t=1/Math.max(1e-4,i-E),function(e){return n((h(e)-E)*t,0,1)}}(),c=function(t){return function(e){var n,r,i,o,s,h,l,c;return i=a.expr[e],h=y.expr[e],o=a.props[e],l=y.props[e],s=function(){throw console.warn(p.toMarkup()),new Error(this.node.toString()+" - Invalid expression result on track `"+e+"`")},r=p.attribute(e),c=t.values[e],n=t._animator,i&&h?function(t,e,o){return function(e,o){var a,l;return t[0]=a=r.T.validate(i(e,o),t[0],s),t[1]=l=r.T.validate(h(e,o),t[1],s),t[2]=n.lerp(r.T,a,l,u(e),t[2])}}(c,a,y):i?function(t,e,o){return function(e,o){var a;return t[0]=a=r.T.validate(i(e,o),t[0],s),t[1]=n.lerp(r.T,a,l,u(e),t[1])}}(c,a,y):h?function(t,e,i){return function(e,i){var a;return t[0]=a=r.T.validate(h(e,i),t[0],s),t[1]=n.lerp(r.T,o,a,u(e),t[1])}}(c,a,y):function(t,e,i){return function(e,i){return t[0]=n.lerp(r.T,o,l,u(e),t[0])}}(c,a,y)}}(this),o={};for(l in a.expr)null==o[l]&&(o[l]=c(l));for(l in y.expr)null==o[l]&&(o[l]=c(l));for(l in a.props)null==o[l]&&(o[l]=c(l));for(l in y.props)null==o[l]&&(o[l]=c(l));return this.bindExpr(o)}},e.prototype.change=function(t,e,n){return t["track.target"]||t["track.script"]||t["track.mode"]?this.rebuild():t["seek.seek"]||n?this.update():void 0},e}(i),e.exports=o},{"../../../util":175,"../../primitive":44}],97:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("../base/parent"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","transition","transform","mask","visible","active"],e.prototype.init=function(){return this.animate=null,this.uniforms=null,this.state={isVisible:!0,isActive:!0,enter:1,exit:1},this.latched=null,this.locked=null},e.prototype.make=function(){var t,e,n;return this.uniforms={transitionFrom:this._attributes.make(this._types.vec4()),transitionTo:this._attributes.make(this._types.vec4()),transitionActive:this._attributes.make(this._types.bool()),transitionScale:this._attributes.make(this._types.vec4()),transitionBias:this._attributes.make(this._types.vec4()),transitionEnter:this._attributes.make(this._types.number()),transitionExit:this._attributes.make(this._types.number()),transitionSkew:this._attributes.make(this._types.number())},e=this._inherit("slide"),n=this._inherit("visible"),t=this._inherit("active"),this._listen(e,"transition.latch",function(t){return function(e){return t.latch(e.step)}}(this)),this._listen(e,"transition.release",function(t){return function(){return t.release()}}(this)),this._listen(n,"visible.change",function(t){return function(){return t.update(t.state.isVisible=n.isVisible)}}(this)),this._listen(t,"active.change",function(e){return function(){return e.update(e.state.isActive=t.isActive)}}(this)),this.animate=this._animator.make(this._types.vec2(1,1),{step:function(t){return function(e){return t.state.enter=e.x,t.state.exit=e.y,t.update()}}(this),complete:function(t){return function(e){return t.complete(e)}}(this)}),this.move=null!=this.props.from||null!=this.props.to},e.prototype.unmake=function(){return this.animate.dispose()},e.prototype.latch=function(t){var e,n,r,i,o,s;return this.locked=null,this.latched=i={isVisible:this.state.isVisible,isActive:this.state.isActive,step:t},s=this.isVisible,s?void 0:(r=i.step>=0,o=r?[0,1]:[1,0],e=o[0],n=o[1],this.animate.set(e,n))},e.prototype.release=function(){var t,e,n,r,i,o,s,a,u,h,l,c,p,f,d;return h=this.latched,f=this.state,this.latched=null,h.isVisible!==f.isVisible&&(u=h.step>=0,d=f.isVisible,l=d?[1,1]:u?[1,0]:[0,1],s=l[0],a=l[1],c=this.props,r=c.duration,i=c.durationEnter,o=c.durationExit,null==i&&(i=r),null==o&&(o=r),r=d*i+!d*o,p=this.props,t=p.delay,e=p.delayEnter,n=p.delayExit,null==e&&(e=t),null==n&&(n=t),t=d*e+!d*n,this.animate.immediate({x:s,y:a},{duration:r,delay:t,ease:"linear"}),this.locked={isVisible:!0,isActive:h.isActive||f.isActive}),this.update()},e.prototype.complete=function(t){return t?(this.locked=null,this.update()):void 0},e.prototype.update=function(){var t,e,n,r,i,o,s,a;if(null==this.latched)return o=this.props,e=o.enter,n=o.exit,null==e&&(e=this.state.enter),null==n&&(n=this.state.exit),r=e*n,a=r>0,i=1>r,this.uniforms.transitionEnter.value=e,this.uniforms.transitionExit.value=n,this.uniforms.transitionActive.value=i,a&&(a=!!this.state.isVisible),null!=this.locked&&(a=this.locked.isVisible),this.isVisible!==a&&(this.isVisible=a,this.trigger({type:"visible.change"})),t=!!(this.state.isActive||(null!=(s=this.locked)?s.isActive:void 0)),this.isActive!==t?(this.isActive=t,this.trigger({type:"active.change"})):void 0},e.prototype.change=function(t,e,n){var r,i,o,s,a,u,h,l,c;return(t["transition.enter"]||t["transition.exit"]||n)&&this.update(),t["transition.stagger"]||n?(a=this.props.stagger,i=a.x<0,o=a.y<0,s=a.z<0,r=a.w<0,h=Math.abs(a.x),l=Math.abs(a.y),c=Math.abs(a.z),u=Math.abs(a.w),this.uniforms.transitionSkew.value=h+l+c+u,this.uniforms.transitionScale.value.set((1-2*i)*h,(1-2*o)*l,(1-2*s)*c,(1-2*r)*u),this.uniforms.transitionBias.value.set(i*h,o*l,s*c,r*u)):void 0},e}(r),e.exports=i},{"../../../util":175,"../base/parent":47}],98:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../../primitive"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","object","visible","operator","style","compose"],e.defaults={zWrite:!1,zTest:!1,color:"#ffffff"},e.prototype.init=function(){return this.compose=null},e.prototype.resize=function(){var t,e,n,r,i;if(this.compose&&this.bind.source)return e=this.bind.source.getActiveDimensions(),i=e.width,n=e.height,t=e.depth,r=e.items,this.remapUVScale.set(i,n)},e.prototype.make=function(){var t,e,n,r;return this._helpers.bind.make([{to:"operator.source",trait:"source"}]),null!=this.bind.source?(r={remapUVScale:this._attributes.make(this._types.vec2())},this.remapUVScale=r.remapUVScale.value,n=this._shaders.shader(),t=this.props.alpha,this.bind.source.is("image")?(n.pipe("screen.pass.uv",r),n=this.bind.source.imageShader(n)):(n.pipe("screen.map.xy",r),n=this.bind.source.sourceShader(n)),t||n.pipe("color.opaque"),e=this._helpers.style.uniforms(),this.compose=this._renderables.make("screen",{map:n,uniforms:e,linear:!0}),this._helpers.visible.make(),this._helpers.object.make([this.compose])):void 0},e.prototype.made=function(){return this.resize()},e.prototype.unmake=function(){return this._helpers.bind.unmake(),this._helpers.visible.unmake(),this._helpers.object.unmake()},e.prototype.change=function(t,e,n){return t["operator.source"]||t["compose.alpha"]?this.rebuild():void 0},e}(i),e.exports=r},{"../../../util":175,"../../primitive":44}],99:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("../base/parent"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","root","scene","vertex","texture","rtt","source","index","image"],e.defaults={minFilter:"linear",magFilter:"linear",type:"unsignedByte"},e.prototype.init=function(){return this.rtt=this.scene=this.camera=this.width=this.height=this.history=this.rootSize=this.size=null},e.prototype.indexShader=function(t){return t},e.prototype.imageShader=function(t){return this.rtt.shaderRelative(t)},e.prototype.sourceShader=function(t){return this.rtt.shaderAbsolute(t,this.history)},e.prototype.getDimensions=function(){return{items:1,width:this.width,height:this.height,depth:this.history}},e.prototype.getActiveDimensions=function(){return this.getDimensions()},e.prototype.make=function(){var t,e,n,r,i,o,s,a,u,h,l,c,p,f,d;return this.parentRoot=this._inherit("root"),this.rootSize=this.parentRoot.getSize(),this._listen(this.parentRoot,"root.pre",this.pre),this._listen(this.parentRoot,"root.update",this.update),this._listen(this.parentRoot,"root.render",this.render),this._listen(this.parentRoot,"root.post",this.post),this._listen(this.parentRoot,"root.camera",this.setCamera),this._listen(this.parentRoot,"root.resize",function(t){return this.resize(t.size)}),null!=this.rootSize?(s=this.props,o=s.minFilter,i=s.magFilter,l=s.type,a=this.props,f=a.width,e=a.height,r=a.history,h=a.size,u=h===this.node.attributes["rtt.size"]["enum"].relative,d=u?this.rootSize.renderWidth:1,n=u?this.rootSize.renderHeight:1,this.width=Math.round(null!=f?f*d:this.rootSize.renderWidth),this.height=Math.round(null!=e?e*n:this.rootSize.renderHeight),this.history=r,this.aspect=t=this.width/this.height,null==this.scene&&(this.scene=this._renderables.make("scene")),this.rtt=this._renderables.make("renderToTexture",{scene:this.scene,camera:this._context.defaultCamera,width:this.width,height:this.height,frames:this.history,minFilter:o,magFilter:i,type:l}),t=f||e?t:this.rootSize.aspect,p=null!=f?f:this.rootSize.viewWidth,c=null!=e?e:this.rootSize.viewHeight,this.size={renderWidth:this.width,renderHeight:this.height,aspect:t,viewWidth:p,viewHeight:c,pixelRatio:this.height/c}):void 0},e.prototype.made=function(){return this.trigger({type:"source.rebuild"}),this.size?this.trigger({type:"root.resize",size:this.size}):void 0},e.prototype.unmake=function(t){return null!=this.rtt?(this.rtt.dispose(),t||this.scene.dispose(),this.rtt=this.width=this.height=this.history=null):void 0},e.prototype.change=function(t,e,n){return e.texture||t["rtt.width"]||t["rtt.height"]?this.rebuild():t["root.camera"]||n?(this._unattach(),this._attach(this.props.camera,"camera",this.setCamera,this,this,!0),this.setCamera()):void 0},e.prototype.adopt=function(t){var e,n,r,i,o;for(i=t.renders,o=[],e=0,n=i.length;n>e;e++)r=i[e],o.push(this.scene.add(r));return o},e.prototype.unadopt=function(t){var e,n,r,i,o;for(i=t.renders,o=[],e=0,n=i.length;n>e;e++)r=i[e],o.push(this.scene.remove(r));return o},e.prototype.resize=function(t){var e,n,r,i;return this.rootSize=t,n=this.props,i=n.width,e=n.height,t=n.size,r=t===this.node.attributes["rtt.size"]["enum"].relative,!this.rtt||null==i||null==e||r?this.rebuild():void 0},e.prototype.select=function(t){return this._root.node.model.select(t,[this.node])},e.prototype.watch=function(t,e){return this._root.node.model.watch(t,e)},e.prototype.unwatch=function(t){return this._root.node.model.unwatch(t)},e.prototype.pre=function(t){return this.trigger(t)},e.prototype.update=function(t){var e;return null!=(e=this.getOwnCamera())&&(e.aspect=this.aspect||1,e.updateProjectionMatrix()),this.trigger(t)},e.prototype.render=function(t){var e;return this.trigger(t),null!=(e=this.rtt)?e.render(this.getCamera()):void 0},e.prototype.post=function(t){return this.trigger(t)},e.prototype.setCamera=function(){var t,e;return t=null!=(e=this.select(this.props.camera)[0])?e.controller:void 0,this.camera!==t?(this.camera=t,this.rtt.camera=this.getCamera(),this.trigger({type:"root.camera"})):this.camera?void 0:this.trigger({type:"root.camera"})},e.prototype.getOwnCamera=function(){var t;return null!=(t=this.camera)?t.getCamera():void 0},e.prototype.getCamera=function(){var t;return null!=(t=this.getOwnCamera())?t:this._inherit("root").getCamera()},e.prototype.vertex=function(t,e){return 2===e?t.pipe("view.position"):3===e?t.pipe("root.position"):t},e}(r),e.exports=i},{"../../../util":175,"../base/parent":47}],100:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("../../primitive"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","shader"],e.freeform=!0,e.prototype.init=function(){return this.shader=null},e.prototype.make=function(){var t,e,n,r,i,o,s,a,u,h,l,c;if(s=this.props,r=s.language,t=s.code,"glsl"!==r)throw new Error("GLSL required");for(this._helpers.bind.make([{to:"shader.sources",trait:"source",multiple:!0}]),u=this._shaders.fetch(t),l=this._types,c={},o=function(t){return function(t){var e;switch(t){case"i":return l["int"]();case"f":return l.number();case"v2":return l.vec2();case"v3":return l.vec3();case"v4":return l.vec4();case"m3":return l.mat3();case"m4":return l.mat4();case"t":return l.object();default:return e=t.split(""),"v"===e.pop()?l.array(o(e.join(""))):null}}}(this),a=u._signatures.uniform,n=0,i=a.length;i>n;n++)e=a[n],(h=o(e.type))&&(c[e.name]=h);return this.reconfigure({props:{uniform:c}})},e.prototype.made=function(){return this.trigger({type:"source.rebuild"})},e.prototype.unmake=function(){return this.shader=null},e.prototype.change=function(t,e,n){return t["shader.uniforms"]||t["shader.code"]||t["shader.language"]?this.rebuild():void 0},e.prototype.shaderBind=function(t){var e,n,r,i,o,s,a,u,h,l,c,p,f;null==t&&(t={}),a=this.props,i=a.language,e=a.code,u=this.node.attributes;for(r in u)f=u[r],null!=f.type&&null!=f["short"]&&"uniform"===f.ns&&null==t[s=f["short"]]&&(t[s]=f);if(null!=(p=this.props.uniforms))for(r in p)f=p[r],t[r]=f;if(l=this._shaders.shader(),null!=this.bind.sources)for(h=this.bind.sources,n=0,o=h.length;o>n;n++)c=h[n],l.require(c.sourceShader(this._shaders.shader()));return l.pipe(e,t)},e}(r),e.exports=i},{"../../../util":175,"../../primitive":44}],101:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../operator/operator"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","operator","texture","text","format","font"],e.defaults={minFilter:"linear",magFilter:"linear"},e.prototype.init=function(){return e.__super__.init.apply(this,arguments),this.atlas=this.buffer=this.used=this.time=null,this.filled=!1},e.prototype.sourceShader=function(t){return this.buffer.shader(t)},e.prototype.textShader=function(t){return this.atlas.shader(t)},e.prototype.textIsSDF=function(){return this.props.sdf>0},e.prototype.textHeight=function(){return this.props.detail},e.prototype.make=function(){var t,e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g;return this._helpers.bind.make([{to:"operator.source",trait:"raw"}]),l=this.props,h=l.minFilter,u=l.magFilter,d=l.type,c=this.props,o=c.font,f=c.style,m=c.variant,v=c.weight,n=c.detail,p=c.sdf,this.atlas=this._renderables.make("textAtlas",{font:o,size:n,style:f,variant:m,weight:v,outline:p,minFilter:h,magFilter:u,type:d}),h=THREE.NearestFilter,u=THREE.NearestFilter,d=THREE.FloatType,r=this.bind.source.getDimensions(),a=r.items,g=r.width,s=r.height,e=r.depth,this.buffer=this._renderables.make("voxelBuffer",{width:g,height:s,depth:e,channels:4,items:a,minFilter:h,magFilter:u,type:d}),t=this.atlas,i=this.buffer.streamer.emit,this.buffer.streamer.emit=function(e){return t.map(e,i)},this.clockParent=this._inherit("clock"),this._listen("root","root.update",this.update)},e.prototype.made=function(){return e.__super__.made.apply(this,arguments),this.resize()},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),this.buffer&&(this.buffer.dispose(),this.buffer=null),this.atlas?(this.atlas.dispose(),this.atlas=null):void 0},e.prototype.update=function(){var t,e,n;return e=this.bind.source.rawBuffer(),t=this.buffer,this.filled&&!this.props.live||!this.through?void 0:(this.time=this.clockParent.getTime(),n=this.used,this.atlas.begin(),this.used=this.through(),this.buffer.write(this.used),this.atlas.end(),this.filled=!0,n!==this.used?this.trigger({type:"source.resize"}):void 0)},e.prototype.change=function(t,e,n){var r,i,o,s,a,u;return e.font?this.rebuild():t["format.expr"]||t["format.digits"]||t["format.data"]||n?(u=this.props,i=u.digits,o=u.expr,r=u.data,null==o&&(o=null!=r?function(t,e,n,i,o){return r[o]}:function(t){return t}),s=o.length,null!=i&&(o=function(t){return function(e,n,r,o,s,a,u,h,l,c){return+t(e,n,r,o,s,a,u,h,l,c).toPrecision(i)}}(o)),a=s>8?function(t){return function(e,n,r,i,s,a,u,h,l,c,p){return e(o(n,r,i,s,a,u,h,l,t.time.clock,t.time.step))}}(this):function(t){return function(t,e,n,r,i,s,a,u,h){return t(o(e,n,r,i,s,a,u,h))}}(this),this.through=this.bind.source.rawBuffer().through(a,this.buffer)):void 0},e}(i),e.exports=r},{"../../../util":175,"../operator/operator":78}],102:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../../primitive"),o=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","object","visible","style","label","attach","geometry","position"],e.prototype.make=function(){var t,n,r,i,s,a,u,h,l,c,p,f,d,m,v,g,E,y;return e.__super__.make.apply(this,arguments),this._helpers.bind.make([{to:"label.text",trait:"text"},{to:"geometry.points",trait:"source"},{to:"geometry.colors",trait:"source"}]),null!=this.bind.points&&null!=this.bind.text?(l=this.bind.points.getDimensions(),m=this.bind.text.getDimensions(),v=this.bind.text.textIsSDF(),s=Math.min(l.items,m.items),y=Math.min(l.width,m.width),i=Math.min(l.height,m.height),r=Math.min(l.depth,m.depth),c=this.bind.points.sourceShader(this._shaders.shader()),c=this._helpers.position.pipeline(c),f=this.bind.text.sourceShader(this._shaders.shader()),u=this._shaders.shader().pipe("label.map"),u.pipe(this.bind.text.textShader(this._shaders.shader())), +a={spriteDepth:this.node.attributes["attach.depth"],spriteOffset:this.node.attributes["attach.offset"],spriteSnap:this.node.attributes["attach.snap"],spriteScale:this._attributes.make(this._types.number()),outlineStep:this._attributes.make(this._types.number()),outlineExpand:this._attributes.make(this._types.number()),outlineColor:this.node.attributes["label.background"]},this.spriteScale=a.spriteScale,this.outlineStep=a.outlineStep,this.outlineExpand=a.outlineExpand,p=v?"label.outline":"label.alpha",n=this._shaders.shader().pipe(p,a),this.bind.colors&&(t=this._shaders.shader(),this.bind.colors.sourceShader(t)),h=this._helpers.object.mask(),d=this._helpers.style.uniforms(),E=this._inherit("unit").getUnitUniforms(),g=o.JS.merge(E,d,a),this.sprite=this._renderables.make("sprite",{uniforms:g,width:y,height:i,depth:r,items:s,position:c,sprite:f,map:u,combine:n,color:t,mask:h,linear:!0}),this._helpers.visible.make(),this._helpers.object.make([this.sprite])):void 0},e.prototype.unmake=function(){return this._helpers.bind.unmake(),this._helpers.visible.unmake(),this._helpers.object.unmake(),this.sprite=null},e.prototype.resize=function(){var t,e,n,r,i,o;return r=this.bind.points.getActiveDimensions(),i=this.bind.text.getActiveDimensions(),n=Math.min(r.items,i.items),o=Math.min(r.width,i.width),e=Math.min(r.height,i.height),t=Math.min(r.depth,i.depth),this.sprite.geometry.clip(o,e,t,n)},e.prototype.change=function(t,e,n){var r,i,o,s,a;if(e.geometry||t["label.text"])return this.rebuild();if(null!=this.bind.points)return a=this.props.size,o=this.props.outline,r=this.props.expand,i=this.bind.text.textHeight(),s=a/i,this.outlineExpand.value=r/s*16/255,this.outlineStep.value=o/s*16/255,this.spriteScale.value=s},e}(i),e.exports=r},{"../../../util":175,"../../primitive":44}],103:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("../operator/resample"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","bind","operator","resample","sampler:x","sampler:y","sampler:z","sampler:w","include","text"],e.prototype.init=function(){return this.sourceSpec=[{to:"operator.source",trait:"text"}]},e.prototype.textShader=function(t){return this.bind.source.textShader(t)},e.prototype.textIsSDF=function(){var t;return(null!=(t=this.bind.source)?t.props.sdf:void 0)>0},e.prototype.textHeight=function(){var t;return null!=(t=this.bind.source)?t.props.detail:void 0},e}(r),e.exports=i},{"../../../util":175,"../operator/resample":81}],104:[function(t,e,n){var r,i,o,s,a=function(t,e){function n(){this.constructor=t}for(var r in e)u.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},u={}.hasOwnProperty;r=t("../data/buffer"),s=t("../data/voxel"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return a(e,t),e.traits=["node","buffer","active","data","texture","voxel","text","font"],e.defaults={minFilter:"linear",magFilter:"linear"},e.finals={channels:1},e.prototype.init=function(){return e.__super__.init.apply(this,arguments),this.atlas=null},e.prototype.textShader=function(t){return this.atlas.shader(t)},e.prototype.textIsSDF=function(){return this.props.sdf>0},e.prototype.textHeight=function(){return this.props.detail},e.prototype.make=function(){var t,e,n,i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S;return d=this.props,f=d.minFilter,p=d.magFilter,R=d.type,m=this.props,h=m.font,w=m.style,H=m.variant,M=m.weight,s=m.detail,T=m.sdf,this.atlas=this._renderables.make("textAtlas",{font:h,size:s,style:w,variant:H,weight:M,outline:T,minFilter:f,magFilter:p,type:R}),this.minFilter=THREE.NearestFilter,this.magFilter=THREE.NearestFilter,this.type=THREE.FloatType,r.prototype.make.call(this),f=null!=(v=this.minFilter)?v:this.props.minFilter,p=null!=(g=this.magFilter)?g:this.props.magFilter,R=null!=(E=this.type)?E:this.props.type,S=this.props.width,l=this.props.height,i=this.props.depth,y=this.props.bufferWidth,_=this.props.bufferHeight,b=this.props.bufferDepth,e=this.props.channels,c=this.props.items,a=this.spec={channels:e,items:c,width:S,height:l,depth:i},this.items=a.items,this.channels=a.channels,n=this.props.data,a=o.Data.getDimensions(n,a),x=this.space,x.width=Math.max(y,a.width||1),x.height=Math.max(_,a.height||1),x.depth=Math.max(b,a.depth||1),this.buffer=this._renderables.make(this.storage,{width:x.width,height:x.height,depth:x.depth,channels:4,items:c,minFilter:f,magFilter:p,type:R}),t=this.atlas,u=this.buffer.streamer.emit,this.buffer.streamer.emit=function(e){return t.map(e,u)}},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),this.atlas?(this.atlas.dispose(),this.atlas=null):void 0},e.prototype.update=function(){return this.atlas.begin(),e.__super__.update.apply(this,arguments),this.atlas.end()},e.prototype.change=function(t,n,r){return n.font?this.rebuild():e.__super__.change.call(this,t,n,r)},e}(s),e.exports=i},{"../../../util":175,"../data/buffer":55,"../data/voxel":61}],105:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("../base/parent"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","clock","seek","play"],e.prototype.init=function(){return this.skew=0,this.last=0,this.time={now:+new Date/1e3,time:0,delta:0,clock:0,step:0}},e.prototype.make=function(){return this._listen("clock","clock.tick",this.tick)},e.prototype.reset=function(){return this.skew=0},e.prototype.tick=function(t){var e,n,r,i,o,s,a,u,h,l,c,p,f;return h=this.props,i=h.from,f=h.to,c=h.speed,l=h.seek,o=h.pace,n=h.delay,u=h.realtime,s=this._inherit("clock").getTime(),p=u?s.time:s.clock,r=u?s.delta:s.step,a=c/o,this.skew+=r*(a-1),this.last>p&&(this.skew=0),this.time.now=s.now+this.skew,this.time.time=s.time,this.time.delta=s.delta,e=null!=l?l:s.clock+this.skew,this.time.clock=Math.min(f,i+Math.max(0,e-n*a)),this.time.step=r*a,this.last=p,this.trigger(t)},e.prototype.getTime=function(){return this.time},e}(i),e.exports=r},{"../base/parent":47}],106:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("../base/parent"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","clock","now"],e.prototype.init=function(){var t;return this.now=t=+new Date/1e3,this.skew=0,this.time={now:t,time:0,delta:0,clock:0,step:0}},e.prototype.make=function(){return this.clockParent=this._inherit("clock"),this._listen("clock","clock.tick",this.tick)},e.prototype.unmake=function(){return this.clockParent=null},e.prototype.change=function(t,e,n){return t["date.now"]?this.skew=0:void 0},e.prototype.tick=function(t){var e,n,r,i,o,s,a;return i=this.props,e=i.now,s=i.seek,n=i.pace,a=i.speed,r=this.clockParent.getTime(),this.skew+=r.step*n/a,null!=s&&(this.skew=s),this.time.now=this.time.time=this.time.clock=(null!=(o=this.props.now)?o:this.now)+this.skew,this.time.delta=this.time.step=r.delta,this.trigger(t)},e.prototype.getTime=function(){return this.time},e}(i),e.exports=r},{"../base/parent":47}],107:[function(t,e,n){var r,i;i=t("./types"),r={node:{id:i.nullable(i.string()),classes:i.classes()},entity:{active:i.bool(!0)},object:{visible:i.bool(!0)},unit:{scale:i.nullable(i.number()),fov:i.nullable(i.number()),focus:i.nullable(i.number(1),!0)},span:{range:i.nullable(i.vec2(-1,1))},view:{range:i.array(i.vec2(-1,1),4)},view3:{position:i.vec3(),quaternion:i.quat(),rotation:i.vec3(),scale:i.vec3(1,1,1),eulerOrder:i.swizzle("xyz")},view4:{position:i.vec4(),scale:i.vec4(1,1,1,1)},layer:{depth:i.number(1),fit:i.fit("y")},vertex:{pass:i.vertexPass()},fragment:{pass:i.fragmentPass(),gamma:i.bool(!1)},transform3:{position:i.vec3(),quaternion:i.quat(),rotation:i.vec3(),eulerOrder:i.swizzle("xyz"),scale:i.vec3(1,1,1),matrix:i.mat4(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},transform4:{position:i.vec4(),scale:i.vec4(1,1,1,1),matrix:i.mat4(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},camera:{proxy:i.bool(!1),position:i.nullable(i.vec3()),quaternion:i.nullable(i.quat()),rotation:i.nullable(i.vec3()),lookAt:i.nullable(i.vec3()),up:i.nullable(i.vec3()),eulerOrder:i.swizzle("xyz"),fov:i.nullable(i.number(1))},polar:{bend:i.number(1),helix:i.number(0)},spherical:{bend:i.number(1)},stereographic:{bend:i.number(1)},interval:{axis:i.axis()},area:{axes:i.swizzle([1,2],2)},volume:{axes:i.swizzle([1,2,3],3)},origin:{origin:i.vec4()},scale:{divide:i.number(10),unit:i.number(1),base:i.number(10),mode:i.scale(),start:i.bool(!0),end:i.bool(!0),zero:i.bool(!0),factor:i.positive(i.number(1)),nice:i.bool(!0)},grid:{lineX:i.bool(!0),lineY:i.bool(!0),crossed:i.bool(!1),closedX:i.bool(!1),closedY:i.bool(!1)},axis:{detail:i["int"](1),crossed:i.bool(!1)},data:{data:i.nullable(i.data()),expr:i.nullable(i.emitter()),bind:i.nullable(i.func()),live:i.bool(!0)},buffer:{channels:i["enum"](4,[1,2,3,4]),items:i["int"](1),fps:i.nullable(i["int"](60)),hurry:i["int"](5),limit:i["int"](60),realtime:i.bool(!1),observe:i.bool(!1),aligned:i.bool(!1)},sampler:{centered:i.bool(!1),padding:i.number(0)},array:{width:i.nullable(i.positive(i["int"](1),!0)),bufferWidth:i["int"](1),history:i["int"](1)},matrix:{width:i.nullable(i.positive(i["int"](1),!0)),height:i.nullable(i.positive(i["int"](1),!0)),history:i["int"](1),bufferWidth:i["int"](1),bufferHeight:i["int"](1)},voxel:{width:i.nullable(i.positive(i["int"](1),!0)),height:i.nullable(i.positive(i["int"](1),!0)),depth:i.nullable(i.positive(i["int"](1),!0)),bufferWidth:i["int"](1),bufferHeight:i["int"](1),bufferDepth:i["int"](1)},resolve:{expr:i.nullable(i.func()),items:i["int"](1)},style:{opacity:i.positive(i.number(1)),color:i.color(),blending:i.blending(),zWrite:i.bool(!0),zTest:i.bool(!0),zIndex:i.positive(i.round()),zBias:i.number(0),zOrder:i.nullable(i["int"]())},geometry:{points:i.select(),colors:i.nullable(i.select())},point:{size:i.positive(i.number(4)),sizes:i.nullable(i.select()),shape:i.shape(),optical:i.bool(!0),fill:i.bool(!0),depth:i.number(1)},line:{width:i.positive(i.number(2)),depth:i.positive(i.number(1)),join:i.join(),stroke:i.stroke(),proximity:i.nullable(i.number(1/0)),closed:i.bool(!1)},mesh:{fill:i.bool(!0),shaded:i.bool(!1),map:i.nullable(i.select()),lineBias:i.number(5)},strip:{line:i.bool(!1)},face:{line:i.bool(!1)},arrow:{size:i.number(3),start:i.bool(!1),end:i.bool(!1)},ticks:{normal:i.vec3(0,0,1),size:i.positive(i.number(10)),epsilon:i.positive(i.number(.001))},attach:{offset:i.vec2(0,-20),snap:i.bool(!1),depth:i.number(0)},format:{digits:i.nullable(i.positive(i.number(3))),data:i.nullable(i.data()),expr:i.nullable(i.func()),live:i.bool(!0)},font:{font:i.font("sans-serif"),style:i.string(),variant:i.string(),weight:i.string(),detail:i.number(24),sdf:i.number(5)},label:{text:i.select(),size:i.number(16),outline:i.number(2),expand:i.number(0),background:i.color(1,1,1)},overlay:{opacity:i.number(1),zIndex:i.positive(i.round(0))},dom:{points:i.select(),html:i.select(),size:i.number(16),outline:i.number(2),zoom:i.number(1),color:i.nullable(i.color()),attributes:i.nullable(i.object()),pointerEvents:i.bool(!1)},texture:{minFilter:i.filter("nearest"),magFilter:i.filter("nearest"),type:i.type("float")},shader:{sources:i.nullable(i.select()),language:i.string("glsl"),code:i.string(),uniforms:i.nullable(i.object())},include:{shader:i.select()},operator:{source:i.select()},spread:{unit:i.mapping(),items:i.nullable(i.vec4()),width:i.nullable(i.vec4()),height:i.nullable(i.vec4()),depth:i.nullable(i.vec4()),alignItems:i.anchor(),alignWidth:i.anchor(),alignHeight:i.anchor(),alignDepth:i.anchor()},grow:{scale:i.number(1),items:i.nullable(i.anchor()),width:i.nullable(i.anchor()),height:i.nullable(i.anchor()),depth:i.nullable(i.anchor())},split:{order:i.transpose("wxyz"),axis:i.nullable(i.axis()),length:i["int"](1),overlap:i["int"](0)},join:{order:i.transpose("wxyz"),axis:i.nullable(i.axis()),overlap:i["int"](0)},swizzle:{order:i.swizzle()},transpose:{order:i.transpose()},repeat:{items:i.number(1),width:i.number(1),height:i.number(1),depth:i.number(1)},slice:{items:i.nullable(i.vec2()),width:i.nullable(i.vec2()),height:i.nullable(i.vec2()),depth:i.nullable(i.vec2())},lerp:{size:i.mapping("absolute"),items:i.nullable(i.number()),width:i.nullable(i.number()),height:i.nullable(i.number()),depth:i.nullable(i.number())},subdivide:{items:i.nullable(i.positive(i["int"](),!0)),width:i.nullable(i.positive(i["int"](),!0)),height:i.nullable(i.positive(i["int"](),!0)),depth:i.nullable(i.positive(i["int"](),!0)),bevel:i.number(1),lerp:i.bool(!0)},resample:{indices:i.number(4),channels:i.number(4),sample:i.mapping(),size:i.mapping("absolute"),items:i.nullable(i.number()),width:i.nullable(i.number()),height:i.nullable(i.number()),depth:i.nullable(i.number())},readback:{type:i.type("float"),expr:i.nullable(i.func()),data:i.data(),channels:i["enum"](4,[1,2,3,4]),items:i.nullable(i["int"]()),width:i.nullable(i["int"]()),height:i.nullable(i["int"]()),depth:i.nullable(i["int"]())},root:{speed:i.number(1),camera:i.select("[camera]")},inherit:{source:i.select(),traits:i.array(i.string())},rtt:{size:i.mapping("absolute"),width:i.nullable(i.number()),height:i.nullable(i.number()),history:i["int"](1)},compose:{alpha:i.bool(!1)},present:{index:i["int"](1),directed:i.bool(!0),length:i.number(0)},slide:{order:i.nullable(i["int"](0)),steps:i.number(1),early:i["int"](0),late:i["int"](0),from:i.nullable(i["int"](0)),to:i.nullable(i["int"](1))},transition:{stagger:i.vec4(),enter:i.nullable(i.number(1)),exit:i.nullable(i.number(1)),delay:i.number(0),delayEnter:i.nullable(i.number(0)),delayExit:i.nullable(i.number(0)),duration:i.number(.3),durationEnter:i.nullable(i.number(0)),durationExit:i.nullable(i.number(0))},move:{from:i.vec4(),to:i.vec4()},seek:{seek:i.nullable(i.number(0))},track:{target:i.select(),script:i.object({}),ease:i.ease("cosine")},trigger:{trigger:i.nullable(i["int"](1),!0)},step:{playback:i.ease("linear"),stops:i.nullable(i.array(i.number())),delay:i.number(0),duration:i.number(.3),pace:i.number(0),speed:i.number(1),rewind:i.number(2),skip:i.bool(!0),realtime:i.bool(!1)},play:{delay:i.number(0),pace:i.number(1),speed:i.number(1),from:i.number(0),to:i.number(1/0),realtime:i.bool(!1),loop:i.bool(!1)},now:{now:i.nullable(i.timestamp()),seek:i.nullable(i.number(0)),pace:i.number(1),speed:i.number(1)}},e.exports=r},{"./types":115}],108:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("./transform"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","include","fragment","bind"],e.prototype.make=function(){return this._helpers.bind.make([{to:"include.shader",trait:"shader",optional:!0}])},e.prototype.unmake=function(){return this._helpers.bind.unmake()},e.prototype.change=function(t,e,n){return e.include||t["fragment.gamma"]?this.rebuild():void 0},e.prototype.fragment=function(t,n){return null!=this.bind.shader&&n===this.props.pass&&(this.props.gamma&&t.pipe("mesh.gamma.out"),t.pipe(this.bind.shader.shaderBind()),t.split(),this.props.gamma&&t.pipe("mesh.gamma.in"),t.pass()),e.__super__.fragment.call(this,t,n)},e}(i),e.exports=r},{"./transform":111}],109:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("./transform"),o=Math.PI,r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","vertex","layer"],e.prototype.make=function(){return this._listen("root","root.resize",this.update),this.uniforms={layerScale:this._attributes.make(this._types.vec4()),layerBias:this._attributes.make(this._types.vec4())}},e.prototype.update=function(){var t,e,n,r,i,s,a,u,h,l,c,p;switch(n=this._inherit("root").getCamera(),p=this._inherit("root").getSize(),e=null!=(u=n.aspect)?u:1,s=null!=(h=n.fov)?h:1,a=Math.tan(s*o/360),t=this.node.attributes["layer.fit"]["enum"],l=this.props,i=l.fit,r=l.depth,c=l.scale,i){case t.contain:i=e>1?t.y:t.x;break;case t.cover:i=e>1?t.x:t.y}switch(i){case t.x:this.uniforms.layerScale.value.set(a*e,a*e);break;case t.y:this.uniforms.layerScale.value.set(a,a)}return this.uniforms.layerBias.value.set(0,0,-r,0)},e.prototype.change=function(t,e,n){return t["layer.fit"]||t["layer.depth"]||n?this.update():void 0},e.prototype.vertex=function(t,e){return 2===e?t.pipe("layer.position",this.uniforms):3===e?t.pipe("root.position"):t},e}(i),e.exports=r},{"./transform":111}],110:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("../base/parent"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","include","mask","bind"],e.prototype.make=function(){return this._helpers.bind.make([{to:"include.shader",trait:"shader",optional:!0}])},e.prototype.unmake=function(){return this._helpers.bind.unmake()},e.prototype.change=function(t,e,n){return e.include?this.rebuild():void 0},e.prototype.mask=function(t){var e,n,r;return null!=this.bind.shader?t?(r=this._shaders.shader(),r.pipe(Util.GLSL.identity("vec4")),r.fan(),r.pipe(t),r.next(),r.pipe(this.bind.shader.shaderBind()),r.end(),r.pipe("float combine(float a, float b) { return min(a, b); }")):(r=this._shaders.shader(),r.pipe(this.bind.shader.shaderBind())):r=t,null!=(e=null!=(n=this._inherit("mask"))?n.mask(r):void 0)?e:r},e}(i),e.exports=r},{"../base/parent":47}],111:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("../base/parent"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","vertex","fragment"],e.prototype.vertex=function(t,e){var n,r;return null!=(n=null!=(r=this._inherit("vertex"))?r.vertex(t,e):void 0)?n:t},e.prototype.fragment=function(t,e){var n,r;return null!=(n=null!=(r=this._inherit("fragment"))?r.fragment(t,e):void 0)?n:t},e}(r),e.exports=i},{"../base/parent":47}],112:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./transform"),o=t("../../../util"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","vertex","transform3"],e.prototype.make=function(){return this.uniforms={transformMatrix:this._attributes.make(this._types.mat4())},this.composer=o.Three.transformComposer()},e.prototype.unmake=function(){return delete this.uniforms},e.prototype.change=function(t,e,n){var r,i,o,s,a,u;if(t["transform3.pass"])return this.rebuild();if(e.transform3||n)return o=this.props.position,s=this.props.quaternion,a=this.props.rotation,u=this.props.scale,i=this.props.matrix,r=this.props.eulerOrder,this.uniforms.transformMatrix.value=this.composer(o,a,s,u,i,r)},e.prototype.vertex=function(t,n){return n===this.props.pass&&t.pipe("transform3.position",this.uniforms),e.__super__.vertex.call(this,t,n)},e}(r),e.exports=i},{"../../../util":175,"./transform":111}],113:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("./transform"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","vertex","transform4"],e.prototype.make=function(){return this.uniforms={transformMatrix:this._attributes.make(this._types.mat4()),transformOffset:this.node.attributes["transform4.position"]},this.transformMatrix=this.uniforms.transformMatrix.value},e.prototype.unmake=function(){return delete this.uniforms},e.prototype.change=function(t,e,n){var r,i,o;if(t["transform4.pass"])return this.rebuild();if(e.transform4||n)return i=this.props.scale,r=this.props.matrix,o=this.transformMatrix,o.copy(r),o.scale(i)},e.prototype.vertex=function(t,n){return n===this.props.pass&&t.pipe("transform4.position",this.uniforms),e.__super__.vertex.call(this,t,n)},e}(r),e.exports=i},{"./transform":111}],114:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("./transform"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","include","vertex","bind"],e.prototype.make=function(){return this._helpers.bind.make([{to:"include.shader",trait:"shader",optional:!0}])},e.prototype.unmake=function(){return this._helpers.bind.unmake()},e.prototype.change=function(t,e,n){return e.include?this.rebuild():void 0},e.prototype.vertex=function(t,n){return null!=this.bind.shader&&n===this.props.pass&&t.pipe(this.bind.shader.shaderBind()),e.__super__.vertex.call(this,t,n)},e}(r),e.exports=i},{"./transform":111}],115:[function(t,e,n){var r,i,o,s=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};i=t("../../util"),r={array:function(t,e,n){var r,i;return null==n&&(n=null),r=t.lerp?function(e,n,r,i){var o,s,a,u;for(a=Math.min(e.length,n.length),o=s=0,u=a;u>=0?u>s:s>u;o=u>=0?++s:--s)r[o]=t.lerp(e[o],n[o],r[o],i);return r}:void 0,i=t.op?function(e,n,r,i){var o,s,a,u;for(a=Math.min(e.length,n.length),o=s=0,u=a;u>=0?u>s:s>u;o=u>=0?++s:--s)r[o]=t.op(e[o],n[o],r[o],i);return r}:void 0,null==n||n instanceof Array||(n=[n]),{uniform:function(){return t.uniform?t.uniform()+"v":void 0},make:function(){var r,i,o,s;if(null!=n)return n.slice();if(!e)return[];for(s=[],r=i=0,o=e;o>=0?o>i:i>o;r=o>=0?++i:--i)s.push(t.make());return s},validate:function(n,r,i){var o,s,a,u,h,l;for(n instanceof Array||(n=[n]),u=r.length=e?e:n.length,o=a=0,h=u;h>=0?h>a:a>h;o=h>=0?++a:--a)s=null!=(l=n[o])?l:t.make(),r[o]=t.validate(s,r[o],i);return r},equals:function(e,n){var r,i,o,s,a,u;if(r=e.length,i=n.length,r!==i)return!1;for(a=Math.min(r,i),o=s=0,u=a;u>=0?u>s:s>u;o=u>=0?++s:--s)if(!("function"==typeof t.equals?t.equals(e[o],n[o]):void 0))return!1;return!0},lerp:r,op:i,clone:function(e){var n,r,i,o;for(i=[],n=0,r=e.length;r>n;n++)o=e[n],i.push(t.clone(o));return i}}},letters:function(t,e,n){var i,o,s,a,u;if(null==n&&(n=null),null!=n)for(n===""+n&&(n=n.split("")),o=s=0,a=n.length;a>s;o=++s)u=n[o],n[o]=t.validate(u,u);return i=r.array(t,e,n),{uniform:function(){return i.uniform()},make:function(){return i.make()},validate:function(t,e,n){return t===""+t&&(t=t.split("")),i.validate(t,e,n)},equals:function(t,e){return i.equals(t,e)},clone:i.clone}},nullable:function(t,e){var n,r,i,o;return null==e&&(e=!1),o=e?t.make():null,n=t.emitter?function(e,n){return null==n?e:null==e?n:t.emitter(e,n)}:void 0,r=t.lerp?function(e,n,r,i){return null===e||null===n?.5>i?e:n:(null==r&&(r=t.make()),o=t.lerp(e,n,r,i),r)}:void 0,i=t.op?function(e,n,r,i){return null===e||null===n?null:(null==r&&(r=t.make()),o=t.op(e,n,r,i))}:void 0,{make:function(){return o},validate:function(e,n,r){return null===e?e:(null===n&&(n=t.make()),t.validate(e,n,r))},uniform:function(){return"function"==typeof t.uniform?t.uniform():void 0},equals:function(e,n){var r,i,o;return r=null===e,i=null===n,r&&i?!0:r^i?!1:null!=(o="function"==typeof t.equals?t.equals(e,n):void 0)?o:e===n},lerp:r,op:i,emitter:n}},"enum":function(t,e,n){var r,i,o,s,a,u,h;for(null==e&&(e=[]),null==n&&(n={}),r=0,h={},i=0,s=e.length;s>i;i++)o=e[i],o!==+o&&null==n[o]&&(n[o]=r++);for(u=0,a=e.length;a>u;u++)o=e[u],o===+o&&(h[o]=o);for(o in n)r=n[o],h[r]=!0;return null==h[t]&&(t=n[t]),{"enum":function(){return n},make:function(){return t},validate:function(t,e,r){var i;return i=h[t]?t:n[t],null!=i?i:r()}}},enumber:function(t,e,n){var i;return null==n&&(n={}),i=r["enum"](t,e,n),{"enum":i["enum"],uniform:function(){return"f"},make:function(){var e;return null!=(e=i.make())?e:+t},validate:function(t,e,n){return t===+t?t:i.validate(t,e,n)},op:function(t,e,n,r){return r(t,e)}}},select:function(t){return null==t&&(t="<"),{make:function(){return t},validate:function(t,e,n){return"string"==typeof t?t:"object"==typeof t?t:n()}}},bool:function(t){return t=!!t,{uniform:function(){return"f"},make:function(){return t},validate:function(t,e,n){return!!t}}},"int":function(t){return null==t&&(t=0),t=+Math.round(t),{uniform:function(){return"i"},make:function(){return t},validate:function(t,e,n){var r;return t!==(r=+t)?n():Math.round(r)||0},op:function(t,e,n,r){return r(t,e)}}},round:function(t){return null==t&&(t=0),t=+Math.round(t),{uniform:function(){return"f"},make:function(){return t},validate:function(t,e,n){var r;return t!==(r=+t)?n():Math.round(r)||0},op:function(t,e,n,r){return r(t,e)}}},number:function(t){return null==t&&(t=0),{uniform:function(){return"f"},make:function(){return+t},validate:function(t,e,n){var r;return t!==(r=+t)?n():r||0},op:function(t,e,n,r){return r(t,e)}}},positive:function(t,e){return null==e&&(e=!1),{uniform:t.uniform,make:t.make,validate:function(n,r,i){return n=t.validate(n,r,i),0>n||e&&0>=n?i():n},op:function(t,e,n,r){return r(t,e)}}},string:function(t){return null==t&&(t=""),{make:function(){return""+t},validate:function(t,e,n){var r;return t!==(r=""+t)?n():r}}},func:function(){return{make:function(){return function(){}},validate:function(t,e,n){return"function"==typeof t?t:n()}}},emitter:function(){return{make:function(){return function(t){return t(1,1,1,1)}},validate:function(t,e,n){return"function"==typeof t?t:n()},emitter:function(t,e){return i.Data.getLerpEmitter(t,e)}}},object:function(t){return{make:function(){return null!=t?t:{}},validate:function(t,e,n){return"object"==typeof t?t:n()},clone:function(t){return JSON.parse(JSON.stringify(t))}}},timestamp:function(t){return null==t&&(t=null),"string"==typeof t&&(t=Date.parse(t)),{uniform:function(){return"f"},make:function(){return null!=t?t:+new Date},validate:function(t,e,n){var r;return t=Date.parse(t),t!==(r=+t)?n():t},op:function(t,e,n,r){return r(t,e)}}},vec2:function(t,e){var n;return null==t&&(t=0),null==e&&(e=0),n=[t,e],{uniform:function(){return"v2"},make:function(){return new THREE.Vector2(t,e)},validate:function(r,i,o){var s,a,u,h;if(r===+r&&(r=[r]),r instanceof THREE.Vector2)i.copy(r);else if(r instanceof Array)r=r.concat(n.slice(r.length)),i.set.apply(i,r);else{if(null==r)return o();u=null!=(s=r.x)?s:t,h=null!=(a=r.y)?a:e,i.set(u,h)}return i},equals:function(t,e){return t.x===e.x&&t.y===e.y},op:function(t,e,n,r){return n.x=r(t.x,e.x),n.y=r(t.y,e.y),n}}},ivec2:function(t,e){var n,i;return null==t&&(t=0),null==e&&(e=0),i=r.vec2(t,e),n=i.validate,i.validate=function(t,e,r){return n(t,e,r),e.x=Math.round(e.x),e.y=Math.round(e.y),e},i},vec3:function(t,e,n){var r;return null==t&&(t=0),null==e&&(e=0),null==n&&(n=0),r=[t,e,n],{uniform:function(){return"v3"},make:function(){return new THREE.Vector3(t,e,n)},validate:function(i,o,s){var a,u,h,l,c,p;if(i===+i&&(i=[i]),i instanceof THREE.Vector3)o.copy(i);else if(i instanceof Array)i=i.concat(r.slice(i.length)),o.set.apply(o,i);else{if(null==i)return s();l=null!=(a=i.x)?a:t,c=null!=(u=i.y)?u:e,p=null!=(h=i.z)?h:n,o.set(l,c,p)}return o},equals:function(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z},op:function(t,e,n,r){return n.x=r(t.x,e.x),n.y=r(t.y,e.y),n.z=r(t.z,e.z),n}}},ivec3:function(t,e,n){var i,o;return null==t&&(t=0),null==e&&(e=0),null==n&&(n=0),o=r.vec3(t,e,n),i=o.validate,o.validate=function(t,e){return i(t,e,invalid),e.x=Math.round(e.x),e.y=Math.round(e.y),e.z=Math.round(e.z),e},o},vec4:function(t,e,n,r){var i;return null==t&&(t=0),null==e&&(e=0),null==n&&(n=0),null==r&&(r=0),i=[t,e,n,r],{uniform:function(){return"v4"},make:function(){return new THREE.Vector4(t,e,n,r)},validate:function(o,s,a){var u,h,l,c,p,f,d,m;if(o===+o&&(o=[o]),o instanceof THREE.Vector4)s.copy(o);else if(o instanceof Array)o=o.concat(i.slice(o.length)),s.set.apply(s,o);else{if(null==o)return a();f=null!=(u=o.x)?u:t,d=null!=(h=o.y)?h:e,m=null!=(l=o.z)?l:n,p=null!=(c=o.w)?c:r,s.set(f,d,m,p)}return s},equals:function(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z&&t.w===e.w},op:function(t,e,n,r){return n.x=r(t.x,e.x),n.y=r(t.y,e.y),n.z=r(t.z,e.z),n.w=r(t.w,e.w),n}}},ivec4:function(t,e,n,i){var o,s;return null==t&&(t=0),null==e&&(e=0),null==n&&(n=0),null==i&&(i=0),s=r.vec4(t,e,n,i),o=s.validate,s.validate=function(t,e){return o(t,e,invalid),e.x=Math.round(e.x),e.y=Math.round(e.y),e.z=Math.round(e.z),e.w=Math.round(e.w),e},s},mat3:function(t,e,n,r,i,o,s,a,u){var h;return null==t&&(t=1),null==e&&(e=0),null==n&&(n=0),null==r&&(r=0),null==i&&(i=1),null==o&&(o=0),null==s&&(s=0),null==a&&(a=0),null==u&&(u=1),h=[t,e,n,r,i,o,s,a,u],{uniform:function(){return"m4"},make:function(){var h;return h=new THREE.Matrix3,h.set(t,e,n,r,i,o,s,a,u),h},validate:function(t,e,n){if(t instanceof THREE.Matrix3)e.copy(t);else{if(!(t instanceof Array))return n();t=t.concat(h.slice(t.length)),e.set.apply(e,t)}return e}}},mat4:function(t,e,n,r,i,o,s,a,u,h,l,c,p,f,d,m){var v;return null==t&&(t=1),null==e&&(e=0),null==n&&(n=0),null==r&&(r=0),null==i&&(i=0),null==o&&(o=1),null==s&&(s=0),null==a&&(a=0),null==u&&(u=0),null==h&&(h=0),null==l&&(l=1),null==c&&(c=0),null==p&&(p=0),null==f&&(f=0),null==d&&(d=0),null==m&&(m=1),v=[t,e,n,r,i,o,s,a,u,h,l,c,p,f,d,m],{uniform:function(){return"m4"},make:function(){var v;return v=new THREE.Matrix4,v.set(t,e,n,r,i,o,s,a,u,h,l,c,p,f,d,m),v},validate:function(t,e,n){if(t instanceof THREE.Matrix4)e.copy(t);else{if(!(t instanceof Array))return n();t=t.concat(v.slice(t.length)),e.set.apply(e,t)}return e}}},quat:function(t,e,n,i){var o;return null==t&&(t=0),null==e&&(e=0),null==n&&(n=0),null==i&&(i=1),o=r.vec4(t,e,n,i),{uniform:function(){return"v4"},make:function(){return new THREE.Quaternion},validate:function(t,e,n){return t instanceof THREE.Quaternion?e.copy(t):e=o.validate(t,e,n),e.normalize(),e},equals:function(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z&&t.w===e.w},op:function(t,e,n,r){return n.x=r(t.x,e.x),n.y=r(t.y,e.y),n.z=r(t.z,e.z),n.w=r(t.w,e.w),n.normalize(),n},lerp:function(t,e,n,r){return THREE.Quaternion.slerp(t,e,n,r),n}}},color:function(t,e,n){var r;return null==t&&(t=.5),null==e&&(e=.5),null==n&&(n=.5),r=[t,e,n],{uniform:function(){return"c"},make:function(){return new THREE.Color(t,e,n)},validate:function(i,o,s){var a,u,h,l,c,p;if(i===""+i?i=(new THREE.Color).setStyle(i):i===+i&&(i=new THREE.Color(i)),i instanceof THREE.Color)o.copy(i);else if(i instanceof Array)i=i.concat(r.slice(i.length)),o.setRGB.apply(o,i);else{if(null==i)return s();p=null!=(h=i.r)?h:t,u=null!=(l=i.g)?l:e,a=null!=(c=i.b)?c:n,o.set(p,u,a)}return o},equals:function(t,e){return t.r===e.r&&t.g===e.g&&t.b===e.b},op:function(t,e,n,r){return n.r=r(t.r,e.r),n.g=r(t.g,e.g),n.b=r(t.b,e.b),n}}},axis:function(t,e){var n,r,i;return null==t&&(t=1),null==e&&(e=!1),n={x:1,y:2,z:3,w:4,W:1,H:2,D:3,I:4,zero:0,"null":0,width:1,height:2,depth:3,items:4},r=e?[0,1,2,3,4]:[1,2,3,4],null!=(i=n[t])&&(t=i),{make:function(){return t},validate:function(t,e,o){var a;return null!=(i=n[t])&&(t=i),t=null!=(a=Math.round(t))?a:0,s.call(r,t)>=0?t:o()}}},transpose:function(t){var e,n;return null==t&&(t=[1,2,3,4]),n=r.letters(r.axis(null,!1),0,t), +e=r.letters(r.axis(null,!1),4,t),{make:function(){return e.make()},validate:function(t,r,i){var o,s,a,u,h;return u=[1,2,3,4],n.validate(t,u,i),u.length<4&&(a=[1,2,3,4].filter(function(t){return-1===u.indexOf(t)}),u=u.concat(a)),h=function(){var t,e,n;for(n=[],o=t=0,e=u.length;e>t;o=++t)s=u[o],n.push(u.indexOf(s)===o);return n}(),h.indexOf(!1)<0?e.validate(u,r,i):i()},equals:e.equals,clone:e.clone}},swizzle:function(t,e){var n,i;return null==t&&(t=[1,2,3,4]),null==e&&(e=null),null==e&&(e=t.length),t=t.slice(0,e),i=r.letters(r.axis(null,!1),0,t),n=r.letters(r.axis(null,!0),e,t),{make:function(){return n.make()},validate:function(r,o,s){var a;return a=t.slice(),i.validate(r,a,s),a.length0?1/s-1:0,v=this.props.position,_=this.props.scale,g=this.props.quaternion,E=this.props.rotation,f=this.props.range,l=this.props.eulerOrder,M=f[0].x,S=f[1].x,k=f[2].x,a=f[0].y-M||1,u=f[1].y-S||1,h=f[2].y-k||1,x=_.x,w=_.y,R=_.z,m=a>0?1:-1,y=i.Axis.recenterAxis(S,u,s),S=y[0],u=y[1],r=Math.abs(u),c=a+(r*m-a)*s,b=c/x,T=u/w,this.aspect=o=Math.abs(b/T),this.uniforms.polarFocus.value=p,this.uniforms.polarAspect.value=o,this.viewMatrix.set(2/c,0,0,-(2*M+a)/a,0,2/u,0,-(2*S+u)/u,0,0,2/h,-(2*k+h)/h,0,0,0,1),H=this.composer(v,E,g,_,null,l),this.viewMatrix.multiplyMatrices(H,this.viewMatrix),t["view.range"]||e.polar?this.trigger({type:"view.range"}):void 0},e.prototype.vertex=function(t,n){return 1===n&&t.pipe("polar.position",this.uniforms),e.__super__.vertex.call(this,t,n)},e.prototype.axis=function(t){var e,n,r;return r=this.props.range[t-1],n=r.x,e=r.y,2===t&&this.bend>0&&(e=Math.max(Math.abs(e),Math.abs(n)),n=Math.max(-this.focus/this.aspect,n)),new THREE.Vector2(n,e)},e}(o),e.exports=r},{"../../../util":175,"./view":122}],119:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;o=t("./view"),i=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","object","visible","view","view3","spherical","vertex"],e.prototype.make=function(){var t;return e.__super__.make.apply(this,arguments),t=this._attributes.types,this.uniforms={sphericalBend:this.node.attributes["spherical.bend"],sphericalFocus:this._attributes.make(this._types.number()),sphericalAspectX:this._attributes.make(this._types.number()),sphericalAspectY:this._attributes.make(this._types.number()),sphericalScaleY:this._attributes.make(this._types.number()),viewMatrix:this._attributes.make(this._types.mat4())},this.viewMatrix=this.uniforms.viewMatrix.value,this.composer=i.Three.transformComposer(),this.aspectX=1,this.aspectY=1},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),delete this.viewMatrix,delete this.objectMatrix,delete this.aspectX,delete this.aspectY,delete this.uniforms},e.prototype.change=function(t,e,n){var r,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k,A,C,P,L,z,O;if(e.view||e.view3||e.spherical||n)return this.bend=u=this.props.bend,this.focus=m=u>0?1/u-1:0,y=this.props.position,w=this.props.scale,_=this.props.quaternion,b=this.props.rotation,v=this.props.range,p=this.props.eulerOrder,L=v[0].x,z=v[1].x,O=v[2].x,h=v[0].y-L||1,l=v[1].y-z||1,c=v[2].y-O||1,k=w.x,A=w.y,C=w.z,T=i.Axis.recenterAxis(z,l,u),z=T[0],l=T[1],x=i.Axis.recenterAxis(O,c,u),O=x[0],c=x[1],g=h>0?1:-1,E=l>0?1:-1,r=Math.abs(c),f=h+(r*g-h)*u,d=l+(r*E-l)*u,H=f/k,M=d/A,S=c/C,this.aspectX=o=Math.abs(H/S),this.aspectY=s=Math.abs(M/S/o),a=l/h*k/A*2,this.scaleY=R=Math.min(s/u,1+(a-1)*u),this.uniforms.sphericalBend.value=u,this.uniforms.sphericalFocus.value=m,this.uniforms.sphericalAspectX.value=o,this.uniforms.sphericalAspectY.value=s,this.uniforms.sphericalScaleY.value=R,this.viewMatrix.set(2/f,0,0,-(2*L+h)/h,0,2/d,0,-(2*z+l)/l,0,0,2/c,-(2*O+c)/c,0,0,0,1),P=this.composer(y,b,_,w,null,p),this.viewMatrix.multiplyMatrices(P,this.viewMatrix),t["view.range"]||e.spherical?this.trigger({type:"view.range"}):void 0},e.prototype.vertex=function(t,n){return 1===n&&t.pipe("spherical.position",this.uniforms),e.__super__.vertex.call(this,t,n)},e.prototype.axis=function(t){var e,n,r;return r=this.props.range[t-1],n=r.x,e=r.y,3===t&&this.bend>0&&(e=Math.max(Math.abs(e),Math.abs(n)),n=Math.max(-this.focus/this.aspectX+.001,n)),new THREE.Vector2(n,e)},e}(o),e.exports=r},{"../../../util":175,"./view":122}],120:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;o=t("./view"),i=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","object","visible","view","view3","stereographic","vertex"],e.prototype.make=function(){var t;return e.__super__.make.apply(this,arguments),t=this._attributes.types,this.uniforms={stereoBend:this.node.attributes["stereographic.bend"],viewMatrix:this._attributes.make(this._types.mat4())},this.viewMatrix=this.uniforms.viewMatrix.value,this.composer=i.Three.transformComposer()},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),delete this.viewMatrix,delete this.rotationMatrix,delete this.uniforms},e.prototype.change=function(t,e,n){var r,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b;if(e.view||e.view3||e.stereographic||n)return this.bend=r=this.props.bend,l=this.props.position,d=this.props.scale,c=this.props.quaternion,p=this.props.rotation,h=this.props.range,u=this.props.eulerOrder,y=h[0].x,_=h[1].x,b=h[2].x,o=h[0].y-y||1,s=h[1].y-_||1,a=h[2].y-b||1,m=d.x,v=d.y,g=d.z,f=i.Axis.recenterAxis(b,a,r,1),b=f[0],a=f[1],this.uniforms.stereoBend.value=r,this.viewMatrix.set(2/o,0,0,-(2*y+o)/o,0,2/s,0,-(2*_+s)/s,0,0,2/a,-(2*b+a)/a,0,0,0,1),E=this.composer(l,p,c,d,null,u),this.viewMatrix.multiplyMatrices(E,this.viewMatrix),t["view.range"]||e.stereographic?this.trigger({type:"view.range"}):void 0},e.prototype.vertex=function(t,n){return 1===n&&t.pipe("stereographic.position",this.uniforms),e.__super__.vertex.call(this,t,n)},e}(o),e.exports=r},{"../../../util":175,"./view":122}],121:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;o=t("./view"),i=t("../../../util"),r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.traits=["node","object","visible","view","view4","stereographic","vertex"],e.prototype.make=function(){return e.__super__.make.apply(this,arguments),this.uniforms={basisOffset:this._attributes.make(this._types.vec4()),basisScale:this._attributes.make(this._types.vec4()),stereoBend:this.node.attributes["stereographic.bend"]},this.basisScale=this.uniforms.basisScale.value,this.basisOffset=this.uniforms.basisOffset.value},e.prototype.unmake=function(){return e.__super__.unmake.apply(this,arguments),delete this.basisScale,delete this.basisOffset,delete this.uniforms},e.prototype.change=function(t,e,n){var r,o,s,a,u,h,l,c,p,f,d,m,v,g;if(e.view||e.view4||e.stereographic||n)return this.bend=r=this.props.bend,c=this.props.position,f=this.props.scale,h=this.props.range,m=h[0].x,v=h[1].x,g=h[2].x,d=h[3].x,s=h[0].y-m||1,a=h[1].y-v||1,u=h[2].y-g||1,o=h[3].y-d||1,l=function(t,e){return t.x*=e.x,t.y*=e.y,t.z*=e.z,t.w*=e.w},p=i.Axis.recenterAxis(d,o,r,1),d=p[0],o=p[1],this.basisScale.set(2/s,2/a,2/u,2/o),this.basisOffset.set(-(2*m+s)/s,-(2*v+a)/a,-(2*g+u)/u,-(2*d+o)/o),l(this.basisScale,f),l(this.basisOffset,f),this.basisOffset.add(c),t["view.range"]||e.stereographic?this.trigger({type:"view.range"}):void 0},e.prototype.vertex=function(t,n){return 1===n&&t.pipe("stereographic4.position",this.uniforms),e.__super__.vertex.call(this,t,n)},e}(o),e.exports=r},{"../../../util":175,"./view":122}],122:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("../transform/transform"),i=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return o(e,t),e.traits=["node","object","visible","view","vertex"],e.prototype.make=function(){return this._helpers.visible.make()},e.prototype.unmake=function(){return this._helpers.visible.unmake()},e.prototype.axis=function(t){return this.props.range[t-1]},e}(r),e.exports=i},{"../transform/transform":111}],123:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("./databuffer"),o=t("../../util"),r=function(t){function e(t,n,r){this.width=r.width||1,this.history=r.history||1,this.samples=this.width,this.wrap=this.history>1,r.width=this.width,r.height=this.history,r.depth=1,e.__super__.constructor.call(this,t,n,r)}return s(e,t),e.prototype.build=function(t){return e.__super__.build.apply(this,arguments),this.index=0,this.pad=0,this.streamer=this.generate(this.data)},e.prototype.setActive=function(t){return this.pad=Math.max(0,this.width-t)},e.prototype.fill=function(){var t,e,n,r,i,o,s,a,u;for(t=this.callback,"function"==typeof t.reset&&t.reset(),s=this.streamer,r=s.emit,u=s.skip,e=s.count,n=s.done,a=s.reset,a(),o=this.samples-this.pad,i=0;!n()&&o>i&&t(r,i++)!==!1;);return Math.floor(e()/this.items)},e.prototype.write=function(t){return null==t&&(t=this.samples),t*=this.items,this.texture.write(this.data,0,this.index,t,1),this.dataPointer.set(.5,this.index+.5),this.index=(this.index+this.history-1)%this.history,this.filled=Math.min(this.history,this.filled+1)},e.prototype.through=function(t,e){var n,r,i,s,a,u,h,l;return h=l=this.streamer,n=h.consume,r=h.done,s=(i=e.streamer).emit,a=0,u=function(){return n(function(e,n,r,i){return t(s,e,n,r,i,a)})},u=o.Data.repeatCall(u,this.items),function(t){return function(){var e;for(l.reset(),i.reset(),e=t.samples-t.pad,a=0;!r()&&e>a;)u(),a++;return l.count()}}(this)},e}(i),e.exports=r},{"../../util":175,"./databuffer":126}],124:[function(t,e,n){var r,i,o,s,a,u,h=function(t,e){function n(){this.constructor=t}for(var r in e)l.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},l={}.hasOwnProperty;s=t("../renderable"),u=t("../../util"),o=t("./texture/datatexture"),i=t("./texture/backedtexture"),r=function(t){function e(t,n,r){null==this.width&&(this.width=r.width||512),null==this.height&&(this.height=r.height||512),null==this.channels&&(this.channels=r.channels||4),null==this.backed&&(this.backed=r.backed||!1),this.samples=this.width*this.height,e.__super__.constructor.call(this,t,n),this.build(r)}return h(e,t),e.prototype.shader=function(t){return t.pipe("map.2d.data",this.uniforms),t.pipe("sample.2d",this.uniforms),this.channels<4&&t.pipe(u.GLSL.swizzleVec4(["0000","x000","xw00","xyz0"][this.channels])),t},e.prototype.build=function(t){var e;return this.klass=e=this.backed?i:o,this.texture=new e(this.gl,this.width,this.height,this.channels,t),this.uniforms={dataPointer:{type:"v2",value:new THREE.Vector2(0,0)}},this._adopt(this.texture.uniforms),this.reset()},e.prototype.reset=function(){return this.rows=[],this.bottom=0},e.prototype.resize=function(t,e){if(!this.backed)throw new Error("Cannot resize unbacked texture atlas");return t>2048&&e>2048?console.warn("Giant text atlas "+t+"x"+e+"."):console.info("Resizing text atlas "+t+"x"+e+"."),this.texture.resize(t,e),this.width=t,this.height=e,this.samples=t*e},e.prototype.collapse=function(t){var e,n,r;return r=this.rows,r.splice(r.indexOf(t),1),this.bottom=null!=(e=null!=(n=r[r.length-1])?n.bottom:void 0)?e:0,this.last===t?this.last=null:void 0},e.prototype.allocate=function(t,e,n,r){var i,o,s,u,h,l,c,p,f,d,m,v;if(v=this.width,s=this.height,p=2*n,e>v)return this.resize(2*v,2*s),this.last=null,this.allocate(t,e,n,r);if(d=this.last,null!=d&&d.height>=n&&d.heightl;u=++l)if(d=f[u],o=d.top-i,o>=n&&0>h&&(h=u,m=i),i=d.bottom,d.height>=n&&d.height=0)d=new a(m,n),this.rows.splice(h,0,d);else{if(m=i,i+=n,i>=s)return this.resize(2*v,2*s),this.last=null,this.allocate(t,e,n,r);d=new a(m,n),this.rows.push(d),this.bottom=i}d.append(t,e,n,r),this.last=d},e.prototype.read=function(){return this.texture.textureObject},e.prototype.write=function(t,e,n,r,i){return this.texture.write(t,e,n,r,i)},e.prototype.dispose=function(){return this.texture.dispose(),this.data=null,e.__super__.dispose.apply(this,arguments)},e}(s),a=function(){function t(t,e){this.top=t,this.bottom=t+e,this.width=0,this.height=e,this.alive=0,this.keys=[]}return t.prototype.append=function(t,e,n,r){var i,o;return i=this.width,o=this.top,this.alive++,this.width+=e,this.keys.push(t),r(this,i,o)},t}(),e.exports=r},{"../../util":175,"../renderable":161,"./texture/backedtexture":133,"./texture/datatexture":134}],125:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../renderable"),o=t("../../util"),r=function(t){function e(t,n,r){null==this.items&&(this.items=r.items||1),null==this.samples&&(this.samples=r.samples||1),null==this.channels&&(this.channels=r.channels||4),null==this.callback&&(this.callback=r.callback||function(){}),e.__super__.constructor.call(this,t,n)}return s(e,t),e.prototype.dispose=function(){return e.__super__.dispose.apply(this,arguments)},e.prototype.update=function(){var t;return t=this.fill(),this.write(t),t},e.prototype.setActive=function(t,e,n,r){},e.prototype.setCallback=function(t){this.callback=t},e.prototype.write=function(){},e.prototype.fill=function(){},e.prototype.generate=function(t){return o.Data.getStreamer(t,this.samples,this.channels,this.items)},e}(i),e.exports=r},{"../../util":175,"../renderable":161}],126:[function(t,e,n){var r,i,o,s,a=function(t,e){function n(){this.constructor=t}for(var r in e)u.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},u={}.hasOwnProperty;r=t("./buffer"),o=t("./texture/datatexture"),s=t("../../util"),i=function(t){function e(t,n,r){this.width=r.width||1,this.height=r.height||1,this.depth=r.depth||1,null==this.samples&&(this.samples=this.width*this.height*this.depth),e.__super__.constructor.call(this,t,n,r),this.build(r)}return a(e,t),e.prototype.shader=function(t,e){var n;return null==e&&(e=4),this.items>1||this.depth>1?(4!==e&&t.pipe(s.GLSL.extendVec(e,4)),t.pipe("map.xyzw.texture",this.uniforms)):2!==e&&t.pipe(s.GLSL.truncateVec(e,2)),n=this.wrap?".wrap":"",t.pipe("map.2d.data"+n,this.uniforms),t.pipe("sample.2d",this.uniforms),this.channels<4&&t.pipe(s.GLSL.swizzleVec4(["0000","x000","xw00","xyz0"][this.channels])),t},e.prototype.build=function(t){return this.data=new Float32Array(this.samples*this.channels*this.items),this.texture=new o(this.gl,this.items*this.width,this.height*this.depth,this.channels,t),this.filled=0,this.used=0,this._adopt(this.texture.uniforms),this._adopt({dataPointer:{type:"v2",value:new THREE.Vector2},textureItems:{type:"f",value:this.items},textureHeight:{type:"f",value:this.height}}),this.dataPointer=this.uniforms.dataPointer.value,this.streamer=this.generate(this.data)},e.prototype.dispose=function(){return this.data=null,this.texture.dispose(),e.__super__.dispose.apply(this,arguments)},e.prototype.getFilled=function(){return this.filled},e.prototype.setCallback=function(t){return this.callback=t,this.filled=0},e.prototype.copy=function(t){var e,n,r,i,o;for(i=Math.min(t.length,this.samples*this.channels*this.items),e=this.data,n=r=0,o=i;o>=0?o>r:r>o;n=o>=0?++r:--r)e[n]=t[n];return this.write(Math.ceil(i/this.channels/this.items))},e.prototype.write=function(t){var e,n;return null==t&&(t=this.samples),e=t/this.width,t*=this.items,n=1>e?t:this.items*this.width,e=Math.ceil(e),this.texture.write(this.data,0,0,n,e),this.dataPointer.set(.5,.5),this.filled=1,this.used=t},e.prototype.through=function(t,e){var n,r,i,o,a,u,h,l;return h=l=this.streamer,n=h.consume,r=h.done,o=(i=e.streamer).emit,a=0,u=function(){return n(function(e,n,r,i){return t(o,e,n,r,i,a)})},u=s.Data.repeatCall(u,this.items),function(t){return function(){var e;for(l.reset(),i.reset(),e=t.used,a=0;!r()&&e>a;)u(),a++;return l.count()}}(this)},e}(r),e.exports=i},{"../../util":175,"./buffer":125,"./texture/datatexture":134}],127:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./databuffer"),o=t("../../util"),i=function(t){function e(t,n,r){this.width=r.width||1,this.height=r.height||1,this.history=r.history||1,this.samples=this.width*this.height,this.wrap=this.history>1,r.depth=this.history,e.__super__.constructor.call(this,t,n,r)}return s(e,t),e.prototype.build=function(t){return e.__super__.build.apply(this,arguments),this.index=0,this.pad={x:0,y:0},this.streamer=this.generate(this.data)},e.prototype.getFilled=function(){return this.filled},e.prototype.setActive=function(t,e){var n;return n=[Math.max(0,this.width-t),Math.max(0,this.height-e)],this.pad.x=n[0],this.pad.y=n[1],n},e.prototype.fill=function(){var t,e,n,r,i,o,s,a,u,h,l,c,p,f;if(t=this.callback,"function"==typeof t.reset&&t.reset(),l=this.streamer,r=l.emit,f=l.skip,e=l.count,n=l.done,p=l.reset,p(),u=this.width,h=this.pad.x,a=this.samples-this.pad.y*u,i=o=s=0,h)for(;!n()&&a>s&&(s++,c=t(r,i,o),++i===u-h&&(f(h),i=0,o++),c!==!1););else for(;!n()&&a>s&&(s++,c=t(r,i,o),++i===u&&(i=0,o++),c!==!1););return Math.floor(e()/this.items)},e.prototype.write=function(t){var e,n;return null==t&&(t=this.samples),t*=this.items,n=this.width*this.items,e=Math.ceil(t/n),this.texture.write(this.data,0,this.index*this.height,n,e),this.dataPointer.set(.5,this.index*this.height+.5),this.index=(this.index+this.history-1)%this.history,this.filled=Math.min(this.history,this.filled+1)},e.prototype.through=function(t,e){var n,r,i,s,a,u,h,l,c;return l=c=this.streamer,n=l.consume,r=l.done,s=(i=e.streamer).emit,a=u=0,h=function(){return n(function(e,n,r,i){return t(s,e,n,r,i,a,u)})},h=o.Data.repeatCall(h,this.items),function(t){return function(){var e,n,o,s;if(c.reset(),i.reset(),o=t.width,s=t.pad.x,n=t.samples-t.pad.y*o,a=u=e=0,s)for(;!r()&&n>e;)e++,h(),++a===o-s&&(skip(s),a=0,u++);else for(;!r()&&n>e;)e++,h(),++a===o&&(a=0,u++);return c.count()}}(this)},e}(r),e.exports=i},{"../../util":175,"./databuffer":126}],128:[function(t,e,n){var r,i,o,s,a=function(t,e){function n(){this.constructor=t}for(var r in e)u.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},u={}.hasOwnProperty;o=t("../renderable"),i=t("./rendertotexture"),s=t("../../util"),r=function(t){function e(t,n,r){null==this.items&&(this.items=r.items||1),null==this.channels&&(this.channels=r.channels||4),null==this.width&&(this.width=r.width||1),null==this.height&&(this.height=r.height||1),null==this.depth&&(this.depth=r.depth||1),r.format=THREE.RGBAFormat,r.width=this._width=this.items*this.width,r.height=this._height=this.height*this.depth,r.frames=1,delete r.items,delete r.depth,delete r.channels,e.__super__.constructor.call(this,t,n,r),this._adopt({textureItems:{type:"f",value:this.items},textureHeight:{type:"f",value:this.height}})}return a(e,t),e.prototype.shaderAbsolute=function(t){return null==t&&(t=this.shaders.shader()),t.pipe("map.xyzw.texture",this.uniforms),e.__super__.shaderAbsolute.call(this,t,1,2)},e}(i),e.exports=r},{"../../util":175,"../renderable":161,"./rendertotexture":131}],129:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./buffer"),o=t("../../util"),i=function(t){function e(t,n,r){this.width=r.width||1,this.height=r.height||1,this.depth=r.depth||1,null==this.samples&&(this.samples=this.width*this.height*this.depth),e.__super__.constructor.call(this,t,n,r),this.build(r)}return s(e,t),e.prototype.build=function(t){return this.data=[],this.data.length=this.samples,this.filled=0,this.pad={x:0,y:0,z:0},this.streamer=this.generate(this.data)},e.prototype.dispose=function(){return this.data=null,e.__super__.dispose.apply(this,arguments)},e.prototype.getFilled=function(){return this.filled},e.prototype.setActive=function(t,e,n){var r;return r=[this.width-t,this.height-e,this.depth-n],this.pad.x=r[0],this.pad.y=r[1],this.pad.z=r[2],r},e.prototype.read=function(){return this.data},e.prototype.copy=function(t){var e,n,r,i,o,s;for(r=Math.min(t.length,this.samples),e=this.data,s=[],n=i=0,o=r;o>=0?o>i:i>o;n=o>=0?++i:--i)s.push(e[n]=t[n]);return s},e.prototype.fill=function(){var t,e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g;if(t=this.callback,"function"==typeof t.reset&&t.reset(),d=this.streamer,r=d.emit,g=d.skip,e=d.count,n=d.done,v=d.reset,v(),l=this.width,h=this.height,c=this.depth,p=this.pad.x,f=this.pad.y,u=this.samples-this.pad.z*l*h,i=o=s=a=0,p>0||f>0)for(;!n()&&u>a&&(a++,m=t(r,i,o,s),++i===l-p&&(g(p),i=0,++o===h-f&&(g(l*f),o=0,s++)),m!==!1););else for(;!n()&&u>a&&(a++,m=t(r,i,o,s),++i===l&&(i=0,++o===h&&(o=0,s++)),m!==!1););return this.filled=1,e()},e}(r),e.exports=i},{"../../util":175,"./buffer":125}],130:[function(t,e,n){var r,i,o,s,a,u,h=function(t,e){function n(){this.constructor=t}for(var r in e)l.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},l={}.hasOwnProperty;a=t("../renderable"),r=t("./buffer"),i=t("./memo"),o=t("../meshes/memoscreen"),u=t("../../util"),s=function(t){function e(t,n,r){null==this.items&&(this.items=r.items||1),null==this.channels&&(this.channels=r.channels||4),null==this.width&&(this.width=r.width||1),null==this.height&&(this.height=r.height||1),null==this.depth&&(this.depth=r.depth||1),null==this.type&&(this.type=r.type||THREE.FloatType),null==this.stpq&&(this.stpq=r.stpq||!1),this.isFloat=this.type===THREE.FloatType,this.active=this.sampled=this.rect=this.pad=null,e.__super__.constructor.call(this,t,n),this.build(r)}return h(e,t),e.prototype.build=function(t){var e,n,r,s,a,h,l,c,p,f,d,m,v,g;return p=t.map,h=t.indexer,l=null!=h&&!h.empty(),c=this.items,g=this.width,a=this.height,n=this.depth,d=this.stpq,f=p,l&&(this._adopt({indexModulus:{type:"v4",value:new THREE.Vector4(c,c*g,c*g*a,1)}}),f=this.shaders.shader(),f.require(p),f.require(h),f.pipe("float.index.pack",this.uniforms)),this.isFloat&&this.channels>1&&(this.floatMemo=new i(this.renderer,this.shaders,{items:c,channels:4,width:g,height:a,depth:n,history:0,type:THREE.FloatType}),this.floatCompose=new o(this.renderer,this.shaders,{map:f,items:c,width:g,height:a,depth:n,stpq:d}),this.floatMemo.adopt(this.floatCompose),d=!1,f=this.shaders.shader(),this.floatMemo.shaderAbsolute(f)),this.isFloat?(m=this.channels,e=4):(m=1,e=this.channels),m>1?(r=this.shaders.shader(),r.pipe(u.GLSL.mapByte2FloatOffset(m)),r.require(f),r.pipe("float.stretch"),r.pipe("float.encode"),f=r):this.isFloat&&(r=this.shaders.shader(),r.pipe(f),r.pipe(u.GLSL.truncateVec4(4,1)),r.pipe("float.encode"),f=r),this.byteMemo=new i(this.renderer,this.shaders,{items:c*m,channels:4,width:g,height:a,depth:n,history:0,type:THREE.UnsignedByteType}),this.byteCompose=new o(this.renderer,this.shaders,{map:f,items:c*m,width:g,height:a,depth:n,stpq:d}),this.byteMemo.adopt(this.byteCompose),v=c*g*m,s=a*n,this.samples=this.width*this.height*this.depth,this.bytes=new Uint8Array(v*s*4),this.isFloat&&(this.floats=new Float32Array(this.bytes.buffer)),this.data=this.isFloat?this.floats:this.bytes,this.streamer=this.generate(this.data),this.active={items:0,width:0,height:0,depth:0},this.sampled={items:0,width:0,height:0,depth:0},this.rect={w:0,h:0},this.pad={x:0,y:0,z:0,w:0},this.stretch=m,this.isIndexed=l,this.setActive(c,g,a,n)},e.prototype.generate=function(t){return u.Data.getStreamer(t,this.samples,4,this.items)},e.prototype.setActive=function(t,e,n,r){var i,o,s,a,u,h,l,c;if(t!==this.active.items||e!==this.active.width||n!==this.active.height||r!==this.active.depth)return o=[t,e,n,r],this.active.items=o[0], +this.active.width=o[1],this.active.height=o[2],this.active.depth=o[3],null!=(s=this.floatCompose)&&s.cover(e,n,r),null!=(a=this.byteCompose)&&a.cover(e*this.stretch,n,r),t=this.items,e=this.active.width,n=1===this.depth?this.active.height:this.height,r=this.active.depth,c=t*e*this.stretch,i=n*r,u=[t,e,n,r],this.sampled.items=u[0],this.sampled.width=u[1],this.sampled.height=u[2],this.sampled.depth=u[3],h=[c,i],this.rect.w=h[0],this.rect.h=h[1],l=[this.sampled.width-this.active.width,this.sampled.height-this.active.height,this.sampled.depth-this.active.depth,this.sampled.items-this.active.items],this.pad.x=l[0],this.pad.y=l[1],this.pad.z=l[2],this.pad.w=l[3],l},e.prototype.update=function(t){var e,n;return null!=(e=this.floatMemo)&&e.render(t),null!=(n=this.byteMemo)?n.render(t):void 0},e.prototype.post=function(){return this.renderer.setRenderTarget(this.byteMemo.target.write),this.gl.readPixels(0,0,this.rect.w,this.rect.h,gl.RGBA,gl.UNSIGNED_BYTE,this.bytes)},e.prototype.readFloat=function(t){var e;return null!=(e=this.floatMemo)?e.read(t):void 0},e.prototype.readByte=function(t){var e;return null!=(e=this.byteMemo)?e.read(t):void 0},e.prototype.setCallback=function(t){return this.emitter=this.callback(t)},e.prototype.callback=function(t){var e,n,r,i,o;return this.isIndexed?(r=this.width,n=this.height,i=this.depth,o=this.items,e=function(e,i,s,a){var u,h,l,c,p;return u=a,p=u%o,u=(u-p)/o,h=u%r,u=(u-h)/r,l=u%n,u=(u-l)/n,c=u,t(e,i,s,a,h,l,c,p)},e.reset=function(){return"function"==typeof t.reset?t.reset():void 0},e):t},e.prototype.iterate=function(){var t,e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b;for(i=this.emitter,"function"==typeof i.reset&&i.reset(),E=this.streamer,e=E.consume,b=E.skip,n=E.count,r=E.done,_=E.reset,_(),c=0|this.sampled.width,l=0|this.sampled.height,p=0|this.sampled.depth,f=0|this.sampled.items,m=0|this.pad.x,v=0|this.pad.y,g=0|this.pad.z,d=0|this.pad.w,h=c*l*f*(p-g),this.isIndexed||(t=i,i=function(e,n,r,i){return t(e,n,r,i,o,s,a,u)}),o=s=a=u=l=0;!r()&&h>l&&(l++,y=e(i),++u===f-d&&(b(m),u=0,++o===c-m&&(b(f*m),o=0,++s===l-v&&(b(f*c*v),s=0,a++))),y!==!1););return Math.floor(n()/f)},e.prototype.dispose=function(){var t,e,n,r,i,o;return null!=(t=this.floatMemo)&&t.unadopt(this.floatCompose),null!=(e=this.floatMemo)&&e.dispose(),null!=(n=this.floatCompose)&&n.dispose(),null!=(r=this.byteMemo)&&r.unadopt(this.byteCompose),null!=(i=this.byteMemo)&&i.dispose(),null!=(o=this.byteCompose)&&o.dispose(),this.floatMemo=this.byteMemo=this.floatCompose=this.byteCompose=null},e}(a),e.exports=s},{"../../util":175,"../meshes/memoscreen":155,"../renderable":161,"./buffer":125,"./memo":128}],131:[function(t,e,n){var r,i,o,s,a=function(t,e){function n(){this.constructor=t}for(var r in e)u.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},u={}.hasOwnProperty;o=t("../renderable"),r=t("./texture/rendertarget"),s=t("../../util"),i=function(t){function e(t,n,r){var i;this.scene=null!=(i=r.scene)?i:new THREE.Scene,this.camera=r.camera,e.__super__.constructor.call(this,t,n),this.build(r)}return a(e,t),e.prototype.shaderRelative=function(t){return null==t&&(t=this.shaders.shader()),t.pipe("sample.2d",this.uniforms)},e.prototype.shaderAbsolute=function(t,e,n){var r;return null==e&&(e=1),null==n&&(n=4),null==t&&(t=this.shaders.shader()),1>=e?(n>2&&t.pipe(s.GLSL.truncateVec(n,2)),t.pipe("map.2d.data",this.uniforms),t.pipe("sample.2d",this.uniforms)):(r=s.GLSL.sample2DArray(Math.min(e,this.target.frames)),4>n&&t.pipe(s.GLSL.extendVec(n,4)),t.pipe("map.xyzw.2dv"),t.split(),t.pipe("map.2d.data",this.uniforms),t.pass(),t.pipe(r,this.uniforms))},e.prototype.build=function(t){var e;return this.camera||(this.camera=new THREE.PerspectiveCamera,this.camera.position.set(0,0,3),this.camera.lookAt(new THREE.Vector3)),"function"==typeof(e=this.scene).inject&&e.inject(),this.target=new r(this.gl,t.width,t.height,t.frames,t),this.target.warmup(function(t){return function(e){return t.renderer.setRenderTarget(e)}}(this)),this.renderer.setRenderTarget(null),this._adopt(this.target.uniforms),this._adopt({dataPointer:{type:"v2",value:new THREE.Vector2(.5,.5)}}),this.filled=0},e.prototype.adopt=function(t){var e,n,r,i,o;for(i=t.renders,o=[],e=0,n=i.length;n>e;e++)r=i[e],o.push(this.scene.add(r));return o},e.prototype.unadopt=function(t){var e,n,r,i,o;for(i=t.renders,o=[],e=0,n=i.length;n>e;e++)r=i[e],o.push(this.scene.remove(r));return o},e.prototype.render=function(t){var e;return null==t&&(t=this.camera),this.renderer.render(null!=(e=this.scene.scene)?e:this.scene,t,this.target.write),this.target.cycle(),this.filled=0?d>l:l>d;h=d>=0?++l:--l)u=("00"+Math.max(0,8*-h+128-8*!h).toString(16)).slice(-2),r.push("#"+u+u+u);return m=new Uint8Array(p*c*2),this.canvas=n,this.context=o,this.lineHeight=c,this.maxWidth=p,this.colors=r,this.scratch=m,this._allocate=this.allocate.bind(this),this._write=this.write.bind(this)},e.prototype.reset=function(){return e.__super__.reset.apply(this,arguments),this.mapped={}},e.prototype.begin=function(){var t,e,n,r,i;for(n=this.rows,r=[],t=0,e=n.length;e>t;t++)i=n[t],r.push(i.alive=0);return r},e.prototype.end=function(){var t,e,n,r,i,o,s,a,u;for(o=this.mapped,s=this.rows.slice(),t=0,r=s.length;r>t;t++)if(u=s[t],0===u.alive){for(a=u.keys,n=0,i=a.length;i>n;n++)e=a[n],delete o[e];this.collapse(u)}},e.prototype.map=function(t,e){var n,r,i,o,s,a,u;return s=this.mapped,r=s[t],null!=r?(r.row.alive++,e(r.x,r.y,r.w,r.h)):(this.draw(t),i=this.scratch,a=this.scratchW,o=this.scratchH,n=this._allocate,u=this._write,n(t,a,o,function(n,r,h){return s[t]={x:r,y:h,w:a,h:o,row:n},u(i,r,h,a,o),e(r,h,a,o)}))},e.prototype.draw=function(t){var e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R;if(x=this.width,h=this.lineHeight,y=this.outline,o=this.context,a=this.scratch,g=this.maxWidth,i=this.colors,w=y+1,R=Math.round(1.05*h-1),m=o.measureText(t),x=Math.min(g,Math.ceil(m.width+2*w+1)),o.clearRect(0,0,x,h),0===this.outline){for(o.fillText(t,w,R),s=(c=o.getImageData(0,0,x,h)).data,p=3,l=f=0,_=s.length/4;_>=0?_>f:f>_;l=_>=0?++f:--f)a[l]=s[p],p+=4;return this.scratchW=x,this.scratchH=h}for(o.globalCompositeOperation="source-over",l=d=b=y+1;1>=b?1>=d:d>=1;l=1>=b?++d:--d)p=l>1?2*l-2:l,o.strokeStyle=i[p-1],o.lineWidth=p,o.strokeText(t,w,R);for(o.globalCompositeOperation="multiply",o.fillText(t,w,R),s=(c=o.getImageData(0,0,x,h)).data,p=0,u=this.gamma,l=E=0,T=s.length/4;T>=0?T>E:E>T;l=T>=0?++E:--E)e=s[p],v=e?s[p+1]/e:1,.5===u&&(v=Math.sqrt(v)),v=Math.min(1,Math.max(0,v)),n=256-e,r=n+(e-n)*v,a[l]=Math.max(0,Math.min(255,r+2)),p+=4;return this.scratchW=x,this.scratchH=h},e}(r),e.exports=o},{"./atlas":124}],133:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;o=t("../../../Util"),i=t("./datatexture"),r=function(t){function e(t,n,r,i,o){e.__super__.constructor.call(this,t,n,r,i,o),this.data=new this.ctor(this.n)}return s(e,t),e.prototype.resize=function(t,e){var n,r,i,o;return r=this.data,o=this.width,i=this.height,this.width=t,this.height=e,this.n=t*e*this.channels,this.data=new this.ctor(this.n),n=this.gl,n.bindTexture(n.TEXTURE_2D,this.texture),n.pixelStorei(n.UNPACK_ALIGNMENT,1),n.texImage2D(n.TEXTURE_2D,0,this.format,t,e,0,this.format,this.type,this.data),this.uniforms.dataResolution.value.set(1/t,1/e),this.write(r,0,0,o,i)},e.prototype.write=function(t,n,r,i,o){var s,a,u,h,l,c,p,f,d,m,v,g;if(f=this.width,a=this.data,s=this.channels,u=0,f===i&&0===n)for(h=r*i*s,c=i*o*s;c>u;)a[h++]=t[u++];else for(p=f*s,d=i*s,m=n*s,g=r,v=r+o;v>g;){for(l=0,h=m+g*p;l++=0?r>n:n>r;t=r>=0?++n:--n)i.push(e());return i}.call(this),this.reads=function(){var n,r,i;for(i=[],t=n=0,r=this.buffers;r>=0?r>n:n>r;t=r>=0?++n:--n)i.push(e());return i}.call(this),this.write=e(),this.index=0,this.uniforms={dataResolution:{type:"v2",value:new THREE.Vector2(1/this.width,1/this.height)},dataTexture:{type:"t",value:this.reads[0]},dataTextures:{type:"tv",value:this.reads}}},t.prototype.cycle=function(){var t,e,n,r,i,o,s,a,u;for(o=["__webglTexture","__webglFramebuffer","__webglRenderbuffer"],e=this.buffers,n=function(t,e){var n,r,i;for(n=0,i=o.length;i>n;n++)r=o[n],e[r]=t[r];return null},t=function(t,n){return(t+n+2*e)%e},n(this.write,this.targets[this.index]),u=this.reads,r=i=0,s=u.length;s>i;r=++i)a=u[r],n(this.targets[t(this.index,-r)],a);return this.index=t(this.index,1),n(this.targets[this.index],this.write)},t.prototype.warmup=function(t){var e,n,r,i;for(i=[],e=n=0,r=this.buffers;r>=0?r>n:n>r;e=r>=0?++n:--n)t(this.write),i.push(this.cycle());return i},t.prototype.dispose=function(){var t,e,n,r;for(n=this.targets,t=0,e=n.length;e>t;t++)r=n[t],r.dispose();return this.targets=this.reads=this.write=null},t}(),e.exports=r},{}],136:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./databuffer"),i=t("../../util"),o=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return s(e,t),e.prototype.build=function(t){return e.__super__.build.apply(this,arguments),this.pad={x:0,y:0,z:0},this.streamer=this.generate(this.data)},e.prototype.setActive=function(t,e,n){var r;return r=[Math.max(0,this.width-t),Math.max(0,this.height-e),Math.max(0,this.depth-n)],this.pad.x=r[0],this.pad.y=r[1],this.pad.z=r[2],r},e.prototype.fill=function(){var t,e,n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g;if(t=this.callback,"function"==typeof t.reset&&t.reset(),d=this.streamer,r=d.emit,g=d.skip,e=d.count,n=d.done,v=d.reset,v(),l=this.width,h=this.height,c=this.depth,p=this.pad.x,f=this.pad.y,u=this.samples-this.pad.z*l*h,i=o=s=a=0,p>0||f>0)for(;!n()&&u>a&&(a++,m=t(r,i,o,s),++i===l-p&&(g(p),i=0,++o===h-f&&(g(l*f),o=0,s++)),m!==!1););else for(;!n()&&u>a&&(a++,m=t(r,i,o,s),++i===l&&(i=0,++o===h&&(o=0,s++)),m!==!1););return Math.floor(e()/this.items)},e.prototype.through=function(t,e){var n,r,o,s,a,u,h,l,c,p;return c=p=this.streamer,n=c.consume,r=c.done,s=(o=e.streamer).emit,a=u=h=0,l=function(){return n(function(e,n,r,i){return t(s,e,n,r,i,a,u,h)})},l=i.Data.repeatCall(l,this.items),function(t){return function(){var e,n,i,s,c,f,d;if(p.reset(),o.reset(),s=t.width,i=t.height,c=t.depth,f=t.pad.x,d=t.pad.y,n=t.samples-t.pad.z*s*i,a=u=h=e=0,f>0||d>0)for(;!r()&&n>e;)e++,l(),++a===s-f&&(skip(f),a=0,++u===i-d&&(skip(s*d),u=0,h++));else for(;!r()&&n>e;)e++,l(),++a===s&&(a=0,++u===i&&(u=0,h++));return p.count()}}(this)},e}(r),e.exports=o},{"../../util":175,"./databuffer":126}],137:[function(t,e,n){var r;r={sprite:t("./meshes/sprite"),point:t("./meshes/point"),line:t("./meshes/line"),surface:t("./meshes/surface"),face:t("./meshes/face"),strip:t("./meshes/strip"),arrow:t("./meshes/arrow"),screen:t("./meshes/screen"),memoScreen:t("./meshes/memoscreen"),debug:t("./meshes/debug"),dataBuffer:t("./buffer/databuffer"),arrayBuffer:t("./buffer/arraybuffer"),matrixBuffer:t("./buffer/matrixbuffer"),voxelBuffer:t("./buffer/voxelbuffer"),pushBuffer:t("./buffer/pushbuffer"),renderToTexture:t("./buffer/rendertotexture"),memo:t("./buffer/memo"),readback:t("./buffer/readback"),atlas:t("./buffer/atlas"),textAtlas:t("./buffer/textatlas"),scene:t("./scene")},e.exports=r},{"./buffer/arraybuffer":123,"./buffer/atlas":124,"./buffer/databuffer":126,"./buffer/matrixbuffer":127,"./buffer/memo":128,"./buffer/pushbuffer":129,"./buffer/readback":130,"./buffer/rendertotexture":131,"./buffer/textatlas":132,"./buffer/voxelbuffer":136,"./meshes/arrow":150,"./meshes/debug":152,"./meshes/face":153,"./meshes/line":154,"./meshes/memoscreen":155,"./meshes/point":156,"./meshes/screen":157,"./meshes/sprite":158,"./meshes/strip":159,"./meshes/surface":160,"./scene":162}],138:[function(t,e,n){var r;r=function(){function t(t,e,n){this.classes=t,this.renderer=e,this.shaders=n}return t.prototype.getTypes=function(){return Object.keys(this.classes)},t.prototype.make=function(t,e){return new this.classes[t](this.renderer,this.shaders,e)},t}(),e.exports=r},{}],139:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("./clipgeometry"),r=function(t){function e(t){var n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k,A,C,P,L,z,O,D,F,U,B,N,V,I,j,G,W,q,X,Y;for(e.__super__.constructor.call(this,t),this._clipUniforms(),this.sides=V=+t.sides||12,this.samples=N=+t.samples||2,this.strips=j=+t.strips||1,this.ribbons=B=+t.ribbons||1,this.layers=_=+t.layers||1,this.flip=d=null!=(A=t.flip)?A:!1,this.anchor=r=null!=(C=t.anchor)?C:d?0:N-1,s=j*B*_,H=(V+2)*s,W=2*V*s,this.addAttribute("index",new THREE.BufferAttribute(new Uint16Array(3*W),1)),this.addAttribute("position4",new THREE.BufferAttribute(new Float32Array(4*H),4)),this.addAttribute("arrow",new THREE.BufferAttribute(new Float32Array(3*H),3)),this.addAttribute("attach",new THREE.BufferAttribute(new Float32Array(2*H),2)),this._autochunk(),v=this._emitter("index"),M=this._emitter("position4"),o=this._emitter("arrow"),a=this._emitter("attach"),p=[],E=g=0,P=V;P>=0?P>g:g>P;E=P>=0?++g:--g)i=E/V*τ,p.push([Math.cos(i),Math.sin(i),1]);for(l=0,m=b=0,L=s;L>=0?L>b:b>L;m=L>=0?++b:--b){for(G=l++,h=G+V+1,E=T=0,z=V;z>=0?z>T:T>z;E=z>=0?++T:--T)n=l+E%V,u=l+(E+1)%V,v(G),v(n),v(u),v(u),v(n),v(h);l+=V+1}for(I=d?1:-1,f=d?N-1:0,x=r+I,q=r,y=w=0,O=_;O>=0?O>w:w>O;y=O>=0?++w:--w)for(Y=R=0,D=B;D>=0?D>R:R>D;Y=D>=0?++R:--R)for(X=S=0,F=j;F>=0?F>S:S>F;X=F>=0?++S:--S){for(M(q,X,Y,y),o(0,0,0),a(x,f),E=k=0,U=V;U>=0?U>k:k>U;E=U>=0?++k:--k)M(q,X,Y,y),c=p[E],o(c[0],c[1],c[2]),a(x,f);M(q,X,Y,y),o(0,0,1),a(x,f)}this._finalize(),this.clip()}return o(e,t),e.prototype.clip=function(t,e,n,r){var i,o,s,a;return null==t&&(t=this.samples),null==e&&(e=this.strips),null==n&&(n=this.ribbons),null==r&&(r=this.layers),a=Math.max(0,t-1),this._clipGeometry(t,e,n,r),t>this.anchor?(i=[r,n,e],o=[this.layers,this.ribbons,this.strips],s=this.sides*this._reduce(i,o)):s=0,this._offsets([{start:0,count:6*s}])},e}(i),e.exports=r},{"./clipgeometry":140}],140:[function(t,e,n){var r,i,o,s,a=function(t,e){function n(){this.constructor=t}for(var r in e)u.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},u={}.hasOwnProperty;i=t("./geometry"),o=!1,s=function(){var t;return t=+new Date,function(e){var n;return n=+new Date-t,console.log(e,n+" ms"),n}},r=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return a(e,t),e.prototype._clipUniforms=function(){return this.geometryClip=new THREE.Vector4(1e10,1e10,1e10,1e10),this.geometryResolution=new THREE.Vector4,this.mapSize=new THREE.Vector4,null==this.uniforms&&(this.uniforms={}),this.uniforms.geometryClip={type:"v4",value:this.geometryClip},this.uniforms.geometryResolution={type:"v4",value:this.geometryResolution},this.uniforms.mapSize={type:"v4",value:this.mapSize}},e.prototype._clipGeometry=function(t,e,n,r){var i,o;return i=function(t){return Math.max(0,t-1)},o=function(t){return 1/Math.max(1,t-1)},this.geometryClip.set(i(t),i(e),i(n),i(r)),this.geometryResolution.set(o(t),o(e),o(n),o(r))},e.prototype._clipMap=function(t,e,n,r){return this.mapSize.set(t,e,n,r)},e.prototype._clipOffsets=function(t,e,n,r,i,o,s,a,u){var h,l,c;return h=[r,n,e,i],c=[a,s,o,u],l=this._reduce(h,c),this._offsets([{start:0,count:l*t}])},e}(i),e.exports=r},{"./geometry":142}],141:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("./clipgeometry"),i=function(t){function e(t){var n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k,A;for(e.__super__.constructor.call(this,t),this._clipUniforms(),this.items=a=+t.items||2,this.width=M=+t.width||1,this.height=i=+t.height||1,this.depth=r=+t.depth||1,this.sides=R=Math.max(0,a-2),w=M*i*r,m=a*w,H=R*w,this.addAttribute("index",new THREE.BufferAttribute(new Uint16Array(3*H),1)),this.addAttribute("position4",new THREE.BufferAttribute(new Float32Array(4*m),4)),this._autochunk(),s=this._emitter("index"),v=this._emitter("position4"),n=0,o=h=0,E=w;E>=0?E>h:h>E;o=E>=0?++h:--h){for(u=c=0,y=R;y>=0?y>c:c>y;u=y>=0?++c:--c)s(n),s(n+u+1),s(n+u+2);n+=a}for(A=p=0,_=r;_>=0?_>p:p>_;A=_>=0?++p:--p)for(k=f=0,b=i;b>=0?b>f:f>b;k=b>=0?++f:--f)for(S=d=0,T=M;T>=0?T>d:d>T;S=T>=0?++d:--d)for(l=g=0,x=a;x>=0?x>g:g>x;l=x>=0?++g:--g)v(S,k,A,l);this._finalize(),this.clip()}return o(e,t),e.prototype.clip=function(t,e,n,r){var i;return null==t&&(t=this.width),null==e&&(e=this.height),null==n&&(n=this.depth),null==r&&(r=this.items),i=Math.max(0,r-2),this._clipGeometry(t,e,n,r),this._clipOffsets(3,t,e,n,i,this.width,this.height,this.depth,this.sides)},e}(r),e.exports=i},{"./clipgeometry":140}],142:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=!1,o=function(){var t;return t=+new Date,function(e){var n;return n=+new Date-t,console.log(e,n+" ms"),n}},r=function(t){function e(){THREE.BufferGeometry.call(this),null==this.uniforms&&(this.uniforms={}),null==this.offsets&&(this.offsets=[]),i&&(this.tock=o()),this.chunked=!1,this.limit=65535}return s(e,t),e.prototype._reduce=function(t,e){var n,r,i,o,s,a,u;for(a=!1,r=i=0,o=t.length;o>i;r=++i)n=t[r],s=e[r],a&&(t[r]=s),n>1&&(a=!0);return u=t.reduce(function(t,e){return t*e})},e.prototype._emitter=function(t){var e,n,r,i,o,s,a,u;return n=this.attributes[t],r=n.itemSize,e=n.array,o=0,s=function(t){return e[o++]=t},u=function(t,n){return e[o++]=t,e[o++]=n},a=function(t,n,r){return e[o++]=t,e[o++]=n,e[o++]=r},i=function(t,n,r,i){return e[o++]=t,e[o++]=n,e[o++]=r,e[o++]=i},[null,s,u,a,i][r]},e.prototype._autochunk=function(){var t,e,n,r,i,o;n=this.attributes.index,o=this.attributes;for(r in o)if(e=o[r],"index"!==r&&n){i=e.array.length/e.itemSize,i>this.limit&&(this.chunked=!0);break}return this.chunked&&!n.u16?(n.u16=t=n.array,n.array=new Uint32Array(t.length)):void 0},e.prototype._finalize=function(){var t;if(this.chunked)return t=this.attributes.index,this.chunks=this._chunks(t.array,this.limit),this._chunkify(t,this.chunks),i?this.tock(this.constructor.name):void 0},e.prototype._chunks=function(t,e){var n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E;for(i=[],f=0,E=t[0],o=t[0],v=function(t){var e,n,r;return r=3*f,n=3*t,e=n-r,i.push({index:E,start:r,count:e,end:n})},d=Math.floor(t.length/3),m=0,s=a=0,g=d;g>=0?g>a:a>g;s=g>=0?++a:--a)u=t[m++],h=t[m++],l=t[m++],p=Math.min(u,h,l),c=Math.max(u,h,l),n=Math.min(E,p),r=Math.max(o,c),r-n>e&&(v(s),n=p,r=c,f=s),E=n,o=r;return v(d),i},e.prototype._chunkify=function(t,e){var n,r,i,o,s,a,u,h,l,c;if(t.u16){for(r=t.array,c=t.u16,o=0,a=e.length;a>o;o++)for(n=e[o],u=n.index,i=s=h=n.start,l=n.end;l>=h?l>s:s>l;i=l>=h?++s:--s)c[i]=r[i]-u;return t.array=t.u16,delete t.u16}},e.prototype._offsets=function(t){var e,n,r,i,o,s,a,u,h,l,c,p;if(this.chunked)for(i=this.chunks,c=this.offsets,c.length=null,s=0,u=t.length;u>s;s++)for(l=t[s],p=l.start,o=l.count-p,a=0,h=i.length;h>a;a++)r=i[a],n=r.start,e=r.end,(n>=p&&o>n||e>p&&o>=e||p>n&&e>o)&&(n=Math.max(p,n),e=Math.min(o,e),c.push({index:r.index,start:n,count:e-n}));else this.offsets=t;return null},e}(THREE.BufferGeometry),e.exports=r},{}],143:[function(t,e,n){n.Geometry=t("./geometry"),n.ArrowGeometry=t("./arrowgeometry"),n.FaceGeometry=t("./facegeometry"),n.LineGeometry=t("./linegeometry"),n.ScreenGeometry=t("./screengeometry"),n.SpriteGeometry=t("./spritegeometry"),n.StripGeometry=t("./stripgeometry"),n.SurfaceGeometry=t("./surfacegeometry")},{"./arrowgeometry":139,"./facegeometry":141,"./geometry":142,"./linegeometry":144,"./screengeometry":145,"./spritegeometry":146,"./stripgeometry":147,"./surfacegeometry":148}],144:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("./clipgeometry"),i=function(t){function e(t){var n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k,A,C,P,L,z,O,D,F,U,B,N,V,I,j,G,W,q,X,Y,Z,K,Q,J,$,tt,et;for(e.__super__.constructor.call(this,t),this._clipUniforms(),this.closed=o=t.closed||!1,this.samples=I=(+t.samples||2)+(o?1:0),this.strips=W=+t.strips||1,this.ribbons=N=+t.ribbons||1,this.layers=v=+t.layers||1,this.detail=s=+t.detail||1,E=I-1,this.joints=f=s-1,this.vertices=K=(E-1)*f+I,this.segments=j=(E-1)*f+E,J=I-(o?1:0),x=K*W*N*v*2,H=j*W*N*v,X=2*H,this.addAttribute("index",new THREE.BufferAttribute(new Uint16Array(3*X),1)),this.addAttribute("position4",new THREE.BufferAttribute(new Float32Array(4*x),4)),this.addAttribute("line",new THREE.BufferAttribute(new Float32Array(2*x),2)),this.addAttribute("strip",new THREE.BufferAttribute(new Float32Array(2*x),2)),s>1&&this.addAttribute("joint",new THREE.BufferAttribute(new Float32Array(x),1)),this._autochunk(),l=this._emitter("index"),w=this._emitter("position4"),g=this._emitter("line"),G=this._emitter("strip"),s>1&&(p=this._emitter("joint")),i=0,h=_=0,S=N*v;S>=0?S>_:_>S;h=S>=0?++_:--_)for(c=b=0,k=W;k>=0?k>b:b>k;c=k>=0?++b:--b){for(d=T=0,P=j;P>=0?P>T:T>P;d=P>=0?++T:--T)l(i),l(i+1),l(i+2),l(i+2),l(i+1),l(i+3),i+=2;i+=2}if(u=o?function(){return 0}:function(t){return 0===t?-1:t===I-1?1:0},s>1)for(m=R=0,L=v;L>=0?L>R:R>L;m=L>=0?++R:--R)for(et=M=0,z=N;z>=0?z>M:M>z;et=z>=0?++M:--M)for(tt=V=0,O=W;O>=0?O>V:V>O;tt=O>=0?++V:--V)for($=q=0,D=I;D>=0?D>q:q>D;$=D>=0?++q:--q)if(o&&($%=J),a=u($),0!==a)w($,tt,et,m),w($,tt,et,m),g(a,1),g(a,-1),G(0,j),G(0,j),p(.5),p(.5);else for(y=Y=0,F=s;F>=0?F>Y:Y>F;y=F>=0?++Y:--Y)w($,tt,et,m),w($,tt,et,m),g(a,1),g(a,-1),G(0,j),G(0,j),p(y/f),p(y/f);else for(m=Z=0,U=v;U>=0?U>Z:Z>U;m=U>=0?++Z:--Z)for(et=Q=0,B=N;B>=0?B>Q:Q>B;et=B>=0?++Q:--Q)for(tt=n=0,A=W;A>=0?A>n:n>A;tt=A>=0?++n:--n)for($=r=0,C=I;C>=0?C>r:r>C;$=C>=0?++r:--r)o&&($%=J),a=u($),w($,tt,et,m),w($,tt,et,m),g(a,1),g(a,-1),G(0,j),G(0,j);this._finalize(),this.clip()}return o(e,t),e.prototype.clip=function(t,e,n,r){var i,o;return null==t&&(t=this.samples-this.closed),null==e&&(e=this.strips),null==n&&(n=this.ribbons),null==r&&(r=this.layers),i=Math.max(0,t-(this.closed?0:1)),o=t+(t-2)*this.joints,i=o-1,this._clipGeometry(o,e,n,r),this._clipOffsets(6,i,e,n,r,this.segments,this.strips,this.ribbons,this.layers)},e}(r),e.exports=i},{"./clipgeometry":140}],145:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;i=t("./surfacegeometry"),r=function(t){function e(t){var n,r;null==this.uniforms&&(this.uniforms={}),this.uniforms.geometryScale={type:"v4",value:new THREE.Vector4},t.width=Math.max(2,null!=(n=+t.width)?n:2),t.height=Math.max(2,null!=(r=+t.height)?r:2),this.cover(),e.__super__.constructor.call(this,t)}return o(e,t),e.prototype.cover=function(t,e,n,r){this.scaleX=null!=t?t:1,this.scaleY=null!=e?e:1,this.scaleZ=null!=n?n:1,this.scaleW=null!=r?r:1},e.prototype.clip=function(t,n,r,i){var o;return null==t&&(t=this.width),null==n&&(n=this.height),null==r&&(r=this.surfaces),null==i&&(i=this.layers),e.__super__.clip.call(this,t,n,r,i),o=function(t){return 1/Math.max(1,t-1)},this.uniforms.geometryScale.value.set(o(t)*this.scaleX,o(n)*this.scaleY,o(r)*this.scaleZ,o(i)*this.scaleW)},e}(i),e.exports=r},{"./surfacegeometry":148}],146:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("./clipgeometry"),i=function(t){function e(t){var n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k,A,C;for(e.__super__.constructor.call(this,t),this._clipUniforms(),this.items=a=+t.items||2,this.width=S=+t.width||1,this.height=i=+t.height||1,this.depth=r=+t.depth||1,w=a*S*i*r,v=4*w,H=2*w,this.addAttribute("index",new THREE.BufferAttribute(new Uint16Array(3*H),1)),this.addAttribute("position4",new THREE.BufferAttribute(new Float32Array(4*v),4)),this.addAttribute("sprite",new THREE.BufferAttribute(new Float32Array(2*v),2)),this._autochunk(),s=this._emitter("index"),g=this._emitter("position4"),R=this._emitter("sprite"),E=[[-1,-1],[-1,1],[1,-1],[1,1]],n=0,o=u=0,y=w;y>=0?y>u:u>y;o=y>=0?++u:--u)s(n),s(n+1),s(n+2),s(n+1),s(n+2),s(n+3),n+=4;for(C=h=0,_=r;_>=0?_>h:h>_;C=_>=0?++h:--h)for(A=p=0,b=i;b>=0?b>p:p>b;A=b>=0?++p:--p)for(k=f=0,T=S;T>=0?T>f:f>T;k=T>=0?++f:--f)for(l=d=0,x=a;x>=0?x>d:d>x;l=x>=0?++d:--d)for(m=0,c=E.length;c>m;m++)M=E[m],g(k,A,C,l),R(M[0],M[1]);this._finalize(),this.clip()}return o(e,t),e.prototype.clip=function(t,e,n,r){return null==t&&(t=this.width),null==e&&(e=this.height),null==n&&(n=this.depth),null==r&&(r=this.items),this._clipGeometry(t,e,n,r),this._clipOffsets(6,t,e,n,r,this.width,this.height,this.depth,this.items)},e}(r),e.exports=i},{"./clipgeometry":140}],147:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("./clipgeometry"),i=function(t){function e(t){var n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k,A,C,P,L,z;for(e.__super__.constructor.call(this,t),this._clipUniforms(),this.items=u=+t.items||2,this.width=C=+t.width||1,this.height=o=+t.height||1,this.depth=r=+t.depth||1,this.sides=S=Math.max(0,u-2),M=C*o*r,g=u*M,A=S*M,this.addAttribute("index",new THREE.BufferAttribute(new Uint16Array(3*A),1)),this.addAttribute("position4",new THREE.BufferAttribute(new Float32Array(4*g),4)),this.addAttribute("strip",new THREE.BufferAttribute(new Float32Array(3*g),3)),this._autochunk(),a=this._emitter("index"),E=this._emitter("position4"),k=this._emitter("strip"),n=0,s=l=0,b=M;b>=0?b>l:l>b;s=b>=0?++l:--l){for(m=n,h=f=0,T=S;T>=0?T>f:f>T;h=T>=0?++f:--f)1&h?(a(m+1),a(m),a(m+2)):(a(m),a(m+1),a(m+2)),m++;n+=u}for(p=u-1,z=d=0,x=r;x>=0?x>d:d>x;z=x>=0?++d:--d)for(L=v=0,w=o;w>=0?w>v:v>w;L=w>=0?++v:--v)for(P=y=0,R=C;R>=0?R>y:y>R;P=R>=0?++y:--y){for(i=1,E(P,L,z,0),k(1,2,i),c=_=1,H=p;H>=1?H>_:_>H;c=H>=1?++_:--_)E(P,L,z,c),k(c-1,c+1,i=-i);E(P,L,z,p),k(p-2,p-1,-i)}this._finalize(),this.clip()}return o(e,t),e.prototype.clip=function(t,e,n,r){var i;return null==t&&(t=this.width),null==e&&(e=this.height),null==n&&(n=this.depth),null==r&&(r=this.items),i=Math.max(0,r-2),this._clipGeometry(t,e,n,r),this._clipOffsets(3,t,e,n,i,this.width,this.height,this.depth,this.sides)},e}(r),e.exports=i},{"./clipgeometry":140}],148:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("./clipgeometry"),i=function(t){function e(t){var n,r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k,A,C,P,L,z,O,D,F,U,B,N,V,I,j; +for(e.__super__.constructor.call(this,t),this._clipUniforms(),this.closedX=r=t.closedX||!1,this.closedY=i=t.closedY||!1,this.width=U=(+t.width||2)+(r?1:0),this.height=h=(+t.height||2)+(i?1:0),this.surfaces=D=+t.surfaces||1,this.layers=m=+t.layers||1,B=U-(r?1:0),N=h-(i?1:0),this.segmentsX=L=Math.max(0,U-1),this.segmentsY=z=Math.max(0,h-1),_=U*h*D*m,x=L*z*D*m,F=2*x,this.addAttribute("index",new THREE.BufferAttribute(new Uint16Array(3*F),1)),this.addAttribute("position4",new THREE.BufferAttribute(new Float32Array(4*_),4)),this.addAttribute("surface",new THREE.BufferAttribute(new Float32Array(2*_),2)),this._autochunk(),c=this._emitter("index"),b=this._emitter("position4"),O=this._emitter("surface"),n=0,l=v=0,R=D*m;R>=0?R>v:v>R;l=R>=0?++v:--v){for(p=g=0,H=z;H>=0?H>g:g>H;p=H>=0?++g:--g){for(f=E=0,M=L;M>=0?M>E:E>M;f=M>=0?++E:--E)c(n),c(n+1),c(n+U),c(n+U),c(n+1),c(n+U+1),n++;n++}n+=U}for(a=r?function(){return 0}:function(t){return 0===t?-1:t===L?1:0},u=i?function(){return 0}:function(t){return 0===t?-1:t===z?1:0},d=y=0,S=m;S>=0?S>y:y>S;d=S>=0?++y:--y)for(j=T=0,k=D;k>=0?k>T:T>k;j=k>=0?++T:--T)for(I=w=0,A=h;A>=0?A>w:w>A;I=A>=0?++w:--w)for(i&&(I%=N),s=u(I),V=P=0,C=U;C>=0?C>P:P>C;V=C>=0?++P:--P)r&&(V%=B),o=a(V),b(V,I,j,d),O(o,s);this._finalize(),this.clip()}return o(e,t),e.prototype.clip=function(t,e,n,r){var i,o;return null==t&&(t=this.width),null==e&&(e=this.height),null==n&&(n=this.surfaces),null==r&&(r=this.layers),i=Math.max(0,t-1),o=Math.max(0,e-1),this._clipGeometry(t,e,n,r),this._clipOffsets(6,i,o,n,r,this.segmentsX,this.segmentsY,this.surfaces,this.layers)},e.prototype.map=function(t,e,n,r){return null==t&&(t=this.width),null==e&&(e=this.height),null==n&&(n=this.surfaces),null==r&&(r=this.layers),this._clipMap(t,e,n,r)},e}(r),e.exports=i},{"./clipgeometry":140}],149:[function(t,e,n){n.Scene=t("./scene"),n.Factory=t("./factory"),n.Renderable=t("./scene"),n.Classes=t("./classes")},{"./classes":137,"./factory":138,"./scene":162}],150:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;o=t("./base"),i=t("../geometry").ArrowGeometry,r=function(t){function e(t,n,r){var o,s,a,u,h,l,c,p,f,d,m,v,g,E;e.__super__.constructor.call(this,t,n,r),g=r.uniforms,f=r.material,m=r.position,o=r.color,p=r.mask,c=r.map,s=r.combine,v=r.stpq,l=r.linear,null==g&&(g={}),h=null!=g.styleColor,this.geometry=new i({sides:r.sides,samples:r.samples,strips:r.strips,ribbons:r.ribbons,layers:r.layers,anchor:r.anchor,flip:r.flip}),this._adopt(g),this._adopt(this.geometry.uniforms),u=n.material(),E=u.vertex,E.pipe(this._vertexColor(o,p)),E.require(this._vertexPosition(m,f,c,1,v)),E.pipe("arrow.position",this.uniforms),E.pipe("project.position",this.uniforms),u.fragment=a=this._fragmentColor(h,f,o,p,c,1,v,s,l),a.pipe("fragment.color",this.uniforms),this.material=this._material(u.link({})),d=new THREE.Mesh(this.geometry,this.material),d.frustumCulled=!1,d.matrixAutoUpdate=!1,this._raw(d),this.renders=[d]}return s(e,t),e.prototype.dispose=function(){return this.geometry.dispose(),this.material.dispose(),this.renders=this.geometry=this.material=null,e.__super__.dispose.apply(this,arguments)},e}(o),e.exports=r},{"../geometry":143,"./base":151}],151:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../renderable"),o=t("../../util"),r=function(t){function e(t,n,r){var i;e.__super__.constructor.call(this,t,n,r),this.zUnits=null!=(i=r.zUnits)?i:0}return s(e,t),e.prototype.raw=function(){var t,e,n,r;for(r=this.renders,t=0,e=r.length;e>t;t++)n=r[t],this._raw(n);return null},e.prototype.depth=function(t,e){var n,r,i,o;for(o=this.renders,n=0,r=o.length;r>n;n++)i=o[n],this._depth(i,t,e);return null},e.prototype.polygonOffset=function(t,e){var n,r,i,o;for(o=this.renders,n=0,r=o.length;r>n;n++)i=o[n],this._polygonOffset(i,t,e);return null},e.prototype.show=function(t,e,n){var r,i,o,s,a;for(s=this.renders,a=[],r=0,i=s.length;i>r;r++)o=s[r],a.push(this._show(o,t,e,n));return a},e.prototype.hide=function(){var t,e,n,r;for(r=this.renders,t=0,e=r.length;e>t;t++)n=r[t],this._hide(n);return null},e.prototype._material=function(t){var e,n,r,i,o,s,a,u;for(s=this.renderer.getPrecision(),u=" precision "+s+" float;\n precision "+s+" int;\nuniform mat4 modelMatrix;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewMatrix;\nuniform mat3 normalMatrix;\nuniform vec3 cameraPosition;",e=" precision "+s+" float;\n precision "+s+" int;\nuniform mat4 viewMatrix;\nuniform vec3 cameraPosition;",o=new THREE.RawShaderMaterial(t),a=["vertexGraph","fragmentGraph"],n=0,i=a.length;i>n;n++)r=a[n],o[r]=t[r];return o.vertexShader=[u,o.vertexShader].join("\n"),o.fragmentShader=[e,o.fragmentShader].join("\n"),o},e.prototype._raw=function(t){return t.rotationAutoUpdate=!1,t.frustumCulled=!1,t.matrixAutoUpdate=!1,t.material.defaultAttributeValues=void 0},e.prototype._depth=function(t,e,n){var r;return r=t.material,r.depthWrite=e,r.depthTest=n},e.prototype._polygonOffset=function(t,e,n){var r,i;return n-=this.zUnits,r=0!==n,i=t.material,i.polygonOffset=r,r?(i.polygonOffsetFactor=e,i.polygonOffsetUnits=n):void 0},e.prototype._show=function(t,e,n,r){var i;return e=!0,i=t.material,t.renderOrder=-r,t.visible=!0,i.transparent=e,i.blending=n,null},e.prototype._hide=function(t){return t.visible=!1},e.prototype._vertexColor=function(t,e){var n;if(t||e)return n=this.shaders.shader(),t&&(n.require(t),n.pipe("mesh.vertex.color",this.uniforms)),e&&(n.require(e),n.pipe("mesh.vertex.mask",this.uniforms)),n},e.prototype._vertexPosition=function(t,e,n,r,i){var o,s;return s=this.shaders.shader(),(n||e&&e!==!0)&&(o={},(r>0||i)&&(o.POSITION_MAP=""),r>0&&(o[["POSITION_U","POSITION_UV","POSITION_UVW","POSITION_UVWO"][r-1]]=""),i&&(o.POSITION_STPQ="")),s.require(t),s.pipe("mesh.vertex.position",this.uniforms,o)},e.prototype._fragmentColor=function(t,e,n,r,i,s,a,u,h){var l,c,p,f;return c=this.shaders.shader(),f=!1,p=!1,l={},s>0&&(l[["POSITION_U","POSITION_UV","POSITION_UVW","POSITION_UVWO"][s-1]]=""),a&&(l.POSITION_STPQ=""),t&&(c.pipe("style.color",this.uniforms),f=!0,(n||i||e)&&((!h||n)&&c.pipe("mesh.gamma.in"),p=!0)),n&&(c.isolate(),c.pipe("mesh.fragment.color",this.uniforms),(!h||f)&&c.pipe("mesh.gamma.in"),c.end(),f&&c.pipe(o.GLSL.binaryOperator("vec4","*")),h&&f&&c.pipe("mesh.gamma.out"),f=!0,p=!0),i&&(!f&&u&&c.pipe(o.GLSL.constant("vec4","vec4(1.0)")),c.isolate(),c.require(i),c.pipe("mesh.fragment.map",this.uniforms,l),h||c.pipe("mesh.gamma.in"),c.end(),u?c.pipe(u):f&&c.pipe(o.GLSL.binaryOperator("vec4","*")),f=!0,p=!0),e&&(f||c.pipe(o.GLSL.constant("vec4","vec4(1.0)")),e===!0?c.pipe("mesh.fragment.shaded",this.uniforms):(c.require(e),c.pipe("mesh.fragment.material",this.uniforms,l)),p=!0),p&&!h&&c.pipe("mesh.gamma.out"),r&&(c.pipe("mesh.fragment.mask",this.uniforms),f&&c.pipe(o.GLSL.binaryOperator("vec4","*"))),c},e}(i),e.exports=r},{"../../util":175,"../renderable":161}],152:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("./base"),i=function(t){function e(t,n,r){var i;e.__super__.constructor.call(this,t,n,r),this.geometry=new THREE.PlaneGeometry(1,1),this.material=new THREE.MeshBasicMaterial({map:r.map}),this.material.side=THREE.DoubleSide,i=new THREE.Mesh(this.geometry,this.material),i.position.x+=r.x||0,i.position.y+=r.y||0,i.frustumCulled=!1,i.scale.set(2,2,2),i.__debug=!0,this.objects=[i]}return o(e,t),e.prototype.dispose=function(){return this.geometry.dispose(),this.material.dispose(),this.objects=this.geometry=this.material=null,e.__super__.dispose.apply(this,arguments)},e}(r),e.exports=i},{"./base":151}],153:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./base"),o=t("../geometry").FaceGeometry,i=function(t){function e(t,n,r){var i,s,a,u,h,l,c,p,f,d,m,v,g,E;e.__super__.constructor.call(this,t,n,r),g=r.uniforms,f=r.material,m=r.position,i=r.color,p=r.mask,c=r.map,s=r.combine,v=r.stpq,l=r.linear,null==g&&(g={}),null==f&&(f=!0),h=null!=g.styleColor,this.geometry=new o({items:r.items,width:r.width,height:r.height,depth:r.depth}),this._adopt(g),this._adopt(this.geometry.uniforms),u=n.material(),E=u.vertex,E.pipe(this._vertexColor(i,p)),E.require(this._vertexPosition(m,f,c,2,v)),f||E.pipe("face.position",this.uniforms),f&&E.pipe("face.position.normal",this.uniforms),E.pipe("project.position",this.uniforms),u.fragment=a=this._fragmentColor(h,f,i,p,c,2,v,s,l),a.pipe("fragment.color",this.uniforms),this.material=this._material(u.link({side:THREE.DoubleSide})),d=new THREE.Mesh(this.geometry,this.material),this._raw(d),this.renders=[d]}return s(e,t),e.prototype.dispose=function(){return this.geometry.dispose(),this.material.dispose(),this.renders=this.geometry=this.material=null,e.__super__.dispose.apply(this,arguments)},e}(r),e.exports=i},{"../geometry":143,"./base":151}],154:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./base"),o=t("../geometry").LineGeometry,i=function(t){function e(t,n,r){var i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R;e.__super__.constructor.call(this,t,n,r),w=r.uniforms,g=r.material,y=r.position,s=r.color,v=r.mask,m=r.map,a=r.combine,T=r.stpq,d=r.linear,i=r.clip,x=r.stroke,f=r.join,_=r.proximity,null==w&&(w={}),x=[null,"dotted","dashed"][x],p=null!=w.styleColor,f=null!=(b=["miter","round","bevel"][f])?b:"miter",h={miter:1,round:4,bevel:2}[f],this.geometry=new o({samples:r.samples,strips:r.strips,ribbons:r.ribbons,layers:r.layers,anchor:r.anchor,closed:r.closed,detail:h}),this._adopt(w),this._adopt(this.geometry.uniforms),c=n.material(),u={},x&&(u.LINE_STROKE=""),i&&(u.LINE_CLIP=""),null!=_&&(u.LINE_PROXIMITY=""),u["LINE_JOIN_"+f.toUpperCase()]="",h>1&&(u.LINE_JOIN_DETAIL=h),R=c.vertex,R.pipe(this._vertexColor(s,v)),R.require(this._vertexPosition(y,g,m,2,T)),R.pipe("line.position",this.uniforms,u),R.pipe("project.position",this.uniforms),l=c.fragment,x&&l.pipe("fragment.clip."+x,this.uniforms),i&&l.pipe("fragment.clip.ends",this.uniforms),null!=_&&l.pipe("fragment.clip.proximity",this.uniforms),l.pipe(this._fragmentColor(p,g,s,v,m,2,T,a,d)),l.pipe("fragment.color",this.uniforms),this.material=this._material(c.link({side:THREE.DoubleSide})),E=new THREE.Mesh(this.geometry,this.material),this._raw(E),this.renders=[E]}return s(e,t),e.prototype.dispose=function(){return this.geometry.dispose(),this.material.dispose(),this.renders=this.geometry=this.material=null,e.__super__.dispose.apply(this,arguments)},e}(r),e.exports=i},{"../geometry":143,"./base":151}],155:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("./screen"),o=t("../../util"),r=function(t){function e(t,n,r){var i,o,s,a,u,h,l,c,p,f,d,m;for(this.memo=(h=r.items,m=r.width,o=r.height,i=r.depth,d=r.stpq,r),a=function(t){return 1/Math.max(1,t)},u=function(t){return 1/Math.max(1,t-1)},this.uniforms={remapUVScale:{type:"v2",value:new THREE.Vector2(h*m,o*i)},remapModulus:{type:"v2",value:new THREE.Vector2(h,o)},remapModulusInv:{type:"v2",value:new THREE.Vector2(a(h),a(o))},remapSTPQScale:{type:"v4",value:new THREE.Vector4(u(m),u(o),u(i),u(h))}},c=n.shader(),c.pipe("screen.map.xyzw",this.uniforms),null!=r.map&&(d&&c.pipe("screen.map.stpq",this.uniforms),c.pipe(r.map)),e.__super__.constructor.call(this,t,n,{map:c,linear:!0}),f=this.renders,s=0,l=f.length;l>s;s++)p=f[s],p.transparent=!1}return s(e,t),e.prototype.cover=function(t,e,n,r){var i,o,s;return null==t&&(t=this.memo.width),null==e&&(e=this.memo.height),null==n&&(n=this.memo.depth),null==r&&(r=this.memo.items),i=function(t){return 1/Math.max(1,t-1)},this.uniforms.remapSTPQScale.value.set(i(t),i(e),i(n),i(r)),o=t/this.memo.width,s=n/this.memo.depth,1===this.memo.depth&&(s=e/this.memo.height),this.geometry.cover(o,s)},e}(i),e.exports=r},{"../../util":175,"./screen":157}],156:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./base"),o=t("../geometry").SpriteGeometry,i=function(t){function e(t,n,r){var i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k,A,C,P,L,z,O;e.__super__.constructor.call(this,t,n,r),z=r.uniforms,_=r.material,w=r.position,u=r.color,P=r.size,y=r.mask,E=r.map,h=r.combine,g=r.linear,A=r.shape,b=r.optical,d=r.fill,L=r.stpq,null==z&&(z={}),A=null!=(R=+A)?R:0,null==d&&(d=!0),v=null!=z.styleColor,C=["circle","square","diamond","up","down","left","right"],x=["circle","generic","generic","generic","generic","generic","generic"],k=[1.2,1,1.414,1.16,1.16,1.16,1.16],T=null!=(H=x[A])?H:x[0],s=null!=(M=C[A])?M:C[0],i=null!=(S=b&&k[A])?S:1,a=d?T:T+".hollow",this.geometry=new o({items:r.items,width:r.width,height:r.height,depth:r.depth}),this._adopt(z),this._adopt(this.geometry.uniforms),l={POINT_SHAPE_SCALE:+(i+1e-5)},f=n.material(),O=f.vertex,O.pipe(this._vertexColor(u,y)),P?(O.isolate(),O.require(P),O.require("point.size.varying",this.uniforms),O.end()):O.require("point.size.uniform",this.uniforms),O.require(this._vertexPosition(w,_,E,2,L)),O.pipe("point.position",this.uniforms,l),O.pipe("project.position",this.uniforms),f.fragment=p=this._fragmentColor(v,_,u,y,E,2,L,h,g),c=n.material(),c.vertex.pipe(O),p=c.fragment.pipe(f.fragment),p.require("point.mask."+s,this.uniforms),p.require("point.alpha."+a,this.uniforms),p.pipe("point.edge",this.uniforms),m=n.material(),m.vertex.pipe(O),p=m.fragment.pipe(f.fragment),p.require("point.mask."+s,this.uniforms),p.require("point.alpha."+a,this.uniforms),p.pipe("point.fill",this.uniforms),this.fillMaterial=this._material(m.link({side:THREE.DoubleSide})),this.edgeMaterial=this._material(c.link({side:THREE.DoubleSide})),this.fillObject=new THREE.Mesh(this.geometry,this.fillMaterial),this.edgeObject=new THREE.Mesh(this.geometry,this.edgeMaterial),this._raw(this.fillObject),this._raw(this.edgeObject),this.renders=[this.fillObject,this.edgeObject]}return s(e,t),e.prototype.show=function(t,e,n,r){return this._show(this.edgeObject,!0,e,n,r),this._show(this.fillObject,t,e,n,r)},e.prototype.dispose=function(){return this.geometry.dispose(),this.edgeMaterial.dispose(),this.fillMaterial.dispose(),this.renders=this.edgeObject=this.fillObject=this.geometry=this.edgeMaterial=this.fillMaterial=null,e.__super__.dispose.apply(this,arguments)},e}(r),e.exports=i},{"../geometry":143,"./base":151}],157:[function(t,e,n){var r,i,o,s,a=function(t,e){function n(){this.constructor=t}for(var r in e)u.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},u={}.hasOwnProperty;r=t("./base"),o=t("../geometry").ScreenGeometry,s=t("../../util"),i=function(t){function e(t,n,r){var i,s,a,u,h,l,c,p,f,d;e.__super__.constructor.call(this,t,n,r),f=r.uniforms,l=r.map,i=r.combine,p=r.stpq,h=r.linear,null==f&&(f={}),u=null!=f.styleColor,this.geometry=new o({width:r.width,height:r.height}),this._adopt(f),this._adopt(this.geometry.uniforms),a=n.material(),d=a.vertex,d.pipe("raw.position.scale",this.uniforms),d.fan(),d.pipe("stpq.xyzw.2d",this.uniforms),d.next(),d.pipe("screen.position",this.uniforms),d.join(),a.fragment=s=this._fragmentColor(u,!1,null,null,l,2,p,i,h),s.pipe("fragment.color",this.uniforms),this.material=this._material(a.link({side:THREE.DoubleSide})),c=new THREE.Mesh(this.geometry,this.material),c.frustumCulled=!1,this._raw(c),this.renders=[c]}return a(e,t),e.prototype.dispose=function(){return this.geometry.dispose(),this.material.dispose(),this.renders=this.geometry=this.material=null,e.__super__.dispose.apply(this,arguments)},e}(r),e.exports=i},{"../../util":175,"../geometry":143,"./base":151}],158:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./base"),o=t("../geometry").SpriteGeometry,i=function(t){function e(t,n,r){var i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_;e.__super__.constructor.call(this,t,n,r),y=r.uniforms,m=r.material,v=r.position,g=r.sprite,f=r.map,s=r.combine,p=r.linear,i=r.color,d=r.mask,E=r.stpq,null==y&&(y={}),c=null!=y.styleColor,this.geometry=new o({items:r.items,width:r.width,height:r.height,depth:r.depth}),this._adopt(y),this._adopt(this.geometry.uniforms),h=n.material(),_=h.vertex,_.pipe(this._vertexColor(i,d)),_.require(this._vertexPosition(v,m,f,2,E)),_.require(g),_.pipe("sprite.position",this.uniforms),_.pipe("project.position",this.uniforms),h.fragment=u=this._fragmentColor(c,m,i,d,f,2,E,s,p),a=n.material(),a.vertex.pipe(_),a.fragment.pipe(u),a.fragment.pipe("fragment.transparent",this.uniforms),l=n.material(),l.vertex.pipe(_),l.fragment.pipe(u),l.fragment.pipe("fragment.solid",this.uniforms),this.fillMaterial=this._material(l.link({side:THREE.DoubleSide})),this.edgeMaterial=this._material(a.link({side:THREE.DoubleSide})),this.fillObject=new THREE.Mesh(this.geometry,this.fillMaterial),this.edgeObject=new THREE.Mesh(this.geometry,this.edgeMaterial),this._raw(this.fillObject),this._raw(this.edgeObject),this.renders=[this.fillObject,this.edgeObject]}return s(e,t),e.prototype.show=function(t,e,n,r){return this._show(this.edgeObject,!0,e,n,r),this._show(this.fillObject,t,e,n,r)},e.prototype.dispose=function(){return this.geometry.dispose(),this.edgeMaterial.dispose(),this.fillMaterial.dispose(),this.nreders=this.geometry=this.edgeMaterial=this.fillMaterial=this.edgeObject=this.fillObject=null,e.__super__.dispose.apply(this,arguments)},e}(r),e.exports=i},{"../geometry":143,"./base":151}],159:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;r=t("./base"),o=t("../geometry").StripGeometry,i=function(t){function e(t,n,r){var i,s,a,u,h,l,c,p,f,d,m,v,g,E;e.__super__.constructor.call(this,t,n,r),g=r.uniforms,f=r.material,m=r.position,i=r.color,p=r.mask,c=r.map,s=r.combine,l=r.linear,v=r.stpq,null==g&&(g={}),null==f&&(f=!0),h=null!=g.styleColor,this.geometry=new o({items:r.items,width:r.width,height:r.height,depth:r.depth}),this._adopt(g),this._adopt(this.geometry.uniforms),u=n.material(),E=u.vertex,E.pipe(this._vertexColor(i,p)),E.require(this._vertexPosition(m,f,c,2,v)),f||E.pipe("mesh.position",this.uniforms),f&&E.pipe("strip.position.normal",this.uniforms),E.pipe("project.position",this.uniforms),u.fragment=a=this._fragmentColor(h,f,i,p,c,2,v,s,l),a.pipe("fragment.color",this.uniforms),this.material=this._material(u.link({side:THREE.DoubleSide})),d=new THREE.Mesh(this.geometry,this.material),this._raw(d),this.renders=[d]}return s(e,t),e.prototype.dispose=function(){return this.geometry.dispose(),this.material.dispose(),this.renders=this.geometry=this.material=null,e.__super__.dispose.apply(this,arguments)},e}(r),e.exports=i},{"../geometry":143,"./base":151}],160:[function(t,e,n){var r,i,o,s,a=function(t,e){function n(){this.constructor=t}for(var r in e)u.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},u={}.hasOwnProperty;r=t("./base"),o=t("../geometry").SurfaceGeometry,s=t("../../util"),i=function(t){function e(t,n,r){var i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b;e.__super__.constructor.call(this,t,n,r),_=r.uniforms,v=r.material,E=r.position,i=r.color,m=r.mask,d=r.map,s=r.combine,f=r.linear,y=r.stpq,p=r.intUV,null==_&&(_={}),null==v&&(v=!0),c=null!=_.styleColor,l=null!=_.surfaceHollow,this.geometry=new o({width:r.width,height:r.height,surfaces:r.surfaces,layers:r.layers,closedX:r.closedX,closedY:r.closedY}),this._adopt(_),this._adopt(this.geometry.uniforms),h=n.material(),b=h.vertex,p&&(a={POSITION_UV_INT:""}),b.pipe(this._vertexColor(i,m)),b.require(this._vertexPosition(E,v,d,2,y)),v||b.pipe("surface.position",this.uniforms,a),v&&b.pipe("surface.position.normal",this.uniforms,a),b.pipe("project.position",this.uniforms),h.fragment=u=this._fragmentColor(c,v,i,m,d,2,y,s,f),u.pipe("fragment.color",this.uniforms),this.material=this._material(h.link({side:THREE.DoubleSide})),g=new THREE.Mesh(this.geometry,this.material),this._raw(g),this.renders=[g]}return a(e,t),e.prototype.dispose=function(){return this.geometry.dispose(),this.material.dispose(),this.renders=this.geometry=this.material=null,e.__super__.dispose.apply(this,arguments)},e}(r),e.exports=i},{"../../util":175,"../geometry":143,"./base":151}],161:[function(t,e,n){var r;r=function(){function t(t,e){this.renderer=t,this.shaders=e,this.gl=this.renderer.context,null==this.uniforms&&(this.uniforms={})}return t.prototype.dispose=function(){return this.uniforms=null},t.prototype._adopt=function(t){var e,n;for(e in t)n=t[e],this.uniforms[e]=n},t.prototype._set=function(t){var e,n;for(e in t)n=t[e],null!=this.uniforms[e]&&(this.uniforms[e].value=n)},t}(),e.exports=r},{}],162:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty,u=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};i=t("./renderable"),r=function(t){function e(){e.__super__.constructor.apply(this,arguments),this.rotationAutoUpdate=!1,this.frustumCulled=!1,this.matrixAutoUpdate=!1}return s(e,t),e}(THREE.Object3D),o=function(t){function e(t,n,i){e.__super__.constructor.call(this,t,n,i),this.root=new r,null!=(null!=i?i.scene:void 0)&&(this.scene=i.scene),null==this.scene&&(this.scene=new THREE.Scene),this.pending=[],this.async=0,this.scratch=new THREE.WebGLRenderTarget(1,1),this.camera=new THREE.PerspectiveCamera}return s(e,t),e.prototype.inject=function(t){return null!=t&&(this.scene=t),this.scene.add(this.root)},e.prototype.unject=function(){var t;return null!=(t=this.scene)?t.remove(this.root):void 0},e.prototype.add=function(t){return this.async?this.pending.push(t):this._add(t)},e.prototype.remove=function(t){return this.pending=this.pending.filter(function(e){return e!==t}),null!=t.parent?this._remove(t):void 0},e.prototype._add=function(t){return this.root.add(t)},e.prototype._remove=function(t){return this.root.remove(t)},e.prototype.dispose=function(){return null!=this.root.parent?this.unject():void 0},e.prototype.warmup=function(t){return this.async=+t||0},e.prototype.render=function(){var t,e,n,r,i,o,s;if(this.pending.length){for(e=this.root.children,t=[],n=r=0,o=this.async;(o>=0?o>r:r>o)&&(i=this.pending.shift(),i);n=o>=0?++r:--r)this._add(i),t.push(t);return s=e.map(function(t){var e;return e=t.visible}),e.map(function(e){return e.visible=u.call(t,e)<0}),this.renderer.render(this.scene,this.camera,this.scratch),e.map(function(t,e){return t.visible=s[e]})}},e.prototype.toJSON=function(){return this.root.toJSON()},e}(i),e.exports=o},{"./renderable":161}],163:[function(t,e,n){var r,i;i=t("../../vendor/shadergraph/src"),r=function(t){var e;return e=function(e){var n,r,i,o,s;if(o=t[e],null!=o)return o;if(r="#"===(i=e[0])||"."===i||":"===i||"["===i,s=r?e:"#"+e,n=document.querySelector(s),null!=n&&"SCRIPT"===n.tagName)return n.textContent||n.innerText;throw new Error("Unknown shader `"+e+"`")},new i(e,{autoInspect:!0})},e.exports=r},{"../../vendor/shadergraph/src":208}],164:[function(t,e,n){n.Factory=t("./factory"),n.Snippets=t("../../build/shaders")},{"../../build/shaders":1,"./factory":163}],165:[function(t,e,n){THREE.Bootstrap.registerPlugin("splash",{defaults:{color:"mono",fancy:!0},listen:["ready","mathbox/init:init","mathbox/progress:progress","mathbox/destroy:destroy"],uninstall:function(){return this.destroy()},ready:function(t,e){return e.MathBox&&!this.div?init(t,e):void 0},init:function(t,e){var n,r,i,o,s,a,u;return this.destroy(),n=this.options.color,i='
\n \n
\n
',this.div=r=document.createElement("div"),r.innerHTML=i,e.element.appendChild(r),s=2*Math.random()-1,a=2*Math.random()-1,u=2*Math.random()-1,o=1/Math.sqrt(s*s+a*a+u*u),this.loader=r.querySelector(".mathbox-loader"),this.bar=r.querySelector(".mathbox-progress > div"),this.gyro=r.querySelectorAll(".mathbox-logo > div"),this.transforms=["rotateZ(22deg) rotateX(24deg) rotateY(30deg)","rotateZ(11deg) rotateX(12deg) rotateY(15deg) scale3d(.6, .6, .6)"],this.random=[s*o,a*o,u*o],this.start=e.Time.now,this.timer=null},progress:function(t,e){var n,r,i,o,s,a,u,h,l,c,p,f,d,m;if(this.div&&(n=t.current,p=t.total,f=p>n,clearTimeout(this.timer),f?(this.loader.classList.remove("mathbox-exit"),this.loader.style.display="block"):(this.loader.classList.add("mathbox-exit"),this.timer=setTimeout(function(t){return function(){return t.loader.style.display="none"}}(this),150)),m=p>n?.1*Math.round(1e3*n/p)+"%":"100%",this.bar.style.width=m,this.options.fancy)){for(d=this.random,i=Math.max(0,Math.min(1,e.Time.now-this.start)),s=function(t,n){return null==n&&(n=0),t.replace(/(-?[0-9.e]+)deg/g,function(t,r){return+r+d[n++]*i*e.Time.step*60+"deg"})},h=this.gyro,l=[],o=a=0,u=h.length;u>a;o=++a)r=h[o],this.transforms[o]=c=s(this.transforms[o]),l.push(r.style.transform=r.style.WebkitTransform=c);return l}},destroy:function(){var t;return null!=(t=this.div)&&t.remove(),this.div=null}})},{}],166:[function(t,e,n){var r,i,o;o=t("../util").Ease,i=function(){function t(t){this.context=t,this.anims=[]}return t.prototype.make=function(t,e){var n;return n=new r(this,this.context.time,t,e),this.anims.push(n),n},t.prototype.unmake=function(t){var e;return this.anims=function(){var n,r,i,o;for(i=this.anims,o=[],n=0,r=i.length;r>n;n++)e=i[n],e!==t&&o.push(e);return o}.call(this)},t.prototype.update=function(){var t,e;return e=this.context.time,this.anims=function(){var n,r,i,o;for(i=this.anims,o=[],n=0,r=i.length;r>n;n++)t=i[n],t.update(e)!==!1&&o.push(t);return o}.call(this)},t.prototype.lerp=function(t,e,n,r,i){var o,s,a,u;if(null==i&&(i=t.make()),t.lerp)i=t.lerp(e,n,i,r);else if(t.emitter){if(s=e.emitterFrom,u=n.emitterTo,null!=s&&null!=u&&s===u)return s.lerp(r),s;o=t.emitter(e,n),e.emitterFrom=o,n.emitterTo=o}else t.op?(a=function(t,e){return t===+t&&e===+e?t+(e-t)*r:r>.5?e:t},i=t.op(e,n,i,a)):i=r>.5?n:e;return i},t}(),r=function(){function t(t,e,n,r){this.animator=t,this.time=e,this.type=n,this.options=r,this.value=this.type.make(),this.target=this.type.make(),this.queue=[]}return t.prototype.dispose=function(){return this.animator.unmake(this)},t.prototype.set=function(){var t,e,n;return e=this.target,n=arguments.length>1?[].slice.call(arguments):arguments[0],t=!1,n=this.type.validate(n,e,function(){return t=!0}),t||(e=n),this.cancel(),this.target=this.value,this.value=e,this.notify()},t.prototype.getTime=function(){var t,e;return t=this.options.clock,e=t?t.getTime():this.time,this.options.realtime?e.time:e.clock},t.prototype.cancel=function(t){var e,n,r,i,o,s;for(null==t&&(t=this.getTime()),o=this.queue,n=function(){var e,n,r;for(r=[],e=0,n=o.length;n>e;e++)s=o[e],s.end>=t&&r.push(s);return r}(),this.queue=function(){var e,n,r;for(r=[],e=0,n=o.length;n>e;e++)s=o[e],s.endr;r++)s=n[r],"function"==typeof s.complete&&s.complete(!1);"function"==typeof(e=this.options).complete&&e.complete(!1)},t.prototype.notify=function(){var t;return"function"==typeof(t=this.options).step?t.step(this.value):void 0},t.prototype.immediate=function(t,e){var n,r,i,o,s,a,u,h,l,c;return i=e.duration,r=e.delay,o=e.ease,h=e.step,n=e.complete,c=this.getTime(),u=c+r,s=u+i,a=!1,l=this.type.make(),t=this.type.validate(t,l,function(){return a=!0,null}),void 0!==t&&(l=t),this.cancel(u),this.queue.push({from:null,to:l,start:u,end:s,ease:o,step:h,complete:n})},t.prototype.update=function(t){var e,n,r,i,s,a,u,h,l,c,p,f,d,m,v,g;if(this.time=t,0===this.queue.length)return!0;for(r=this.getTime(),g=this.value,c=this.queue,e=!1;!e;){if(p=f=c[0],h=p.from,v=p.to,d=p.start,a=p.end,m=p.step,i=p.complete,s=p.ease,null==h&&(h=f.from=this.type.clone(this.value)),u=o.clamp((r-d)/Math.max(1e-5,a-d)||0,0,1),0===u)return;if(l=function(){switch(s){case"linear":case 0:return null;case"cosine":case 1:return o.cosine;case"binary":case 2:return o.binary;case"hold":case 3:return o.hold;default:return o.cosine}}(),null!=l&&(u=l(u)),e=1>u,g=e?this.animator.lerp(this.type,h,v,u,g):v,"function"==typeof m&&m(g),!e&&("function"==typeof i&&i(!0),"function"==typeof(n=this.options).complete&&n.complete(!0),c.shift(),0===c.length))break}return this.value=g,this.notify()},t}(),e.exports=i},{"../util":175}],167:[function(t,e,n){var r,i;i=t("../util"),r=function(){function t(t,e,n){var r,i,o,s,a,u,h,l,c,p;for(this._context=t,this._up=e,this._targets=n,l=this._context.controller.getRoot(),null==this._targets&&(this._targets=[l]),this.isRoot=1===this._targets.length&&this._targets[0]===l,this.isLeaf=1===this._targets.length&&null==this._targets[0].children,u=this._targets,r=i=0,s=u.length;s>i;r=++i)c=u[r],this[r]=c;for(this.length=this._targets.length,h=this._context.controller.getTypes(),o=0,a=h.length;a>o;o++)p=h[o],"root"!==p&&!function(t){return function(e){return t[e]=function(n,r){return t.add(e,n,r)}}}(this)(p)}return t.prototype.v2=function(){return this},t.prototype.select=function(t){var e;return e=this._context.model.select(t,this.isRoot?null:this._targets),this._push(e)},t.prototype.eq=function(t){return this._targets.length>t?this._push([this._targets[t]]):this._push([])},t.prototype.filter=function(t){var e;return"string"==typeof t&&(e=this._context.model._matcher(t),t=function(t){return e(t)}),this._push(this._targets.filter(t))},t.prototype.map=function(t){var e,n,r,i;for(i=[],e=n=0,r=this.length;r>=0?r>n:n>r;e=r>=0?++n:--n)i.push(t(this[e],e,this));return i},t.prototype.each=function(t){var e,n,r;for(e=n=0,r=this.length;r>=0?r>n:n>r;e=r>=0?++n:--n)t(this[e],e,this);return this},t.prototype.add=function(t,e,n){var r,i,o,s,a,u,h;if(r=this._context.controller,this.isLeaf)return this._pop().add(t,e,n);for(a=[],u=this._targets,i=0,o=u.length;o>i;i++)h=u[i],s=r.make(t,e,n),r.add(s,h),a.push(s);return this._push(a)},t.prototype.remove=function(t){var e,n,r,i;if(t)return this.select(t).remove();for(r=this._targets.slice().reverse(),e=0,n=r.length;n>e;e++)i=r[e],this._context.controller.remove(i);return this._pop()},t.prototype.set=function(t,e){var n,r,i,o;for(i=this._targets,n=0,r=i.length;r>n;n++)o=i[n],this._context.controller.set(o,t,e);return this},t.prototype.getAll=function(t){var e,n,r,i,o;for(r=this._targets,i=[],e=0,n=r.length;n>e;e++)o=r[e],i.push(this._context.controller.get(o,t));return i},t.prototype.get=function(t){var e;return null!=(e=this._targets[0])?e.get(t):void 0},t.prototype.evaluate=function(t,e){var n;return null!=(n=this._targets[0])?n.evaluate(t,e):void 0},t.prototype.bind=function(t,e){var n,r,i,o;for(i=this._targets,n=0,r=i.length;r>n;n++)o=i[n],this._context.controller.bind(o,t,e);return this},t.prototype.unbind=function(t){var e,n,r,i;for(r=this._targets,e=0,n=r.length;n>e;e++)i=r[e],this._context.controller.unbind(i,t);return this},t.prototype.end=function(){return(this.isLeaf?this._pop():this)._pop()},t.prototype._push=function(e){return new t(this._context,this,e); +},t.prototype._pop=function(){var t;return null!=(t=this._up)?t:this},t.prototype._reset=function(){var t,e;return null!=(t=null!=(e=this._up)?e.reset():void 0)?t:this},t.prototype.map=function(t){return this._targets.map(t)},t.prototype.on=function(){var t;return t=arguments,this._targets.map(function(e){return e.on.apply(e,t)}),this},t.prototype.off=function(){var t;return t=arguments,this._targets.map(function(e){return e.on.apply(e,t)}),this},t.prototype.toString=function(){var t;return t=this._targets.map(function(t){return t.toString()}),this._targets.length>1?"["+t.join(", ")+"]":t[0]},t.prototype.toMarkup=function(){var t;return t=this._targets.map(function(t){return t.toMarkup()}),t.join("\n\n")},t.prototype.print=function(){return i.Pretty.print(this._targets.map(function(t){return t.toMarkup()}).join("\n\n")),this},t.prototype.debug=function(){var t,e,n,r,i,o,s,a;for(e=this.inspect(),console.log("Renderables: ",e.renderables),console.log("Renders: ",e.renders),console.log("Shaders: ",e.shaders),t=function(t){return t.constructor.toString().match("function +([^(]*)")[1]},a=[],o=e.shaders,n=0,r=o.length;r>n;n++)s=o[n],i=t(s.owner),a.push(i+" - Vertex"),a.push(s.vertex),a.push(i+" - Fragment"),a.push(s.fragment);return ShaderGraph.inspect(a)},t.prototype.inspect=function(t,e,n){var r,i,o,s,a,u,h,l,c,p,f,d,m;for("boolean"==typeof e&&(n=e,e=null),null==n&&(n=!0),l=function(t){var e,n;return null!=(e=null!=(n=t.controller)?n.objects:void 0)?e:[]},c=d=function(t,n){var r,i,o,s;if(null==n&&(n=[]),(!e||t.traits.hash[e])&&n.push(l(t)),null!=t.children)for(s=t.children,i=0,o=s.length;o>i;i++)r=s[i],d(r,n);return n},i=function(t){return t=t.reduce(function(t,e){return t.concat(e)},[]),t=t.filter(function(e,n){return null!=e&&t.indexOf(e)===n})},h=function(t,e){var n;return n={},n.owner=t,n.geometry=e.geometry,n.material=e.material,n.vertex=e.material.vertexGraph,n.fragment=e.material.fragmentGraph,n},o={nodes:this._targets.slice(),renderables:[],renders:[],shaders:[]},p=this._targets,s=0,u=p.length;u>s;s++){m=p[s],n&&m.print(t,"info"),r={renderables:f=i(c(m)),renders:i(f.map(function(t){return t.renders})),shaders:i(f.map(function(t){var e;return null!=(e=t.renders)?e.map(function(e){return h(t,e)}):void 0}))};for(a in r)o[a]=o[a].concat(r[a])}return o},t}(),e.exports=r},{"../util":175}],168:[function(t,e,n){var r,i;i=t("../util"),r=function(){function t(t,e){this.model=t,this.primitives=e}return t.prototype.getRoot=function(){return this.model.getRoot()},t.prototype.getTypes=function(){return this.primitives.getTypes()},t.prototype.make=function(t,e,n){return this.primitives.make(t,e,n)},t.prototype.get=function(t,e){return t.get(e)},t.prototype.set=function(t,e,n){var r,i;try{return t.set(e,n)}catch(i){return r=i,t.print(null,"warn"),console.error(r)}},t.prototype.bind=function(t,e,n){var r,i;try{return t.bind(e,n)}catch(i){return r=i,t.print(null,"warn"),console.error(r)}},t.prototype.unbind=function(t,e){var n,r;try{return t.unbind(e)}catch(r){return n=r,t.print(null,"warn"),console.error(n)}},t.prototype.add=function(t,e){return null==e&&(e=this.model.getRoot()),e.add(t)},t.prototype.remove=function(t){var e;return e=t.parent,e?e.remove(t):void 0},t}(),e.exports=r},{"../util":175}],169:[function(t,e,n){n.Animator=t("./animator"),n.API=t("./api"),n.Controller=t("./controller")},{"./animator":166,"./api":167,"./controller":168}],170:[function(t,e,n){var r=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};n.setOrigin=function(t,e,n){var i,o,s,a;return+e===e&&(e=[e]),o=r.call(e,1)>=0?0:n.x,s=r.call(e,2)>=0?0:n.y,a=r.call(e,3)>=0?0:n.z,i=r.call(e,4)>=0?0:n.w,t.set(o,s,a,i)},n.addOrigin=function(){var t;return t=new THREE.Vector4,function(e,r,i){return n.setOrigin(t,r,i),e.add(t)}}(),n.setDimension=function(t,e){var n,r,i,o;return r=1===e?1:0,i=2===e?1:0,o=3===e?1:0,n=4===e?1:0,t.set(r,i,o,n)},n.setDimensionNormal=function(t,e){var n,r,i,o;return r=1===e?1:0,i=2===e?1:0,o=3===e?1:0,n=4===e?1:0,t.set(i,o+r,n,0)},n.recenterAxis=function(){var t;return t=[0,0],function(e,n,r,i){var o,s,a,u,h,l;return null==i&&(i=0),r>0&&(h=e,l=e+n,o=Math.max(Math.abs(h),Math.abs(l)),s=o*i,u=Math.min(h,l),a=Math.max(h,l),e=u+(-o+s-u)*r,n=a+(o+s-a)*r-e),t[0]=e,t[1]=n,t}}()},{}],171:[function(t,e,n){e.exports=self={bind:function(t,e){return function(n,r){r.__binds||(r.__binds=[]);var i=t;_.isArray(n)&&(i=n[0],n=n[1]);for(var o=/^([^.:]*(?:\.[^.:]+)*)?(?:\:(.*))?$/.exec(n),s=o[1].split(/\./g),a=s.pop(),u=o[2]||a,h=s.shift(),l={"this":r}[h]||e[h]||t[h]||i;l&&(n=s.shift());)l=l[n];if(l&&(l.on||l.addEventListener)){var c=function(e){r[u]&&r[u](e,t)};self._polyfill(l,["addEventListener","on"],function(t){l[t](a,c)});var p={target:l,name:a,callback:c};return r.__binds.push(p),c}throw"Cannot bind '"+n+"' in "+this.__name}},unbind:function(){return function(t){t.__binds&&(t.__binds.forEach(function(t){self._polyfill(t.target,["removeEventListener","off"],function(e){t.target[e](t.name,t.callback)})}.bind(this)),t.__binds=[])}},apply:function(t){THREE.EventDispatcher.prototype.apply(t),t.trigger=self._trigger,t.triggerOnce=self._triggerOnce,t.on=t.addEventListener,t.off=t.removeEventListener,t.dispatchEvent=t.trigger},_triggerOnce:function(t){this.trigger(t),this._listeners&&delete this._listeners[t.type]},_trigger:function(t){if(void 0!==this._listeners){var e=t.type,n=this._listeners[e];if(void 0!==n){n=n.slice();var r=n.length;t.target=this;for(var i=0;r>i;i++)n[i].call(this,t,this)}}},_polyfill:function(t,e,n){e.map(function(e){return t.method}),e.length&&n(e[0])}}},{}],172:[function(t,e,n){var r;n.getSizes=r=function(t){var e,n;for(n=[],e=t;"string"!=typeof e&&null!=(null!=e?e.length:void 0);)n.push(e.length),e=e[0];return n},n.getDimensions=function(t,e){var n,i,o,s,a,u,h,l,c,p,f,d,m,v,g;return null==e&&(e={}),a=e.items,n=e.channels,g=e.width,s=e.height,i=e.depth,o={},t&&t.length?(v=r(t),l=v.length,o.channels=1!==n&&v.length>1?v.pop():n,o.items=1!==a&&v.length>1?v.pop():a,o.width=1!==g&&v.length>1?v.pop():g,o.height=1!==s&&v.length>1?v.pop():s,o.depth=1!==i&&v.length>1?v.pop():i,u=l,1===n&&u++,1===a&&u>1&&u++,1===g&&u>2&&u++,1===s&&u>3&&u++,h=null!=(c=v.pop())?c:1,1>=u&&(h/=null!=(p=o.channels)?p:1),2>=u&&(h/=null!=(f=o.items)?f:1),3>=u&&(h/=null!=(d=o.width)?d:1),4>=u&&(h/=null!=(m=o.height)?m:1),h=Math.floor(h),null==o.width&&(o.width=h,h=1),null==o.height&&(o.height=h,h=1),null==o.depth&&(o.depth=h,h=1),o):{items:a,channels:n,width:null!=g?g:0,height:null!=s?s:0,depth:null!=i?i:0}},n.repeatCall=function(t,e){switch(e){case 0:return function(){return!0};case 1:return function(){return t()};case 2:return function(){return t(),t()};case 3:return function(){return t(),t(),t(),t()};case 4:return function(){return t(),t(),t(),t()};case 6:return function(){return t(),t(),t(),t(),t(),t()};case 8:return function(){return t(),t(),t(),t(),t(),t()}}},n.makeEmitter=function(t,e,n){var r,i,o,s;for(r=function(){switch(n){case 0:return function(){return!0};case 1:return function(e){return e(t())};case 2:return function(e){return e(t(),t())};case 3:return function(e){return e(t(),t(),t())};case 4:return function(e){return e(t(),t(),t(),t())};case 6:return function(e){return e(t(),t(),t(),t(),t(),t())};case 8:return function(e){return e(t(),t(),t(),t(),t(),t(),t(),t())}}}(),o=null;e>0;)i=Math.min(e,8),s=function(){switch(i){case 1:return function(t){return r(t)};case 2:return function(t){return r(t),r(t)};case 3:return function(t){return r(t),r(t),r(t)};case 4:return function(t){return r(t),r(t),r(t),r(t)};case 5:return function(t){return r(t),r(t),r(t),r(t),r(t)};case 6:return function(t){return r(t),r(t),r(t),r(t),r(t),r(t)};case 7:return function(t){return r(t),r(t),r(t),r(t),r(t),r(t),r(t)};case 8:return function(t){return r(t),r(t),r(t),r(t),r(t),r(t),r(t),r(t)}}}(),o=null!=o?function(t,e){return function(n){return t(n),e(n)}}(s,o):s,e-=i;return s=null!=o?o:function(){return!0},s.reset=t.reset,s.rebind=t.rebind,s},n.getThunk=function(t){var e,n,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S;switch(H=r(t),d=H.length,e=H.pop(),n=H.pop(),i=H.pop(),o=H.pop(),s=!1,d){case 0:S=function(){return 0},S.reset=function(){};break;case 1:h=0,S=function(){return t[h++]},S.reset=function(){return h=0};break;case 2:h=l=0,a=null!=(m=t[l])?m:[],S=function(){var n,r;return r=a[h++],h===e&&(h=0,l++,a=null!=(n=t[l])?n:[]),r},S.reset=function(){var e;h=l=0,a=null!=(e=t[l])?e:[]};break;case 3:h=l=c=0,R=null!=(v=t[c])?v:[],a=null!=(g=R[l])?g:[],S=function(){var r,i,o;return o=a[h++],h===e&&(h=0,l++,l===n&&(l=0,c++,R=null!=(r=t[c])?r:[]),a=null!=(i=R[l])?i:[]),o},S.reset=function(){var e,n;h=l=c=0,R=null!=(e=t[c])?e:[],a=null!=(n=R[l])?n:[]};break;case 4:h=l=c=p=0,M=null!=(E=t[p])?E:[],R=null!=(y=M[c])?y:[],a=null!=(_=R[l])?_:[],S=function(){var r,o,s,u;return u=a[h++],h===e&&(h=0,l++,l===n&&(l=0,c++,c===i&&(c=0,p++,M=null!=(r=t[p])?r:[]),R=null!=(o=M[c])?o:[]),a=null!=(s=R[l])?s:[]),u},S.reset=function(){var e,n,r;h=l=c=p=0,M=null!=(e=t[p])?e:[],R=null!=(n=M[c])?n:[],a=null!=(r=R[l])?r:[]};break;case 5:h=l=c=p=f=0,u=null!=(b=t[f])?b:[],M=null!=(T=u[p])?T:[],R=null!=(x=M[c])?x:[],a=null!=(w=R[l])?w:[],S=function(){var r,s,d,m,v;return v=a[h++],h===e&&(h=0,l++,l===n&&(l=0,c++,c===i&&(c=0,p++,p===o&&(p=0,f++,u=null!=(r=t[f])?r:[]),M=null!=(s=u[p])?s:[]),R=null!=(d=M[c])?d:[]),a=null!=(m=R[l])?m:[]),v},S.reset=function(){var e,n,r,i;h=l=c=p=f=0,u=null!=(e=t[f])?e:[],M=null!=(n=u[p])?n:[],R=null!=(r=M[c])?r:[],a=null!=(i=R[l])?i:[]}}return S.rebind=function(o){return t=o,H=r(t),H.length&&(e=H.pop()),H.length&&(n=H.pop()),H.length&&(i=H.pop()),H.length?o=H.pop():void 0},S},n.getStreamer=function(t,e,n,r){var i,o,s,a,u,h,l,c,p;return l=u=h=0,c=function(){return l=e*n*r,u=h=0},o=function(){return h},s=function(){return 0>=l-u},p=function(){switch(n){case 1:return function(t){u+=t,h+=t};case 2:return function(t){u+=2*t,h+=t};case 3:return function(t){u+=3*t,h+=t};case 4:return function(t){u+=4*t,h+=t}}}(),i=function(){switch(n){case 1:return function(e){e(t[u++]),++h};case 2:return function(e){e(t[u++],t[u++]),++h};case 3:return function(e){e(t[u++],t[u++],t[u++]),++h};case 4:return function(e){e(t[u++],t[u++],t[u++],t[u++]),++h}}}(),a=function(){switch(n){case 1:return function(e){t[u++]=e,++h};case 2:return function(e,n){t[u++]=e,t[u++]=n,++h};case 3:return function(e,n,r){t[u++]=e,t[u++]=n,t[u++]=r,++h};case 4:return function(e,n,r,i){t[u++]=e,t[u++]=n,t[u++]=r,t[u++]=i,++h}}}(),i.reset=c,a.reset=c,c(),{emit:a,consume:i,skip:p,count:o,done:s,reset:c}},n.getLerpEmitter=function(t,e){var n,r,i,o,s,a,u,h,l,c,p;return p=new Float32Array(4096),s=a=.5,u=h=l=c=0,r=function(t,e,n,r){return l++,p[u++]=t*s,p[u++]=e*s,p[u++]=n*s,p[u++]=r*s},i=function(t,e,n,r){return c++,p[h++]+=t*a,p[h++]+=e*a,p[h++]+=n*a,p[h++]+=r*a},n=Math.max(t.length,e.length),o=3>=n?function(n,o,s){var a,f,d,m,v,g;for(u=h=l=c=0,t(r,o,s),e(i,o,s),d=Math.min(l,c),f=0,g=[],a=m=0,v=d;v>=0?v>m:m>v;a=v>=0?++m:--m)g.push(n(p[f++],p[f++],p[f++],p[f++]));return g}:5>=n?function(n,o,s,a,f){var d,m,v,g,E,y;for(u=h=l=c=0,t(r,o,s,a,f),e(i,o,s,a,f),v=Math.min(l,c),m=0,y=[],d=g=0,E=v;E>=0?E>g:g>E;d=E>=0?++g:--g)y.push(n(p[m++],p[m++],p[m++],p[m++]));return y}:7>=n?function(n,o,s,a,f,d,m){var v,g,E,y,_;for(u=h=l=c=0,t(r,o,s,a,f,d,m),e(i,o,s,a,f,d,m),g=Math.min(l,c),v=0,_=[],m=E=0,y=g;y>=0?y>E:E>y;m=y>=0?++E:--E)_.push(n(p[v++],p[v++],p[v++],p[v++]));return _}:9>=n?function(n,o,s,a,f,d,m,v,g){var E,y,_,b;for(u=h=l=c=0,t(r,o,s,a,f,d,m,v,g),e(i,o,s,a,f,d,m,v,g),E=Math.min(l,c),g=0,b=[],v=y=0,_=E;_>=0?_>y:y>_;v=_>=0?++y:--y)b.push(n(p[g++],p[g++],p[g++],p[g++]));return b}:function(n,o,s,a,f,d,m,v,g,E,y){var _,b,T,x;for(u=h=0,t(r,o,s,a,f,d,m,v,g,E,y),e(i,o,s,a,f,d,m,v,g,E,y),_=Math.min(l,c),g=0,x=[],v=b=0,T=_;T>=0?T>b:b>T;v=T>=0?++b:--b)x.push(n(p[g++],p[g++],p[g++],p[g++]));return x},o.lerp=function(t){var e;return e=[1-t,t],s=e[0],a=e[1],e},o},n.getLerpThunk=function(t,e){var r,i,o,s,a,u;return i=n.getSizes(t).reduce(function(t,e){return t*e}),o=n.getSizes(e).reduce(function(t,e){return t*e}),r=Math.min(i,o),a=n.getThunk(t),u=n.getThunk(e),s=new Float32Array(r),s.lerp=function(t){var e,n,i,o;for(a.reset(),u.reset(),i=0,o=[];r>i;)e=a(),n=u(),o.push(s[i++]=e+(n-e)*t);return o},s}},{}],173:[function(t,e,n){var r,i;i=Math.PI,r={clamp:function(t,e,n){return Math.max(e,Math.min(n,t))},cosine:function(t){return.5-.5*Math.cos(r.clamp(t,0,1)*i)},binary:function(t){return+(t>=.5)},hold:function(t){return+(t>=1)}},e.exports=r},{}],174:[function(t,e,n){var r,i,o,s,a,u=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};i="xyzw".split(""),r={0:-1,x:0,y:1,z:2,w:3},o=function(t){return t===""+t&&(t=t.split("")),t===+t&&(t=[t]),t},a=function(t){return t===+t&&(t="vec"+t),"vec1"===t&&(t="float"),t},s=function(t){return t=""+t,t.indexOf(".")<0?t+=".0":void 0},n.mapByte2FloatOffset=function(t){var e;return null==t&&(t=4),e=s(t),"vec4 float2ByteIndex(vec4 xyzw, out float channelIndex) {\n float relative = xyzw.w / "+e+";\n float w = floor(relative);\n channelIndex = (relative - w) * "+e+";\n return vec4(xyzw.xyz, w);\n}"},n.sample2DArray=function(t){var e,n;return n=function(t,e){var r,i;return t===e?i="return texture2D(dataTextures["+t+"], uv);":(r=Math.ceil(t+(e-t)/2),i="if (z < "+(r-.5)+") {\n "+n(t,r-1)+"\n}\nelse {\n "+n(r,e)+"\n}"),i=i.replace(/\n/g,"\n ")},e=n(0,t-1),"uniform sampler2D dataTextures["+t+"];\n\nvec4 sample2DArray(vec2 uv, float z) {\n "+e+"\n}"},n.binaryOperator=function(t,e,n){return t=a(t),null!=n?t+" binaryOperator("+t+" a) {\n return a "+e+" "+n+";\n}":t+" binaryOperator("+t+" a, "+t+" b) {\n return a "+e+" b;\n}"},n.extendVec=function(t,e,r){var i,o,u,h;return null==r&&(r=0),t>e?n.truncateVec(t,e):(o=e-t,t=a(t),e=a(e),r=s(r),u=function(){h=[];for(var t=0;o>=0?o>=t:t>=o;o>=0?t++:t--)h.push(t);return h}.apply(this).map(function(t){return t?r:"v"}),i=u.join(","),e+" extendVec("+t+" v) { return "+e+"("+i+"); }")},n.truncateVec=function(t,e){var r;return e>t?n.extendVec(t,e):(r="."+"xyzw".substr(0,e),t=a(t),e=a(e),e+" truncateVec("+t+" v) { return v"+r+"; }")},n.injectVec4=function(t){var e,n,i,s,a,u,h;for(h=["0.0","0.0","0.0","0.0"],t=o(t),t=t.map(function(t){return t===""+t?r[t]:t}),i=s=0,a=t.length;a>s;i=++s)n=t[i],h[n]=["a","b","c","d"][i];return u=h.slice(0,4).join(", "),e=["float a","float b","float c","float d"].slice(0,t.length),"vec4 inject("+e+") {\n return vec4("+u+");\n}"},n.swizzleVec4=function(t,e){var n,i;for(null==e&&(e=null),n=["0.0","xyzw.x","xyzw.y","xyzw.z","xyzw.w"],null==e&&(e=t.length),t=o(t),t=t.map(function(t){var e;return e=+t,u.call([0,1,2,3,4],e)>=0&&(t=+t),t===""+t&&(t=r[t]+1),n[t]});t.lengths;e=++s)u=t[e],l=i[e],n=r[u],c[n]="xyzw."+l;return h=c.join(", "),"vec4 invertSwizzle(vec4 xyzw) {\n return vec4("+h+");\n}"},n.identity=function(t){var e;return e=[].slice.call(arguments),e.length>1?(e=e.map(function(t,e){return["inout",t,String.fromCharCode(97+e)].join(" ")}),e=e.join(", "),"void identity("+e+") { }"):t+" identity("+t+" x) {\n return x;\n}"},n.constant=function(t,e){return t+" constant() {\n return "+e+";\n}"},n.toType=a},{}],175:[function(t,e,n){n.Axis=t("./axis"),n.Data=t("./data"),n.Ease=t("./ease"),n.GLSL=t("./glsl"),n.JS=t("./js"),n.Pretty=t("./pretty"),n.Three=t("./three"),n.Ticks=t("./ticks"),n.VDOM=t("./vdom")},{"./axis":170,"./data":172,"./ease":173,"./glsl":174,"./js":176,"./pretty":177,"./three":178,"./ticks":179,"./vdom":180}],176:[function(t,e,n){n.merge=function(){var t,e,n,r,i,o;for(o={},t=0,n=arguments.length;n>t;t++){r=arguments[t];for(e in r)i=r[e],o[e]=i}return o},n.clone=function(t){return JSON.parse(JSON.serialize(t))},n.parseQuoted=function(t){var e,n,r,i,o,s,a,u,h,l;for(e="",l=function(t){return t=t.replace(/\\/g,"")},a=function(t){return e.length&&s.push(l(e)),e=null!=t?t:""},t=t.split(/(?=(?:\\.|["' ,]))/g),u=!1,s=[],i=0,o=t.length;o>i;i++)switch(r=t[i],n=r[0],h=r.slice(1),n){case'"':case"'":if(u)u===n?(u=!1,a(h)):e+=r;else{if(""!==e)throw new Error("ParseError: String `"+t+"` does not contain comma-separated quoted tokens.");u=n,e+=h}break;case" ":case",":u?e+=r:a(h);break;default:e+=r}return a(),s}},{}],177:[function(t,e,n){var r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E;r=5,i=1e-4,o=function(t,e){return Math.abs(t/e-Math.round(t/e))i?"-":"",i+=n):"1"!==n&&(i+=r?""+n:"*"+n),i+"/"+e},u=[{1:1},{1:1,"τ":2*Math.PI},{1:1,"π":Math.PI},{1:1,"τ":2*Math.PI,"π":Math.PI},{1:1,e:Math.E},{1:1,"τ":2*Math.PI,e:Math.E},{1:1,"π":Math.PI,e:Math.E},{1:1,"τ":2*Math.PI,"π":Math.PI,e:Math.E}],c=[[420,[2,3,5,7]],[88200,[2,3,5,7]],[60060,[2,3,5,7,11,13]],[861764,[2,17,19,23,29]],[65536,[2]],[1e6,[2,5]]],g=function(t){var e,n,o,a,p,f,d,m,v,g;return t&&(e=t.cache,o=t.compact,v=t.tau,d=t.pi,a=t.e,g=t.threshold,m=t.precision),o=+!!(null!=o?o:!0),v=+!!(null!=v?v:!0),d=+!!(null!=d?d:!0),a=+!!(null!=a?a:!0),e=+!!(null!=e?e:!0),g=+(null!=g?g:i),m=+(null!=m?m:r),p=v+2*d+4*a,n=p+g+m,f=e?{}:null,function(t){var e,n,i,a,d,m,v,g,E,y,_,b,T,x,w,R,H,M;if(null!=f){if(null!=(n=f[t]))return n;if(t===Math.round(t))return f[t]=""+t}w=""+t,e=w.length+w.indexOf(".")+2,b=function(t){var n;return n=t.length,e>=n?(w=""+t,e=n):void 0},H=u[p];for(g in H)if(d=H[g],s(t/d))b(""+l(t/d,1,g,o));else for(m=0,E=c.length;E>m;m++)if(M=c[m],a=M[0],_=M[1],x=t/d*a,s(x)){for(v=0,y=_.length;y>v;v++)for(R=_[v];s(T=x/R)&&s(i=a/R);)x=T,a=i;b(""+h(t/d,a,g,o));break}return(""+t).length>r&&b(""+t.toPrecision(r)),null!=f&&(f[t]=w),w}},E=function(t,e){return null==e&&(e="info"),t=v(t),console[e].apply(console,t)},v=function(t){var e,n,r,i,o,s,a,u;return a="color:rgb(128,0,128)",n="color:rgb(144,64,0)",s="color:rgb(0,0,192)",i="color:rgb(0,70,156)",u="color:inherit",o=!1,r=0,e=[],t=t.replace(/(\\[<={}> "'])|(=>|[<={}> "'])/g,function(t,h,l){var c;return(null!=h?h.length:void 0)?h:o&&'"'!==l&&"'"!==l?l:r&&'"'!==l&&"'"!==l&&"{"!==l&&"}"!==l?l:c=function(){switch(l){case"<":return e.push(a),"%c<";case">":return e.push(a),e.push(u),"%c>%c";case" ":return e.push(n)," %c";case"=":case"=>":return e.push(a),"%c"+l;case'"':case"'":return o=!o,o?(e.push(r?n:s),l+"%c"):(e.push(r?i:a),"%c"+l);case"{":return 0===r++?(e.push(i),"%c"+l):l;case"}":return 0===--r?(e.push(a),l+"%c"):l;default:return l}}()}),[t].concat(e)},m=function(t,e){return d(t,e,"=")},f=function(t,e){return d(t,e,"=>")},d=function(){var t;return t=g({compact:!1}),function(e,n,r){var i,o,s;return i=function(t){return t===""+ +t||t.match(/^[A-Za-z_][A-Za-z0-9]*$/)?t:JSON.stringify(t)},s=function(t){return t.match('\n*"')?t:"{"+t+"}"},o=function(e){var n,r;if(e instanceof Array)return"["+e.map(o).join(", ")+"]";switch(typeof e){case"string":return e.match("\n")?'"\n'+e+'"\n':'"'+e+'"';case"function":return e=""+e,e.match("\n"),e=e.replace(/^function (\([^)]+\))/,"$1 =>"),e=e.replace(/^(\([^)]+\)) =>\s*{\s*return\s*([^}]+)\s*;\s*}/,"$1 => $2");case"number":return t(e);default:return null!=e&&e!==!!e?null!=e._up?o(e.map(function(t){return t})):e.toMarkup?e.toString():"{"+function(){var t;t=[];for(n in e)r=e[n],e.hasOwnProperty(n)&&t.push(i(n)+": "+o(r));return t}().join(", ")+"}":""+JSON.stringify(e)}},[e,r,s(o(n))].join("")}}(),a=function(t){return t=t.replace(/&/g,"&"),t=t.replace(/",t=a(t),r=0,i=n.length;i>r;r++)e=n[r],t=t.replace(/%([a-z])/,function(t,e){var r;switch(r=n.shift(),e){case"c":return'';default:return a(r)}});return o+=t,o+=""},e.exports={markup:v,number:g,print:E,format:p,JSX:{prop:m,bind:f}}},{}],178:[function(t,e,n){n.paramToGL=function(t,e){return e===THREE.RepeatWrapping?t.REPEAT:e===THREE.ClampToEdgeWrapping?t.CLAMP_TO_EDGE:e===THREE.MirroredRepeatWrapping?t.MIRRORED_REPEAT:e===THREE.NearestFilter?t.NEAREST:e===THREE.NearestMipMapNearestFilter?t.NEAREST_MIPMAP_NEAREST:e===THREE.NearestMipMapLinearFilter?t.NEAREST_MIPMAP_LINEAR:e===THREE.LinearFilter?t.LINEAR:e===THREE.LinearMipMapNearestFilter?t.LINEAR_MIPMAP_NEAREST:e===THREE.LinearMipMapLinearFilter?t.LINEAR_MIPMAP_LINEAR:e===THREE.UnsignedByteType?t.UNSIGNED_BYTE:e===THREE.UnsignedShort4444Type?t.UNSIGNED_SHORT_4_4_4_4:e===THREE.UnsignedShort5551Type?t.UNSIGNED_SHORT_5_5_5_1:e===THREE.UnsignedShort565Type?t.UNSIGNED_SHORT_5_6_5:e===THREE.ByteType?t.BYTE:e===THREE.ShortType?t.SHORT:e===THREE.UnsignedShortType?t.UNSIGNED_SHORT:e===THREE.IntType?t.INT:e===THREE.UnsignedIntType?t.UNSIGNED_INT:e===THREE.FloatType?t.FLOAT:e===THREE.AlphaFormat?t.ALPHA:e===THREE.RGBFormat?t.RGB:e===THREE.RGBAFormat?t.RGBA:e===THREE.LuminanceFormat?t.LUMINANCE:e===THREE.LuminanceAlphaFormat?t.LUMINANCE_ALPHA:e===THREE.AddEquation?t.FUNC_ADD:e===THREE.SubtractEquation?t.FUNC_SUBTRACT:e===THREE.ReverseSubtractEquation?t.FUNC_REVERSE_SUBTRACT:e===THREE.ZeroFactor?t.ZERO:e===THREE.OneFactor?t.ONE:e===THREE.SrcColorFactor?t.SRC_COLOR:e===THREE.OneMinusSrcColorFactor?t.ONE_MINUS_SRC_COLOR:e===THREE.SrcAlphaFactor?t.SRC_ALPHA:e===THREE.OneMinusSrcAlphaFactor?t.ONE_MINUS_SRC_ALPHA:e===THREE.DstAlphaFactor?t.DST_ALPHA:e===THREE.OneMinusDstAlphaFactor?t.ONE_MINUS_DST_ALPHA:e===THREE.DstColorFactor?t.DST_COLOR:e===THREE.OneMinusDstColorFactor?t.ONE_MINUS_DST_COLOR:e===THREE.SrcAlphaSaturateFactor?t.SRC_ALPHA_SATURATE:0},n.paramToArrayStorage=function(t){switch(t){case THREE.UnsignedByteType:return Uint8Array;case THREE.ByteType:return Int8Array;case THREE.ShortType:return Int16Array;case THREE.UnsignedShortType:return Uint16Array;case THREE.IntType:return Int32Array;case THREE.UnsignedIntType:return Uint32Array;case THREE.FloatType:return Float32Array}},n.swizzleToEulerOrder=function(t){return t.map(function(t){return["","X","Y","Z"][t]}).join("")},n.transformComposer=function(){var t,e,r,i,o;return t=new THREE.Euler,r=new THREE.Quaternion,e=new THREE.Vector3,i=new THREE.Vector3,o=new THREE.Matrix4,function(s,a,u,h,l,c){return null==c&&(c="XYZ"),null!=a?(c instanceof Array&&(c=n.swizzleToEulerOrder(c)),t.setFromVector3(a,c),r.setFromEuler(t)):r.set(0,0,0,1),null!=u&&r.multiply(u),null!=s?e.copy(s):e.set(0,0,0),null!=h?i.copy(h):i.set(1,1,1),o.compose(e,r,i),null!=l&&o.multiplyMatrices(o,l),o}}},{}],179:[function(t,e,n){var r,i,o,s,a;o=function(t,e,n,r,i,o,s,a,u,h){var l,c,p,f,d,m,v,g,E,y;return null==h&&(h=!0),n||(n=10),r||(r=1),i||(i=10),o||(o=1),v=e-t,d=v/n,h?(r||(r=1),i||(i=10),m=r*Math.pow(i,Math.floor(Math.log(d/r)/Math.log(i))),p=i%2===0?[i/2,1,.5]:i%3===0?[i/3,1,1/3]:[1],E=function(){var t,e,n;for(n=[],t=0,e=p.length;e>t;t++)c=p[t],n.push(m*c);return n}(),l=1/0,g=E.reduce(function(t,e){var n;return c=e/d,n=Math.max(c,1/c),l>n?(l=n,e):t},m),g*=o,t=Math.ceil(t/g+ +!s)*g,e=(Math.floor(e/g)-+!a)*g,n=Math.ceil((e-t)/g),y=function(){var e,r,i;for(i=[],f=e=0,r=n;r>=0?r>=e:e>=r;f=r>=0?++e:--e)i.push(t+f*g);return i}(),u||(y=y.filter(function(t){return 0!==t})),y):(y=function(){var e,r,i;for(i=[],f=e=0,r=n;r>=0?r>=e:e>=r;f=r>=0?++e:--e)i.push(t+f*d);return i}(),s||y.shift(),a||y.pop(),u||(y=y.filter(function(t){return 0!==t})),y)},s=function(t,e,n,r,i,o,s,a,u,h){throw new Error("Log ticks not yet implemented.")},r=0,i=1,a=function(t,e,n,a,u,h,l,c,p,f,d){switch(t){case r:return o(e,n,a,u,h,l,c,p,f,d);case i:return s(e,n,a,u,h,l,c,p,f,d)}},n.make=a,n.linear=o,n.log=s},{}],180:[function(t,e,n){var r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b;for(r=[],l=0,i={},a=function(){return{id:l++,type:null,props:null,children:null,rendered:null,instance:null}},h=function(t){var e,n,i,o;for(t*=2,t=Math.max(0,r.length-t),o=[],e=n=0,i=t;i>=0?i>n:n>i;e=i>=0?++n:--n)o.push(r.push(a()));return o},u=function(t,e,n){var i;return i=r.length?r.pop():a(),i.type=null!=t?t:"div",i.props=null!=e?e:null,i.children=null!=n?n:null,i},g=function(t){var e,n,i,o;if(t.type&&(n=t.children,t.type=t.props=t.children=t.instance=null,r.push(t),null!=n))for(i=0,o=n.length;o>i;i++)e=n[i],g(e)},o=function(t,e,n,r,s){var a,h,l,c,p,f,d,v,g,E,T,x,w,R,H,M,S,k,A,C,P,L,z,O,D,F,U,B,N,V;if(null!=t){if(null==e)return m(t,r,s);if(t instanceof Node){if(F=t===e)return}else F=typeof t==typeof e&&null!==e&&null!==t&&t.type===e.type;if(F){if(t.instance=e.instance,B=(null!=(P=t.type)?P.isComponentClass:void 0)?t.type:i[t.type],A=null!=e?e.props:void 0,H=t.props,c=null!=(L=null!=e?e.children:void 0)?L:null,R=t.children,null!=H&&(H.children=R),null!=B){if(f=n._COMPONENT_DIRTY,null!=A!=(null!=H)&&(f=!0),c!==R&&(f=!0),null!=A&&null!=H){if(!f)for(E in A)H.hasOwnProperty(E)||(f=!0);if(!f)for(E in H)V=H[E],(C=A[E])!==V&&(f=!0)}if(f){p=e.instance,null==t.props&&(t.props={}),z=p.defaultProps;for(g in z)N=z[g],null==(a=t.props)[g]&&(a[g]=N);t.props.children=t.children,"function"==typeof p.willReceiveProps&&p.willReceiveProps(t.props),U=n._COMPONENT_FORCE||(null!=(O="function"==typeof p.shouldUpdate?p.shouldUpdate(t.props):void 0)?O:!0),U&&(M=p.getNextState(),"function"==typeof p.willUpdate&&p.willUpdate(t.props,M)),S=p.props,k=p.applyNextState(),p.props=t.props,p.children=t.children,U&&(t=t.rendered="function"==typeof p.render?p.render(u,t.props,t.children):void 0,o(t,e.rendered,n,r,s),"function"==typeof p.didUpdate&&p.didUpdate(S,k))}return}if(null!=A)for(E in A)H.hasOwnProperty(E)||b(n,E,A[E]);if(null!=H)for(E in H)V=H[E],(C=A[E])!==V&&"children"!==E&&y(n,E,V,C);if(null!=R)if("string"==(D=typeof R)||"number"===D)R!==c&&(n.textContent=R);else if(null!=R.type)o(R,c,n.childNodes[0],n,0);else if(l=n.childNodes,null!=c)for(d=v=0,x=R.length;x>v;d=++v)h=R[d],o(h,c[d],l[d],n,d);else for(d=T=0,w=R.length;w>T;d=++T)h=R[d],o(h,null,l[d],n,d);else null!=c&&(_(null,n),n.innerHTML="");return}return _(e.instance,n),n.remove(),m(t,r,s)}return null!=e?(_(e.instance,n),e.node.remove()):void 0},m=function(t,e,n){var r,o,s,a,h,l,c,p,f,d,v,g,E,_,b,T,x,w,R,H;if(null==n&&(n=0),w=(null!=(g=t.type)?g.isComponentClass:void 0)?t.type:i[t.type],t instanceof Node)v=t;else{if(null!=w){if(h=(null!=(E=t.type)?E.isComponentClass:void 0)?t.type:i[t.type],!h)return t=t.rendered=u("noscript"),v=m(t,e,n);t.instance=a=new h(e),null==t.props&&(t.props={}),_=a.defaultProps;for(p in _)R=_[p],null==(r=t.props)[p]&&(r[p]=R);return t.props.children=t.children,a.props=t.props,a.children=t.children,a.setState("function"==typeof a.getInitialState?a.getInitialState():void 0),"function"==typeof a.willMount&&a.willMount(),t=t.rendered="function"==typeof a.render?a.render(u,t.props,t.children):void 0,v=m(t,e,n),"function"==typeof a.didMount&&a.didMount(t),v._COMPONENT=a,v}if("string"==(b=typeof t)||"number"===b)v=document.createTextNode(t);else{v=document.createElement(t.type),T=t.props;for(f in T)H=T[f],y(v,f,H)}if(s=t.children,null!=s)if("string"==(x=typeof s)||"number"===x)v.textContent=s;else if(null!=s.type)m(s,v,0);else for(l=c=0,d=s.length;d>c;l=++c)o=s[l],m(o,v,l)}return e.insertBefore(v,e.childNodes[n]),v},_=function(t,e){var n,r,i,o,s,a;if(t){"function"==typeof t.willUnmount&&t.willUnmount();for(i in t)delete t[i]}for(s=e.childNodes,a=[],r=0,o=s.length;o>r;r++)n=s[r],_(n._COMPONENT,n),a.push(delete n._COMPONENT);return a},v=function(t){var e,n,r,i;if("undefined"==typeof document)return!0;if(null!=document.documentElement.style[t])return t;for(t=t[0].toUpperCase()+t.slice(1),i=["webkit","moz","ms","o"],e=0,n=i.length;n>e;e++)if(r=i[e],null!=document.documentElement.style[r+t])return r+t},d={},E=["transform"],c=0,f=E.length;f>c;c++)p=E[c],d[p]=v(p);y=function(t,e,n,r){var i,o,s;{if("style"!==e)return null!=t[e]?void(t[e]=n):void(t instanceof Node&&t.setAttribute(e,n));for(i in n)s=n[i],(null!=r?r[i]:void 0)!==s&&(t.style[null!=(o=d[i])?o:i]=s)}},b=function(t,e,n){var r,i,o;if("style"!==e)null!=t[e]&&(t[e]=void 0),t instanceof Node&&t.removeAttribute(e);else for(r in n)o=n[r],t.style[null!=(i=d[r])?i:r]=""},s=function(t){var e,n,r,i,o;r={willMount:"componentWillMount",didMount:"componentDidMount",willReceiveProps:"componentWillReceiveProps",shouldUpdate:"shouldComponentUpdate",willUpdate:"componentWillUpdate",didUpdate:"componentDidUpdate",willUnmount:"componentWillUnmount"};for(n in r)i=r[n],null==t[n]&&(t[n]=t[i]);return e=function(){function e(e,n,r,i){var o,s,a,u;this.props=null!=n?n:{},this.state=null!=r?r:null,this.children=null!=i?i:null,o=function(t,e){return"function"==typeof t?t.bind(e):t};for(s in t)u=t[s],this[s]=o(u,this);a=null,this.setState=function(t){null==a&&(a=t?null!=a?a:{}:null);for(s in t)u=t[s],a[s]=u;e._COMPONENT_DIRTY=!0},this.forceUpdate=function(){var t,n;for(e._COMPONENT_FORCE=e._COMPONENT_DIRTY=!0,t=e,n=[];t=t.parentNode;)t._COMPONENT?n.push(t._COMPONENT_FORCE=!0):n.push(void 0);return n},this.getNextState=function(){return a},this.applyNextState=function(){var t,n;return e._COMPONENT_FORCE=e._COMPONENT_DIRTY=!1,t=this.state,n=[null,a],a=n[0],this.state=n[1],t}}return e}(),e.isComponentClass=!0,e.prototype.defaultProps=null!=(o="function"==typeof t.getDefaultProps?t.getDefaultProps():void 0)?o:{},e},e.exports={element:u,recycle:g,apply:o,hint:h,Types:i,createClass:s}},{}],181:[function(t,e,n){var r;r=function(){function t(e,n){this.parent=null!=n?n:null,this.id=t.id(),this.nodes=[],e&&this.add(e)}return t.index=0,t.id=function(e){return++t.index},t.IN=0,t.OUT=1,t.prototype.inputs=function(){var t,e,n,r,i,o,s,a,u;for(e=[],a=this.nodes,t=0,r=a.length;r>t;t++)for(o=a[t],u=o.inputs,n=0,i=u.length;i>n;n++)s=u[n],null===s.input&&e.push(s);return e},t.prototype.outputs=function(){var t,e,n,r,i,o,s,a,u;for(s=[],a=this.nodes,t=0,n=a.length;n>t;t++)for(i=a[t],u=i.outputs,e=0,r=u.length;r>e;e++)o=u[e],0===o.output.length&&s.push(o);return s},t.prototype.getIn=function(t){var e;return function(){var n,r,i,o;for(i=this.inputs(),o=[],n=0,r=i.length;r>n;n++)e=i[n],e.name===t&&o.push(e);return o}.call(this)[0]},t.prototype.getOut=function(t){var e;return function(){var n,r,i,o;for(i=this.outputs(),o=[],n=0,r=i.length;r>n;n++)e=i[n],e.name===t&&o.push(e);return o}.call(this)[0]},t.prototype.add=function(t,e){var n,r,i;{if(!t.length){if(t.graph&&!e)throw new Error("Adding node to two graphs at once");return t.graph=this,this.nodes.push(t)}for(r=0,i=t.length;i>r;r++)n=t[r],this.add(n)}},t.prototype.remove=function(t,e){var n,r,i;{if(!t.length){if(t.graph!==this)throw new Error("Removing node from wrong graph.");return e||t.disconnect(),this.nodes.splice(this.nodes.indexOf(t),1),t.graph=null}for(r=0,i=t.length;i>r;r++)n=t[r],this.remove(n)}},t.prototype.adopt=function(t){var e,n,r;{if(!t.length)return t.graph.remove(t,!0),this.add(t,!0);for(n=0,r=t.length;r>n;n++)e=t[n],this.adopt(e)}},t}(),e.exports=r},{}],182:[function(t,e,n){n.Graph=t("./graph"),n.Node=t("./node"),n.Outlet=t("./outlet"),n.IN=n.Graph.IN,n.OUT=n.Graph.OUT},{"./graph":181,"./node":183,"./outlet":184}],183:[function(t,e,n){var r,i,o;r=t("./graph"),o=t("./outlet"),i=function(){function t(e,n){this.owner=e,this.graph=null,this.inputs=[],this.outputs=[],this.all=[],this.outlets=null,this.id=t.id(),this.setOutlets(n)}return t.index=0,t.id=function(e){return++t.index},t.prototype.getIn=function(t){var e;return function(){var n,r,i,o;for(i=this.inputs,o=[],n=0,r=i.length;r>n;n++)e=i[n],e.name===t&&o.push(e);return o}.call(this)[0]},t.prototype.getOut=function(t){var e;return function(){var n,r,i,o;for(i=this.outputs,o=[],n=0,r=i.length;r>n;n++)e=i[n],e.name===t&&o.push(e);return o}.call(this)[0]},t.prototype.get=function(t){return this.getIn(t)||this.getOut(t)},t.prototype.setOutlets=function(t){var e,n,r,i,s,a,u,h,l,c,p,f;if(null!=t){if(null==this.outlets){for(this.outlets={},r=0,u=t.length;u>r;r++)p=t[r],p instanceof o||(p=o.make(p)),this._add(p);return}for(n=function(t){return[t.name,t.inout,t.type].join("-")},c={},i=0,h=t.length;h>i;i++)p=t[i], +c[n(p)]=!0;f=this.outlets;for(a in f)p=f[a],a=n(p),c[a]?c[a]=p:this._remove(p);for(s=0,l=t.length;l>s;s++)p=t[s],e=c[n(p)],e instanceof o?this._morph(e,p):(p instanceof o||(p=o.make(p)),this._add(p))}return this.outlets},t.prototype.connect=function(t,e,n){var r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b;for(d={},s={},b=function(t){return _+"/"+t.hint},m=t.inputs,a=0,l=m.length;l>a;a++)r=m[a],(n||!r.input)&&(_=r.type,o=b(r),s[o]||(s[o]=r),d[_]=f=d[_]||[],f.push(r));for(y=this.outputs,y=y.filter(function(t){return!(e&&t.output.length)}),v=y.slice(),u=0,c=v.length;c>u;u++)E=v[u],_=E.type,o=b(E),i=d[_],(r=s[o])&&(E.connect(r),delete s[o],i.splice(i.indexOf(r),1),y.splice(y.indexOf(E),1));if(!y.length)return this;for(g=y.slice(),h=0,p=g.length;p>h;h++)E=g[h],_=E.type,i=d[_],i&&i.length&&E.connect(i.shift());return this},t.prototype.disconnect=function(t){var e,n,r,i,o,s,a;for(s=this.inputs,e=0,r=s.length;r>e;e++)o=s[e],o.disconnect();for(a=this.outputs,n=0,i=a.length;i>n;n++)o=a[n],o.disconnect();return this},t.prototype._key=function(t){return[t.name,t.inout].join("-")},t.prototype._add=function(t){var e;if(e=this._key(t),t.node)throw new Error("Adding outlet to two nodes at once.");if(this.outlets[e])throw new Error("Adding two identical outlets to same node. ("+e+")");return t.node=this,t.inout===r.IN&&this.inputs.push(t),t.inout===r.OUT&&this.outputs.push(t),this.all.push(t),this.outlets[e]=t},t.prototype._morph=function(t,e){var n;return n=this._key(e),delete this.outlets[n],t.morph(e),n=this._key(e),this.outlets[n]=e},t.prototype._remove=function(t){var e,n;if(n=this._key(t),e=t.inout,t.node!==this)throw new Error("Removing outlet from wrong node.");return t.disconnect(),t.node=null,delete this.outlets[n],t.inout===r.IN&&this.inputs.splice(this.inputs.indexOf(t),1),t.inout===r.OUT&&this.outputs.splice(this.outputs.indexOf(t),1),this.all.splice(this.all.indexOf(t),1),this},t}(),e.exports=i},{"./graph":181,"./outlet":184}],184:[function(t,e,n){var r,i;r=t("./graph"),i=function(){function t(e,n,r,i,o,s){this.inout=e,this.name=n,this.hint=r,this.type=i,this.meta=null!=o?o:{},this.id=s,null==this.hint&&(this.hint=t.hint(this.name)),this.node=null,this.input=null,this.output=[],null==this.id&&(this.id=t.id(this.hint))}return t.make=function(e,n){var r,i,o,s;if(null==n&&(n={}),i=n,null!=e.meta){o=e.meta;for(r in o)s=o[r],i[r]=s}return new t(e.inout,e.name,e.hint,e.type,i)},t.index=0,t.id=function(e){return"_io_"+ ++t.index+"_"+e},t.hint=function(t){return t=t.replace(/^_io_[0-9]+_/,""),t=t.replace(/_i_o$/,""),t=t.replace(/(In|Out|Inout|InOut)$/,"")},t.prototype.morph=function(t){return this.inout=t.inout,this.name=t.name,this.hint=t.hint,this.type=t.type,this.meta=t.meta},t.prototype.dupe=function(e){var n;return null==e&&(e=this.id),n=t.make(this),n.name=e,n},t.prototype.connect=function(t){if(this.inout===r.IN&&t.inout===r.OUT)return t.connect(this);if(this.inout!==r.OUT||t.inout!==r.IN)throw new Error("Can only connect out to in.");if(t.input!==this)return t.disconnect(),t.input=this,this.output.push(t)},t.prototype.disconnect=function(t){var e,n,r,i;if(this.input&&this.input.disconnect(this),this.output.length){if(!t){for(i=this.output,e=0,r=i.length;r>e;e++)t=i[e],t.input=null;return this.output=[]}if(n=this.output.indexOf(t),n>=0)return this.output.splice(n,1),t.input=null}},t}(),e.exports=i},{"./graph":181}],185:[function(t,e,n){var r,i,o,s,a,u;i=t("../graph"),a=t("../linker").Program,o=t("../linker").Layout,u=!1,r=function(){function t(){var t;null==this.namespace&&(this.namespace=a.entry()),this.node=new i.Node(this,null!=(t="function"==typeof this.makeOutlets?this.makeOutlets():void 0)?t:{})}return t.previous=function(t){var e;return null!=(e=t.input)?e.node.owner:void 0},t.prototype.refresh=function(){var t;return this.node.setOutlets(null!=(t="function"==typeof this.makeOutlets?this.makeOutlets():void 0)?t:{})},t.prototype.clone=function(){return new t},t.prototype.compile=function(t,e){var n;return n=new a(t,null!=e?e:a.entry(),this.node.graph),this.call(n,0),n.assemble()},t.prototype.link=function(t,e){var n,r;return r=this.compile(t,e),n=new o(t,this.node.graph),this._include(r,n,0),this["export"](n,0),n.link(r)},t.prototype.call=function(t,e){},t.prototype.callback=function(t,e,n,r,i){},t.prototype["export"]=function(t,e){},t.prototype._info=function(t){var e,n,r;return r=null!=(e=null!=(n=this.node.owner.snippet)?n._name:void 0)?e:this.node.owner.namespace,null!=t?r+="."+t:void 0},t.prototype._outlet=function(t,e){var n;return n=i.Outlet.make(t,e),n.meta.def=t,n},t.prototype._call=function(t,e,n){return e.call(this.node,t,n)},t.prototype._require=function(t,e){return e.require(this.node,t)},t.prototype._inputs=function(e,n,r){var i,o,s,a,u,h,l;for(u=e.main.signature,l=[],o=0,s=u.length;s>o;o++)i=u[o],a=this.node.get(i.name),l.push(null!=(h=t.previous(a))?h.call(n,r+1):void 0);return l},t.prototype._callback=function(t,e,n,r,i,o){return e.callback(this.node,t,n,r,i,o)},t.prototype._include=function(t,e,n){return e.include(this.node,t,n)},t.prototype._link=function(e,n,r){var i,o,a,h,l,c,p,f,d,m,v,g;for(u&&console.log("block::_link",this.toString(),e.namespace),d=e.symbols,g=[],a=0,l=d.length;l>a;a++){if(h=d[a],o=e.externals[h],p=this.node.get(o.name),!p)throw new s("External not found on "+this._info(o.name));if(null==p.meta.child){for(m=[p,p,null],c=m[0],f=m[1],i=m[2];!i&&f;)v=[p.meta.parent,f],f=v[0],p=v[1];if(i=t.previous(p),!i)throw new s("Missing connection on "+this._info(o.name));u&&console.log("callback -> ",this.toString(),o.name,p),i.callback(n,r+1,h,o,p.input),g.push(null!=i?i["export"](n,r+1):void 0)}}return g},t.prototype._trace=function(e,n,r){var i,o,s,a,h,l,c;for(u&&console.log("block::_trace",this.toString(),e.namespace),h=e.main.signature,c=[],o=0,s=h.length;s>o;o++)i=h[o],a=this.node.get(i.name),c.push(null!=(l=t.previous(a))?l["export"](n,r+1):void 0);return c},t}(),s=function(t){var e;return e=new Error(t),e.name="OutletError",e},s.prototype=new Error,e.exports=r},{"../graph":205,"../linker":210}],186:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("./block"),i=function(t){function e(t){this.snippet=t,this.namespace=this.snippet.namespace,e.__super__.constructor.apply(this,arguments)}return o(e,t),e.prototype.clone=function(){return new e(this.snippet)},e.prototype.makeOutlets=function(){var t,e,n,r,i,o,s;return r=this.snippet.main.signature,e=this.snippet.externals,s=this.snippet.symbols,o=function(){var t,e,n;for(n=[],t=0,e=r.length;e>t;t++)i=r[t],n.push(this._outlet(i,{callback:!1}));return n}.call(this),t=function(){var t,r,i;for(i=[],t=0,r=s.length;r>t;t++)n=s[t],i.push(this._outlet(e[n],{callback:!0}));return i}.call(this),o.concat(t)},e.prototype.call=function(t,e){return this._call(this.snippet,t,e),this._inputs(this.snippet,t,e)},e.prototype["export"]=function(t,e){return t.visit(this.namespace,e)?(this._link(this.snippet,t,e),this._trace(this.snippet,t,e)):void 0},e}(r),e.exports=i},{"./block":185}],187:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;o=t("../graph"),r=t("./block"),i=function(t){function e(t){this.graph=t,e.__super__.constructor.apply(this,arguments)}return s(e,t),e.prototype.refresh=function(){return e.__super__.refresh.apply(this,arguments),delete this.subroutine},e.prototype.clone=function(){return new e(this.graph)},e.prototype.makeOutlets=function(){var t,e,n,r,i,s,a,u,h,l,c,p;for(this.make(),u=[],n=[],h=[],t=function(t){return function(t,e){var n,r;return t.meta.callback?t.inout===o.IN?(r=t.dupe(),null==(n=r.meta).child&&(n.child=t),t.meta.parent=r,u.push(r)):void 0:e.push(t.type)}}(this),l=this.graph.inputs(),e=0,i=l.length;i>e;e++)a=l[e],t(a,n);for(c=this.graph.outputs(),r=0,s=c.length;s>r;r++)a=c[r],t(a,h);return n=n.join(","),h=h.join(","),p="("+n+")("+h+")",u.push({name:"callback",type:p,inout:o.OUT,meta:{callback:!0,def:this.subroutine.main}}),u},e.prototype.make=function(){return this.subroutine=this.graph.compile(this.namespace)},e.prototype["export"]=function(t,e){return t.visit(this.namespace,e)?(this._link(this.subroutine,t,e),this.graph["export"](t,e)):void 0},e.prototype.call=function(t,e){return this._require(this.subroutine,t,e)},e.prototype.callback=function(t,e,n,r,i){return this._include(this.subroutine,t,e),this._callback(this.subroutine,t,e,n,r,i)},e}(r),e.exports=i},{"../graph":205,"./block":185}],188:[function(t,e,n){n.Block=t("./block"),n.Call=t("./call"),n.Callback=t("./callback"),n.Isolate=t("./isolate"),n.Join=t("./join")},{"./block":185,"./call":186,"./callback":187,"./isolate":189,"./join":190}],189:[function(t,e,n){var r,i,o,s=function(t,e){function n(){this.constructor=t}for(var r in e)a.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},a={}.hasOwnProperty;i=t("../graph"),r=t("./block"),o=function(t){function e(t){this.graph=t,e.__super__.constructor.apply(this,arguments)}return s(e,t),e.prototype.refresh=function(){return e.__super__.refresh.apply(this,arguments),delete this.subroutine},e.prototype.clone=function(){return new e(this.graph)},e.prototype.makeOutlets=function(){var t,e,n,r,o,s,a,u,h,l,c,p,f,d,m;for(this.make(),l=[],d={},e={},c=["inputs","outputs"],r=0,s=c.length;s>r;r++)for(m=c[r],p=this.graph[m](),o=0,a=p.length;a>o;o++)h=p[o],u=void 0,"return"!==(f=h.hint)&&"callback"!==f||h.inout!==i.OUT||(u=h.hint),null!=d[u]&&(u=void 0),n=h.dupe(u),null==(t=n.meta).child&&(t.child=h),h.meta.parent=n,null!=u&&(d[u]=!0),e[h.name]=n,l.push(n);return l},e.prototype.make=function(){return this.subroutine=this.graph.compile(this.namespace)},e.prototype.call=function(t,e){return this._call(this.subroutine,t,e),this._inputs(this.subroutine,t,e)},e.prototype["export"]=function(t,e){return t.visit(this.namespace,e)?(this._link(this.subroutine,t,e),this._trace(this.subroutine,t,e),this.graph["export"](t,e)):void 0},e.prototype.callback=function(t,e,n,r,i){return i=i.meta.child,i.node.owner.callback(t,e,n,r,i)},e}(r),e.exports=o},{"../graph":205,"./block":185}],190:[function(t,e,n){var r,i,o=function(t,e){function n(){this.constructor=t}for(var r in e)s.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;r=t("./block"),i=function(t){function e(t){this.nodes=t,e.__super__.constructor.apply(this,arguments)}return o(e,t),e.prototype.clone=function(){return new e(this.nodes)},e.prototype.makeOutlets=function(){return[]},e.prototype.call=function(t,e){var n,r,i,o,s,a;for(s=this.nodes,a=[],r=0,i=s.length;i>r;r++)o=s[r],n=o.owner,a.push(n.call(t,e));return a},e.prototype["export"]=function(t,e){var n,r,i,o,s,a;for(s=this.nodes,a=[],r=0,i=s.length;i>r;r++)o=s[r],n=o.owner,a.push(n["export"](t,e));return a},e}(r),e.exports=i},{"./block":185}],191:[function(t,e,n){var r,i,o;o=t("./queue"),i=t("./hash"),r=function(t){var e,n;return e={},n=o(100),function(r){var o,s;return s=r.length>32?"##"+i(r).toString(16):r,o=n(s),null!=o&&delete e[o],null==e[s]&&(e[s]=t(r)),e[s].clone()}},e.exports=r},{"./hash":193,"./queue":197}],192:[function(t,e,n){var r,i,o,s,a;o=t("../graph").Graph,r=t("../block"),a=t("../visualize"),i=function(){function t(t,e,n){this.language=t,this.fetch=e,this.config=n,this.graph()}return t.prototype.pipe=function(e,n,r,i){return e instanceof t?this._concat(e):null!=e&&this._call(e,n,r,i),this},t.prototype.call=function(t,e,n,r){return this.pipe(t,e,n,r)},t.prototype.require=function(e,n,r,i){return e instanceof t?this._import(e):null!=e&&(this.callback(),this._call(e,n,r,i),this.end()),this},t.prototype["import"]=function(t,e,n,r){return this.require(t,e,n,r)},t.prototype.split=function(){return this._group("_combine",!0),this},t.prototype.fan=function(){return this._group("_combine",!1),this},t.prototype.isolate=function(){return this._group("_isolate"),this},t.prototype.callback=function(){return this._group("_callback"),this},t.prototype.next=function(){return this._next(),this},t.prototype.pass=function(){var t;return t=this._stack[2].end,this.end(),this._state.end=this._state.end.concat(t),this},t.prototype.end=function(){var t,e,n,r;return n=this._exit(),r=n[0],t=n[1],e=r.op,this[e]&&this[e](r,t),this},t.prototype.join=function(){return this.end()},t.prototype.graph=function(){for(var t,e;(null!=(e=this._stack)?e.length:void 0)>1;)this.end();return this._graph&&this._tail(this._state,this._graph),t=this._graph,this._graph=new o,this._state=new s,this._stack=[this._state],t},t.prototype.compile=function(t){return null==t&&(t="main"),this.graph().compile(t)},t.prototype.link=function(t){return null==t&&(t="main"),this.graph().link(t)},t.prototype.serialize=function(){return a.serialize(this._graph)},t.prototype.empty=function(){return 0===this._graph.nodes.length},t.prototype._concat=function(t){var e,n,i;if(0===t._state.nodes.length)return this;this._tail(t._state,t._graph);try{e=new r.Isolate(t._graph)}catch(i){throw n=i,this.config.autoInspect&&a.inspect(n,this._graph,t),n}return this._auto(e),this},t.prototype._import=function(t){var e,n,i;if(0===t._state.nodes.length)throw"Can't import empty callback";this._tail(t._state,t._graph);try{e=new r.Callback(t._graph)}catch(i){throw n=i,this.config.autoInspect&&a.inspect(n,this._graph,t),n}return this._auto(e),this},t.prototype._combine=function(t,e){var n,r,i,o,s,a,u,h;for(a=t.start,r=0,o=a.length;o>r;r++)for(h=a[r],u=e.end,i=0,s=u.length;s>i;i++)n=u[i],n.connect(h,t.multi);return e.end=t.end,e.nodes=e.nodes.concat(t.nodes)},t.prototype._isolate=function(t,e){var n,i,o,s;if(t.nodes.length){s=this._subgraph(t),this._tail(t,s);try{n=new r.Isolate(s)}catch(o){throw i=o,this.config.autoInspect&&a.inspect(i,this._graph,s),i}return this._auto(n)}},t.prototype._callback=function(t,e){var n,i,o,s;if(t.nodes.length){s=this._subgraph(t),this._tail(t,s);try{n=new r.Callback(s)}catch(o){throw i=o,this.config.autoInspect&&a.inspect(i,this._graph,s),i}return this._auto(n)}},t.prototype._call=function(t,e,n,i){var o,s;return s=this.fetch(t),s.bind(this.config,e,n,i),o=new r.Call(s),this._auto(o)},t.prototype._subgraph=function(t){var e;return e=new o(null,this._graph),e.adopt(t.nodes),e},t.prototype._tail=function(t,e){var n;if(n=t.end.concat(t.tail),n=n.filter(function(t,e){return n.indexOf(t)===e}),n.length>1&&(n=new r.Join(n),n=[n.node],this._graph.add(n)),e.tail=n[0],t.end=n,t.tail=[],!e.tail)throw new Error("Cannot finalize empty graph");return e.compile=function(t){return function(n){var r,i;null==n&&(n="main");try{return e.tail.owner.compile(t.language,n)}catch(i){throw r=i,t.config.autoInspect&&e.inspect(r),r}}}(this),e.link=function(t){return function(n){var r,i;null==n&&(n="main");try{return e.tail.owner.link(t.language,n)}catch(i){throw r=i,t.config.autoInspect&&e.inspect(r),r}}}(this),e["export"]=function(t){return function(t,n){return e.tail.owner["export"](t,n)}}(this),e.inspect=function(t){return null==t&&(t=null),a.inspect(t,e)}},t.prototype._group=function(t,e){return this._push(t,e),this._push(),this},t.prototype._next=function(){var t;return t=this._pop(),this._state.start=this._state.start.concat(t.start),this._state.end=this._state.end.concat(t.end),this._state.nodes=this._state.nodes.concat(t.nodes),this._state.tail=this._state.tail.concat(t.tail),this._push()},t.prototype._exit=function(){return this._next(),this._pop(),[this._pop(),this._state]},t.prototype._push=function(t,e){return this._stack.unshift(new s(t,e)),this._state=this._stack[0]},t.prototype._pop=function(){var t;return this._state=this._stack[1],null==this._state&&(this._state=new s),null!=(t=this._stack.shift())?t:new s},t.prototype._auto=function(t){return t.node.inputs.length?this._append(t):this._insert(t)},t.prototype._append=function(t){var e,n,r,i,o;for(i=t.node,this._graph.add(i),o=this._state.end,n=0,r=o.length;r>n;n++)e=o[n],e.connect(i);return this._state.start.length||(this._state.start=[i]),this._state.end=[i],this._state.nodes.push(i),i.outputs.length?void 0:this._state.tail.push(i)},t.prototype._prepend=function(t){var e,n,r,i,o;for(r=t.node,this._graph.add(r),i=this._state.start,e=0,n=i.length;n>e;e++)o=i[e],r.connect(o);return this._state.end.length||(this._state.end=[r]),this._state.start=[r],this._state.nodes.push(r),r.outputs.length?void 0:this._state.tail.push(r)},t.prototype._insert=function(t){var e;return e=t.node,this._graph.add(e),this._state.start.push(e),this._state.end.push(e),this._state.nodes.push(e),e.outputs.length?void 0:this._state.tail.push(e)},t}(),s=function(){function t(t,e,n,r,i,o){this.op=null!=t?t:null,this.multi=null!=e?e:!1,this.start=null!=n?n:[],this.end=null!=r?r:[],this.nodes=null!=i?i:[],this.tail=null!=o?o:[]}return t}(),e.exports=i},{"../block":188,"../graph":205,"../visualize":216}],193:[function(t,e,n){var r,i,o,s,a,u,h,l;r=3432918353,i=461845907,o=3864292196,s=2246822507,a=3266489909,h=function(t,e){var n,r,i,o;return n=t>>>16&65535,r=65535&t,i=e>>>16&65535,o=65535&e,r*o+(n*o+r*i<<16>>>0)|0},null!=Math.imul&&(l=Math.imul(4294967295,5),-5===l&&(h=Math.imul)),u=function(t){var e,n,u,l,c,p;for(c=t.length,l=Math.floor(c/2),u=e=0,p=function(){return t.charCodeAt(u++)},n=function(t,n){var s;return s=t|n<<16,s^=s<<9,s=h(s,r),s=s<<15|s>>>17,s=h(s,i),e^=s,e=e<<13|e>>>19,e=h(e,5),e=e+o|0};l--;)n(p(),p());return 1&c&&n(p(),0),e^=c,e^=e>>>16,e=h(e,s),e^=e>>>13,e=h(e,a),e^=e>>>16},e.exports=u},{}],194:[function(t,e,n){n.Factory=t("./factory"),n.Material=t("./material"),n.library=t("./library"),n.cache=t("./cache"),n.queue=t("./queue"),n.hash=t("./hash")},{"./cache":191,"./factory":192,"./hash":193,"./library":195,"./material":196,"./queue":197}],195:[function(t,e,n){var r;r=function(t,e,n){var r,i,o,s;return r=null,s={},null!=e&&("function"==typeof e?r=function(r){return n(t,r,e(r))}:"object"==typeof e&&(r=function(r){if(null==e[r])throw new Error("Unknown snippet `"+r+"`");return n(t,r,e[r])})),o=function(e){return n(t,"",e)},null==r?o:(i=function(t){return t.match(/[{;]/)?o(t):(s[t]=!0,r(t))},i.used=function(t){return null==t&&(t=s),s=t},i)},e.exports=r},{}],196:[function(t,e,n){var r,i,o,s;o=!1,i=t("../visualize"),s=function(){var t;return t=+new Date,function(e){var n;return n=+new Date-t,console.log(e,n+" ms"),n}},r=function(){function t(t,e){this.vertex=t,this.fragment=e,o&&(this.tock=s())}return t.prototype.build=function(t){return this.link(t)},t.prototype.link=function(t){var e,n,r,s,a,u,h,l,c,p,f,d,m,v;for(null==t&&(t={}),f={},m={},e={},v=this.vertex.link("main"),n=this.fragment.link("main"),u=[v,n],r=0,a=u.length;a>r;r++){p=u[r],h=p.uniforms;for(s in h)d=h[s],f[s]=d;l=p.varyings;for(s in l)d=l[s],m[s]=d;c=p.attributes;for(s in c)d=c[s],e[s]=d}return t.vertexShader=v.code,t.vertexGraph=v.graph,t.fragmentShader=n.code,t.fragmentGraph=n.graph,t.attributes=e,t.uniforms=f,t.varyings=m,t.inspect=function(){return i.inspect("Vertex Shader",v,"Fragment Shader",n.graph)},o&&this.tock("Material build"),t},t.prototype.inspect=function(){return i.inspect("Vertex Shader",this.vertex,"Fragment Shader",this.fragment.graph)},t}(),e.exports=r},{"../visualize":216}],197:[function(t,e,n){var r;r=function(t){var e,n,r,i,o,s;return null==t&&(t=100),i={},r=null,s=null,n=0,e=function(t){return t.prev=null,t.next=r,null!=r&&(r.prev=t),r=t,null==s?s=t:void 0},o=function(t){var e,n;return n=t.prev,e=t.next,null!=n&&(n.next=e),null!=e&&(e.prev=n),r===t&&(r=e),s===t?s=n:void 0},function(a){var u,h;return(h=i[a]&&h!==r)?(o(h),e(h)):(n===t?(u=s.key,o(s),delete i[u]):n++,h={next:r,prev:null,key:a},e(h),i[a]=h),u}},e.exports=r},{}],198:[function(t,e,n){var r,i,o,s;r=function(t){var e,n,r,s,a;return n=t.ast,r=t.code,a=t.signatures,s=i(a),e=o(r,s),[a,e]},s=function(){var t;return t=+new Date,function(e){var n;return n=+new Date-t,console.log(e,n+" ms"),n}},i=function(t){var e,n,r,i,o,s,a,u,h,l;for(s={},h=function(t){return s[t.name]=!0},h(t.main),a=["external","internal","varying","uniform","attribute"],e=0,i=a.length;i>e;e++)for(r=a[e],u=t[r],n=0,o=u.length;o>n;n++)l=u[n],h(l);return s},o=function(t,e){var n,r;return r=new RegExp("\\b("+function(){var t;t=[];for(n in e)t.push(n);return t}().join("|")+")\\b","g"),t=t.replace(/\/\/[^\n]*/g,""),t=t.replace(/\/\*([^*]|\*[^\/])*\*\//g,""),function(i,o,s){var a,u,h,l;null==i&&(i=""),null==o&&(o={}),null==s&&(s={}),h={};for(n in e)h[n]=null!=o[n]?n:i+n;return a=t.replace(r,function(t){return h[t]}),u=function(){var t;t=[];for(n in s)l=s[n],t.push("#define "+n+" "+l);return t}(),u.length&&u.push(""),u.join("\n")+a}},e.exports=r},{}],199:[function(t,e,n){e.exports={SHADOW_ARG:"_i_o",RETURN_ARG:"return"}},{}],200:[function(t,e,n){var r,i,o,s,a,u,h;e.exports=i={},i["in"]=0,i.out=1,i.inout=2,s=function(t){return t.token.data},i.node=function(t){var e,n;return"function"===(null!=(e=t.children[5])?e.type:void 0)?i["function"](t):"keyword"===(null!=(n=t.token)?n.type:void 0)?i.external(t):void 0},i.external=function(t){var e,n,r,i,o,a,u,h,l,c,p,f,d;for(e=t.children,p=s(e[1]),f=s(e[3]),d=s(e[4]),a=e[5],"attribute"!==p&&"uniform"!==p&&"varying"!==p&&(p="global"),h=[],c=a.children,n=i=0,o=c.length;o>i;n=++i)e=c[n],"ident"===e.type&&(r=s(e),u=a.children[n+1],l="quantifier"===(null!=u?u.type:void 0),h.push({decl:"external",storage:p,type:d,ident:r,quant:!!l,count:l}));return h},i["function"]=function(t){var e,n,r,o,a,u,h,l,c,p;return r=t.children,l=s(r[1]),c=s(r[3]),p=s(r[4]),u=r[5],h=s(u.children[0]),e=u.children[1],n=u.children[2],a=function(){var t,n,r,s;for(r=e.children,s=[],t=0,n=r.length;n>t;t++)o=r[t],s.push(i.argument(o));return s}(),[{decl:"function",storage:l,type:p,ident:h,body:!!n,args:a}]},i.argument=function(t){var e,n,r,i,o,a,u,h;return e=t.children,u=s(e[1]),i=s(e[2]),h=s(e[4]),o=e[5],r=s(o.children[0]),a=o.children[1],n=a?a.children[0].token.data:void 0,{decl:"argument",storage:u,inout:i,type:h,ident:r,quant:!!a,count:n}},i.param=function(t,e,n,r,o){var s,a,u;return a=[],null!=e&&a.push(e),null!=n&&a.push(n),a.push(""),a=a.join(" "),u=r?"["+o+"]":"",""!==t&&(t+=" "),s=function(e,n){return(n?t:"")+(""+a+e+u)},s.split=function(t){return i.param(t,e,n,r,o)},s},h="undefined"!=typeof window,u=h&&!!window.THREE,o={"int":0,"float":0,vec2:u?THREE.Vector2:null,vec3:u?THREE.Vector3:null,vec4:u?THREE.Vector4:null,mat2:null,mat3:u?THREE.Matrix3:null,mat4:u?THREE.Matrix4:null,sampler2D:0,samplerCube:0},a={"int":"i","float":"f",vec2:"v2",vec3:"v3",vec4:"v4",mat2:"m2",mat3:"m3",mat4:"m4",sampler2D:"t",samplerCube:"t"},i.type=function(t,e,n,s,u,h){var l,c,p,f,d,m,v;return l={"in":i["in"],out:i.out,inout:i.inout},d={"const":"const"},m=a[e],n&&(m+="v"),v=o[e],(null!=v?v.call:void 0)&&(v=new v),n&&(v=[v]),c=null!=(f=l[u])?f:l["in"],h=d[h],p=i.param(u,h,e,n,s),new r(t,m,e,p,v,c)},r=function(){function t(t,e,n,r,i,o,s){this.name=t,this.type=e,this.spec=n,this.param=r,this.value=i,this.inout=o,this.meta=s}return t.prototype.split=function(){var e,n,r,o;return r=null!=this.meta.shadowed,e=r?"in":"out",n=r?i["in"]:i.out,o=this.param.split(e),new t(this.name,this.type,this.spec,o,this.value,n)},t.prototype.copy=function(e,n){var r;return r=new t(null!=e?e:this.name,this.type,this.spec,this.param,this.value,this.inout,n)},t}()},{}],201:[function(t,e,n){var r,i,o;i=t("../graph"),r=t("./constants"),e.exports=o={unshadow:function(t){var e;return e=t.replace(r.SHADOW_ARG,""),e!==t?e:null},lines:function(t){return t.join("\n")},list:function(t){return t.join(", ")},statements:function(t){return t.join(";\n")},body:function(t){return{entry:t,type:"void",params:[],signature:[],"return":"",vars:{},calls:[],post:[],chain:{}}},define:function(t,e){return"#define "+t+" "+e},"function":function(t,e,n,r,i){return t+" "+e+"("+n+") {\n"+r+i+"}"},invoke:function(t,e,n){return t=t?t+" = ":"",n=o.list(n)," "+t+e+"("+n+")"},same:function(t,e){var n,i,o,s,a;for(o=s=0,a=t.length;a>s;o=++s){if(n=t[o],i=e[o],!i)return!1;if(n.type!==i.type)return!1;if(n.name===r.RETURN_ARG!=(i.name===r.RETURN_ARG))return!1}return!0},call:function(t,e,n,i,s){var a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w;for(u=[],T="",x=1,f=0,d=i.length;d>f;f++){if(a=i[f],v=a.name,h=l=t(v),y=null,m=null,g=!1,c=a.inout,p=v===r.RETURN_ARG,(w=null!=(_=a.meta)?_.shadowed:void 0)&&(y=t(w),y&&(s.vars[y]=" "+a.param(y),s.calls.push(" "+y+" = "+l),e(w)?m={shadowed:y}:a=a.split())),(w=null!=(b=a.meta)?b.shadow:void 0)&&(y=t(w))){if(e(w)){m={shadow:y};continue}a=a.split(),g=!0}p?T=l:g||u.push(null!=y?y:l),e(v)?(E="push",p?""===s["return"]?(E="unshift",h=v,s.type=a.spec,s["return"]=" return "+l,s.vars[l]=" "+a.param(l)):(s.vars[l]=" "+a.param(l),s.params.push(a.param(l,!0))):s.params.push(a.param(l,!0)),a=a.copy(h,m),s.signature[E](a)):s.vars[l]=" "+a.param(l)}return s.calls.push(o.invoke(T,n,u))},build:function(t,e){var n,r,i,s,a,u,h,l,c,p,f;return a=t.entry,i=null,e&&1===e.length&&"main"!==a&&(n=t,r=e[0].module,o.same(t.signature,r.main.signature)&&(i=o.define(a,r.entry))),null==i&&(f=function(){var e,n;e=t.vars,n=[];for(p in e)s=e[p],n.push(s);return n}(),e=t.calls,h=t.post,u=t.params,c=t.type,l=t["return"],e=e.concat(h),""!==l&&e.push(l),e.push(""),f.length?(f.push(""),f=o.statements(f)+"\n"):f="",e=o.statements(e),u=o.list(u),i=o["function"](c,a,u,f,e)),{signature:t.signature,code:i,name:a}},links:function(t){var e,n,r,i;for(i={defs:[],bodies:[]},e=0,r=t.length;r>e;e++)n=t[e],o.link(n,i);return i.defs=o.lines(i.defs),i.bodies=o.statements(i.bodies),""===i.defs&&delete i.defs,""===i.bodies&&delete i.bodies,i},link:function(t){return function(t,e){var n,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S;if(y=t.module,b=t.name,l=t.external,g=y.main,h=y.entry,o.same(g.signature,l.signature))return e.defs.push(o.define(b,h));for(p=[],w=[],E={},M=[y.namespace,r.RETURN_ARG].join(""),R=l.signature,f=0,d=R.length;d>f;f++)u=R[f],v=u.inout===i.IN?p:w,v.push(u);for(H=g.signature,_=0,m=H.length;m>_;_++)u=H[_],v=u.inout===i.IN?p:w,T=v.shift(),a=T.name,a===r.RETURN_ARG&&(a=M),E[u.name]=a;return s=function(t){return E[t]},n=function(){return!0},c=o.body(),o.call(s,n,h,g.signature,c),c.entry=h,E={"return":M},s=function(t){var e;return null!=(e=E[t])?e:t},x=o.body(),S=o.call(s,n,h,l.signature,x),x.calls=c.calls,x.entry=b,e.bodies.push(o.build(c).code.split(" {")[0]),e.bodies.push(o.build(x).code)}}(this),defuse:function(t){var e,n,r,i,o,s,a,u,h,l,c,p,f,d,m;for(f=/([A-Za-z0-9_]+\s+)?[A-Za-z0-9_]+\s+[A-Za-z0-9_]+\s*\([^)]*\)\s*;\s*/gm,m=function(t){return t.replace(f,function(t){return""})},n=t.split(/(?=[{}])/g),l=0,o=a=0,u=n.length;u>a;o=++a){switch(e=n[o],e[0]){case"{":l++;break;case"}":l--}if(0===l){for(r=e.split(/^[ \t]*#/m),s=p=0,h=r.length;h>p;s=++p)c=r[s],s>0?(c=c.split(/\n/),i=c.shift(),d=c.join("\n"),r[s]=[i,m(d)].join("\n")):r[s]=m(c);n[o]=r.join("#")}}return t=n.join("")},dedupe:function(t){var e,n;return e={},n=/((attribute|uniform|varying)\s+)[A-Za-z0-9_]+\s+([A-Za-z0-9_]+)\s*(\[[^\]]*\]\s*)?;\s*/gm,t.replace(n,function(t,n,r,i,o){return e[i]?"":(e[i]=!0,t)})},hoist:function(t){var e,n,r,i,o,s,a,u;for(u=/^#define ([^ ]+ _pg_[0-9]+_|_pg_[0-9]+_ [^ ]+)$/,o=t.split(/\n/g),e=[],a=[],n=0,r=o.length;r>n;n++)i=o[n],s=i.match(u)?e:a,s.push(i);return e.concat(a).join("\n")}}},{"../graph":205,"./constants":199}],202:[function(t,e,n){var r,i,o,s,a;for(n.compile=t("./compile"),n.parse=t("./parse"),n.generate=t("./generate"),s=t("./constants"),a=r=0,o=s.length;o>r;a=++r)i=s[a],n[i]=a},{"./compile":198,"./constants":199,"./generate":201,"./parse":203}],203:[function(t,e,n){var r,i,o,s,a,u,h,l,c,p,f,d,m,v;m=t("../../vendor/glsl-tokenizer"),c=t("../../vendor/glsl-parser"),s=t("./decl"),r=t("./constants"),o=!1,h=function(t,e){var n,r;return n=l(t,e),r=p(n,e)},l=function(t,e){var n,r,i,s,a,u,h,l,p,f,v;o&&(v=d());try{p=m().process(c(),e),f=p[0],n=f[0],a=p[1]}catch(s){r=s,a=[{message:r}]}if(o&&v("GLSL Tokenize & Parse"),u=function(t){var e,n;return t=t.split("\n"),e=(""+t.length).length,n=function(t){return(t=""+t).lengthh;h++)i=a[h],console.error(t+" -",i.message);throw new Error("GLSL parse error")}return n},p=function(t,e){var n,r,s,h,l,c,p;return o&&(p=d()),c=[],v(u,i(c),t,""),h=f(c),s=h[0],r=h[1],n=h[2],l=a(s,r,n),o&&p("GLSL AST"),{ast:t,code:e,signatures:l}},u=function(t,e){switch(t.type){case"decl":return e(s.node(t)),!1}return!0},i=function(t){return function(e){var n,r,i,o;if(null!=e){for(o=[],n=0,r=e.length;r>n;n++)i=e[n],o.push(t.push(i));return o}}},f=function(t){var e,n,r,i,o,s,a,u,h;for(a=null,i=[],n=[],u={},r=!1,o=0,s=t.length;s>o;o++)h=t[o],h.body?(u[h.ident]&&(n=function(){var t,r,i;for(i=[],t=0,r=n.length;r>t;t++)e=n[t],e.ident!==h.ident&&i.push(e);return i}(),delete u[h.ident]),i.push(h),"main"===h.ident?(a=h,r=!0):r||(a=h)):"global"===h.storage?i.push(h):(n.push(h),u[h.ident]=!0);return[a,i,n]},a=function(t,e,n){var i,o,a,u,h,l,c,p,f;for(p={uniform:[],attribute:[],varying:[],external:[],internal:[],global:[],main:null},o=function(t){return s.type(t.ident,t.type,t.quant,t.count,t.inout,t.storage)},a=function(t,e){var n,i,a,u,h,l,c,p,f,d,m;for(d=function(){var e,n,r,s;for(r=t.args,s=[],e=0,n=r.length;n>e;e++)i=r[e],s.push(o(i));return s}(),c=0,p=d.length;p>c;c++)u=d[c],u.inout===s.inout&&(n=u,a=u.copy(),n.inout=s["in"],a.inout=s.out,a.meta={shadow:n.name},a.name+=r.SHADOW_ARG,n.meta={shadowed:a.name},d.push(a));return"void"!==t.type&&d.unshift(s.type(r.RETURN_ARG,t.type,!1,"","out")),l=function(){var t,e,n;for(n=[],t=0,e=d.length;e>t;t++)u=d[t],u.inout===s["in"]&&n.push(u.type);return n}().join(","),f=function(){var t,e,n;for(n=[],t=0,e=d.length;e>t;t++)u=d[t],u.inout===s.out&&n.push(u.type);return n}().join(","),m="("+l+")("+f+")",h={name:t.ident,type:m,signature:d,inout:e,spec:t.type}},p.main=a(t,s.out),u=0,l=e.length;l>u;u++)f=e[u],p.internal.push({name:f.ident});for(h=0,c=n.length;c>h;h++)switch(f=n[h],f.decl){case"external":i=o(f),p[f.storage].push(i);break;case"function":i=a(f,s["in"]),p.external.push(i)}return p},o=!1,v=function(t,e,n,r){var i,s,a,u,h,l,c,p;if(o&&console.log(r,n.type,null!=(l=n.token)?l.data:void 0,null!=(c=n.token)?c.type:void 0),h=t(n,e))for(p=n.children,s=a=0,u=p.length;u>a;s=++a)i=p[s],v(t,e,i,r+" ",o);return null},d=function(){var t;return t=+new Date,function(e){var n;return n=+new Date-t,console.log(e,n+" ms"),n}},e.exports=v,e.exports=h},{"../../vendor/glsl-parser":219,"../../vendor/glsl-tokenizer":223,"./constants":199,"./decl":200}],204:[function(t,e,n){var r;r=function(){function t(e,n){this.parent=null!=n?n:null,this.id=t.id(),this.nodes=[],e&&this.add(e)}return t.index=0,t.id=function(e){return++t.index},t.IN=0,t.OUT=1,t.prototype.inputs=function(){var t,e,n,r,i,o,s,a,u;for(e=[],a=this.nodes,t=0,r=a.length;r>t;t++)for(o=a[t],u=o.inputs,n=0,i=u.length;i>n;n++)s=u[n],null===s.input&&e.push(s);return e},t.prototype.outputs=function(){var t,e,n,r,i,o,s,a,u;for(s=[],a=this.nodes,t=0,n=a.length;n>t;t++)for(i=a[t],u=i.outputs,e=0,r=u.length;r>e;e++)o=u[e],0===o.output.length&&s.push(o);return s},t.prototype.getIn=function(t){var e;return function(){var n,r,i,o;for(i=this.inputs(),o=[],n=0,r=i.length;r>n;n++)e=i[n],e.name===t&&o.push(e);return o}.call(this)[0]},t.prototype.getOut=function(t){var e;return function(){var n,r,i,o;for(i=this.outputs(),o=[],n=0,r=i.length;r>n;n++)e=i[n],e.name===t&&o.push(e);return o}.call(this)[0]},t.prototype.add=function(t,e){var n,r,i;{if(!t.length){if(t.graph&&!e)throw new Error("Adding node to two graphs at once");return t.graph=this,this.nodes.push(t)}for(r=0,i=t.length;i>r;r++)n=t[r],this.add(n)}},t.prototype.remove=function(t,e){var n,r,i;{if(!t.length){if(t.graph!==this)throw new Error("Removing node from wrong graph.");return e||t.disconnect(),this.nodes.splice(this.nodes.indexOf(t),1),t.graph=null}for(r=0,i=t.length;i>r;r++)n=t[r],this.remove(n)} +},t.prototype.adopt=function(t){var e,n,r;{if(!t.length)return t.graph.remove(t,!0),this.add(t,!0);for(n=0,r=t.length;r>n;n++)e=t[n],this.adopt(e)}},t}(),e.exports=r},{}],205:[function(t,e,n){n.Graph=t("./graph"),n.Node=t("./node"),n.Outlet=t("./outlet"),n.IN=n.Graph.IN,n.OUT=n.Graph.OUT},{"./graph":204,"./node":206,"./outlet":207}],206:[function(t,e,n){var r,i,o;r=t("./graph"),o=t("./outlet"),i=function(){function t(e,n){this.owner=e,this.graph=null,this.inputs=[],this.outputs=[],this.all=[],this.outlets=null,this.id=t.id(),this.setOutlets(n)}return t.index=0,t.id=function(e){return++t.index},t.prototype.getIn=function(t){var e;return function(){var n,r,i,o;for(i=this.inputs,o=[],n=0,r=i.length;r>n;n++)e=i[n],e.name===t&&o.push(e);return o}.call(this)[0]},t.prototype.getOut=function(t){var e;return function(){var n,r,i,o;for(i=this.outputs,o=[],n=0,r=i.length;r>n;n++)e=i[n],e.name===t&&o.push(e);return o}.call(this)[0]},t.prototype.get=function(t){return this.getIn(t)||this.getOut(t)},t.prototype.setOutlets=function(t){var e,n,r,i,s,a,u,h,l,c,p,f;if(null!=t){if(null==this.outlets){for(this.outlets={},r=0,u=t.length;u>r;r++)p=t[r],p instanceof o||(p=o.make(p)),this._add(p);return}for(n=function(t){return[t.name,t.inout,t.type].join("-")},c={},i=0,h=t.length;h>i;i++)p=t[i],c[n(p)]=!0;f=this.outlets;for(a in f)p=f[a],a=n(p),c[a]?c[a]=p:this._remove(p);for(s=0,l=t.length;l>s;s++)p=t[s],e=c[n(p)],e instanceof o?this._morph(e,p):(p instanceof o||(p=o.make(p)),this._add(p))}return this.outlets},t.prototype.connect=function(t,e,n){var r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b;for(d={},s={},b=function(t){return _+"/"+t.hint},m=t.inputs,a=0,l=m.length;l>a;a++)r=m[a],(n||!r.input)&&(_=r.type,o=b(r),s[o]||(s[o]=r),d[_]=f=d[_]||[],f.push(r));for(y=this.outputs,y=y.filter(function(t){return!(e&&t.output.length)}),v=y.slice(),u=0,c=v.length;c>u;u++)E=v[u],_=E.type,o=b(E),i=d[_],(r=s[o])&&(E.connect(r),delete s[o],i.splice(i.indexOf(r),1),y.splice(y.indexOf(E),1));if(!y.length)return this;for(g=y.slice(),h=0,p=g.length;p>h;h++)E=g[h],_=E.type,i=d[_],i&&i.length&&E.connect(i.shift());return this},t.prototype.disconnect=function(t){var e,n,r,i,o,s,a;for(s=this.inputs,e=0,r=s.length;r>e;e++)o=s[e],o.disconnect();for(a=this.outputs,n=0,i=a.length;i>n;n++)o=a[n],o.disconnect();return this},t.prototype._key=function(t){return[t.name,t.inout].join("-")},t.prototype._add=function(t){var e;if(e=this._key(t),t.node)throw new Error("Adding outlet to two nodes at once.");if(this.outlets[e])throw new Error("Adding two identical outlets to same node. ("+e+")");return t.node=this,t.inout===r.IN&&this.inputs.push(t),t.inout===r.OUT&&this.outputs.push(t),this.all.push(t),this.outlets[e]=t},t.prototype._morph=function(t,e){var n;return n=this._key(e),delete this.outlets[n],t.morph(e),n=this._key(e),this.outlets[n]=e},t.prototype._remove=function(t){var e,n;if(n=this._key(t),e=t.inout,t.node!==this)throw new Error("Removing outlet from wrong node.");return t.disconnect(),t.node=null,delete this.outlets[n],t.inout===r.IN&&this.inputs.splice(this.inputs.indexOf(t),1),t.inout===r.OUT&&this.outputs.splice(this.outputs.indexOf(t),1),this.all.splice(this.all.indexOf(t),1),this},t}(),e.exports=i},{"./graph":204,"./outlet":207}],207:[function(t,e,n){var r,i;r=t("./graph"),i=function(){function t(e,n,r,i,o,s){this.inout=e,this.name=n,this.hint=r,this.type=i,this.meta=null!=o?o:{},this.id=s,null==this.hint&&(this.hint=t.hint(this.name)),this.node=null,this.input=null,this.output=[],null==this.id&&(this.id=t.id(this.hint))}return t.make=function(e,n){var r,i,o,s;if(null==n&&(n={}),i=n,null!=e.meta){o=e.meta;for(r in o)s=o[r],i[r]=s}return new t(e.inout,e.name,e.hint,e.type,i)},t.index=0,t.id=function(e){return"_io_"+ ++t.index+"_"+e},t.hint=function(t){return t=t.replace(/^_io_[0-9]+_/,""),t=t.replace(/_i_o$/,""),t=t.replace(/(In|Out|Inout|InOut)$/,"")},t.prototype.morph=function(t){return this.inout=t.inout,this.name=t.name,this.hint=t.hint,this.type=t.type,this.meta=t.meta},t.prototype.dupe=function(e){var n;return null==e&&(e=this.id),n=t.make(this),n.name=e,n},t.prototype.connect=function(t){if(this.inout===r.IN&&t.inout===r.OUT)return t.connect(this);if(this.inout!==r.OUT||t.inout!==r.IN)throw new Error("Can only connect out to in.");if(t.input!==this)return t.disconnect(),t.input=this,this.output.push(t)},t.prototype.disconnect=function(t){var e,n,r,i;if(this.input&&this.input.disconnect(this),this.output.length){if(!t){for(i=this.output,e=0,r=i.length;r>e;e++)t=i[e],t.input=null;return this.output=[]}if(n=this.output.indexOf(t),n>=0)return this.output.splice(n,1),t.input=null}},t}(),e.exports=i},{"./graph":204}],208:[function(t,e,n){var r,i,o,s,a,u,h,l,c,p,f,d,m;r=t("./block"),i=t("./factory"),o=t("./glsl"),s=t("./graph"),a=t("./linker"),l=t("./visualize"),f=i.library,c=i.cache,m=l.visualize,p=l.inspect,h=a.Snippet,d=function(t,e){var n,r,i,o;null==e&&(e={}),r={};for(n in t)o=t[n],r[n]=null!=(i=e[n])?i:t[n];return r},u=function(){function t(e,n){var r;return this instanceof t?(r={globalUniforms:!1,globalVaryings:!0,globalAttributes:!0,globals:[],autoInspect:!1},this.config=d(r,n),void(this.fetch=c(f(o,e,h.load)))):new t(e,n)}return t.prototype.shader=function(t){var e;return null==t&&(t={}),e=d(this.config,t),new i.Factory(o,this.fetch,e)},t.prototype.material=function(t){return new i.Material(this.shader(t),this.shader(t))},t.prototype.inspect=function(e){return t.inspect(e)},t.prototype.visualize=function(e){return t.visualize(e)},t.Block=r,t.Factory=i,t.GLSL=o,t.Graph=s,t.Linker=a,t.Visualize=l,t.inspect=function(t){return p(t)},t.visualize=function(t){return m(t)},t}(),e.exports=u,"undefined"!=typeof window&&(window.ShaderGraph=u)},{"./block":188,"./factory":194,"./glsl":202,"./graph":205,"./linker":210,"./visualize":216}],209:[function(t,e,n){var r,i,o;r=t("../graph"),i=t("./priority"),o=function(t,e,n,o){var s,a,u,h,l,c,p,f,d,m,v,g,E,y;return h=t.generate,u={},g=[],E={},y={},a={},f={},m=function(){var t,r,s,c,p,d,m,_,b;for(d in o)m=o[d],v(m.node,m.module);return _=l(n),t=_[0],n=_[1],null!=e&&(t.entry=e),p=h.build(t,n),b=function(){var t;t=[];for(d in f)c=f[d],t.push(c);return t}().sort(function(t,e){return i.compare(t.priority,e.priority)}),s=b.map(function(t){return t.code}),s.push(p.code),r=h.lines(s),{namespace:p.name,library:f,body:p.code,code:r,main:p,entry:p.name,symbols:g,externals:u,uniforms:E,varyings:y,attributes:a}},l=function(t){return function(t){var e,n,r,i,o,s;for(t=function(){var e;e=[];for(s in t)n=t[s],e.push(n);return e}(),t.sort(function(t,e){return e.priority-t.priority}),r=function(t,n,r){var i,o,s,a;return c(t,n,r),a=n.main,s=n.entry,o=function(e){return d(t,e)},i=function(e){return p(t,e)},h.call(o,i,s,a.signature,e)},e=h.body(),i=0,o=t.length;o>i;i++)n=t[i],r(n.node,n.module,n.priority);return[e,t]}}(this),s=function(t,e,n){var r;return r=f[t],null!=r?r.priority=i.max(r.priority,n):f[t]={code:e,priority:n}},c=function(t,e,n){var r,o,u,h,l,c,p,f;n=i.make(n),l=e.library;for(h in l)u=l[h],s(h,u.code,i.nest(n,u.priority));s(e.namespace,e.body,n),c=e.uniforms;for(o in c)r=c[o],E[o]=r;p=e.varyings;for(o in p)r=p[o],y[o]=r;f=e.attributes;for(o in f)r=f[o],a[o]=r;return v(t,e)},v=function(t,e){var n,r,i,o,s,a,h,l,c;for(h=e.symbols,l=[],i=0,a=h.length;a>i;i++)if(s=h[i],r=e.externals[s],p(t,r.name)){n={};for(o in r)c=r[o],n[o]=c;n.name=d(t,r.name),u[s]=n,l.push(g.push(s))}else l.push(void 0);return l},p=function(t,e){var n;return n=t.get(e),n.inout===r.IN?null===n.input:n.inout===r.OUT?0===n.output.length:void 0},d=function(t,e){var n;return(n=t.get(e))?(n.input&&(n=n.input),e=n.name,n.id):null},m()},e.exports=o},{"../graph":205,"./priority":213}],210:[function(t,e,n){n.Snippet=t("./snippet"),n.Program=t("./program"),n.Layout=t("./layout"),n.assemble=t("./assemble"),n.link=t("./link"),n.priority=t("./priority"),n.load=n.Snippet.load},{"./assemble":209,"./layout":211,"./link":212,"./priority":213,"./program":214,"./snippet":215}],211:[function(t,e,n){var r,i,o,s;i=t("./snippet"),s=t("./link"),o=!1,r=function(){function t(t,e){this.language=t,this.graph=e,this.links=[],this.includes=[],this.modules={},this.visits={}}return t.prototype.callback=function(t,e,n,r,i){return this.links.push({node:t,module:e,priority:n,name:r,external:i})},t.prototype.include=function(t,e,n){var r;return null!=(r=this.modules[e.namespace])?r.priority=Math.max(n,r.priority):(this.modules[e.namespace]=!0,this.includes.push({node:t,module:e,priority:n}))},t.prototype.visit=function(t){return o&&console.log("Visit",t,!this.visits[t]),this.visits[t]?!1:this.visits[t]=!0},t.prototype.link=function(t){var e,n,r;e=s(this.language,this.links,this.includes,t),r=new i;for(n in e)r[n]=e[n];return r.graph=this.graph,r},t}(),e.exports=r},{"./link":212,"./snippet":215}],212:[function(t,e,n){var r,i,o;r=t("../graph"),i=t("./priority"),o=function(t,e,n,o){var s,a,u,h,l,c,p,f,d,m,v,g;return h=t.generate,c=[],m=[],u={},v={},a={},g={},f={},d=function(){var t,r,s,p,d,m,E,y,_,b;for(s=h.links(e),p=[],null!=s.defs&&p.push(s.defs),null!=s.bodies&&p.push(s.bodies),d=0,m=n.length;m>d;d++)y=n[d],l(y.node,y.module,y.priority);return b=function(){var t;t=[];for(_ in f)E=f[_],t.push(E);return t}().sort(function(t,e){return i.compare(t.priority,e.priority)}),c=b.map(function(t){return t.code}),t=h.lines(c),t=h.defuse(t),p.length&&(t=[h.lines(p),t].join("\n")),t=h.hoist(t),t=h.dedupe(t),r=o,{namespace:r.main.name,code:t,main:r.main,entry:r.main.name,externals:u,uniforms:v,attributes:a,varyings:g}},s=function(t,e,n){var r;return r=f[t],null!=r?r.priority=i.max(r.priority,n):f[t]={code:e,priority:n}},l=function(t,e,n){var r,o,h,l,c,f,d,E,y,_,b,T,x;n=i.make(n),E=e.library;for(d in E)f=E[d],s(d,f.code,i.nest(n,f.priority));s(e.namespace,e.body,n),y=e.uniforms;for(l in y)r=y[l],v[l]=r;_=e.varyings;for(l in _)r=_[l],g[l]=r;b=e.attributes;for(l in b)r=b[l],a[l]=r;for(T=e.symbols,x=[],h=0,c=T.length;c>h;h++)l=T[h],o=e.externals[l],p(t,o.name)?(u[l]=o,x.push(m.push(l))):x.push(void 0);return x},p=function(t,e){var n,i,o,s;if(i=t.get(e),!i)throw n=null!=(o=null!=(s=t.owner.snippet)?s._name:void 0)?o:t.owner.namespace,new Error("Unable to link program. Unlinked callback `"+e+"` on `"+n+"`");return i.inout===r.IN?null===i.input:i.inout===r.OUT?0===i.output.length:void 0},d()},e.exports=o},{"../graph":205,"./priority":213}],213:[function(t,e,n){n.make=function(t){var e;return null==t&&(t=[]),t instanceof Array||(t=[null!=(e=+t)?e:0]),t},n.nest=function(t,e){return t.concat(e)},n.compare=function(t,e){var n,r,i,o,s,a;for(i=Math.min(t.length,e.length),n=r=0,a=i;a>=0?a>r:r>a;n=a>=0?++r:--r){if(o=t[n],s=e[n],o>s)return-1;if(s>o)return 1}return t=t.length,e=e.length,t>e?-1:e>t?1:0},n.max=function(t,e){return n.compare(t,e)>0?e:t}},{}],214:[function(t,e,n){var r,i,o;i=t("./snippet"),o=t("./assemble"),r=function(){function t(t,e,n){this.language=t,this.namespace=e,this.graph=n,this.calls={},this.requires={}}return t.index=0,t.entry=function(){return"_pg_"+ ++t.index+"_"},t.prototype.call=function(t,e,n){var r,i;return i=e.namespace,(r=this.calls[i])?r.priority=Math.max(r.priority,n):this.calls[i]={node:t,module:e,priority:n},this},t.prototype.require=function(t,e){var n;return n=e.namespace,this.requires[n]={node:t,module:e}},t.prototype.assemble=function(){var e,n,r,s;e=o(this.language,null!=(r=this.namespace)?r:t.entry,this.calls,this.requires),s=new i;for(n in e)s[n]=e[n];return s.graph=this.graph,s},t}(),e.exports=r},{"./assemble":209,"./snippet":215}],215:[function(t,e,n){var r;r=function(){function t(t,e,n,r,i){var o;this.language=t,this._signatures=e,this._compiler=n,this._name=r,this._original=i,this.namespace=null,this.code=null,this.main=null,this.entry=null,this.uniforms=null,this.externals=null,this.symbols=null,this.attributes=null,this.varyings=null,this.language||delete this.language,this._signatures||delete this._signatures,this._compiler||delete this._compiler,this._original||delete this._original,this._name||(this._name=null!=(o=this._signatures)?o.main.name:void 0)}return t.index=0,t.namespace=function(){return"_sn_"+ ++t.index+"_"},t.load=function(e,n,r){var i,o,s,a;return o=e.parse(n,r),s=e.compile(o),a=s[0],i=s[1],new t(e,a,i,n,r)},t.prototype.clone=function(){return new t(this.language,this._signatures,this._compiler,this._name,this._original)},t.prototype.bind=function(e,n,r,i){var o,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R,H,M,S,k,A,C,P,L,z,O,D,F,U,B,N,V,I,j,G;if(n===""+n?(L=[n,null!=r?r:{},null!=i?i:{}],r=L[0],n=L[1],i=L[2]):r!==""+r&&(z=[null!=r?r:{},void 0],i=z[0],r=z[1]),this.main=this._signatures.main,this.namespace=null!=(O=null!=r?r:this.namespace)?O:t.namespace(),this.entry=this.namespace+this.main.name,this.uniforms={},this.varyings={},this.attributes={},this.externals={},this.symbols=[],d={},f={},m=function(t){return f[t]=!0,t},M=function(t){return function(e){return t.namespace+e}}(this),e.globals)for(D=e.globals,v=0,b=D.length;b>v;v++)y=D[v],m(y);for(a=e.globalUniforms?m:M,u=e.globalVaryings?m:M,o=e.globalAttributes?m:M,s=M,G=function(t){return function(t){return d[t.name]=!0}}(this),I=function(t){return function(e,n){return t.uniforms[a(null!=n?n:e.name)]=e}}(this),j=function(t){return function(e){return t.varyings[u(e.name)]=e}}(this),h=function(t){return function(e){return t.attributes[o(e.name)]=e}}(this),p=function(t){return function(e){var n;return n=s(e.name),t.externals[n]=e,t.symbols.push(n)}}(this),P=function(t){return{type:t.type,name:t.name,value:t.value}},F=this._signatures.uniform,g=0,T=F.length;T>g;g++)l=F[g],G(l);for(U=this._signatures.uniform,_=0,x=U.length;x>_;_++)l=U[_],I(P(l));for(B=this._signatures.varying,S=0,w=B.length;w>S;S++)l=B[S],j(P(l));for(N=this._signatures.external,k=0,R=N.length;R>k;k++)l=N[k],p(l);for(V=this._signatures.attribute,C=0,H=V.length;H>C;C++)l=V[C],h(P(l));for(A in n)l=n[A],d[A]&&I(l,A);return this.body=this.code=this._compiler(this.namespace,f,i),i&&(c=function(){var t;t=[];for(E in i)j=i[E],t.push("#define "+E+" "+j);return t}().join("\n"),c.length&&(this._original=[c,"//----------------------------------------",this._original].join("\n"))),null},t}(),e.exports=r},{}],216:[function(t,e,n){var r,i,o,s,a,u;r=t("../Graph").Graph,n.serialize=a=t("./serialize"),n.markup=i=t("./markup"),u=function(t){var e;if(t)return t.nodes?(e=a(t),i.process(e)):t},s=function(t){return null==t?t:t instanceof Array?t.map(s):null!=t.vertex&&null!=t.fragment?[s(t.vertex,s(t.fragment))]:null!=t._graph?t._graph:null!=t.graph?t.graph:t},o=function(t){var e,n,r,i;for(i=[],n=0,r=t.length;r>n;n++)e=t[n],e instanceof Array?i=i.concat(o(e)):null!=e&&i.push(e);return i},n.visualize=function(){var t,e;return e=o(s([].slice.call(arguments))),i.merge(function(){var n,r,i;for(i=[],n=0,r=e.length;r>n;n++)t=e[n],t&&i.push(u(t));return i}())},n.inspect=function(){var t,e,r,o,s,a;for(t=n.visualize.apply(null,arguments),r=i.overlay(t),a=document.querySelectorAll(".shadergraph-overlay"),o=0,s=a.length;s>o;o++)e=a[o],e.remove();return document.body.appendChild(r),t.update(),r}},{"../Graph":182,"./markup":217,"./serialize":218}],217:[function(t,e,n){var r,i,o,s,a,u,h,l,c,p,f,d,m,v,g,E;h=t("../factory/hash"),g=function(t){return(""+t).replace(/^\s+|\s+$/g,"")},a=function(t,e,n,r){return"rgba("+[t,e,n,r].join(", ")+")"},l=function(t,e){var n,r,i,o,s,u,l;return null==e&&(e=1),r=1193046^h(t),l=255&r,i=r>>>8&255,n=r>>>16&255,o=Math.max(l,i,n),u=140/o,s=Math.round(o/3),l=Math.min(255,Math.round(u*Math.max(l,s))),i=Math.min(255,Math.round(u*Math.max(i,s))),n=Math.min(255,Math.round(u*Math.max(n,s))),a(l,i,n,e)},u=function(t){return t=null!=t?t:"",t.replace(/&/g,"&").replace(//g,">").replace(/'/g,"'").replace(/"/g,""")},m=function(t){var e,n;return n=[],e=i(t,n),e.update=function(){return s(e,n)},r(e),e},r=function(t){var e,n,r,i,o;for(n=t.querySelectorAll(".shadergraph-code"),o=[],r=0,i=n.length;i>r;r++)e=n[r],o.push(function(){var t;return t=e,t.parentNode.classList.add("shadergraph-has-code"),t.parentNode.addEventListener("click",function(e){return t.style.display={block:"none",none:"block"}[t.style.display||"none"]})}());return o},o=function(t){var e,n,r,i,o,s,a,u,h,l,c,p,f,d,m;for(c={},u={},f=t.nodes,e=0,i=f.length;i>e;e++)l=f[e],c[l.id]=l;for(d=t.links,n=0,o=d.length;o>n;n++)a=d[n],null==u[h=a.from]&&(u[h]=[]),u[a.from].push(a);for(p=function(t,e){var n,r,i,o;if(null==e&&(e=0),t.depth=Math.max(null!=(o=t.depth)?o:0,e),i=u[t.id])for(n=0,r=i.length;r>n;n++)a=i[n],p(c[a.to],e+1);return null},m=t.nodes,r=0,s=m.length;s>r;r++)l=m[r],null==l.depth&&p(l);return null},i=function(t,e){var n,r,s,a,h,c,p,f,d,m,v,E,y,_,b,T,x,w,R,H,M,S,k,A,C,P;for(o(t),P=document.createElement("div"),P.classList.add("shadergraph-graph"),c=[],M={},S=t.nodes,f=0,E=S.length;E>f;f++){for(R=S[f],r=document.createElement("div"),r.classList.add("shadergraph-node"),r.classList.add("shadergraph-node-"+R.type),r.innerHTML='
'+u(R.name)+"
",n=function(t,e){var n,i;return n=l(t.type),i=document.createElement("div"),i.classList.add("shadergraph-outlet"),i.classList.add("shadergraph-outlet-"+e),i.innerHTML='
\n
'+u(t.type)+'
\n
'+u(t.name)+"
",r.appendChild(i),M[t.id]=i.querySelector(".shadergraph-point")},k=R.inputs,d=0,y=k.length;y>d;d++)H=k[d],n(H,"in");for(A=R.outputs,m=0,_=A.length;_>m;m++)H=A[m],n(H,"out");null!=R.graph?r.appendChild(i(R.graph,e)):(s=document.createElement("div"),s.classList.add("shadergraph-clear"),r.appendChild(s)),null!=R.code&&(p=document.createElement("div"),p.classList.add("shadergraph-code"),p.innerHTML=u(g(R.code)),r.appendChild(p)),h=c[R.depth],null==h&&(h=document.createElement("div"),h.classList.add("shadergraph-column"),c[R.depth]=h),h.appendChild(r)}for(v=0,b=c.length;b>v;v++)h=c[v],null!=h&&P.appendChild(h);for(C=t.links,w=0,T=C.length;T>w;w++)x=C[w],a=l(x.type),e.push({color:a,out:M[x.out],"in":M[x["in"]]});return P},v=function(t){return t*t},d=function(t,e,n,r){var i,o,s,a,u,h,l,c;return o=n-t,s=r-e,i=Math.sqrt(v(o)+v(s)),c=Math.abs(s)>Math.abs(o),c?(h=(t+n)/2,l=(e+r)/2,a=s>0?.3:-.3,u=Math.min(Math.abs(o)/2,20+i/8),["M",t,e,"C",t+u,e+",",h,l-i*a,h,l,"C",h,l+i*a,n-u,r+",",n,r].join(" ")):(u=Math.min(Math.abs(o)/2.5,20+i/4),["M",t,e,"C",t+u,e+",",n-u,r+",",n,r].join(" "))},c=function(t){return null==t&&(t="svg"),document.createElementNS("http://www.w3.org/2000/svg",t)},s=function(t,e){var n,r,i,o,s,a,u,h,l,p,f,m;if(null!=t.parentNode){for(f=t.getBoundingClientRect(),s=0,u=e.length;u>s;s++)p=e[s],n=p.out.getBoundingClientRect(),r=p["in"].getBoundingClientRect(),p.coords={x1:(n.left+n.right)/2-f.left,y1:(n.top+n.bottom)/2-f.top,x2:(r.left+r.right)/2-f.left,y2:(r.top+r.bottom)/2-f.top};for(m=t.querySelector("svg"),null!=m&&t.removeChild(m),i=t;i.parentNode&&0===i.offsetHeight;)i=i.parentNode;for(m=c(),m.setAttribute("width",i.offsetWidth),m.setAttribute("height",i.offsetHeight),a=0,h=e.length;h>a;a++)p=e[a],o=p.coords,l=c("path"),l.setAttribute("d",d(o.x1,o.y1,o.x2,o.y2)),l.setAttribute("stroke",p.color),l.setAttribute("stroke-width",3),l.setAttribute("fill","transparent"),m.appendChild(l);return t.appendChild(m)}},f=function(t){var e,n,r,i;return n=document.createElement("div"),n.setAttribute("class","shadergraph-overlay"),e=document.createElement("div"),e.setAttribute("class","shadergraph-close"),e.innerHTML="×",i=document.createElement("div"),i.setAttribute("class","shadergraph-view"),r=document.createElement("div"),r.setAttribute("class","shadergraph-inside"),r.appendChild(t),i.appendChild(r),n.appendChild(i),n.appendChild(e),e.addEventListener("click",function(){return n.parentNode.removeChild(n)}),n},E=function(t){var e;return t instanceof Node?t:(e=document.createElement("span"),e.innerText=null!=t?t:"",e)},p=function(t){var e,n,r,i;if(1!==t.length){for(e=document.createElement("div"),r=0,i=t.length;i>r;r++)n=t[r],e.appendChild(E(n));return e.update=function(){var e,r,i;for(i=[],e=0,r=t.length;r>e;e++)n=t[e],i.push("function"==typeof n.update?n.update():void 0);return i},e}return E(t[0])},e.exports={process:m,merge:p,overlay:f}},{"../factory/hash":193}],218:[function(t,e,n){var r,i,o;r=t("../block"),i=function(t){return"("===t.type[0]},o=function(t){var e,n,i,s,a,u,h,l,c,p,f,d,m,v,g,E,y,_,b,T,x,w,R;for(v=[],d=[],b=t.nodes,i=0,l=b.length;l>i;i++){for(m=b[i],_={id:m.id,name:null,type:null,depth:null,graph:null,inputs:[],outputs:[]},v.push(_),s=_.inputs,y=_.outputs,e=m.owner,e instanceof r.Call?(_.name=e.snippet._name,_.type="call",_.code=e.snippet._original):e instanceof r.Callback?(_.name="Callback",_.type="callback",_.graph=o(e.graph)):e instanceof r.Isolate?(_.name="Isolate",_.type="isolate",_.graph=o(e.graph)):e instanceof r.Join?(_.name="Join",_.type="join"):null!=e&&(null==_.name&&(_.name=null!=(T=e.name)?T:e.type),null==_.type&&(_.type=e.type),null==_.code&&(_.code=e.code),null!=e.graph&&(_.graph=o(e.graph))),n=function(t){return t=t.replace(")(",")→("),t=t.replace("()","")},x=m.inputs,a=0,c=x.length;c>a;a++)E=x[a],s.push({id:E.id,name:E.name,type:n(E.type),open:null==E.input});for(w=m.outputs,u=0,p=w.length;p>u;u++)for(E=w[u],y.push({id:E.id,name:E.name,type:n(E.type),open:!E.output.length}),R=E.output,h=0,f=R.length;f>h;h++)g=R[h],d.push({from:m.id,out:E.id,to:g.node.id,"in":g.id,type:n(E.type)})}return{nodes:v,links:d}},e.exports=o},{"../block":188}],219:[function(t,e,n){e.exports=t("./lib/index")},{"./lib/index":221}],220:[function(t,e,n){function r(){return this}function i(t,e){var n=E[t];return e=e||0,n?e>n.lbp&&(n.lbp=e):(n=Object.create(g),n.id=t,n.lbp=e,E[t]=n),n}function o(t){var e,n=d;for(c(),e=n.nud();t=m.length)return void(d=E["(end)"]);if(e=m[v++],n=e.data,i=e.type,"ident"===i)o=f.scope.find(n)||f.create_node(),i=o.type;else if("builtin"===i)o=E["(builtin)"];else if("keyword"===i)o=E["(keyword)"];else if("operator"===i){if(o=E[n],!o)return f.unexpected("unknown operator `"+n+"`")}else{if("float"!==i&&"integer"!==i)return f.unexpected("unexpected token.");i="literal",o=E["(literal)"]}return o&&(o.nud||(o.nud=r),o.children||(o.children=[])),o=Object.create(o),o.token=e,o.type=i,o.data||(o.data=n),d=o}function p(t){return function(){return f.unexpected(t)}}var f,d,m,v,g={nud:function(){return this.children&&this.children.length?this:p("unexpected")()},led:p("missing operator")},E={};i("(ident)").nud=r,i("(keyword)").nud=r,i("(builtin)").nud=r,i("(literal)").nud=r,i("(end)"),i(":"),i(";"),i(","),i(")"),i("]"),i("}"),a("&&",30),a("||",30),s("|",43),s("^",44),s("&",45),s("==",46),s("!=",46),s("<",47),s("<=",47),s(">",47),s(">=",47),s(">>",48),s("<<",48),s("+",50),s("-",50),s("*",60),s("/",60),s("%",60),s("?",20,function(t){return this.children=[t,o(0),(c(":"),o(0))],this.type="ternary",this}),s(".",80,function(t){return d.type="literal",f.fake(d),this.children=[t,d],c(),this}),s("[",80,function(t){return this.children=[t,o(0)],this.type="binary",c("]"),this}),s("(",80,function(t){if(this.children=[t],this.type="call",")"!==d.data)for(;;){if(this.children.push(o(0)),","!==d.data)break;c(",")}return c(")"),this}),u("-"),u("+"),u("!"),u("~"),u("defined"),u("(",function(){return this.type="group",this.children=[o(0)],c(")"),this}),u("++"),u("--"),h("++"),h("--"),l("="),l("+="),l("-="),l("*="),l("/="),l("%="),l("&="),l("|="),l("^="),l(">>="),l("<<="),e.exports=function(t,e){function n(t){f.unshift(t,!1);for(var e=0,r=t.children.length;r>e;++e)n(t.children[e]);f.shift()}f=t,m=e,v=0;var r;if(m.length){if(c(),r=o(0),r.parent=f[0],n(r),v1?void ht("unexpected EOF"):void qt.emit("end")}function n(){return Qt||!Yt.length?!1:(Ct=Zt[0])&&!qt.paused}function r(t){Yt.unshift(t),Yt.shift()}function f(t,e){t.parent=Yt[0];var n=[].unshift.call(this,t);if(e=void 0===e?!0:e,p){for(var r="",i=0,o=this.length-1;o>i;++i)r+=" |";console.log(r,"\\"+t.type,t.token.data)}return e&&Pt!==t&&Pt.children.push(t),Pt=t,n}function M(){var t=[].shift.call(this),e=Xt[this.length],n=!1;if(p){for(var r="",i=0,o=this.length;o>i;++i)r+=" |";console.log(r,"/"+t.type)}return Xt.length?"function"==typeof Xt[0]?n=Xt[0](t):void 0!==e&&(n=e.test?e.test(t.type):e===t.type):n=!0,n&&qt.emit("data",t),Pt=t.parent,t}function S(){function t(){if(Ct.data===Yt[0].expecting)return Yt.scope.exit(),Yt.shift();switch(Ct.type){case"preprocessor":return Yt.fake(it()),void Zt.shift();default:return void Yt.unshift(zt())}}return pt(function(){return Yt.scope.enter(),c},t)()}function N(){if(Yt[0].brace)return"}"!==Ct.data?ht("expected `}`, got "+Ct.data):(Yt[0].brace=!1,Zt.shift(),Yt.shift());switch(Ct.type){case"eof":return Yt.shift();case"keyword":switch(Ct.data){case"for":return Yt.unshift(Nt());case"if":return Yt.unshift(Vt());case"while":return Yt.unshift(It());case"do":return Yt.unshift(Gt());case"break":return Yt.fake(i(P,Ct)),Zt.shift();case"continue":return Yt.fake(i(L,Ct)),Zt.shift();case"discard":return Yt.fake(i(z,Ct)),Zt.shift();case"return":return Yt.unshift(jt());case"precision":return Yt.unshift(Dt())}return Yt.unshift(ot(W));case"ident":var t;if(t=Yt.scope.find(Ct.data))return"struct"===t.parent.type?Yt.unshift(ot(W)):Yt.unshift(at(";"));case"operator":if("{"===Ct.data){Yt[0].brace=!0;var e=Lt();return e.expecting="}",Zt.shift(),Yt.unshift(e)}if(";"===Ct.data)return Zt.shift(),Yt.shift();default:return Yt.unshift(at(";"))}}function Q(){function t(){return"invariant"===Ct.data?d.flags&V?(Yt.unshift(ut()),c):ht("`invariant` is not allowed here"):(Yt.fake(i(D,{data:"",position:Ct.position})),c)}function e(){return o(Ct)?d.flags&I?(Yt.unshift(ut()),c):ht("storage is not allowed here"):(Yt.fake(i(D,{data:"",position:Ct.position})),c)}function n(){return s(Ct)?d.flags&j?ht("parameter is not allowed here"):(Yt.unshift(ut()),c):(Yt.fake(i(D,{data:"",position:Ct.position})),c)}function r(){return a(Ct)?(Yt.unshift(ut()),c):(Yt.fake(i(D,{data:"",position:Ct.position})),c)}function u(){if("struct"===Ct.data)return d.flags&G?(Yt.unshift(st()),c):ht("cannot nest structs");if("keyword"===Ct.type)return Yt.unshift(ut()),c;var t=Yt.scope.find(Ct.data);return t?(Yt.fake(Object.create(t)),Zt.shift(),c):ht("expected user defined type, struct or keyword, got "+Ct.data)}function h(){return","!==Ct.data||d.flags&B?"["===Ct.data?void Yt.unshift(Wt()):")"===Ct.data?Yt.shift():";"===Ct.data?d.stage+3:"ident"!==Ct.type?(console.log(Ct),ht("expected identifier, got "+Ct.data)):(d.collected_name=Zt.shift(),c):Yt.shift()}function l(){return"("===Ct.data?(Zt.unshift(d.collected_name),delete d.collected_name,Yt.unshift(Ut()),d.stage+2):c}function p(){return Zt.unshift(d.collected_name),delete d.collected_name,Yt.unshift(Ot()),c}function f(){return Yt.shift()}var d=Yt[0];return pt(t,e,n,r,u,h,l,p,f)()}function J(){if("ident"===Ct.type){var t=Ct.data;return Yt.unshift(Ft()),void Yt.scope.define(t)}if("operator"===Ct.type){if(","===Ct.data)return Yt[1].flags&B?Zt.shift():Yt.shift();if("="===Ct.data)return Yt[1].flags&U?(Zt.shift(),void Yt.unshift(at(",",";"))):ht("`=` is not allowed here.");if("["===Ct.data)return void Yt.unshift(Wt())}return Yt.shift()}function $(){return"keyword"===Ct.type?(Yt[0].type="keyword",void(Yt[0].mode=k)):"ident"===Ct.type?(Yt[0].type="ident",void(Yt[0].mode=d)):ht("expected keyword or user-defined name, got "+Ct.data)}function tt(){return"keyword"!==Ct.type?ht("expected keyword, got "+Ct.data):(Yt.shift(),Zt.shift())}function et(){return"ident"!==Ct.type?ht("expected user-defined name, got "+Ct.data):(Yt[0].data=Ct.data,Yt.shift(),Zt.shift())}function nt(){function t(t){return h(Yt,t),Yt.shift()}var e=Yt[0].expecting;if(Yt[0].tokens=Yt[0].tokens||[],void 0===Yt[0].parenlevel&&(Yt[0].parenlevel=0,Yt[0].bracelevel=0),Yt[0].parenlevel<1&&e.indexOf(Ct.data)>-1)return t(Yt[0].tokens);switch("("===Ct.data?++Yt[0].parenlevel:")"===Ct.data&&--Yt[0].parenlevel,Ct.data){case"{":++Yt[0].bracelevel;break;case"}":--Yt[0].bracelevel;break;case"(":++Yt[0].parenlevel;break;case")":--Yt[0].parenlevel}return Yt[0].parenlevel<0?ht("unexpected `)`"):Yt[0].bracelevel<0?ht("unexpected `}`"):void Yt[0].tokens.push(Zt.shift())}function rt(t){return function(){return i(t,Ct)}}function it(){return i(K[Ct.type],Ct,Pt)}function ot(t){var e=i(_,Ct,Pt);return e.flags=t,e}function st(t,e){var n=i(g,Ct,Pt);return n.allow_assign=void 0===t?!0:t,n.allow_comma=void 0===e?!0:e,n}function at(){var t=i(R,Ct,Pt);return t.expecting=[].slice.call(arguments),t}function ut(t){var e=Ct;return t&&(e={type:"(implied)",data:"(default)",position:e.position}),i(k,e,Pt)}function ht(t){Qt=!0,qt.emit("error",new Error((t||"unexpected "+Yt)+" at line "+Yt[0].token.line))}function lt(t,e){return ct(t,Ct.type)&&ct(e,Ct.data)}function ct(t,e){switch(typeof t){case"string":return e!==t&&ht("expected `"+t+"`, got "+e+"\n"+Ct.data),!Qt;case"object":return t&&-1===t.indexOf(e)&&ht("expected one of `"+t.join("`, `")+"`, got "+e),!Qt}return!0}function pt(){var t,e,n=[].slice.call(arguments);return function(){var r=Yt[0];return r.stage||(r.stage=0),(t=n[r.stage])?(e=t(),e===c?++r.stage:void(void 0!==e&&(r.stage=e))):ht("parser in undefined state!")}}function ft(t,e){return e=e||"operator",function(){if(lt(e,t)){var n=Zt.shift(),r=Yt[0].children,i=r[r.length-1];return i&&i.token&&n.preceding&&(i.token.succeeding=i.token.succeeding||[],i.token.succeeding=i.token.succeeding.concat(n.preceding)),c}}}function dt(t){return function(){return Yt.unshift(at(t)),c}}function mt(t){return t?function(){var t=Ct.data;return lt("ident")&&(Yt.unshift(Ft()),Yt.scope.define(t),c)}:function(){if(lt("ident")){var t=Object.create(Yt.scope.find(Ct.data));return t.token=Ct,Zt.shift(),c}}}function vt(){return function(){var t=Lt();return t.expecting="}",Yt.unshift(t),c}}function gt(t){return function(){var e=Yt[0].stage;return"{"!==Ct.data?(Yt.unshift(zt()),e+t):(Zt.shift(),c)}}function Et(){return function(){return Yt.shift(),Yt.shift()}}function yt(){_t=pt(ft("struct","keyword"),function(){return"{"===Ct.data?(Yt.fake(i(d,{data:"",position:Ct.position,type:"ident"})),c):mt(!0)()},function(){return Yt.scope.enter(),c},ft("{"),function(){return"}"===Ct.data?(Yt.scope.exit(),Zt.shift(),Yt.shift()):";"===Ct.data?void Zt.shift():void Yt.unshift(ot(X))}),bt=pt(function(){return Zt.shift(),c},function(){return lt("keyword",["lowp","mediump","highp"])&&(Yt.unshift(ut()),c)},function(){return Yt.unshift(ut()),c},function(){return Yt.shift()}),Tt=pt(ft("["),dt("]"),ft("]"),function(){return Yt.shift()}),xt=pt(ft("for","keyword"),ft("("),function(){var t;if("ident"===Ct.type){if((t=Yt.scope.find(Ct.data))||(t=Yt.create_node()),"struct"===t.parent.type)return Yt.unshift(ot(W)), +c}else if("builtin"===Ct.type||"keyword"===Ct.type)return Yt.unshift(ot(W)),c;return dt(";")()},ft(";"),dt(";"),ft(";"),dt(")"),ft(")"),gt(3),vt(),ft("}"),Et()),wt=pt(ft("if","keyword"),ft("("),dt(")"),ft(")"),gt(3),vt(),ft("}"),function(){return"else"===Ct.data?(Zt.shift(),Yt.unshift(zt()),c):Et()()},Et()),Rt=pt(ft("return","keyword"),function(){return";"===Ct.data?c:(Yt.unshift(at(";")),c)},function(){Zt.shift(),Et()()}),Ht=pt(ft("while","keyword"),ft("("),dt(")"),ft(")"),gt(3),vt(),ft("}"),Et()),Mt=pt(ft("do","keyword"),gt(3),vt(),ft("}"),ft("while","keyword"),ft("("),dt(")"),ft(")"),Et()),St=pt(function(){for(var t=1,e=Yt.length;e>t;++t)if(Yt[t].mode===E)return ht("function definition is not allowed within another function");return c},function(){if(lt("ident")){var t=Ct.data,e=Yt.scope.find(t);return Yt.unshift(Ft()),Yt.scope.define(t),Yt.scope.enter(e?e.scope:null),c}},ft("("),function(){return Yt.unshift(Bt()),c},ft(")"),function(){return";"===Ct.data?(Yt.scope.exit(),Yt.shift(),Yt.shift()):c},ft("{"),vt(),ft("}"),function(){return Yt.scope.exit(),c},function(){return Yt.shift(),Yt.shift(),Yt.shift()}),kt=pt(function(){return"void"===Ct.data?(Yt.fake(ut()),Zt.shift(),c):")"===Ct.data?void Yt.shift():"struct"===Ct.data?(Yt.unshift(st(Y,Z)),c):(Yt.unshift(ot(q)),c)},function(){return","===Ct.data?(Zt.shift(),0):")"===Ct.data?void Yt.shift():void ht("expected one of `,` or `)`, got "+Ct.data)})}var _t,bt,Tt,xt,wt,Rt,Ht,Mt,St,kt,At,Ct,Pt,Lt=rt(v),zt=rt(m),Ot=rt(b),Dt=rt(H),Ft=rt(d),Ut=(rt(A),rt(E)),Bt=rt(y),Nt=rt(T),Vt=rt(w),It=rt(x),jt=rt(C),Gt=rt(O),Wt=rt(F),qt=u(t,e),Xt=arguments.length?[].slice.call(arguments):[],Yt=[],Zt=[],Kt=[],Qt=!1;return Yt.shift=M,Yt.unshift=f,Yt.fake=r,Yt.unexpected=ht,Yt.scope=new l(Yt),Yt.create_node=function(){var t=i(d,Ct);return t.parent=qt.program,t},yt(),Pt=Lt(),Pt.expecting="(eof)",Pt.mode=v,Pt.token={type:"(program)",data:"(program)"},At=Pt,qt.program=At,qt.scope=function(t){return 1===arguments.length&&(Yt.scope=t),Yt.scope},Yt.unshift(Pt),qt}function i(t,e){return{mode:t,token:e,children:[],type:Q[t]}}function o(t){return"const"===t.data||"attribute"===t.data||"uniform"===t.data||"varying"===t.data}function s(t){return"in"===t.data||"inout"===t.data||"out"===t.data}function a(t){return"highp"===t.data||"mediump"===t.data||"lowp"===t.data}e.exports=r;var u=t("../../through"),h=t("./expr"),l=t("./scope"),c=new Object,p=!1,f=0,d=f++,m=f++,v=f++,g=f++,E=f++,y=f++,_=f++,b=f++,T=f++,x=f++,w=f++,R=f++,H=f++,M=f++,S=f++,k=f++,A=f++,C=f++,P=f++,L=f++,z=f++,O=f++,D=f++,F=f++,U=1,B=2,N=4,V=8,I=16,j=32,G=64,W=255,q=W&~(U|B|j|V|N),X=W&~(U|V|I|G),Y=!1,Z=!1,K={"block-comment":M,"line-comment":M,preprocessor:S},Q=f=["ident","stmt","stmtlist","struct","function","functionargs","decl","decllist","forloop","whileloop","if","expr","precision","comment","preprocessor","keyword","keyword_or_ident","return","break","continue","discard","do-while","placeholder","quantifier"]},{"../../through":227,"./expr":220,"./scope":222}],222:[function(t,e,n){function r(t){return this.constructor!==r?new r(t):(this.state=t,this.scopes=[],void(this.current=null))}e.exports=r;var i=r,o=i.prototype;o.enter=function(t){this.scopes.push(this.current=this.state[0].scope=t||{})},o.exit=function(){this.scopes.pop(),this.current=this.scopes[this.scopes.length-1]},o.define=function(t){this.current[t]=this.state[0]},o.find=function(t,e){for(var n=this.scopes.length-1;n>-1;--n)if(this.scopes[n].hasOwnProperty(t))return this.scopes[n][t];return null}},{}],223:[function(t,e,n){function r(){function t(t){t.length&&D.queue({type:T[B],data:t,position:I,line:V})}function e(t){for(F=0,W+=t.toString(),O=W.length;L=W[F],O>F;)switch(B){case l:F=H();break;case c:F=R();break;case p:F=w();break;case f:F=M();break;case d:F=A();break;case b:F=k();break;case m:F=C();break;case h:F=P();break;case y:F=x();break;case u:F=r()}U+=F,W=W.slice(F)}function n(e){N.length&&t(N.join("")),B=_,t("(eof)"),D.queue(null)}function r(){return N=N.length?[]:N,"/"===z&&"*"===L?(I=U+F-1,B=l,z=L,F+1):"/"===z&&"/"===L?(I=U+F-1,B=c,z=L,F+1):"#"===L?(B=p,I=U+F,F):/\s/.test(L)?(B=y,I=U+F,F):(j=/\d/.test(L),G=/[^\w_]/.test(L),I=U+F,B=j?d:G?f:h,F)}function x(){return"\n"===L&&++V,/[^\s]/g.test(L)?(t(N.join("")),B=u,F):(N.push(L),z=L,F+1)}function w(){return"\n"===L&&++V,"\n"===L&&"\\"!==z?(t(N.join("")),B=u,F):(N.push(L),z=L,F+1)}function R(){return w()}function H(){return"/"===L&&"*"===z?(N.push(L),t(N.join("")),B=u,F+1):("\n"===L&&++V,N.push(L),z=L,F+1)}function M(){if("."===z&&/\d/.test(L))return B=m,F;if("/"===z&&"*"===L)return B=l,F;if("/"===z&&"/"===L)return B=c,F;if("."===L&&N.length){for(;S(N););return B=m,F}if(";"===L){if(N.length)for(;S(N););return t(L),B=u,F+1}var e=2===N.length&&"="!==L;if(/[\w_\d\s]/.test(L)||e){for(;S(N););return B=u,F}return N.push(L),z=L,F+1}function S(e){for(var n,r=0,i=e.length;;){n=s.indexOf(e.slice(0,e.length+r).join(""));{if(-1!==n)return t(s[n]),I+=s[n].length,N=N.slice(s[n].length),N.length;if(r-=1,i-=1,0>i)return 0}}}function k(){return/[^a-fA-F0-9]/.test(L)?(t(N.join("")),B=u,F):(N.push(L),z=L,F+1)}function A(){return"."===L?(N.push(L),B=m,z=L,F+1):/[eE]/.test(L)?(N.push(L),B=m,z=L,F+1):"x"===L&&1===N.length&&"0"===N[0]?(B=b,N.push(L),z=L,F+1):/[^\d]/.test(L)?(t(N.join("")),B=u,F):(N.push(L),z=L,F+1)}function C(){return"f"===L&&(N.push(L),z=L,F+=1),/[eE]/.test(L)?(N.push(L),z=L,F+1):/[^\d]/.test(L)?(t(N.join("")),B=u,F):(N.push(L),z=L,F+1)}function P(){if(/[^\d\w_]/.test(L)){var e=N.join("");return B=o.indexOf(e)>-1?E:a.indexOf(e)>-1?g:v,t(N.join("")),B=u,F}return N.push(L),z=L,F+1}var L,z,O,D=i(e,n),F=0,U=0,B=u,N=[],V=1,I=0,j=!1,G=!1,W="";return D}e.exports=r;var i=t("../through"),o=t("./lib/literals"),s=t("./lib/operators"),a=t("./lib/builtins"),u=999,h=9999,l=0,c=1,p=2,f=3,d=4,m=5,v=6,g=7,E=8,y=9,_=10,b=11,T=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"]},{"../through":227,"./lib/builtins":224,"./lib/literals":225,"./lib/operators":226}],224:[function(t,e,n){e.exports=["gl_Position","gl_PointSize","gl_ClipVertex","gl_FragCoord","gl_FrontFacing","gl_FragColor","gl_FragData","gl_FragDepth","gl_Color","gl_SecondaryColor","gl_Normal","gl_Vertex","gl_MultiTexCoord0","gl_MultiTexCoord1","gl_MultiTexCoord2","gl_MultiTexCoord3","gl_MultiTexCoord4","gl_MultiTexCoord5","gl_MultiTexCoord6","gl_MultiTexCoord7","gl_FogCoord","gl_MaxLights","gl_MaxClipPlanes","gl_MaxTextureUnits","gl_MaxTextureCoords","gl_MaxVertexAttribs","gl_MaxVertexUniformComponents","gl_MaxVaryingFloats","gl_MaxVertexTextureImageUnits","gl_MaxCombinedTextureImageUnits","gl_MaxTextureImageUnits","gl_MaxFragmentUniformComponents","gl_MaxDrawBuffers","gl_ModelViewMatrix","gl_ProjectionMatrix","gl_ModelViewProjectionMatrix","gl_TextureMatrix","gl_NormalMatrix","gl_ModelViewMatrixInverse","gl_ProjectionMatrixInverse","gl_ModelViewProjectionMatrixInverse","gl_TextureMatrixInverse","gl_ModelViewMatrixTranspose","gl_ProjectionMatrixTranspose","gl_ModelViewProjectionMatrixTranspose","gl_TextureMatrixTranspose","gl_ModelViewMatrixInverseTranspose","gl_ProjectionMatrixInverseTranspose","gl_ModelViewProjectionMatrixInverseTranspose","gl_TextureMatrixInverseTranspose","gl_NormalScale","gl_DepthRangeParameters","gl_DepthRange","gl_ClipPlane","gl_PointParameters","gl_Point","gl_MaterialParameters","gl_FrontMaterial","gl_BackMaterial","gl_LightSourceParameters","gl_LightSource","gl_LightModelParameters","gl_LightModel","gl_LightModelProducts","gl_FrontLightModelProduct","gl_BackLightModelProduct","gl_LightProducts","gl_FrontLightProduct","gl_BackLightProduct","gl_FogParameters","gl_Fog","gl_TextureEnvColor","gl_EyePlaneS","gl_EyePlaneT","gl_EyePlaneR","gl_EyePlaneQ","gl_ObjectPlaneS","gl_ObjectPlaneT","gl_ObjectPlaneR","gl_ObjectPlaneQ","gl_FrontColor","gl_BackColor","gl_FrontSecondaryColor","gl_BackSecondaryColor","gl_TexCoord","gl_FogFragCoord","gl_Color","gl_SecondaryColor","gl_TexCoord","gl_FogFragCoord","gl_PointCoord","radians","degrees","sin","cos","tan","asin","acos","atan","pow","exp","log","exp2","log2","sqrt","inversesqrt","abs","sign","floor","ceil","fract","mod","min","max","clamp","mix","step","smoothstep","length","distance","dot","cross","normalize","faceforward","reflect","refract","matrixCompMult","lessThan","lessThanEqual","greaterThan","greaterThanEqual","equal","notEqual","any","all","not","texture2D","texture2DProj","texture2DLod","texture2DProjLod","textureCube","textureCubeLod"]},{}],225:[function(t,e,n){e.exports=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","void","bool","true","false","discard","return","mat2","mat3","mat4","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","sampler1D","sampler2D","sampler3D","samplerCube","sampler1DShadow","sampler2DShadow","struct","asm","class","union","enum","typedef","template","this","packed","goto","switch","default","inline","noinline","volatile","public","static","extern","external","interface","long","short","double","half","fixed","unsigned","input","output","hvec2","hvec3","hvec4","dvec2","dvec3","dvec4","fvec2","fvec3","fvec4","sampler2DRect","sampler3DRect","sampler2DRectShadow","sizeof","cast","namespace","using"]},{}],226:[function(t,e,n){e.exports=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"]},{}],227:[function(t,e,n){var r;r=function(t,e){var n,r;return r=[],n=[],{output:r,parser:null,write:t,end:e,process:function(e,n){return this.parser=e,t(n),this.flush(),this.parser.flush()},flush:function(){return e(),[r,n]},queue:function(t){var e;return null!=t&&null!=(e=this.parser)?e.write(t):void 0},emit:function(t,e){return"data"===t&&null==e.parent&&r.push(e),"error"===t?n.push(e):void 0}}},e.exports=r},{}]},{},[30]); + + + +/// +'use strict'; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var KG; +(function (KG) { + /* + + from underscorejs + + Copyright (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative + Reporters & Editors + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software.*/ + // I adapted these functions from the amazing underscorejs library. + function isObject(obj) { + var type = typeof obj; + return type === 'function' || type === 'object' && !!obj; + } + function allKeys(obj) { + if (!isObject(obj)) + return []; + var keys = []; + for (var key in obj) + keys.push(key); + return keys; + } + KG.allKeys = allKeys; + function defaults(obj, def) { + if (def == null || obj == null) + return obj; + var keys = allKeys(def), l = keys.length; + for (var i = 0; i < l; i++) { + var key = keys[i]; + if (obj[key] === void 0) + obj[key] = def[key]; + } + return obj; + } + // End of underscorejs functions + function setDefaults(def, defaultValues) { + def = defaults(def, defaultValues); + return def; + } + KG.setDefaults = setDefaults; + function setProperties(def, name, props) { + def[name] = (def[name] || []).concat(props); + return def; + } + KG.setProperties = setProperties; +})(KG || (KG = {})); +/// +var KGAuthor; +(function (KGAuthor) { + function extractTypeAndDef(def) { + if (def.hasOwnProperty('type')) { + return def; + } + else { + def.type = Object.keys(def)[0]; + def.def = def[def.type]; + return def; + } + } + KGAuthor.extractTypeAndDef = extractTypeAndDef; + function parse(data, parsedData) { + data.forEach(function (obj) { + if (KGAuthor.hasOwnProperty(obj.type)) { + parsedData = new KGAuthor[obj.type](obj.def).parse(parsedData); + } + else { + console.log("Sorry, there's no ", obj.type, " object type in KGAuthor. Maybe you have a typo?"); + } + }); + return parsedData; + } + KGAuthor.parse = parse; + function getDefinitionProperty(def) { + if (typeof def == 'string') { + if (def.match(/[\*/+-]/)) { + return '(' + def + ')'; + } + else { + return def; + } + } + else { + return def; + } + } + KGAuthor.getDefinitionProperty = getDefinitionProperty; + function getPropertyAsString(def) { + var d = def; + if (typeof d == 'number') { + return d.toString(); + } + else { + return "(" + d.toString() + ")"; + } + } + KGAuthor.getPropertyAsString = getPropertyAsString; + function getParameterName(str) { + if (typeof str == 'string') { + return str.replace('params.', ''); + } + else { + return str; + } + } + KGAuthor.getParameterName = getParameterName; + function namedCalc(str) { + console.log('name is ', this.name); + return "calcs." + this.name + "." + str; + } + KGAuthor.namedCalc = namedCalc; + function negativeDef(def) { + return multiplyDefs(-1, def); + } + KGAuthor.negativeDef = negativeDef; + function binaryFunction(def1, def2, fn) { + if (typeof def1 == 'number' && typeof def2 == 'number') { + switch (fn) { + case "+": + return def1 + def2; + case "-": + return def1 - def2; + case "/": + return def1 / def2; + case "*": + return def1 * def2; + case "^": + return Math.pow(def1, def2); + } + } + else { + return "(" + getDefinitionProperty(def1) + fn + getDefinitionProperty(def2) + ")"; + } + } + KGAuthor.binaryFunction = binaryFunction; + function addDefs(def1, def2) { + if (def1 == 0) { + return def2; + } + if (def2 == 0) { + return def1; + } + return binaryFunction(def1, def2, '+'); + } + KGAuthor.addDefs = addDefs; + function subtractDefs(def1, def2) { + if (def2 == 0) { + return def1; + } + return binaryFunction(def1, def2, '-'); + } + KGAuthor.subtractDefs = subtractDefs; + function divideDefs(def1, def2) { + if (def1 == 0) { + return 0; + } + if (def2 == 1) { + return def1; + } + return binaryFunction(def1, def2, '/'); + } + KGAuthor.divideDefs = divideDefs; + function absDef(def) { + return ""; + } + KGAuthor.absDef = absDef; + function invertDef(def) { + return binaryFunction(1, def, '/'); + } + KGAuthor.invertDef = invertDef; + function multiplyDefs(def1, def2) { + if (def1 == 0 || def2 == 0) { + return 0; + } + if (def1 == 1) { + return def2; + } + if (def2 == 1) { + return def1; + } + return binaryFunction(def1, def2, '*'); + } + KGAuthor.multiplyDefs = multiplyDefs; + function averageDefs(def1, def2, weight) { + weight = weight || 0.5; + return addDefs(multiplyDefs(weight, def1), multiplyDefs(subtractDefs(1, weight), def2)); + } + KGAuthor.averageDefs = averageDefs; + function squareDef(def) { + return binaryFunction(def, def, '*'); + } + KGAuthor.squareDef = squareDef; + function sqrtDef(def) { + return raiseDefToDef(def, 0.5); + } + KGAuthor.sqrtDef = sqrtDef; + function raiseDefToDef(def1, def2) { + return binaryFunction(def1, def2, '^'); + } + KGAuthor.raiseDefToDef = raiseDefToDef; + function quadraticRootDef(def1, def2, def3, positive) { + var negagtiveB = negativeDef(def2); + var bSquaredMinus4ac = subtractDefs(squareDef(def2), multiplyDefs(4, multiplyDefs(def1, def3))); + var numerator = positive ? addDefs(negagtiveB, sqrtDef(bSquaredMinus4ac)) : subtractDefs(negagtiveB, sqrtDef(bSquaredMinus4ac)); + var denominator = multiplyDefs(2, def1); + return divideDefs(numerator, denominator); + } + KGAuthor.quadraticRootDef = quadraticRootDef; + function paramName(def) { + if (typeof (def) == 'string') { + return def.replace('params.', ''); + } + else { + return def; + } + } + KGAuthor.paramName = paramName; + function makeDraggable(def) { + if (def.hasOwnProperty('draggable') && !def.hasOwnProperty('drag')) { + if ((def.draggable == true) || (def.draggable == 'true')) { + def.drag = []; + if (def.x == "params." + paramName(def.x)) { + def.drag.push({ horizontal: paramName(def.x) }); + } + if (def.y == "params." + paramName(def.y)) { + def.drag.push({ vertical: paramName(def.y) }); + } + } + } + return def; + } + KGAuthor.makeDraggable = makeDraggable; + function curvesFromFunctions(fns, def, graph) { + return fns.map(function (fn) { + var curveDef = copyJSON(def); + if (curveDef.hasOwnProperty('min')) { + fn.min = curveDef.min; + } + if (curveDef.hasOwnProperty('max')) { + fn.max = curveDef.max; + } + if (fn.hasOwnProperty('show')) { + curveDef.show = fn.show; + } + if (fn.hasOwnProperty('parametric')) { + curveDef.parametricFunction = fn; + } + else { + curveDef.univariateFunction = fn; + } + //console.log('creating curve from def', curveDef); + return new KGAuthor.Curve(curveDef, graph); + }); + } + KGAuthor.curvesFromFunctions = curvesFromFunctions; + // allow author to set fill color either by "color" attribute or "fill" attribute + function setFillColor(def) { + if (def.open) { + def.fill = 'white'; + return KG.setDefaults(def, { + color: def.stroke, + stroke: def.color + }); + } + return KG.setDefaults(def, { + color: def.fill, + fill: def.color + }); + } + KGAuthor.setFillColor = setFillColor; + // allow author to set stroke color either by "color" attribute or "stroke" attribute + function setStrokeColor(def) { + return KG.setDefaults(def, { + color: def.stroke, + stroke: def.color + }); + } + KGAuthor.setStrokeColor = setStrokeColor; + // create a fresh copy of a JSON object + function copyJSON(def) { + return JSON.parse(JSON.stringify(def)); + } + KGAuthor.copyJSON = copyJSON; + function replaceVariable(target, search, replacement) { + return "(" + target.split(search).join(replacement) + ")"; + } + KGAuthor.replaceVariable = replaceVariable; + // allow author to specify a function using a single string rather than a function object + function parseFn(def, authorName, codeName) { + if (!def.hasOwnProperty(codeName) && def.hasOwnProperty(authorName)) { + if (codeName == 'parametricFunction') { + def.parametricFunction = { + xFunction: def.xFn, + yFunction: def.yFn, + min: def.min, + max: def.max, + samplePoints: def.samplePoints + }; + } + else { + def[codeName] = { + fn: def[authorName], + ind: (def[authorName].indexOf('(y)') > -1) ? 'y' : 'x', + min: def.min, + max: def.max, + samplePoints: def.samplePoints + }; + } + } + } + KGAuthor.parseFn = parseFn; + // allow author to set a fill color rather than a fill object + function parseFill(def, attr) { + var v = def[attr]; + if (typeof v == 'string') { + def[attr] = { fill: v }; + } + if (typeof v == 'boolean' && v) { + var fillColor = def.hasOwnProperty('fill') ? def.fill : def.color; + def[attr] = { fill: fillColor }; + } + } + KGAuthor.parseFill = parseFill; + // inherit properties from a parent + function inheritFromParent(props, parent, child) { + props.forEach(function (prop) { + if (parent.hasOwnProperty(prop) && !child.hasOwnProperty(prop)) { + child[prop] = parent[prop]; + } + }); + } + KGAuthor.inheritFromParent = inheritFromParent; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var AuthoringObject = /** @class */ (function () { + function AuthoringObject(def) { + this.def = def; + this.name = def.name; + this.subObjects = []; + } + AuthoringObject.prototype.parseSelf = function (parsedData) { + return parsedData; + }; + AuthoringObject.prototype.parse = function (parsedData) { + this.subObjects.forEach(function (obj) { + parsedData = obj.parse(parsedData); + }); + delete this.subObjects; + parsedData = this.parseSelf(parsedData); + return parsedData; + }; + AuthoringObject.prototype.addSecondGraph = function (graph2) { + var def = this.def; + if (def.hasOwnProperty('yScale2Name')) { + def.xScale2Name = graph2.xScale.name; + def.yScale2Name = graph2.yScale.name; + } + this.subObjects.forEach(function (obj) { + obj.addSecondGraph(graph2); + }); + }; + return AuthoringObject; + }()); + KGAuthor.AuthoringObject = AuthoringObject; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Schema = /** @class */ (function (_super) { + __extends(Schema, _super); + function Schema(def) { + var _this = this; + var palette = { + blue: 'd3.schemeCategory10[0]', + orange: 'd3.schemeCategory10[1]', + green: 'd3.schemeCategory10[2]', + red: 'd3.schemeCategory10[3]', + purple: 'd3.schemeCategory10[4]', + brown: 'd3.schemeCategory10[5]', + magenta: 'd3.schemeCategory10[6]', + grey: 'd3.schemeCategory10[7]', + gray: 'd3.schemeCategory10[7]', + olive: 'd3.schemeCategory10[8]' //#637939 + }; + for (var color in def.colors) { + var colorName = def.colors[color]; + if (palette.hasOwnProperty(colorName)) { + def.colors[color] = palette[colorName]; + } + } + def.colors = KG.setDefaults(def.colors || {}, palette); + _this = _super.call(this, def) || this; + _this.colors = def.colors; + _this.idioms = def.idioms; + return _this; + } + Schema.prototype.parseSelf = function (parsedData) { + var colors = this.colors; + parsedData.colors = KG.setDefaults(parsedData.colors || {}, colors); + parsedData.idioms = this.idioms; + return parsedData; + }; + return Schema; + }(KGAuthor.AuthoringObject)); + KGAuthor.Schema = Schema; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Layout = /** @class */ (function (_super) { + __extends(Layout, _super); + function Layout(def) { + var _this = _super.call(this, def) || this; + _this.aspectRatio = 2; + _this.nosvg = false; + var l = _this; + if (def.hasOwnProperty('explanation')) { + l.subObjects.push(new KGAuthor.Explanation(def.explanation)); + } + return _this; + } + Layout.prototype.parseSelf = function (parsedData) { + parsedData.aspectRatio = this.aspectRatio; + parsedData.nosvg = this.nosvg; + return parsedData; + }; + return Layout; + }(KGAuthor.AuthoringObject)); + KGAuthor.Layout = Layout; + var SquareLayout = /** @class */ (function (_super) { + __extends(SquareLayout, _super); + // creates a square layout (aspect ratio of 1) within the main body of the text + // to make a square graph, the ratio of width to height should be 0.82 + function SquareLayout(def) { + var _this = _super.call(this, def) || this; + _this.aspectRatio = 1.22; + return _this; + } + return SquareLayout; + }(Layout)); + KGAuthor.SquareLayout = SquareLayout; + var WideRectangleLayout = /** @class */ (function (_super) { + __extends(WideRectangleLayout, _super); + // creates a rectangle, twice as wide as it is high, within the main body of the text + // to make a square graph, the ratio of width to height should be 0.41 + function WideRectangleLayout(def) { + var _this = _super.call(this, def) || this; + _this.aspectRatio = 2.44; + return _this; + } + return WideRectangleLayout; + }(Layout)); + KGAuthor.WideRectangleLayout = WideRectangleLayout; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var HTMLLayout = /** @class */ (function (_super) { + __extends(HTMLLayout, _super); + function HTMLLayout(def) { + var _this = _super.call(this, def) || this; + var l = _this; + l.nosvg = true; + var divDef = { "html": def['html'] }; + l.subObjects.push(new KGAuthor.Div(divDef)); + return _this; + } + return HTMLLayout; + }(KGAuthor.Layout)); + KGAuthor.HTMLLayout = HTMLLayout; + var HTMLPlusSidebarLayout = /** @class */ (function (_super) { + __extends(HTMLPlusSidebarLayout, _super); + function HTMLPlusSidebarLayout(def) { + var _this = _super.call(this, def) || this; + var l = _this; + l.nosvg = true; + var sidebarDef = def['sidebar']; + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return HTMLPlusSidebarLayout; + }(HTMLLayout)); + KGAuthor.HTMLPlusSidebarLayout = HTMLPlusSidebarLayout; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var OneGraph = /** @class */ (function (_super) { + __extends(OneGraph, _super); + function OneGraph(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var graphDef = def['graph']; + graphDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.74, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.Graph(graphDef)); + return _this; + } + return OneGraph; + }(KGAuthor.SquareLayout)); + KGAuthor.OneGraph = OneGraph; + var OneTree = /** @class */ (function (_super) { + __extends(OneTree, _super); + function OneTree(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var treeDef = def['tree']; + treeDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.74, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.Tree(treeDef)); + return _this; + } + return OneTree; + }(KGAuthor.SquareLayout)); + KGAuthor.OneTree = OneTree; + var OneWideGraph = /** @class */ (function (_super) { + __extends(OneWideGraph, _super); + function OneWideGraph(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var graphDef = def['graph']; + graphDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.74, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.Graph(graphDef)); + return _this; + } + return OneWideGraph; + }(KGAuthor.WideRectangleLayout)); + KGAuthor.OneWideGraph = OneWideGraph; + var OneGraphPlusSidebar = /** @class */ (function (_super) { + __extends(OneGraphPlusSidebar, _super); + function OneGraphPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var graphDef = def['graph'], sidebarDef = def['sidebar']; + graphDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.738, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.Graph(graphDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return OneGraphPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.OneGraphPlusSidebar = OneGraphPlusSidebar; + var OneTreePlusSidebar = /** @class */ (function (_super) { + __extends(OneTreePlusSidebar, _super); + function OneTreePlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var treeDef = def['tree'], sidebarDef = def['sidebar']; + treeDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.738, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.Tree(treeDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return OneTreePlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.OneTreePlusSidebar = OneTreePlusSidebar; + var OneWideGraphPlusSidebar = /** @class */ (function (_super) { + __extends(OneWideGraphPlusSidebar, _super); + function OneWideGraphPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var graphDef = def['graph'], sidebarDef = def['sidebar']; + graphDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.738, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.Graph(graphDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return OneWideGraphPlusSidebar; + }(KGAuthor.WideRectangleLayout)); + KGAuthor.OneWideGraphPlusSidebar = OneWideGraphPlusSidebar; + var OneGraphPlusSidebarRoom200 = /** @class */ (function (_super) { + __extends(OneGraphPlusSidebarRoom200, _super); + function OneGraphPlusSidebarRoom200(def) { + var _this = _super.call(this, def) || this; + _this.aspectRatio = 2; + return _this; + } + return OneGraphPlusSidebarRoom200; + }(OneGraphPlusSidebar)); + KGAuthor.OneGraphPlusSidebarRoom200 = OneGraphPlusSidebarRoom200; + var GeoGebraPlusSidebar = /** @class */ (function (_super) { + __extends(GeoGebraPlusSidebar, _super); + function GeoGebraPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var ggbAppletDef = def['ggbApplet'], sidebarDef = def['sidebar']; + ggbAppletDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.738, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.GeoGebraContainer(ggbAppletDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return GeoGebraPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.GeoGebraPlusSidebar = GeoGebraPlusSidebar; + var MathboxPlusSidebar = /** @class */ (function (_super) { + __extends(MathboxPlusSidebar, _super); + function MathboxPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var mathboxDef = def['mathbox'], sidebarDef = def['sidebar']; + mathboxDef.position = { + "x": 0.025, + "y": 0.025, + "width": 0.95, + "height": 0.95 + }; + l.subObjects.push(new KGAuthor.MathboxContainer(mathboxDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return MathboxPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.MathboxPlusSidebar = MathboxPlusSidebar; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var TwoHorizontalGraphs = /** @class */ (function (_super) { + __extends(TwoHorizontalGraphs, _super); + function TwoHorizontalGraphs(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var leftGraphDef = def['leftGraph'], rightGraphDef = def['rightGraph']; + var leftX = 0.15, rightX = 0.65, topY = 0.1, bottomY = 0.9, width = 0.3, controlHeight = 0.25; + var includeControls = false; + console.log('layout: ', l); + if (def.hasOwnProperty('leftControls')) { + l.subObjects.push(new KGAuthor.DivContainer({ + position: { + x: leftX, + y: bottomY, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['leftControls'] + } + ] + })); + includeControls = true; + } + if (def.hasOwnProperty('rightControls')) { + l.subObjects.push(new KGAuthor.DivContainer({ + position: { + x: rightX, + y: bottomY, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['rightControls'] + } + ] + })); + includeControls = true; + } + var graphHeight = includeControls ? 0.5 : 0.9; + _this.aspectRatio = includeControls ? 2 : 4; + leftGraphDef.position = { + x: leftX, + y: topY, + width: width, + height: graphHeight + }; + l.subObjects.push(new KGAuthor.Graph(leftGraphDef)); + rightGraphDef.position = { + "x": rightX, + "y": topY, + "width": width, + "height": graphHeight + }; + l.subObjects.push(new KGAuthor.Graph(rightGraphDef)); + return _this; + } + return TwoHorizontalGraphs; + }(KGAuthor.Layout)); + KGAuthor.TwoHorizontalGraphs = TwoHorizontalGraphs; + var TwoHorizontalGraphsPlusSidebar = /** @class */ (function (_super) { + __extends(TwoHorizontalGraphsPlusSidebar, _super); + function TwoHorizontalGraphsPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var leftGraphDef = def['leftGraph'], rightGraphDef = def['rightGraph'], sidebarDef = def['sidebar']; + var includeControls = false; + var leftX = 0.1, rightX = 0.6, topY = 0.025, bottomY = 1.2, width = 0.369, controlHeight = 0.3, controlBottom = 0.65; + if (def.hasOwnProperty('leftControls')) { + var leftControlsContainer = { + position: { + x: leftX, + y: controlBottom, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['leftControls'] + } + ] + }; + includeControls = true; + l.subObjects.push(new KGAuthor.DivContainer(leftControlsContainer)); + } + if (def.hasOwnProperty('rightControls')) { + var rightControlsContainer = { + position: { + x: rightX, + y: controlBottom, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['rightControls'] + } + ] + }; + includeControls = true; + l.subObjects.push(new KGAuthor.DivContainer(rightControlsContainer)); + } + var graphHeight = includeControls ? 0.5 : 0.9; + _this.aspectRatio = includeControls ? 1.2 : 2.4; + leftGraphDef.position = { + "x": leftX, + "y": topY, + "width": width, + "height": graphHeight + }; + rightGraphDef.position = { + "x": rightX, + "y": topY, + "width": width, + "height": graphHeight + }; + var leftGraph = new KGAuthor.Graph(leftGraphDef), rightGraph = new KGAuthor.Graph(rightGraphDef), sidebar = new KGAuthor.Sidebar(sidebarDef); + l.subObjects.push(leftGraph); + l.subObjects.push(rightGraph); + l.subObjects.push(sidebar); + return _this; + } + return TwoHorizontalGraphsPlusSidebar; + }(KGAuthor.Layout)); + KGAuthor.TwoHorizontalGraphsPlusSidebar = TwoHorizontalGraphsPlusSidebar; + var MathboxPlusGraph = /** @class */ (function (_super) { + __extends(MathboxPlusGraph, _super); + function MathboxPlusGraph(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var mathboxDef = def['mathbox'], graphDef = def['graph']; + mathboxDef.position = { + "x": 0.05, + "y": 0.025, + "width": 0.45, + "height": 0.9 + }; + graphDef.position = { + "x": 0.6, + "y": 0.2, + "width": 0.3, + "height": 0.6 + }; + l.subObjects.push(new KGAuthor.Mathbox(mathboxDef)); + l.subObjects.push(new KGAuthor.Graph(graphDef)); + return _this; + } + return MathboxPlusGraph; + }(KGAuthor.Layout)); + KGAuthor.MathboxPlusGraph = MathboxPlusGraph; + var GameMatrixPlusGraph = /** @class */ (function (_super) { + __extends(GameMatrixPlusGraph, _super); + function GameMatrixPlusGraph(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var graphDef = def['graph']; + var gameDivDef = { + position: { + x: 0.05, + y: 0.1, + width: 0.35, + height: 0.7 + }, + children: [ + { + type: "GameMatrix", + def: def.game + } + ] + }; + graphDef.position = { + x: 0.6, + y: 0.1, + width: 0.35, + height: 0.7 + }; + l.subObjects.push(new KGAuthor.DivContainer(gameDivDef)); + l.subObjects.push(new KGAuthor.Graph(graphDef)); + return _this; + } + return GameMatrixPlusGraph; + }(KGAuthor.Layout)); + KGAuthor.GameMatrixPlusGraph = GameMatrixPlusGraph; + var GameMatrixPlusGraphPlusSidebar = /** @class */ (function (_super) { + __extends(GameMatrixPlusGraphPlusSidebar, _super); + function GameMatrixPlusGraphPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var graphDef = def['graph']; + var sidebarDef = def['sidebar']; + var gameDivDef = { + position: { + x: 0.05, + y: 0.1, + width: 0.35, + height: 0.7 + }, + children: [ + { + type: "GameMatrix", + def: def.game + } + ] + }; + graphDef.position = { + x: 0.6, + y: 0.1, + width: 0.35, + height: 0.7 + }; + l.subObjects.push(new KGAuthor.DivContainer(gameDivDef)); + l.subObjects.push(new KGAuthor.Graph(graphDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return GameMatrixPlusGraphPlusSidebar; + }(KGAuthor.Layout)); + KGAuthor.GameMatrixPlusGraphPlusSidebar = GameMatrixPlusGraphPlusSidebar; + var GeoGebraPlusGraph = /** @class */ (function (_super) { + __extends(GeoGebraPlusGraph, _super); + function GeoGebraPlusGraph(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var ggbAppletDef = def['ggbApplet'], graphDef = def['graph']; + ggbAppletDef.position = { + "x": 0.05, + "y": 0.025, + "width": 0.45, + "height": 0.9 + }; + graphDef.position = { + "x": 0.6, + "y": 0.2, + "width": 0.3, + "height": 0.6 + }; + l.subObjects.push(new KGAuthor.GeoGebraContainer(ggbAppletDef)); + l.subObjects.push(new KGAuthor.Graph(graphDef)); + return _this; + } + return GeoGebraPlusGraph; + }(KGAuthor.Layout)); + KGAuthor.GeoGebraPlusGraph = GeoGebraPlusGraph; + var GeoGebraPlusGraphPlusSidebar = /** @class */ (function (_super) { + __extends(GeoGebraPlusGraphPlusSidebar, _super); + function GeoGebraPlusGraphPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var ggbAppletDef = def['ggbApplet'], graphDef = def['graph'], sidebarDef = def['sidebar']; + ggbAppletDef.position = { + "x": 0.1, + "y": 0.025, + "width": 0.369, + "height": 0.9 + }; + graphDef.position = { + "x": 0.6, + "y": 0.025, + "width": 0.369, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.GeoGebraContainer(ggbAppletDef)); + l.subObjects.push(new KGAuthor.Graph(graphDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return GeoGebraPlusGraphPlusSidebar; + }(KGAuthor.WideRectangleLayout)); + KGAuthor.GeoGebraPlusGraphPlusSidebar = GeoGebraPlusGraphPlusSidebar; + var MathboxPlusGraphPlusSidebar = /** @class */ (function (_super) { + __extends(MathboxPlusGraphPlusSidebar, _super); + function MathboxPlusGraphPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var mathboxDef = def['mathbox'], graphDef = def['graph'], sidebarDef = def['sidebar']; + mathboxDef.position = { + "x": 0.025, + "y": 0.025, + "width": 0.444, + "height": 0.95 + }; + graphDef.position = { + "x": 0.6, + "y": 0.025, + "width": 0.369, + "height": 0.9 + }; + l.subObjects.push(new KGAuthor.MathboxContainer(mathboxDef)); + l.subObjects.push(new KGAuthor.Graph(graphDef)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return MathboxPlusGraphPlusSidebar; + }(KGAuthor.WideRectangleLayout)); + KGAuthor.MathboxPlusGraphPlusSidebar = MathboxPlusGraphPlusSidebar; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var ThreeHorizontalGraphs = /** @class */ (function (_super) { + __extends(ThreeHorizontalGraphs, _super); + function ThreeHorizontalGraphs(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var leftGraphDef = def['leftGraph'], middleGraphDef = def['middleGraph'], rightGraphDef = def['rightGraph']; + var leftX = 0.05, middleX = 0.35, rightX = 0.65, topY = 0.025, bottomY = 0.65, width = 0.25, controlHeight = 0.3; + var includeControls = false; + console.log('layout: ', l); + if (def.hasOwnProperty('leftControls')) { + l.subObjects.push(new KGAuthor.DivContainer({ + position: { + x: leftX, + y: bottomY, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['leftControls'] + } + ] + })); + includeControls = true; + } + if (def.hasOwnProperty('middleControls')) { + l.subObjects.push(new KGAuthor.DivContainer({ + position: { + x: middleX, + y: bottomY, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['middleControls'] + } + ] + })); + includeControls = true; + } + if (def.hasOwnProperty('rightControls')) { + l.subObjects.push(new KGAuthor.DivContainer({ + position: { + x: rightX, + y: bottomY, + width: width, + height: controlHeight + }, + children: [ + { + type: "Controls", + def: def['rightControls'] + } + ] + })); + includeControls = true; + } + var graphHeight = includeControls ? 0.5 : 0.9; + _this.aspectRatio = includeControls ? 2 : 4; + leftGraphDef.position = { + x: leftX, + y: topY, + width: width, + height: graphHeight + }; + l.subObjects.push(new KGAuthor.Graph(leftGraphDef)); + middleGraphDef.position = { + "x": middleX, + "y": topY, + "width": width, + "height": graphHeight + }; + l.subObjects.push(new KGAuthor.Graph(middleGraphDef)); + rightGraphDef.position = { + "x": rightX, + "y": topY, + "width": width, + "height": graphHeight + }; + l.subObjects.push(new KGAuthor.Graph(rightGraphDef)); + return _this; + } + return ThreeHorizontalGraphs; + }(KGAuthor.Layout)); + KGAuthor.ThreeHorizontalGraphs = ThreeHorizontalGraphs; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var RectanglePlusTwoSquaresPlusSidebar = /** @class */ (function (_super) { + __extends(RectanglePlusTwoSquaresPlusSidebar, _super); + function RectanglePlusTwoSquaresPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var topGraph = def['topGraph'], bottomLeftGraph = def['bottomLeftGraph'], bottomRightGraph = def['bottomRightGraph'], sidebarDef = def['sidebar']; + topGraph.position = { + "x": 0.15, + "y": 0.05, + "width": 0.8, + "height": 0.4 + }; + bottomLeftGraph.position = { + "x": 0.15, + "y": 0.6, + "width": 0.35, + "height": 0.35 + }; + bottomRightGraph.position = { + "x": 0.6, + "y": 0.6, + "width": 0.35, + "height": 0.35 + }; + l.subObjects.push(new KGAuthor.Graph(topGraph)); + l.subObjects.push(new KGAuthor.Graph(bottomLeftGraph)); + l.subObjects.push(new KGAuthor.Graph(bottomRightGraph)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return RectanglePlusTwoSquaresPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.RectanglePlusTwoSquaresPlusSidebar = RectanglePlusTwoSquaresPlusSidebar; + var RectangleBelowTwoSquaresPlusSidebar = /** @class */ (function (_super) { + __extends(RectangleBelowTwoSquaresPlusSidebar, _super); + function RectangleBelowTwoSquaresPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var bottomGraph = def['bottomGraph'], topLeftGraph = def['topLeftGraph'], topRightGraph = def['topRightGraph'], sidebarDef = def['sidebar']; + bottomGraph.position = { + "x": 0.15, + "y": 0.55, + "width": 0.8, + "height": 0.4 + }; + topLeftGraph.position = { + "x": 0.15, + "y": 0.05, + "width": 0.35, + "height": 0.35 + }; + topRightGraph.position = { + "x": 0.6, + "y": 0.05, + "width": 0.35, + "height": 0.35 + }; + l.subObjects.push(new KGAuthor.Graph(bottomGraph)); + l.subObjects.push(new KGAuthor.Graph(topLeftGraph)); + l.subObjects.push(new KGAuthor.Graph(topRightGraph)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return RectangleBelowTwoSquaresPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.RectangleBelowTwoSquaresPlusSidebar = RectangleBelowTwoSquaresPlusSidebar; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var TwoVerticalGraphs = /** @class */ (function (_super) { + __extends(TwoVerticalGraphs, _super); + function TwoVerticalGraphs(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var topGraphDef = def['topGraph'], bottomGraphDef = def['bottomGraph']; + topGraphDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.8, + "height": 0.4 + }; + bottomGraphDef.position = { + "x": 0.15, + "y": 0.525, + "width": 0.8, + "height": 0.4 + }; + var topGraph = new KGAuthor.Graph(topGraphDef), bottomGraph = new KGAuthor.Graph(bottomGraphDef); + topGraph.subObjects.forEach(function (obj) { obj.addSecondGraph(bottomGraph); }); + bottomGraph.subObjects.forEach(function (obj) { obj.addSecondGraph(topGraph); }); + l.subObjects.push(topGraph); + l.subObjects.push(bottomGraph); + return _this; + } + return TwoVerticalGraphs; + }(KGAuthor.SquareLayout)); + KGAuthor.TwoVerticalGraphs = TwoVerticalGraphs; + var TwoVerticalGraphsPlusSidebar = /** @class */ (function (_super) { + __extends(TwoVerticalGraphsPlusSidebar, _super); + function TwoVerticalGraphsPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var topGraphDef = def['topGraph'], bottomGraphDef = def['bottomGraph'], sidebarDef = def['sidebar']; + topGraphDef.position = { + "x": 0.15, + "y": 0.025, + "width": 0.738, + "height": 0.4 + }; + bottomGraphDef.position = { + "x": 0.15, + "y": 0.525, + "width": 0.738, + "height": 0.4 + }; + var topGraph = new KGAuthor.Graph(topGraphDef), bottomGraph = new KGAuthor.Graph(bottomGraphDef), sidebar = new KGAuthor.Sidebar(sidebarDef); + topGraph.subObjects.forEach(function (obj) { obj.addSecondGraph(bottomGraph); }); + bottomGraph.subObjects.forEach(function (obj) { obj.addSecondGraph(topGraph); }); + l.subObjects.push(topGraph); + l.subObjects.push(bottomGraph); + l.subObjects.push(sidebar); + return _this; + } + return TwoVerticalGraphsPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.TwoVerticalGraphsPlusSidebar = TwoVerticalGraphsPlusSidebar; + var TwoVerticalGraphsRoom200 = /** @class */ (function (_super) { + __extends(TwoVerticalGraphsRoom200, _super); + function TwoVerticalGraphsRoom200(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var topGraphDef = def['topGraph'], bottomGraphDef = def['bottomGraph']; + topGraphDef.position = { + "x": 0.1, + "y": 0, + "width": 0.85, + "height": 0.4 + }; + bottomGraphDef.position = { + "x": 0.1, + "y": 0.62, + "width": 0.85, + "height": 0.38 + }; + var topGraph = new KGAuthor.Graph(topGraphDef), bottomGraph = new KGAuthor.Graph(bottomGraphDef); + topGraph.subObjects.forEach(function (obj) { obj.addSecondGraph(bottomGraph); }); + bottomGraph.subObjects.forEach(function (obj) { obj.addSecondGraph(topGraph); }); + l.subObjects.push(topGraph); + l.subObjects.push(bottomGraph); + l.aspectRatio = 1.3; + return _this; + } + return TwoVerticalGraphsRoom200; + }(KGAuthor.Layout)); + KGAuthor.TwoVerticalGraphsRoom200 = TwoVerticalGraphsRoom200; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var SquarePlusTwoVerticalGraphs = /** @class */ (function (_super) { + __extends(SquarePlusTwoVerticalGraphs, _super); + function SquarePlusTwoVerticalGraphs(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var bigGraphDef = def['bigGraph'], topGraphDef = def['topGraph'], bottomGraphDef = def['bottomGraph']; + bigGraphDef.position = { + "x": 0.05, + "y": 0.025, + "width": 0.5, + "height": 0.9 + }; + topGraphDef.position = { + "x": 0.6, + "y": 0.025, + "width": 0.35, + "height": 0.4 + }; + bottomGraphDef.position = { + "x": 0.6, + "y": 0.525, + "width": 0.35, + "height": 0.4 + }; + l.subObjects.push(new KGAuthor.Graph(bigGraphDef)); + l.subObjects.push(new KGAuthor.Graph(topGraphDef)); + l.subObjects.push(new KGAuthor.Graph(bottomGraphDef)); + return _this; + } + return SquarePlusTwoVerticalGraphs; + }(KGAuthor.Layout)); + KGAuthor.SquarePlusTwoVerticalGraphs = SquarePlusTwoVerticalGraphs; + var TwoVerticalSquaresOneBigSquare = /** @class */ (function (_super) { + __extends(TwoVerticalSquaresOneBigSquare, _super); + function TwoVerticalSquaresOneBigSquare(def) { + var _this = _super.call(this, def) || this; + var l = _this; + l.aspectRatio = 1.6; + var bigGraphDef = def['bigGraph'], topGraphDef = def['topGraph'], bottomGraphDef = def['bottomGraph']; + topGraphDef.position = { + "x": 0.1, + "y": 0.05, + "width": 0.25, + "height": 0.40 + }; + bottomGraphDef.position = { + "x": 0.1, + "y": 0.538, + "width": 0.25, + "height": 0.40 + }; + bigGraphDef.position = { + "x": 0.43, + "y": 0.05, + "width": 0.555, + "height": 0.888 + }; + l.subObjects.push(new KGAuthor.Graph(bigGraphDef)); + l.subObjects.push(new KGAuthor.Graph(topGraphDef)); + l.subObjects.push(new KGAuthor.Graph(bottomGraphDef)); + return _this; + } + return TwoVerticalSquaresOneBigSquare; + }(KGAuthor.Layout)); + KGAuthor.TwoVerticalSquaresOneBigSquare = TwoVerticalSquaresOneBigSquare; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var FourGraphs = /** @class */ (function (_super) { + __extends(FourGraphs, _super); + function FourGraphs(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var topLeftGraphDef = def['topLeftGraph'], bottomLeftGraphDef = def['bottomLeftGraph'], topRightGraphDef = def['topRightGraph'], bottomRightGraphDef = def['bottomRightGraph']; + var leftX = 0.05, rightX = 0.55, topY = 0.025, bottomY = 0.525; + topLeftGraphDef.position = { + "x": leftX, + "y": topY, + "width": 0.4, + "height": 0.4 + }; + bottomLeftGraphDef.position = { + "x": leftX, + "y": bottomY, + "width": 0.4, + "height": 0.4 + }; + topRightGraphDef.position = { + "x": rightX, + "y": topY, + "width": 0.4, + "height": 0.4 + }; + bottomRightGraphDef.position = { + "x": rightX, + "y": bottomY, + "width": 0.4, + "height": 0.4 + }; + l.subObjects.push(new KGAuthor.Graph(topLeftGraphDef)); + l.subObjects.push(new KGAuthor.Graph(bottomLeftGraphDef)); + l.subObjects.push(new KGAuthor.Graph(topRightGraphDef)); + l.subObjects.push(new KGAuthor.Graph(bottomRightGraphDef)); + return _this; + } + return FourGraphs; + }(KGAuthor.SquareLayout)); + KGAuthor.FourGraphs = FourGraphs; + var FourGraphsPlusSidebar = /** @class */ (function (_super) { + __extends(FourGraphsPlusSidebar, _super); + function FourGraphsPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var sidebarDef = def['sidebar']; + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return FourGraphsPlusSidebar; + }(FourGraphs)); + KGAuthor.FourGraphsPlusSidebar = FourGraphsPlusSidebar; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var GameMatrixLayout = /** @class */ (function (_super) { + __extends(GameMatrixLayout, _super); + function GameMatrixLayout(def) { + var _this = _super.call(this, def) || this; + var l = _this; + l.nosvg = true; + l.subObjects.push(new KGAuthor.GameMatrix(def.gameMatrix)); + return _this; + } + return GameMatrixLayout; + }(KGAuthor.Layout)); + KGAuthor.GameMatrixLayout = GameMatrixLayout; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Scale = /** @class */ (function (_super) { + __extends(Scale, _super); + function Scale(def) { + var _this = this; + KG.setDefaults(def, { + intercept: 0 + }); + _this = _super.call(this, def) || this; + _this.min = def.domainMin; + _this.max = def.domainMax; + _this.intercept = def.intercept; + return _this; + } + Scale.prototype.parseSelf = function (parsedData) { + parsedData.scales.push(this.def); + return parsedData; + }; + return Scale; + }(KGAuthor.AuthoringObject)); + KGAuthor.Scale = Scale; + var PositionedObject = /** @class */ (function (_super) { + __extends(PositionedObject, _super); + function PositionedObject(def) { + var _this = this; + KG.setDefaults(def, { xAxis: {}, yAxis: {} }); + KG.setDefaults(def.xAxis, { min: 0, max: 10, intercept: 0, title: '', orient: 'bottom' }); + KG.setDefaults(def.yAxis, { min: 0, max: 10, intercept: 0, title: '', orient: 'left' }); + _this = _super.call(this, def) || this; + var po = _this, xMin = def.xAxis.min, xMax = def.xAxis.max, xIntercept = def.xAxis.intercept, xLog = def.xAxis.log, yMin = def.yAxis.min, yMax = def.yAxis.max, yIntercept = def.yAxis.intercept, yLog = def.yAxis.log, leftEdge = def.position.x, rightEdge = KGAuthor.addDefs(def.position.x, def.position.width), bottomEdge = KGAuthor.addDefs(def.position.y, def.position.height), topEdge = def.position.y; + po.xScale = new Scale({ + "name": KG.randomString(10), + "axis": "x", + "domainMin": xMin, + "domainMax": xMax, + "rangeMin": leftEdge, + "rangeMax": rightEdge, + "log": xLog, + "intercept": xIntercept + }); + po.yScale = new Scale({ + "name": KG.randomString(10), + "axis": "y", + "domainMin": yMin, + "domainMax": yMax, + "rangeMin": bottomEdge, + "rangeMax": topEdge, + "log": yLog, + "intercept": yIntercept + }); + po.subObjects = [po.xScale, po.yScale]; + if (po.def.hasOwnProperty('objects')) { + po.def.objects.map(KGAuthor.extractTypeAndDef); + } + return _this; + } + return PositionedObject; + }(KGAuthor.AuthoringObject)); + KGAuthor.PositionedObject = PositionedObject; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Graph = /** @class */ (function (_super) { + __extends(Graph, _super); + function Graph(def) { + var _this = this; + def = KG.setDefaults(def, { objects: [] }); + _this = _super.call(this, def) || this; + var g = _this; + //axes need to update when the other one's domain changes + def.xAxis.otherMin = def.yAxis.min; + def.xAxis.otherMax = def.yAxis.max; + def.yAxis.otherMin = def.xAxis.min; + def.yAxis.otherMax = def.xAxis.max; + g.clipPath = new KGAuthor.ClipPath({ + "name": KG.randomString(10), + "paths": [new KGAuthor.Rectangle({ + x1: def.xAxis.min, + x2: def.xAxis.max, + y1: def.yAxis.min, + y2: def.yAxis.max, + inDef: true + }, g)] + }, g); + g.subObjects.push(g.clipPath); + g.def.objects.unshift({ + type: 'Axis', + def: g.def.xAxis + }); + g.def.objects.unshift({ + type: 'Axis', + def: g.def.yAxis + }); + g.def.objects.forEach(function (obj) { + g.subObjects.push(new KGAuthor[obj.type](obj.def, g)); + }); + console.log(g); + return _this; + } + Graph.prototype.getMarkerName = function (lookup) { + var g = this; + var name = '', found = false; + // look to see if there is already a marker of that name and type + g.subObjects.forEach(function (obj) { + if (obj.hasOwnProperty('color') && obj['color'] == lookup.color && obj.hasOwnProperty('markerType') && obj['markerType'] == lookup.markerType) { + name = obj.name; + found = true; + } + }); + // if there is, return its name + if (found) { + return name; + } + // otherwise create a new marker, add to the graph's subobjects, and return the new marker's name + else { + var newMarker = new KGAuthor[lookup.markerType]({ color: lookup.color }); + g.subObjects.push(newMarker); + return newMarker.name; + } + }; + Graph.prototype.getEndArrowName = function (color) { + return this.getMarkerName({ + markerType: 'EndArrow', + color: color + }); + }; + Graph.prototype.getStartArrowName = function (color) { + return this.getMarkerName({ + markerType: 'StartArrow', + color: color + }); + }; + return Graph; + }(KGAuthor.PositionedObject)); + KGAuthor.Graph = Graph; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Tree = /** @class */ (function (_super) { + __extends(Tree, _super); + function Tree(def) { + var _this = this; + var showGrid = def.showGrid || false; + var graphDef = { + position: def.position, + objects: def.objects, + xAxis: { max: 24, ticks: 24, show: showGrid }, + yAxis: { max: 24, ticks: 24, show: showGrid } + }; + _this = _super.call(this, graphDef) || this; + var t = _this; + t.nodeCoordinates = {}; + t.subObjects.push(new KGAuthor.Grid({ + xStep: 3, + yStep: 3, + show: showGrid + }, t)); + def.nodes.forEach(function (nodeDef) { + t.subObjects.push(new KGAuthor.Node(nodeDef, t)); + }); + if (def.hasOwnProperty('edges')) { + def.edges.forEach(function (edgeDef) { + t.subObjects.push(new KGAuthor.Edge(edgeDef, t)); + }); + } + return _this; + } + return Tree; + }(KGAuthor.Graph)); + KGAuthor.Tree = Tree; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var GeoGebraContainer = /** @class */ (function (_super) { + __extends(GeoGebraContainer, _super); + function GeoGebraContainer(def) { + var _this = this; + def.xAxis = { min: 0, max: 1 }; + def.yAxis = { min: 0, max: 1 }; + _this = _super.call(this, def) || this; + var ggb = _this; + def.xScaleName = ggb.xScale.name; + def.yScaleName = ggb.yScale.name; + ggb.subObjects.push(new KGAuthor.GeoGebraApplet(def)); + return _this; + } + return GeoGebraContainer; + }(KGAuthor.PositionedObject)); + KGAuthor.GeoGebraContainer = GeoGebraContainer; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxContainer = /** @class */ (function (_super) { + __extends(MathboxContainer, _super); + function MathboxContainer(def) { + var _this = this; + // the container, as a div, must have an x and y axis of its own. + // so we must first push down the author's specified x, y, and z axes down to be objects + def.objects.push({ + "type": "MathboxXAxis", + "def": def.xAxis + }); + if (def.xAxis.hasOwnProperty('title')) { + def.objects.push({ + "type": "MathboxLabel", + "def": { + "x": KGAuthor.multiplyDefs(def.xAxis.max, 0.95), + "y": KGAuthor.multiplyDefs(def.yAxis.max, -0.02), + "z": KGAuthor.multiplyDefs(def.zAxis.max, 0.02), + "text": def.xAxis.title, + "color": "black" + } + }); + } + def.objects.push({ + "type": "MathboxYAxis", + "def": def.yAxis + }); + if (def.yAxis.hasOwnProperty('title')) { + def.objects.push({ + "type": "MathboxLabel", + "def": { + "x": KGAuthor.multiplyDefs(def.xAxis.max, -0.02), + "y": KGAuthor.multiplyDefs(def.yAxis.max, 0.95), + "z": KGAuthor.multiplyDefs(def.zAxis.max, 0.02), + "text": def.yAxis.title, + "color": "black" + } + }); + } + def.objects.push({ + "type": "MathboxZAxis", + "def": def.zAxis + }); + if (def.zAxis.hasOwnProperty('title')) { + def.objects.push({ + "type": "MathboxLabel", + "def": { + "x": KGAuthor.multiplyDefs(def.xAxis.max, -0.02), + "y": KGAuthor.multiplyDefs(def.yAxis.max, -0.02), + "z": KGAuthor.multiplyDefs(def.zAxis.max, 0.98), + "text": def.zAxis.title, + "color": "black" + } + }); + } + delete def.zAxis; + def.xAxis = { min: 0, max: 1 }; + def.yAxis = { min: 0, max: 1 }; + _this = _super.call(this, def) || this; + var mb = _this; + def.xScaleName = mb.xScale.name; + def.yScaleName = mb.yScale.name; + def.objects.forEach(function (obj) { + if (obj.type.indexOf('Mathbox') < 0) { + obj.type = 'Mathbox' + obj.type; + } + try { + var newObj = new KGAuthor[obj.type](obj.def); + newObj.subObjects.forEach(function (subOb) { + def.objects.push(subOb); + }); + } + catch (e) { + console.log("There's no object called ", obj.type); + } + }); + console.log('creating mathbox'); + mb.subObjects.push(new KGAuthor.Mathbox(def)); + return _this; + } + return MathboxContainer; + }(KGAuthor.PositionedObject)); + KGAuthor.MathboxContainer = MathboxContainer; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var DivContainer = /** @class */ (function (_super) { + __extends(DivContainer, _super); + function DivContainer(def) { + var _this = this; + def.xAxis = { min: 0, max: 1 }; + def.yAxis = { min: 0, max: 1 }; + _this = _super.call(this, def) || this; + var dc = _this; + dc.subObjects.push(new KGAuthor.PositionedDiv(def, dc)); + return _this; + } + return DivContainer; + }(KGAuthor.PositionedObject)); + KGAuthor.DivContainer = DivContainer; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var GraphObjectGenerator = /** @class */ (function (_super) { + __extends(GraphObjectGenerator, _super); + function GraphObjectGenerator(def, graph) { + var _this = _super.call(this, def) || this; + if (graph) { + _this.def.xScaleName = graph.xScale.name; + _this.def.yScaleName = graph.yScale.name; + if (!def.inDef) { + _this.def.clipPathName = def.clipPathName || graph.clipPath.name; + } + } + _this.subObjects = []; + return _this; + } + GraphObjectGenerator.prototype.extractCoordinates = function (coordinatesKey, xKey, yKey) { + coordinatesKey = coordinatesKey || 'coordinates'; + xKey = xKey || 'x'; + yKey = yKey || 'y'; + var obj = this, def = this.def; + if (def.hasOwnProperty(coordinatesKey) && def[coordinatesKey] != undefined) { + def[xKey] = def[coordinatesKey][0].toString(); + def[yKey] = def[coordinatesKey][1].toString(); + delete def[coordinatesKey]; + } + obj[xKey] = def[xKey].toString(); + obj[yKey] = def[yKey].toString(); + }; + return GraphObjectGenerator; + }(KGAuthor.AuthoringObject)); + KGAuthor.GraphObjectGenerator = GraphObjectGenerator; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var DefObject = /** @class */ (function (_super) { + __extends(DefObject, _super); + function DefObject(def, graph) { + var _this = this; + def.inDef = true; + _this = _super.call(this, def, graph) || this; + return _this; + } + DefObject.prototype.parseSelf = function (parsedData) { + delete this.def.clipPathName; + parsedData.clipPaths.push(this.def); + return parsedData; + }; + return DefObject; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.DefObject = DefObject; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var ClipPath = /** @class */ (function (_super) { + __extends(ClipPath, _super); + function ClipPath() { + return _super !== null && _super.apply(this, arguments) || this; + } + ClipPath.prototype.parseSelf = function (parsedData) { + delete this.def.clipPathName; + parsedData.clipPaths.push(this.def); + return parsedData; + }; + return ClipPath; + }(KGAuthor.DefObject)); + KGAuthor.ClipPath = ClipPath; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Marker = /** @class */ (function (_super) { + __extends(Marker, _super); + function Marker(def, graph) { + var _this = _super.call(this, def, graph) || this; + _this.maskPath = def.maskPath; + return _this; + } + Marker.prototype.parseSelf = function (parsedData) { + parsedData.markers.push(this.def); + return parsedData; + }; + return Marker; + }(KGAuthor.DefObject)); + KGAuthor.Marker = Marker; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var ArrowDef = /** @class */ (function (_super) { + __extends(ArrowDef, _super); + function ArrowDef(def, graph) { + var _this = this; + def.name = KG.randomString(10); + _this = _super.call(this, def, graph) || this; + _this.color = def.color; + _this.arrowPath = def.arrowPath; + return _this; + } + return ArrowDef; + }(KGAuthor.Marker)); + KGAuthor.ArrowDef = ArrowDef; + var StartArrow = /** @class */ (function (_super) { + __extends(StartArrow, _super); + function StartArrow(def, graph) { + var _this = this; + def.refX = 2; + def.maskPath = "M10,1 L10,12 L0,7 L0,5 L10,1"; + def.arrowPath = "M11,2 L11,11 L2,6 L11,2"; + _this = _super.call(this, def, graph) || this; + _this.markerType = 'StartArrow'; + return _this; + } + return StartArrow; + }(ArrowDef)); + KGAuthor.StartArrow = StartArrow; + var EndArrow = /** @class */ (function (_super) { + __extends(EndArrow, _super); + function EndArrow(def, graph) { + var _this = this; + def.refX = 11; + def.maskPath = "M3,1 L3,12 L12,7 L12,5 L3,1"; + def.arrowPath = "M2,2 L2,11 L10,6 L2,2"; + _this = _super.call(this, def, graph) || this; + _this.markerType = 'EndArrow'; + return _this; + } + return EndArrow; + }(ArrowDef)); + KGAuthor.EndArrow = EndArrow; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var GraphObject = /** @class */ (function (_super) { + __extends(GraphObject, _super); + function GraphObject(def, graph) { + var _this = this; + if (def.hasOwnProperty('clipPaths')) { + def.clipPathName = KG.randomString(10); + } + KG.setDefaults(def, { + name: KG.randomString(10) + }); + _this = _super.call(this, def, graph) || this; + var g = _this; + if (def.hasOwnProperty('color')) { + g.color = def.color; + } + if (def.hasOwnProperty("clipPaths")) { + var clipPathObjects = def.clipPaths.map(function (shape) { + var shapeType = Object.keys(shape)[0]; + var shapeDef = shape[shapeType]; + shapeDef.inDef = true; + return new KGAuthor[shapeType](shapeDef, graph); + }); + g.subObjects.push(new KGAuthor.ClipPath({ name: def.clipPathName, paths: clipPathObjects }, graph)); + } + return _this; + } + GraphObject.prototype.parseSelf = function (parsedData) { + parsedData.layers[this.layer].push(this); + return parsedData; + }; + return GraphObject; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.GraphObject = GraphObject; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Axis = /** @class */ (function (_super) { + __extends(Axis, _super); + function Axis(def, graph) { + var _this = this; + KG.setDefaults(def, { + yPixelOffset: 40, + xPixelOffset: 40 + }); + _this = _super.call(this, def, graph) || this; + var a = _this; + a.type = 'Axis'; + a.layer = 2; + if (def.hasOwnProperty('title') && ("" != def.title)) { + if (def.orient == 'bottom') { + a.subObjects.push(new KGAuthor.Label({ + text: def.title, + plainText: true, + x: KGAuthor.averageDefs(graph.xScale.min, graph.xScale.max), + y: graph.yScale.min, + yPixelOffset: -1 * def.yPixelOffset + }, graph)); + } + else if (def.orient == 'left') { + a.subObjects.push(new KGAuthor.Label({ + text: def.title, + plainText: true, + x: graph.xScale.min, + y: KGAuthor.averageDefs(graph.yScale.min, graph.yScale.max), + xPixelOffset: -1 * def.xPixelOffset, + rotate: 90 + }, graph)); + } + else if (def.orient == 'top') { + a.subObjects.push(new KGAuthor.Label({ + text: "\\text{" + def.title + "}", + x: KGAuthor.averageDefs(graph.xScale.min, graph.xScale.max), + y: graph.yScale.min, + yPixelOffset: def.yPixelOffset + }, graph)); + } + else { + a.subObjects.push(new KGAuthor.Label({ + text: "\\text{" + def.title + "}", + x: graph.xScale.min, + y: KGAuthor.averageDefs(graph.yScale.min, graph.yScale.max), + xPixelOffset: def.xPixelOffset, + rotate: 270 + }, graph)); + } + } + return _this; + } + return Axis; + }(KGAuthor.GraphObject)); + KGAuthor.Axis = Axis; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Grid = /** @class */ (function (_super) { + __extends(Grid, _super); + function Grid(def, graph) { + var _this = this; + def = def || {}; + _this = _super.call(this, def, graph) || this; + KG.setDefaults(def, { + strokeWidth: 1, + stroke: 'lightgrey', + lineStyle: 'dotted', + layer: 0, + xStep: 1, + yStep: 1 + }); + var g = _this; + g.subObjects = []; + for (var i = 0; i < 10; i++) { + var x = KGAuthor.multiplyDefs(i, def.xStep), y = KGAuthor.multiplyDefs(i, def.yStep); + var gxDef = KGAuthor.copyJSON(def), gyDef = KGAuthor.copyJSON(def); + gxDef.a = [x, graph.yScale.min]; + gxDef.b = [x, graph.yScale.max]; + gyDef.a = [graph.xScale.min, y]; + gyDef.b = [graph.xScale.max, y]; + g.subObjects.push(new KGAuthor.Segment(gxDef, graph)); + g.subObjects.push(new KGAuthor.Segment(gyDef, graph)); + } + return _this; + } + return Grid; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.Grid = Grid; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Curve = /** @class */ (function (_super) { + __extends(Curve, _super); + function Curve(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + KGAuthor.parseFn(def, 'fn', 'univariateFunction'); + KGAuthor.parseFn(def, 'xFn', 'parametricFunction'); + _this = _super.call(this, def, graph) || this; + var c = _this; + c.type = 'Curve'; + c.layer = def.layer || 1; + c.pts = def.pts || []; + if (def.hasOwnProperty('areaBelow')) { + KG.setDefaults(def.areaBelow, { + color: def.color + }); + KGAuthor.parseFill(def, 'areaBelow'); + KG.setDefaults(def.areaBelow, def.univariateFunction); + KGAuthor.parseFn(def.areaBelow, 'fn', 'univariateFunction1'); + c.subObjects.push(new KGAuthor.Area(def.areaBelow, graph)); + } + if (def.hasOwnProperty('areaAbove')) { + KG.setDefaults(def.areaBelow, { + color: def.color + }); + KGAuthor.parseFill(def, 'areaAbove'); + KG.setDefaults(def.areaAbove, def.univariateFunction); + KGAuthor.parseFn(def.areaAbove, 'fn', 'univariateFunction1'); + def.areaAbove.above = true; + c.subObjects.push(new KGAuthor.Area(def.areaAbove, graph)); + } + if (def.hasOwnProperty('label')) { + var labelDef = KGAuthor.copyJSON(def); + delete labelDef.label; + labelDef = KG.setDefaults(labelDef, def.label); + labelDef = KG.setDefaults(labelDef, { + fontSize: 12, + color: def.color + }); + if (def.hasOwnProperty('univariateFunction')) { + if (labelDef.hasOwnProperty('x') && def.univariateFunction.ind != 'y') { + labelDef.coordinates = [labelDef.x, c.yOfX(labelDef.x)]; + c.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + else if (labelDef.hasOwnProperty('y') && def.univariateFunction.ind != 'x') { + labelDef.coordinates = [c.xOfY(labelDef.y), labelDef.y]; + c.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + } + if (def.hasOwnProperty('parametricFunction')) { + if (labelDef.hasOwnProperty('t')) { + labelDef.coordinates = c.xyOfT(labelDef.t); + c.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + } + } + return _this; + } + Curve.prototype.yOfX = function (x) { + return "(" + KGAuthor.replaceVariable(this.def.univariateFunction.fn, '(x)', "(" + x + ")") + ")"; + }; + Curve.prototype.xOfY = function (y) { + var c = this; + if (c.def.univariateFunction.hasOwnProperty('yFn')) { + return "(" + KGAuthor.replaceVariable(c.def.univariateFunction.yFn, '(y)', "(" + y + ")") + ")"; + } + else { + return "(" + KGAuthor.replaceVariable(c.def.univariateFunction.fn, '(y)', "(" + y + ")") + ")"; + } + }; + Curve.prototype.xyOfT = function (t) { + return [ + KGAuthor.replaceVariable(this.def.parametricFunction.xFunction, '(t)', "(" + t + ")"), + KGAuthor.replaceVariable(this.def.parametricFunction.yFunction, '(t)', "(" + t + ")") + ]; + }; + Curve.prototype.parseSelf = function (parsedData) { + var c = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[c.name] = parsedData.calcs[c.name] || {}; + c.pts.forEach(function (p) { + if (p.hasOwnProperty('x')) { + parsedData.calcs[c.name][p['name']] = { + x: p['x'], + y: c.yOfX(p['x']) + }; + } + if (p.hasOwnProperty('y')) { + parsedData.calcs[c.name][p['name']] = { + x: c.xOfY(p['y']), + y: p['y'] + }; + } + }); + return parsedData; + }; + return Curve; + }(KGAuthor.GraphObject)); + KGAuthor.Curve = Curve; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Line = /** @class */ (function (_super) { + __extends(Line, _super); + function Line(def, graph) { + var _this = this; + KG.setDefaults(def, { + color: 'colors.orange' + }); + // may define line with two points + var xIntercept = def.xIntercept, yIntercept = def.yIntercept, slope = def.slope, invSlope = def.invSlope; + if (def.hasOwnProperty('point') && def.hasOwnProperty('point2')) { + // still need to handle infinite case + slope = KGAuthor.divideDefs(KGAuthor.subtractDefs(def.point[1], def.point2[1]), KGAuthor.subtractDefs(def.point[0], def.point2[0])); + yIntercept = KGAuthor.subtractDefs(def.point[1], KGAuthor.multiplyDefs(slope, def.point[0])); + invSlope = KGAuthor.divideDefs(KGAuthor.subtractDefs(def.point[0], def.point2[0]), KGAuthor.subtractDefs(def.point[1], def.point2[1])); + xIntercept = KGAuthor.subtractDefs(def.point[0], KGAuthor.multiplyDefs(invSlope, def.point[1])); + } + else if (def.hasOwnProperty('xIntercept') && def.hasOwnProperty('yIntercept')) { + slope = KGAuthor.negativeDef(KGAuthor.divideDefs(def.yIntercept, def.xIntercept)); + invSlope = KGAuthor.negativeDef(KGAuthor.divideDefs(def.xIntercept, def.yIntercept)); + } + else if (def.hasOwnProperty('point') && def.hasOwnProperty('yIntercept')) { + slope = KGAuthor.divideDefs(KGAuthor.subtractDefs(def.point[1], def.yIntercept), def.point[0]); + invSlope = KGAuthor.divideDefs(def.point[0], KGAuthor.subtractDefs(def.point[1], def.yIntercept)); + xIntercept = KGAuthor.negativeDef(KGAuthor.multiplyDefs(yIntercept, invSlope)); + } + else if (def.hasOwnProperty('slope') && def.hasOwnProperty('yIntercept')) { + invSlope = KGAuthor.invertDef(def.slope); + xIntercept = KGAuthor.negativeDef(KGAuthor.divideDefs(yIntercept, slope)); + } + else if (def.hasOwnProperty('invSlope') && def.hasOwnProperty('xIntercept')) { + slope = KGAuthor.invertDef(def.invSlope); + yIntercept = KGAuthor.negativeDef(KGAuthor.divideDefs(xIntercept, invSlope)); + } + else if (def.hasOwnProperty('invSlope') && def.hasOwnProperty('yIntercept')) { + slope = KGAuthor.invertDef(def.invSlope); + } + else if (def.hasOwnProperty('slope') && def.hasOwnProperty('point')) { + invSlope = KGAuthor.invertDef(def.slope); + xIntercept = KGAuthor.subtractDefs(def.point[0], KGAuthor.divideDefs(def.point[1], def.slope)); + yIntercept = KGAuthor.subtractDefs(def.point[1], KGAuthor.multiplyDefs(def.point[0], def.slope)); + } + else if (def.hasOwnProperty('invSlope') && def.hasOwnProperty('point')) { + slope = KGAuthor.invertDef(def.invSlope); + xIntercept = KGAuthor.subtractDefs(def.point[0], KGAuthor.divideDefs(def.point[1], slope)); + yIntercept = KGAuthor.subtractDefs(def.point[1], KGAuthor.multiplyDefs(def.point[0], slope)); + } + else if (def.hasOwnProperty('slope')) { + invSlope = KGAuthor.invertDef(def.slope); + xIntercept = 0; + yIntercept = 0; + } + else if (def.hasOwnProperty('yIntercept')) { + invSlope = Infinity; + xIntercept = null; + yIntercept = def.yIntercept; + slope = 0; + } + else if (def.hasOwnProperty('xIntercept')) { + invSlope = 0; + xIntercept = def.xIntercept; + yIntercept = null; + slope = Infinity; + } + else { + xIntercept = 0; + yIntercept = 0; + slope = KGAuthor.divideDefs(def.point[1], def.point[0]); + invSlope = KGAuthor.divideDefs(def.point[0], def.point[1]); + } + def.univariateFunction = { + fn: yIntercept + " + (" + slope + ")*(x)", + yFn: xIntercept + " + (" + invSlope + ")*(y)", + ind: "((" + invSlope + " == 0) ? 'y' : 'x')", + samplePoints: 2 + }; + if (def.hasOwnProperty('min')) { + def.univariateFunction.min = def.min; + delete def.min; + } + if (def.hasOwnProperty('max')) { + def.univariateFunction.max = def.max; + delete def.max; + } + _this = _super.call(this, def, graph) || this; + var l = _this; + l.xIntercept = xIntercept; + l.yIntercept = yIntercept; + l.slope = slope; + l.invSlope = invSlope; + if (def.hasOwnProperty('label') && def.label.hasOwnProperty('r')) { + var labelDef = KGAuthor.copyJSON(def); + delete labelDef.label; + labelDef = KG.setDefaults(labelDef, def.label); + labelDef = KG.setDefaults(labelDef, { + fontSize: 12, + color: def.color, + coordinates: lineRadius(l, labelDef.r, labelDef.center) + }); + console.log(labelDef); + l.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + return _this; + } + Line.prototype.parseSelf = function (parsedData) { + var l = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + var d = { + slope: l.slope.toString(), + invSlope: l.invSlope.toString() + }; + if (l.xIntercept) { + d.xIntercept = l.xIntercept.toString(); + } + if (l.yIntercept) { + d.yIntercept = l.yIntercept.toString(); + } + if (!l.xIntercept) { + d.fixedPoint = "((" + d.yIntercept + ")/(1 - " + l.slope.toString() + "))"; + } + else if (!l.yIntercept) { + d.fixedPoint = "((" + d.xIntercept + ")/(1 - " + l.invSlope.toString() + "))"; + } + else { + d.fixedPoint = "(" + d.invSlope + " == 0 ? (" + d.xIntercept + ")/(1 - " + l.invSlope.toString() + ") : (" + d.yIntercept + ")/(1 - " + l.slope.toString() + "))"; + } + l.pts.forEach(function (p) { + if (p.hasOwnProperty('r')) { + var coordinates = lineRadius(l, p['r'], p['center']); + parsedData.calcs[l.name][p['name']] = { + x: coordinates[0], + y: coordinates[1] + }; + } + }); + parsedData.calcs[l.name] = KG.setDefaults(parsedData.calcs[l.name] || {}, d); + return parsedData; + }; + return Line; + }(KGAuthor.Curve)); + KGAuthor.Line = Line; + function lineIntersection(l1, l2) { + var x = KGAuthor.divideDefs(KGAuthor.addDefs(l1.xIntercept, KGAuthor.multiplyDefs(l1.invSlope, l2.yIntercept)), KGAuthor.subtractDefs("1", KGAuthor.multiplyDefs(l1.invSlope, l2.slope))); + var y = l2.yOfX(x); + return [x, y]; + } + KGAuthor.lineIntersection = lineIntersection; + // Find the intersection of a line with a circle of radius r + function lineRadius(line, r, center) { + var a = KGAuthor.addDefs(1, KGAuthor.squareDef(line.slope)); + var b = KGAuthor.multiplyDefs(2, KGAuthor.multiplyDefs(line.slope, line.yIntercept)); + var c = KGAuthor.subtractDefs(KGAuthor.squareDef(line.yIntercept), KGAuthor.squareDef(r)); + if (center) { + var cx = center[0]; + var cy = center[1] || 0; + b = KGAuthor.subtractDefs(b, KGAuthor.multiplyDefs(2, KGAuthor.addDefs(center[0], KGAuthor.multiplyDefs(line.slope, cy)))); + c = KGAuthor.addDefs(c, KGAuthor.subtractDefs(KGAuthor.addDefs(KGAuthor.squareDef(cx), KGAuthor.squareDef(cy)), KGAuthor.multiplyDefs(2, KGAuthor.multiplyDefs(line.yIntercept, cy)))); + } + var x = KGAuthor.quadraticRootDef(a, b, c, true); + var y = line.yOfX(x); + return [x, y]; + } + KGAuthor.lineRadius = lineRadius; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Ellipse = /** @class */ (function (_super) { + __extends(Ellipse, _super); + function Ellipse(def, graph) { + var _this = this; + KG.setDefaults(def, { + color: 'colors.blue', + opacity: 0.2, + rx: 1, + ry: def.rx + }); + def = KGAuthor.setFillColor(def); + def = KGAuthor.setStrokeColor(def); + _this = _super.call(this, def, graph) || this; + var c = _this; + c.type = 'Circle'; + c.layer = def.layer || 0; + // may define the center using 'coordinates' or 'center' or 'c': + if (def.hasOwnProperty('c')) { + c.extractCoordinates('c'); + } + else if (def.hasOwnProperty('center')) { + c.extractCoordinates('center'); + } + else { + c.extractCoordinates(); + } + def = KGAuthor.makeDraggable(def); + if (def.hasOwnProperty('label')) { + var labelDef = KGAuthor.copyJSON(def); + delete labelDef.label; + labelDef = KG.setDefaults(labelDef, def.label); + labelDef = KG.setDefaults(labelDef, { + fontSize: 10, + color: def.color, + bgcolor: null + }); + c.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + return _this; + } + return Ellipse; + }(KGAuthor.GraphObject)); + KGAuthor.Ellipse = Ellipse; + var Circle = /** @class */ (function (_super) { + __extends(Circle, _super); + function Circle(def, graph) { + var _this = this; + if (def.hasOwnProperty('radius')) { + def.r = def.radius; + delete def.radius; + } + if (def.hasOwnProperty('r')) { + def.rx = def.r; + def.ry = def.r; + } + _this = _super.call(this, def, graph) || this; + return _this; + } + return Circle; + }(Ellipse)); + KGAuthor.Circle = Circle; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Point = /** @class */ (function (_super) { + __extends(Point, _super); + function Point(def, graph) { + var _this = this; + KG.setDefaults(def, { + color: 'colors.blue' + }); + def = KGAuthor.setFillColor(def); + _this = _super.call(this, def, graph) || this; + var p = _this; + p.type = 'Point'; + p.layer = 3; + p.extractCoordinates(); + def = KGAuthor.makeDraggable(def); + if (def.hasOwnProperty('label')) { + var labelDef = KGAuthor.copyJSON(def); + delete labelDef.label; + labelDef = KG.setDefaults(labelDef, def.label); + labelDef = KG.setDefaults(labelDef, { + fontSize: 10, + position: 'bl', + color: def.color, + bgcolor: null + }); + p.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + if (def.hasOwnProperty('droplines')) { + if (def.droplines.hasOwnProperty('vertical')) { + var verticalDroplineDef = KGAuthor.copyJSON(def); + // only drag vertical droplines horizontally + if (verticalDroplineDef.hasOwnProperty('drag')) { + verticalDroplineDef.drag = verticalDroplineDef.drag.filter(function (value, index, arr) { return ((value.directions == 'x') || value.hasOwnProperty('horizontal')); }); + } + if (def.droplines.hasOwnProperty('top')) { + verticalDroplineDef.y = graph.yScale.max; + var xTopAxisLabelDef = KGAuthor.copyJSON(verticalDroplineDef); + xTopAxisLabelDef.y = 'OPPAXIS'; + KG.setDefaults(xTopAxisLabelDef, { + text: def.droplines.top, + fontSize: 10 + }); + p.subObjects.push(new KGAuthor.Label(xTopAxisLabelDef, graph)); + } + p.subObjects.push(new KGAuthor.VerticalDropline(verticalDroplineDef, graph)); + var xAxisLabelDef = KGAuthor.copyJSON(verticalDroplineDef); + xAxisLabelDef.y = 'AXIS'; + KG.setDefaults(xAxisLabelDef, { + text: def.droplines.vertical, + fontSize: 10 + }); + p.subObjects.push(new KGAuthor.Label(xAxisLabelDef, graph)); + } + if (def.droplines.hasOwnProperty('horizontal')) { + var horizontalDroplineDef = KGAuthor.copyJSON(def); + // only drag horizontal droplines vertically + if (horizontalDroplineDef.hasOwnProperty('drag')) { + horizontalDroplineDef.drag = horizontalDroplineDef.drag.filter(function (value, index, arr) { return ((value.directions == 'y') || value.hasOwnProperty('vertical')); }); + } + p.subObjects.push(new KGAuthor.HorizontalDropline(horizontalDroplineDef, graph)); + var yAxisLabelDef = KGAuthor.copyJSON(horizontalDroplineDef); + yAxisLabelDef.x = 'AXIS'; + KG.setDefaults(yAxisLabelDef, { + text: def.droplines.horizontal, + fontSize: 10 + }); + p.subObjects.push(new KGAuthor.Label(yAxisLabelDef, graph)); + } + } + return _this; + } + Point.prototype.parseSelf = function (parsedData) { + var p = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[p.name] = { + x: p.x.toString(), + y: p.y.toString() + }; + return parsedData; + }; + return Point; + }(KGAuthor.GraphObject)); + KGAuthor.Point = Point; + var LineCircleIntersection = /** @class */ (function (_super) { + __extends(LineCircleIntersection, _super); + function LineCircleIntersection(def, graph) { + var _this = this; + var l = new KGAuthor.Line(def.lineDef, graph); + var coordinates = KGAuthor.lineRadius(l, def.radius); + KG.setDefaults(def, { + coordinates: coordinates, + positive: true + }); + _this = _super.call(this, def, graph) || this; + var lci = _this; + lci.subObjects.push(l); + return _this; + } + return LineCircleIntersection; + }(Point)); + KGAuthor.LineCircleIntersection = LineCircleIntersection; + var Points = /** @class */ (function (_super) { + __extends(Points, _super); + function Points(def, graph) { + var _this = _super.call(this, def, graph) || this; + var ps = _this; + var coordinateArray = def.coordinates; + coordinateArray.forEach(function (c) { + var pointDef = JSON.parse(JSON.stringify(def)); + pointDef.coordinates = c; + ps.subObjects.push(new Point(pointDef, graph)); + }); + return _this; + } + return Points; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.Points = Points; + var Node = /** @class */ (function (_super) { + __extends(Node, _super); + function Node(def, tree) { + var _this = this; + KG.setDefaults(def, { + name: KG.randomString(10) + }); + if (def.hasOwnProperty('payoffs')) { + var payoff1 = "\\\\color{${colors.player1}}{" + def.payoffs.player1 + "}"; + var comma = "\\\\color{black}{,\\\\ }"; + var payoff2 = "\\\\color{${colors.player2}}{" + def.payoffs.player2 + "}"; + def.label = { + text: "`" + payoff1 + comma + payoff2 + "`", + position: def.payoffs.position || 'l', + fontSize: 14 + }; + } + _this = _super.call(this, def, tree) || this; + var node = _this; + tree.nodeCoordinates[def.name] = [node.x, node.y]; + node.name = def.name; + if (def.hasOwnProperty('children')) { + var n = def.children.length; + for (var i = 0; i < n; i++) { + var childNum = i + 1; // number of child, with first being 1 rather than 0; + var nodeDef = def.children[i]; + KG.setDefaults(nodeDef, { + name: KG.randomString(10) + }); + var edgeDef = { + node1: def.name, + node2: nodeDef.name, + color: def.color, + label: { text: nodeDef.edgeLabel } + }; + // if selectChildren is true, create a parameter called "select[nodeName]" + // which is used to select which child is active + // when true, clicking on an edge selects that edge + // unless the edge is already selected, in which case no edge is selected + if (def.hasOwnProperty('childSelectParam')) { + var param = def.childSelectParam; + var transitions = new Array(n + 1); + transitions[0] = childNum; + for (var j = 1; j < n + 1; j++) { + transitions[j] = (j == childNum) ? 0 : childNum; + } + edgeDef['click'] = [{ + param: param, + transitions: transitions + }]; + edgeDef['strokeWidth'] = "((params." + def.childSelectParam + " == " + childNum + ") ? 6 : 2)"; + } + tree.subObjects.push(new Node(nodeDef, tree)); + tree.subObjects.push(new KGAuthor.Edge(edgeDef, tree)); + } + } + return _this; + } + return Node; + }(Point)); + KGAuthor.Node = Node; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Segment = /** @class */ (function (_super) { + __extends(Segment, _super); + function Segment(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + if (def.hasOwnProperty('startArrow')) { + def.startArrowName = graph.getStartArrowName(def.color); + } + if (def.hasOwnProperty('endArrow')) { + def.endArrowName = graph.getEndArrowName(def.color); + } + _this = _super.call(this, def, graph) || this; + var s = _this; + s.type = 'Segment'; + s.layer = 1; + s.extractCoordinates('a', 'x1', 'y1'); + s.extractCoordinates('b', 'x2', 'y2'); + // new way of trimming + if (def.hasOwnProperty('trim')) { + console.log('implementing trimming'); + var x1 = s.x1; + var y1 = s.y1; + var x2 = s.x2; + var y2 = s.y2; + s.def.x1 = KGAuthor.averageDefs(x2, x1, def.trim); + s.def.x2 = KGAuthor.averageDefs(x1, x2, def.trim); + s.def.y1 = KGAuthor.averageDefs(y2, y1, def.trim); + s.def.y2 = KGAuthor.averageDefs(y1, y2, def.trim); + } + if (def.hasOwnProperty('label')) { + var labelDef = KGAuthor.copyJSON(def); + delete labelDef.label; + if (typeof def.label === "string") { + def.label = { text: def.label }; + } + labelDef = KG.setDefaults(def.label || {}, labelDef); + labelDef = KG.setDefaults(labelDef, { + fontSize: 12, + color: def.color, + location: 0.5 + }); + labelDef.coordinates = [ + KGAuthor.averageDefs(s.x1, s.x2, labelDef.location), + KGAuthor.averageDefs(s.y1, s.y2, labelDef.location) + ]; + s.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + if (def.hasOwnProperty('handles')) { + var aPointDef = { + x: s.x1, + y: s.y1, + color: def.color, + r: 4, + draggable: def.draggable, + show: def.show + }; + var bPointDef = { + x: s.x2, + y: s.y2, + color: def.color, + r: 4, + draggable: def.draggable, + show: def.show + }; + s.subObjects.push(new KGAuthor.Point(aPointDef, graph)); + s.subObjects.push(new KGAuthor.Point(bPointDef, graph)); + } + return _this; + } + return Segment; + }(KGAuthor.GraphObject)); + KGAuthor.Segment = Segment; + var CrossGraphSegment = /** @class */ (function (_super) { + __extends(CrossGraphSegment, _super); + function CrossGraphSegment(def, graph) { + var _this = this; + def.xScale2Name = ''; + _this = _super.call(this, def, graph) || this; + return _this; + } + return CrossGraphSegment; + }(Segment)); + KGAuthor.CrossGraphSegment = CrossGraphSegment; + var Edge = /** @class */ (function (_super) { + __extends(Edge, _super); + function Edge(def, tree) { + var _this = this; + def.a = tree.nodeCoordinates[def.node1]; + def.b = tree.nodeCoordinates[def.node2]; + _this = _super.call(this, def, tree) || this; + return _this; + } + return Edge; + }(Segment)); + KGAuthor.Edge = Edge; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Arrow = /** @class */ (function (_super) { + __extends(Arrow, _super); + function Arrow(def, graph) { + var _this = this; + def.endArrow = true; + if (def.hasOwnProperty('double')) { + def.startArrow = def.double; + } + def.a = def.begin; + def.b = def.end; + _this = _super.call(this, def, graph) || this; + return _this; + } + return Arrow; + }(KGAuthor.Segment)); + KGAuthor.Arrow = Arrow; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Dropline = /** @class */ (function (_super) { + __extends(Dropline, _super); + function Dropline(def, graph) { + var _this = this; + def.lineStyle = 'dotted'; + delete def.label; + _this = _super.call(this, def, graph) || this; + return _this; + } + return Dropline; + }(KGAuthor.Segment)); + KGAuthor.Dropline = Dropline; + var VerticalDropline = /** @class */ (function (_super) { + __extends(VerticalDropline, _super); + function VerticalDropline(def, graph) { + var _this = this; + def.a = [def.x, graph.xScale.intercept]; + def.b = [def.x, def.y]; + _this = _super.call(this, def, graph) || this; + return _this; + } + return VerticalDropline; + }(Dropline)); + KGAuthor.VerticalDropline = VerticalDropline; + var CrossGraphVerticalDropline = /** @class */ (function (_super) { + __extends(CrossGraphVerticalDropline, _super); + function CrossGraphVerticalDropline(def, graph) { + var _this = this; + def.xScale2Name = ''; + _this = _super.call(this, def, graph) || this; + return _this; + } + return CrossGraphVerticalDropline; + }(VerticalDropline)); + KGAuthor.CrossGraphVerticalDropline = CrossGraphVerticalDropline; + var HorizontalDropline = /** @class */ (function (_super) { + __extends(HorizontalDropline, _super); + function HorizontalDropline(def, graph) { + var _this = this; + def.a = [graph.yScale.intercept, def.y]; + def.b = [def.x, def.y]; + _this = _super.call(this, def, graph) || this; + return _this; + } + return HorizontalDropline; + }(Dropline)); + KGAuthor.HorizontalDropline = HorizontalDropline; + var CrossGraphHorizontalDropline = /** @class */ (function (_super) { + __extends(CrossGraphHorizontalDropline, _super); + function CrossGraphHorizontalDropline(def, graph) { + var _this = this; + def.xScale2Name = ''; + _this = _super.call(this, def, graph) || this; + return _this; + } + return CrossGraphHorizontalDropline; + }(HorizontalDropline)); + KGAuthor.CrossGraphHorizontalDropline = CrossGraphHorizontalDropline; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Area = /** @class */ (function (_super) { + __extends(Area, _super); + function Area(def, graph) { + var _this = this; + KG.setDefaults(def, { + color: 'colors.blue', + opacity: 0.2 + }); + def = KGAuthor.setFillColor(def); + KGAuthor.parseFn(def, 'fn', 'univariateFunction1'); + KGAuthor.parseFn(def, 'fn1', 'univariateFunction1'); + KGAuthor.parseFn(def, 'fn2', 'univariateFunction2'); + _this = _super.call(this, def, graph) || this; + _this.type = 'Area'; + _this.layer = def.layer || 0; + return _this; + } + return Area; + }(KGAuthor.GraphObject)); + KGAuthor.Area = Area; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Rectangle = /** @class */ (function (_super) { + __extends(Rectangle, _super); + function Rectangle(def, graph) { + var _this = this; + KGAuthor.setFillColor(def); + _this = _super.call(this, def, graph) || this; + var rect = _this; + rect.type = 'Rectangle'; + rect.layer = def.layer || 0; + rect.extractCoordinates('a', 'x1', 'y1'); + rect.extractCoordinates('b', 'x2', 'y2'); + if (def.hasOwnProperty('label')) { + var labelDef = KGAuthor.copyJSON(def); + delete labelDef.label; + labelDef = KG.setDefaults(labelDef, def.label); + labelDef = KG.setDefaults(labelDef, { + fontSize: 10, + color: def.color, + bgcolor: null, + x: KGAuthor.averageDefs(rect['x1'], rect['x2']), + y: KGAuthor.averageDefs(rect['y1'], rect['y2']) + }); + rect.subObjects.push(new KGAuthor.Label(labelDef, graph)); + } + return _this; + } + return Rectangle; + }(KGAuthor.GraphObject)); + KGAuthor.Rectangle = Rectangle; + var Overlap = /** @class */ (function (_super) { + __extends(Overlap, _super); + function Overlap(def, graph) { + var _this = this; + var shape1name = KG.randomString(10), shape2name = KG.randomString(10); + def = KGAuthor.setFillColor(def); + KG.setDefaults(def, { + x1: graph.def.xAxis.min, + x2: graph.def.xAxis.max, + y1: graph.def.yAxis.min, + y2: graph.def.yAxis.max, + clipPathName: shape1name, + clipPathName2: shape2name + }); + _this = _super.call(this, def, graph) || this; + var r = _this; + var clipPathObjects = def.shapes.map(function (shape) { + var shapeType = Object.keys(shape)[0]; + var shapeDef = shape[shapeType]; + shapeDef.inDef = true; + return new KGAuthor[shapeType](shapeDef, graph); + }); + // As of now this does at most two; can make more recursive in the future but this handles 80% of the use cases + r.subObjects.push(new KGAuthor.ClipPath({ name: shape1name, paths: [clipPathObjects[0]] }, graph)); + r.subObjects.push(new KGAuthor.ClipPath({ name: shape2name, paths: [clipPathObjects[1]] }, graph)); + return _this; + } + return Overlap; + }(Rectangle)); + KGAuthor.Overlap = Overlap; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Contour = /** @class */ (function (_super) { + __extends(Contour, _super); + function Contour(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + _this = _super.call(this, def, graph) || this; + var c = _this; + c.type = 'Contour'; + c.layer = def.layer || 1; + if (def.hasOwnProperty('coordinates')) { + c.extractCoordinates(); + } + if (!def.hasOwnProperty('level')) { + def.level = def.fn.replace(/\(x\)/g, "(" + def.x + ")").replace(/\(y\)/g, "(" + def.y + ")"); + } + c.level = def.level; + return _this; + } + Contour.prototype.parseSelf = function (parsedData) { + var le = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs.contourLevel = le.level; + return parsedData; + }; + return Contour; + }(KGAuthor.GraphObject)); + KGAuthor.Contour = Contour; + var ContourMap = /** @class */ (function (_super) { + __extends(ContourMap, _super); + function ContourMap(def, graph) { + var _this = this; + KG.setDefaults(def, { + color: "grey", + strokeWidth: 0.5 + }); + _this = _super.call(this, def, graph) || this; + var m = _this; + m.type = 'ContourMap'; + m.layer = def.layer || 1; + m.subObjects = def.levels.map(function (level) { + var contourDef = KGAuthor.copyJSON(def); + delete contourDef.levels; + contourDef.level = level; + return new Contour(contourDef, graph); + }); + console.log('contours: ', m.subObjects); + return _this; + } + return ContourMap; + }(KGAuthor.GraphObject)); + KGAuthor.ContourMap = ContourMap; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var AngleMarker = /** @class */ (function (_super) { + __extends(AngleMarker, _super); + function AngleMarker(def, graph) { + var _this = this; + KG.setDefaults(def, { + name: 'angle', + color: 'colors.grey', + coordinates: [0, 0], + radians: false, + start: 0, + r: KGAuthor.multiplyDefs(0.05, KGAuthor.subtractDefs(graph.def.xAxis.max, graph.def.xAxis.min)), + strokeWidth: 0.75 + }); + def = KGAuthor.setStrokeColor(def); + if (def.hasOwnProperty("measure")) { + def.end = KGAuthor.addDefs(def.start, def.measure); + } + else { + def.measure = KGAuthor.subtractDefs(def.end, def.start); + } + // convert to radians unless already radians + var start = def.radians ? def.start : KGAuthor.multiplyDefs(def.start, 0.01745329252), measure = def.radians ? def.measure : KGAuthor.multiplyDefs(def.measure, 0.01745329252), end = def.radians ? def.end : KGAuthor.multiplyDefs(def.end, 0.01745329252), mid = KGAuthor.addDefs(start, KGAuthor.multiplyDefs(0.5, measure)); + def.parametricFunction = { + xFunction: KGAuthor.addDefs(def.coordinates[0], KGAuthor.multiplyDefs(def.r, "cos(t)")), + yFunction: KGAuthor.addDefs(def.coordinates[1], KGAuthor.multiplyDefs(def.r, "sin(t)")), + min: start, + max: end + }; + _this = _super.call(this, def, graph) || this; + var dm = _this; + dm.measureDegrees = def.radians ? KGAuthor.multiplyDefs(def.measure, 57.2957795131) : def.measure; + dm.measureRadians = KGAuthor.divideDefs(measure, Math.PI); + var labelDef = KG.setDefaults(def.label || {}, { + x: KGAuthor.addDefs(def.coordinates[0], KGAuthor.multiplyDefs(KGAuthor.multiplyDefs(1.7, def.r), "cos(" + mid + ")")), + y: KGAuthor.addDefs(def.coordinates[1], KGAuthor.multiplyDefs(KGAuthor.multiplyDefs(1.7, def.r), "sin(" + mid + ")")), + fontSize: 8, + color: def.stroke, + bgcolor: "none", + radians: false, + show: def.show + }); + var labelTextRadians = "`${calcs." + dm.name + ".measureRadians.toFixed(2)}\\\\pi`", labelTextDegrees = "`${calcs." + dm.name + ".measureDegrees.toFixed(0)}^{\\\\circ}`"; + labelDef.text = labelDef.hasOwnProperty('text') ? def.label.text : labelDef.radians ? labelTextRadians : labelTextDegrees; + dm.subObjects.push(new KGAuthor.Label(labelDef, graph)); + return _this; + } + AngleMarker.prototype.parseSelf = function (parsedData) { + var dm = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[dm.name] = { + measureDegrees: dm.measureDegrees.toString(), + measureRadians: dm.measureRadians.toString() + }; + return parsedData; + }; + return AngleMarker; + }(KGAuthor.Curve)); + KGAuthor.AngleMarker = AngleMarker; + var Angle = /** @class */ (function (_super) { + __extends(Angle, _super); + function Angle(def, graph) { + var _this = this; + var A = new KGAuthor.Point(def.pointA, graph), B = new KGAuthor.Point(def.pointB, graph), C = new KGAuthor.Point(def.pointC, graph); + def.start = "atan2(" + A.y + " - " + B.y + "," + A.x + " - " + B.x + ")"; + def.end = "atan2(" + C.y + " - " + B.y + "," + C.x + " - " + B.x + ")"; + def.coordinates = [B.x, B.y]; + def.radians = true; + KG.setDefaults(def, { + label: { + radians: false + } + }); + _this = _super.call(this, def, graph) || this; + var a = _this; + a.subObjects.push(A); + a.subObjects.push(B); + a.subObjects.push(C); + if (def.showSegments) { + var ABdef = KGAuthor.copyJSON(def), CBdef = KGAuthor.copyJSON(def); + ABdef.a = [B.x, B.y]; + ABdef.b = [A.x, A.y]; + delete ABdef.label; + a.subObjects.push(new KGAuthor.Segment(ABdef, graph)); + CBdef.a = [B.x, B.y]; + CBdef.b = [C.x, C.y]; + delete CBdef.label; + a.subObjects.push(new KGAuthor.Segment(CBdef, graph)); + } + return _this; + } + return Angle; + }(AngleMarker)); + KGAuthor.Angle = Angle; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxObject = /** @class */ (function (_super) { + __extends(MathboxObject, _super); + function MathboxObject(def) { + var _this = _super.call(this, def) || this; + _this.mb = def.mb; + return _this; + } + return MathboxObject; + }(KGAuthor.AuthoringObject)); + KGAuthor.MathboxObject = MathboxObject; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxAxis = /** @class */ (function (_super) { + __extends(MathboxAxis, _super); + function MathboxAxis(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxAxis'; + return _this; + } + return MathboxAxis; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxAxis = MathboxAxis; + var MathboxXAxis = /** @class */ (function (_super) { + __extends(MathboxXAxis, _super); + function MathboxXAxis(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxXAxis'; + return _this; + } + return MathboxXAxis; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxXAxis = MathboxXAxis; + var MathboxYAxis = /** @class */ (function (_super) { + __extends(MathboxYAxis, _super); + function MathboxYAxis(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxYAxis'; + return _this; + } + return MathboxYAxis; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxYAxis = MathboxYAxis; + var MathboxZAxis = /** @class */ (function (_super) { + __extends(MathboxZAxis, _super); + function MathboxZAxis(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxZAxis'; + return _this; + } + return MathboxZAxis; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxZAxis = MathboxZAxis; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxPoint = /** @class */ (function (_super) { + __extends(MathboxPoint, _super); + function MathboxPoint(def) { + var _this = _super.call(this, def) || this; + var p = _this; + p.type = 'MathboxPoint'; + if (def.hasOwnProperty('droplines')) { + // vertical dropline to bottom plane + p.subObjects.push(new KGAuthor.MathboxLine({ + mb: def.mb, + x1: def.x, + x2: def.x, + y1: def.y, + y2: def.y, + z1: 0, + z2: def.z, + stroke: def.stroke, + linestyle: 'dotted' + })); + // dropline to x axis; assume min is 0 for now + p.subObjects.push(new KGAuthor.MathboxLine({ + mb: def.mb, + x1: def.x, + x2: 0, + y1: def.y, + y2: def.y, + z1: 0, + z2: 0, + stroke: def.stroke, + linestyle: 'dotted' + })); + // dropline to y axis; assume min is 0 for now + p.subObjects.push(new KGAuthor.MathboxLine({ + mb: def.mb, + x1: def.x, + x2: def.x, + y1: def.y, + y2: 0, + z1: 0, + z2: 0, + stroke: def.stroke, + linestyle: 'dotted' + })); + } + return _this; + } + return MathboxPoint; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxPoint = MathboxPoint; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxLine = /** @class */ (function (_super) { + __extends(MathboxLine, _super); + function MathboxLine(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxLine'; + return _this; + } + return MathboxLine; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxLine = MathboxLine; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxLabel = /** @class */ (function (_super) { + __extends(MathboxLabel, _super); + function MathboxLabel(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxLabel'; + return _this; + } + return MathboxLabel; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxLabel = MathboxLabel; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxArea = /** @class */ (function (_super) { + __extends(MathboxArea, _super); + function MathboxArea(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxAxis'; + return _this; + } + return MathboxArea; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxArea = MathboxArea; + var Area3D = /** @class */ (function (_super) { + __extends(Area3D, _super); + function Area3D() { + return _super !== null && _super.apply(this, arguments) || this; + } + return Area3D; + }(MathboxArea)); + KGAuthor.Area3D = Area3D; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxPlane = /** @class */ (function (_super) { + __extends(MathboxPlane, _super); + function MathboxPlane(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxPlane'; + return _this; + } + return MathboxPlane; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxPlane = MathboxPlane; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxFunctionSurface = /** @class */ (function (_super) { + __extends(MathboxFunctionSurface, _super); + function MathboxFunctionSurface(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxFunctionSurface'; + return _this; + } + return MathboxFunctionSurface; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxFunctionSurface = MathboxFunctionSurface; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MathboxCurve = /** @class */ (function (_super) { + __extends(MathboxCurve, _super); + function MathboxCurve(def) { + var _this = _super.call(this, def) || this; + var a = _this; + a.type = 'MathboxCurve'; + return _this; + } + return MathboxCurve; + }(KGAuthor.MathboxObject)); + KGAuthor.MathboxCurve = MathboxCurve; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var DivObject = /** @class */ (function (_super) { + __extends(DivObject, _super); + function DivObject() { + return _super !== null && _super.apply(this, arguments) || this; + } + DivObject.prototype.parseSelf = function (parsedData) { + parsedData.divs.push(this); + return parsedData; + }; + return DivObject; + }(KGAuthor.GraphObject)); + KGAuthor.DivObject = DivObject; + var Div = /** @class */ (function (_super) { + __extends(Div, _super); + function Div(def) { + var _this = _super.call(this, def) || this; + _this.type = "Div"; + return _this; + } + return Div; + }(DivObject)); + KGAuthor.Div = Div; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var PositionedDiv = /** @class */ (function (_super) { + __extends(PositionedDiv, _super); + function PositionedDiv(def, divContainer) { + var _this = this; + delete def.xAxis; + delete def.yAxis; + def.xScaleName = divContainer.xScale.name; + def.yScaleName = divContainer.yScale.name; + _this = _super.call(this, def) || this; + _this.type = 'PositionedDiv'; + return _this; + } + return PositionedDiv; + }(KGAuthor.DivObject)); + KGAuthor.PositionedDiv = PositionedDiv; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Table = /** @class */ (function (_super) { + __extends(Table, _super); + function Table(def) { + var _this = _super.call(this, def) || this; + _this.type = 'Table'; + return _this; + } + return Table; + }(KGAuthor.Div)); + KGAuthor.Table = Table; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Label = /** @class */ (function (_super) { + __extends(Label, _super); + function Label(def, graph) { + var _this = this; + var xAxisIntercept = 0, yAxisIntercept = 0; + if (graph.def.hasOwnProperty('xAxis')) { + if (graph.def.xAxis.hasOwnProperty('intercept')) { + xAxisIntercept = graph.def.xAxis.intercept; + } + } + if (graph.def.hasOwnProperty('yAxis')) { + if (graph.def.yAxis.hasOwnProperty('intercept')) { + yAxisIntercept = graph.def.yAxis.intercept; + } + } + if (def.x == 'AXIS') { + def.x = yAxisIntercept; + def.position = "r"; + } + if (def.y == 'AXIS') { + def.y = xAxisIntercept; + def.position = "t"; + } + if (def.hasOwnProperty('position')) { + if (def.position.toLowerCase() == 'bl') { + def.xPixelOffset = 5; + def.yPixelOffset = def.fontSize; + def.align = 'left'; + } + if (def.position.toLowerCase() == 'tl') { + def.xPixelOffset = 5; + def.yPixelOffset = -(def.fontSize + 2); + def.align = 'left'; + } + if (def.position.toLowerCase() == 'tr') { + def.xPixelOffset = -5; + def.yPixelOffset = -(def.fontSize + 2); + def.align = 'right'; + } + if (def.position.toLowerCase() == 'br') { + def.xPixelOffset = -5; + def.yPixelOffset = def.fontSize; + def.align = 'right'; + } + if (def.position.toLowerCase() == 'tr') { + def.xPixelOffset = -5; + def.yPixelOffset = -(def.fontSize + 2); + def.align = 'right'; + } + if (def.position.toLowerCase() == 't') { + def.yPixelOffset = -(def.fontSize + 5); + } + if (def.position.toLowerCase() == 'b') { + def.yPixelOffset = def.fontSize + 2; + } + if (def.position.toLowerCase() == 'r') { + def.xPixelOffset = -8; + def.align = 'right'; + } + if (def.position.toLowerCase() == 'l') { + def.xPixelOffset = 8; + def.align = 'left'; + } + } + _this = _super.call(this, def, graph) || this; + _this.type = 'Label'; + _this.extractCoordinates(); + return _this; + } + return Label; + }(KGAuthor.DivObject)); + KGAuthor.Label = Label; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Sidebar = /** @class */ (function (_super) { + __extends(Sidebar, _super); + function Sidebar(def) { + var _this = this; + def.controls.forEach(function (controlDef) { + KGAuthor.parseControlsDef(controlDef); + }); + _this = _super.call(this, def) || this; + _this.type = 'Sidebar'; + return _this; + } + return Sidebar; + }(KGAuthor.DivObject)); + KGAuthor.Sidebar = Sidebar; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Explanation = /** @class */ (function (_super) { + __extends(Explanation, _super); + function Explanation(def) { + var _this = _super.call(this, def) || this; + _this.type = 'Explanation'; + return _this; + } + return Explanation; + }(KGAuthor.DivObject)); + KGAuthor.Explanation = Explanation; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + function parseControlsDef(controlDef) { + if (controlDef.hasOwnProperty('radioGroup')) { + controlDef.radios = controlDef.radioGroup.options.map(function (option, index) { + return { + param: controlDef.radioGroup.param, + optionValue: index, + label: "\\text{" + option + "}" + }; + }); + } + } + KGAuthor.parseControlsDef = parseControlsDef; + var Controls = /** @class */ (function (_super) { + __extends(Controls, _super); + function Controls(def) { + var _this = this; + parseControlsDef(def); + _this = _super.call(this, def) || this; + _this.type = 'Controls'; + return _this; + } + return Controls; + }(KGAuthor.DivObject)); + KGAuthor.Controls = Controls; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var GameMatrix = /** @class */ (function (_super) { + __extends(GameMatrix, _super); + function GameMatrix(def) { + var _this = _super.call(this, def) || this; + _this.type = 'GameMatrix'; + return _this; + } + return GameMatrix; + }(KGAuthor.DivObject)); + KGAuthor.GameMatrix = GameMatrix; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var GeoGebraApplet = /** @class */ (function (_super) { + __extends(GeoGebraApplet, _super); + function GeoGebraApplet(def) { + var _this = _super.call(this, def) || this; + _this.type = 'GeoGebraApplet'; + return _this; + } + return GeoGebraApplet; + }(KGAuthor.DivObject)); + KGAuthor.GeoGebraApplet = GeoGebraApplet; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var Mathbox = /** @class */ (function (_super) { + __extends(Mathbox, _super); + function Mathbox(def) { + var _this = _super.call(this, def) || this; + var mb = _this; + mb.type = 'Mathbox'; + def.objects.forEach(function (mbo) { mbo.def.mb = mb; }); + return _this; + } + Mathbox.prototype.addObject = function (mbo) { + this.def.objects.push(mbo); + return this; + }; + return Mathbox; + }(KGAuthor.DivObject)); + KGAuthor.Mathbox = Mathbox; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconSchema = /** @class */ (function (_super) { + __extends(EconSchema, _super); + function EconSchema(def) { + var _this = this; + def.idioms = {}; + def.custom = def.custom || "0"; + var idiomMenu = [ + { + PPFlabel: ["PPF", "PPC"], + PPFword: ["frontier", "curve"], + PPFWord: ["Frontier", "Curve"] + }, + { + good1label: ["x_1", "x", "X"], + labor1label: ["L_1", "L_x", "L_X"], + good1word: ["good 1", "good X", "good X"], + good1Word: ["Good 1", "Good X", "Good X"], + good2label: ["x_2", "y", "Y"], + labor2label: ["L_2", "L_y", "L_Y"], + good2word: ["good 2", "good Y", "good Y"], + good2Word: ["Good 2", "Good Y", "Good Y"] + }, + { + oldValueLabel: ["\\ ", "_1", "0"], + newValueLabel: ["^\\prime", "_2", "1"] + } + ]; + //console.log("custom: ", def.custom) + idiomMenu.forEach(function (idiomGroup, index) { + // if the user has specified a choice, use it. + if (index < def.custom.length) { + for (var idiomName in idiomGroup) { + def.idioms[idiomName] = idiomGroup[idiomName][def.custom[index]]; + } + } + // otherwise default to first + else { + for (var idiomName in idiomGroup) { + def.idioms[idiomName] = idiomGroup[idiomName][0]; + } + } + }); + console.log("idioms: ", def.idioms); + def.colors = KG.setDefaults(def.colors || {}, { + // consumer theory + utility: 'purple', + mrs: 'blue', + dispreferred: 'red', + preferred: 'green', + offer: 'blue', + incomeOffer: 'orange', + demand: 'blue', + budget: 'green', + costlier: 'red', + endowment: 'grey', + incEffect: 'orange', + subEffect: 'red', + // producer theory + production: 'blue', + mpl: 'olive', + marginalCost: 'orange', + marginalRevenue: 'olive', + supply: 'orange', + shortRun: 'red', + longRun: 'orange', + profit: 'green', + loss: 'red', + ppf: 'red', + mrt: 'orange', + // equilibrium + price: 'grey', + paretoLens: "'#ffff99'", + equilibriumPrice: 'green', + // macro + consumption: 'blue', + depreciation: "red", + savings: "green", + tax: 'red', + // game theory + player1: 'blue', + player2: 'red', + player3: 'orange', + nature: 'green', + terminal: 'gray' + }); + _this = _super.call(this, def) || this; + _this.idiomMenu = idiomMenu; + return _this; + } + return EconSchema; + }(KGAuthor.Schema)); + KGAuthor.EconSchema = EconSchema; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var BowlesHallidaySchema = /** @class */ (function (_super) { + __extends(BowlesHallidaySchema, _super); + function BowlesHallidaySchema(def) { + var _this = this; + // create color scheme here; I took these from the spreadsheet + var purple = "'#3f007d'", blue = "'#084081'", green = "'#005824'"; + // define any overrides to the defined Econ schema here + def.colors = { + // consumer theory + demand: purple, + supply: blue, + equilibriumPrice: green, + indifferenceCurve: green, + bestResponse: purple + }; + _this = _super.call(this, def) || this; + return _this; + } + return BowlesHallidaySchema; + }(KGAuthor.EconSchema)); + KGAuthor.BowlesHallidaySchema = BowlesHallidaySchema; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EdgeworthBox = /** @class */ (function (_super) { + __extends(EdgeworthBox, _super); + function EdgeworthBox(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var agentA = def['agentA'], agentB = def['agentB']; + var width = 0.738, height = 0.8; + /* if(def.totalGood1 > def.totalGood2) { + height = def.totalGood2*height/def.totalGood1; + } + + if(def.totalGood2 > def.totalGood1) { + height = def.totalGood1*width/def.totalGood2; + } */ + _this.aspectRatio = 2; + agentA.position = { + "x": 0.15, + "y": 0.1, + "width": width, + "height": height + }; + agentB.position = { + "x": 0.15 + width, + "y": 0.1 + height, + "width": -1 * width, + "height": -1 * height + }; + agentA.xAxis.max = agentB.xAxis.max = def.totalGood1; + agentA.yAxis.max = agentB.yAxis.max = def.totalGood2; + agentB.xAxis.orient = 'top'; + agentB.yAxis.orient = 'right'; + l.subObjects.push(new KGAuthor.Graph(agentA)); + l.subObjects.push(new KGAuthor.Graph(agentB)); + return _this; + } + return EdgeworthBox; + }(KGAuthor.Layout)); + KGAuthor.EdgeworthBox = EdgeworthBox; + var EdgeworthBoxSquare = /** @class */ (function (_super) { + __extends(EdgeworthBoxSquare, _super); + function EdgeworthBoxSquare(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var agentA = def['agentA'], agentB = def['agentB']; + var width = 0.74, height = 0.9; + _this.aspectRatio = 1.22; + agentA.position = { + "x": 0.15, + "y": 0.025, + "width": width, + "height": height + }; + agentB.position = { + "x": 0.15 + width, + "y": 0.025 + height, + "width": -1 * width, + "height": -1 * height + }; + agentA.xAxis.max = agentB.xAxis.max = def.totalGood1; + agentA.yAxis.max = agentB.yAxis.max = def.totalGood2; + agentB.xAxis.orient = 'top'; + agentB.yAxis.orient = 'right'; + l.subObjects.push(new KGAuthor.Graph(agentA)); + l.subObjects.push(new KGAuthor.Graph(agentB)); + return _this; + } + return EdgeworthBoxSquare; + }(KGAuthor.SquareLayout)); + KGAuthor.EdgeworthBoxSquare = EdgeworthBoxSquare; + var EdgeworthBoxPlusSidebar = /** @class */ (function (_super) { + __extends(EdgeworthBoxPlusSidebar, _super); + function EdgeworthBoxPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var agentA = def['agentA'], agentB = def['agentB'], sidebarDef = def['sidebar']; + var width = 0.738, height = 0.8; + /* if(def.totalGood1 > def.totalGood2) { + height = def.totalGood2*height/def.totalGood1; + } + + if(def.totalGood2 > def.totalGood1) { + height = def.totalGood1*width/def.totalGood2; + } */ + _this.aspectRatio = 2; + agentA.position = { + "x": 0.15, + "y": 0.1, + "width": width, + "height": height + }; + agentB.position = { + "x": 0.15 + width, + "y": 0.1 + height, + "width": -1 * width, + "height": -1 * height + }; + agentA.xAxis.max = agentB.xAxis.max = def.totalGood1; + agentA.yAxis.max = agentB.yAxis.max = def.totalGood2; + agentB.xAxis.orient = 'top'; + agentB.yAxis.orient = 'right'; + l.subObjects.push(new KGAuthor.Graph(agentA)); + l.subObjects.push(new KGAuthor.Graph(agentB)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return EdgeworthBoxPlusSidebar; + }(KGAuthor.Layout)); + KGAuthor.EdgeworthBoxPlusSidebar = EdgeworthBoxPlusSidebar; + var EdgeworthBoxPlusTwoGraphsPlusSidebar = /** @class */ (function (_super) { + __extends(EdgeworthBoxPlusTwoGraphsPlusSidebar, _super); + function EdgeworthBoxPlusTwoGraphsPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var agentA = def['agentA'], agentB = def['agentB'], graph1 = def['graph1'], graph2 = def['graph2'], sidebarDef = def['sidebar']; + var width = 0.738, height = 0.9; + if (def.totalGood1 > def.totalGood2) { + height = def.totalGood2 * height / def.totalGood1; + } + if (def.totalGood2 > def.totalGood1) { + height = def.totalGood1 * width / def.totalGood2; + } + agentA.position = { + "x": 0.15, + "y": 0.05, + "width": width, + "height": height + }; + agentB.position = { + "x": 0.15 + width, + "y": 0.05 + height, + "width": -1 * width, + "height": -1 * height + }; + graph1.position = { + "x": 0.1, + "y": height + 0.15, + "width": 0.35, + "height": 0.85 - height + }; + graph2.position = { + "x": 0.6, + "y": height + 0.15, + "width": 0.35, + "height": 0.85 - height + }; + agentA.xAxis.max = agentB.xAxis.max = def.totalGood1; + agentA.yAxis.max = agentB.yAxis.max = def.totalGood2; + agentB.xAxis.orient = 'top'; + agentB.yAxis.orient = 'right'; + l.subObjects.push(new KGAuthor.Graph(agentB)); + l.subObjects.push(new KGAuthor.Graph(agentA)); + l.subObjects.push(new KGAuthor.Graph(graph1)); + l.subObjects.push(new KGAuthor.Graph(graph2)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return EdgeworthBoxPlusTwoGraphsPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.EdgeworthBoxPlusTwoGraphsPlusSidebar = EdgeworthBoxPlusTwoGraphsPlusSidebar; + var EdgeworthBoxAboveOneGraphPlusSidebar = /** @class */ (function (_super) { + __extends(EdgeworthBoxAboveOneGraphPlusSidebar, _super); + function EdgeworthBoxAboveOneGraphPlusSidebar(def) { + var _this = _super.call(this, def) || this; + var l = _this; + var agentA = def['agentA'], agentB = def['agentB'], graph = def['graph'], sidebarDef = def['sidebar']; + var width = 0.738, height = 0.9; + if (def.totalGood1 > def.totalGood2) { + height = def.totalGood2 * height / def.totalGood1; + } + if (def.totalGood2 > def.totalGood1) { + height = def.totalGood1 * width / def.totalGood2; + } + agentA.position = { + "x": 0.15, + "y": 0.05, + "width": width, + "height": height + }; + agentB.position = { + "x": 0.15 + width, + "y": 0.05 + height, + "width": -1 * width, + "height": -1 * height + }; + graph.position = { + "x": 0.15, + "y": height + 0.15, + "width": width, + "height": 0.85 - height + }; + agentA.xAxis.max = agentB.xAxis.max = def.totalGood1; + agentA.yAxis.max = agentB.yAxis.max = def.totalGood2; + agentB.xAxis.orient = 'top'; + agentB.yAxis.orient = 'right'; + l.subObjects.push(new KGAuthor.Graph(agentB)); + l.subObjects.push(new KGAuthor.Graph(agentA)); + l.subObjects.push(new KGAuthor.Graph(graph)); + l.subObjects.push(new KGAuthor.Sidebar(sidebarDef)); + return _this; + } + return EdgeworthBoxAboveOneGraphPlusSidebar; + }(KGAuthor.SquareLayout)); + KGAuthor.EdgeworthBoxAboveOneGraphPlusSidebar = EdgeworthBoxAboveOneGraphPlusSidebar; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EntryDeterrence = /** @class */ (function (_super) { + __extends(EntryDeterrence, _super); + function EntryDeterrence(def) { + return _super.call(this, def) || this; + } + return EntryDeterrence; + }(KGAuthor.Tree)); + KGAuthor.EntryDeterrence = EntryDeterrence; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconMultivariateFunction = /** @class */ (function (_super) { + __extends(EconMultivariateFunction, _super); + function EconMultivariateFunction(def) { + var _this = this; + KG.setDefaults(def, { + name: KG.randomString(10) + }); + _this = _super.call(this, def) || this; + var fn = _this; + fn.interpolation = 'curveMonotoneX'; + if (def.hasOwnProperty('alpha')) { + fn.alpha = def.alpha; + fn.exponents = def.exponents || [def.alpha, KGAuthor.subtractDefs(1, def.alpha)]; + fn.coefficients = def.coefficients || [def.alpha, KGAuthor.subtractDefs(1, def.alpha)]; + } + else if (def.hasOwnProperty('exponents')) { + fn.exponents = def.exponents; + fn.alpha = KGAuthor.divideDefs(fn.exponents[0], KGAuthor.addDefs(fn.exponents[0], fn.exponents[1])); + fn.coefficients = def.coefficients; + } + else if (def.hasOwnProperty('coefficients')) { + fn.exponents = def.coefficients; + fn.coefficients = def.coefficients; + fn.alpha = KGAuthor.divideDefs(fn.coefficients[0], KGAuthor.addDefs(fn.coefficients[0], fn.coefficients[1])); + } + return _this; + } + EconMultivariateFunction.prototype.value = function (x) { + return null; + }; + EconMultivariateFunction.prototype.extractLevel = function (def) { + var u = this; + if (def.hasOwnProperty('level') && def.level != undefined) { + return KGAuthor.getDefinitionProperty(def.level); + } + else if (def.hasOwnProperty('point') && def.point != undefined) { + return u.value(def.point); + } + else if (def.hasOwnProperty('budgetLine')) { + var bl = new KGAuthor.EconBudgetLine(def.budgetLine, null); + return u.value(u.optimalBundle(bl)); + } + }; + EconMultivariateFunction.prototype.levelSet = function (def) { + return []; + }; + EconMultivariateFunction.prototype.levelCurve = function (def, graph) { + def.interpolation = this.interpolation; + return KGAuthor.curvesFromFunctions(this.levelSet(def), def, graph); + }; + EconMultivariateFunction.prototype.levelCurveSlope = function (x) { + return null; + }; + EconMultivariateFunction.prototype.areaBelowLevelCurve = function (def, graph) { + var fn = this; + fn.fillBelowRect = null; + def.interpolation = fn.interpolation; + var fns = fn.levelSet(def); + var objs = []; + fns.forEach(function (fn) { + var areaDef = KGAuthor.copyJSON(def); + areaDef.univariateFunction1 = fn; + objs.push(new KGAuthor.Area(areaDef, graph)); + }); + if (fn.fillBelowRect) { + fn.fillBelowRect.show = def.show; + fn.fillBelowRect.fill = def.fill; + objs.push(new KGAuthor.Rectangle(fn.fillBelowRect, graph)); + } + return objs; + }; + EconMultivariateFunction.prototype.areaAboveLevelCurve = function (def, graph) { + var fn = this; + fn.fillAboveRect = null; + def.interpolation = fn.interpolation; + var fns = fn.levelSet(def); + var objs = []; + fns.forEach(function (fn) { + var areaDef = KGAuthor.copyJSON(def); + areaDef.univariateFunction1 = fn; + areaDef.above = true; + objs.push(new KGAuthor.Area(areaDef, graph)); + }); + if (fn.fillAboveRect) { + fn.fillAboveRect.show = def.show; + fn.fillAboveRect.fill = def.fill; + fn.fillAboveRect.inDef = true; + objs.push(new KGAuthor.Rectangle(fn.fillAboveRect, graph)); + } + var clipPathName = def.hasOwnProperty('name') ? def.name + "_above" : KG.randomString(10); + return [ + new KGAuthor.Rectangle({ + clipPathName: clipPathName, + x1: graph.def.xAxis.min, + x2: graph.def.xAxis.max, + y1: graph.def.yAxis.min, + y2: graph.def.yAxis.max, + fill: def.fill, + show: def.show + }, graph), + new KGAuthor.ClipPath({ + "name": clipPathName, + "paths": objs + }, graph) + ]; + }; + EconMultivariateFunction.prototype.lowestCostBundle = function (level, prices) { + return []; // defined at the subclass level + }; + /* Optimization with an exogenous income */ + EconMultivariateFunction.prototype.cornerCondition = function (budgetLine) { + return 'false'; + }; + EconMultivariateFunction.prototype.lagrangeBundle = function (budgetLine) { + return []; + }; + EconMultivariateFunction.prototype.optimalBundle = function (budgetLine) { + return []; + }; + EconMultivariateFunction.prototype.quantityDemanded = function (budgetLine, good) { + return this.optimalBundle(budgetLine)[good - 1]; + }; + EconMultivariateFunction.prototype.priceOfferFunction = function (budgetLine, good, min, max, graph) { + var u = this; + var blDef; + if (budgetLine.hasOwnProperty('point') && budgetLine.point != undefined) { + min = 0.01; + max = 0.99; + blDef = { + p1: '(t)', + p2: '1 - (t)', + m: budgetLine.point[0] + "*(t) + " + budgetLine.point[1] + "*(1-(t))" + }; + } + else { + blDef = (good == 1) ? { p1: '(t)', p2: budgetLine.p2, m: budgetLine.m } : { + p1: budgetLine.p1, + p2: '(t)', + m: budgetLine.m + }; + } + var optimalBundle = u.optimalBundle(new KGAuthor.EconBudgetLine(blDef, graph)); + return [ + { + xFunction: optimalBundle[0], + yFunction: optimalBundle[1], + min: min, + max: max, + samplePoints: 100, + parametric: true + } + ]; + }; + EconMultivariateFunction.prototype.priceOfferCurve = function (budgetLine, good, min, max, def, graph) { + var u = this; + def.interpolation = 'curveMonotoneX'; + return KGAuthor.curvesFromFunctions(u.priceOfferFunction(budgetLine, good, min, max, graph), def, graph); + }; + EconMultivariateFunction.prototype.demandFunction = function (budgetLine, good, graph) { + var u = this, blDef = (good == 1) ? { p1: '(y)', p2: budgetLine.p2, m: budgetLine.m } : { + p1: budgetLine.p1, + p2: '(y)', + m: budgetLine.m + }; + return [ + { + "fn": u.quantityDemanded(new KGAuthor.EconBudgetLine(blDef, graph), good), + "ind": "y", + "samplePoints": 30 + } + ]; + }; + EconMultivariateFunction.prototype.demandCurve = function (budgetLine, good, def, graph) { + var u = this; + def.interpolation = 'curveMonotoneX'; + return KGAuthor.curvesFromFunctions(u.demandFunction(budgetLine, good, graph), def, graph); + }; + /* Net demand and supply from an endowment */ + EconMultivariateFunction.prototype.endowmentDemandFunction = function (budgetLine, good, graph) { + var u = this; + var netDemand = '', netSupply = '', grossDemand = ''; + var x1 = budgetLine.point[0], x2 = budgetLine.point[1]; + if (good == 2) { + var optimalBundle = u.optimalBundle(new KGAuthor.EconBudgetLine({ + p1: budgetLine.p1, + p2: '(y)', + m: "(" + x1 + "*" + budgetLine.p1 + " + " + x2 + "*(y))" + }, graph)); + grossDemand = optimalBundle[1]; + netDemand = KGAuthor.subtractDefs(grossDemand, x2); + netSupply = KGAuthor.subtractDefs(x2, grossDemand); + } + else { + var optimalBundle = u.optimalBundle(new KGAuthor.EconBudgetLine({ + p1: '(y)', + p2: budgetLine.p2, + m: "(" + x1 + "*(y) + " + x2 + "*" + budgetLine.p2 + ")" + }, graph)); + grossDemand = optimalBundle[0]; + netDemand = KGAuthor.subtractDefs(grossDemand, x1); + netSupply = KGAuthor.subtractDefs(x1, grossDemand); + } + return { + grossDemand: [ + { + fn: grossDemand, + ind: 'y' + } + ], + netDemand: [ + { + fn: netDemand, + ind: 'y' + } + ], + netSupply: [ + { + fn: netSupply, + ind: 'y' + } + ] + }; + }; + EconMultivariateFunction.prototype.grossDemandCurve = function (budgetLine, good, def, graph) { + var u = this; + def.interpolation = 'curveMonotoneX'; + return KGAuthor.curvesFromFunctions(u.endowmentDemandFunction(budgetLine, good, graph).grossDemand, def, graph); + }; + EconMultivariateFunction.prototype.netDemandCurve = function (budgetLine, good, def, graph) { + var u = this; + def.interpolation = 'curveMonotoneX'; + return KGAuthor.curvesFromFunctions(u.endowmentDemandFunction(budgetLine, good, graph).netDemand, def, graph); + }; + EconMultivariateFunction.prototype.netSupplyCurve = function (budgetLine, good, def, graph) { + var u = this; + def.interpolation = 'curveMonotoneX'; + return KGAuthor.curvesFromFunctions(u.endowmentDemandFunction(budgetLine, good, graph).netSupply, def, graph); + }; + EconMultivariateFunction.prototype.indirectUtility = function (income, prices) { + return this.extractLevel({ budgetLine: { p1: prices[0], p2: prices[1], m: income } }); + }; + EconMultivariateFunction.prototype.expenditure = function (level, prices) { + var b = this.lowestCostBundle(level, prices); + return KGAuthor.addDefs(KGAuthor.multiplyDefs(b[0], prices[0]), KGAuthor.multiplyDefs(b[1], prices[1])); + }; + EconMultivariateFunction.prototype.laborRequirement = function (level, capital) { + // defined at subclass level + }; + return EconMultivariateFunction; + }(KGAuthor.AuthoringObject)); + KGAuthor.EconMultivariateFunction = EconMultivariateFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var CobbDouglasFunction = /** @class */ (function (_super) { + __extends(CobbDouglasFunction, _super); + function CobbDouglasFunction() { + return _super !== null && _super.apply(this, arguments) || this; + } + CobbDouglasFunction.prototype.value = function (x) { + var e = this.exponents, scalar = this.coefficients.length == 1 ? this.coefficients[0] : 1; + return "(" + scalar + "*(" + x[0] + ")^(" + e[0] + "))*((" + x[1] + ")^(" + e[1] + "))"; + }; + CobbDouglasFunction.prototype.levelSet = function (def) { + var e = this.exponents, scalar = this.coefficients.length == 1 ? this.coefficients[0] : 1, level = KGAuthor.divideDefs(this.extractLevel(def), scalar), xMin = "(" + level + ")^(1/(" + e[0] + " + " + e[1] + "))", yMin = "(" + level + ")^(1/(" + e[0] + " + " + e[1] + "))"; + this.fillBelowRect = { + x1: 0, + x2: xMin, + y1: 0, + y2: yMin, + show: def.show + }; + return [ + { + "fn": "((" + level + ")/(y)^(" + e[1] + "))^(1/(" + e[0] + "))", + "ind": "y", + "min": yMin, + "samplePoints": 30 + }, + { + "fn": "((" + level + ")/(x)^(" + e[0] + "))^(1/(" + e[1] + "))", + "ind": "x", + "min": xMin, + "samplePoints": 30 + } + ]; + }; + CobbDouglasFunction.prototype.levelCurveSlope = function (x) { + var c = this.coefficients; + return KGAuthor.negativeDef(KGAuthor.divideDefs(KGAuthor.multiplyDefs(c[0], x[1]), KGAuthor.multiplyDefs(c[1], x[0]))); + }; + CobbDouglasFunction.prototype.optimalBundle = function (budgetLine) { + var a = this.alpha; + return [KGAuthor.multiplyDefs(a, budgetLine.xIntercept), KGAuthor.multiplyDefs(KGAuthor.subtractDefs(1, a), budgetLine.yIntercept)]; + }; + CobbDouglasFunction.prototype.lowestCostBundle = function (level, prices) { + var e = this.exponents, ratio = KGAuthor.multiplyDefs(KGAuthor.divideDefs(prices[0], prices[1]), KGAuthor.divideDefs(e[1], e[0])), scale = KGAuthor.addDefs(e[0], e[1]), scaledLevel = KGAuthor.raiseDefToDef(level, KGAuthor.divideDefs(1, scale)); + return [ + KGAuthor.divideDefs(scaledLevel, KGAuthor.raiseDefToDef(ratio, KGAuthor.divideDefs(e[1], scale))), + KGAuthor.multiplyDefs(scaledLevel, KGAuthor.raiseDefToDef(ratio, KGAuthor.divideDefs(e[0], scale))) + ]; + }; + CobbDouglasFunction.prototype.laborRequirement = function (level, capital) { + var e = this.exponents; + return "((" + level + ")/(" + capital + ")^(" + e[1] + "))^(1/(" + e[0] + "))"; + }; + return CobbDouglasFunction; + }(KGAuthor.EconMultivariateFunction)); + KGAuthor.CobbDouglasFunction = CobbDouglasFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var MinFunction = /** @class */ (function (_super) { + __extends(MinFunction, _super); + function MinFunction(def) { + var _this = _super.call(this, def) || this; + var fn = _this; + fn.interpolation = 'curveLinear'; + if (def.hasOwnProperty('alpha')) { + fn.coefficients = [KGAuthor.divideDefs(0.5, def.alpha), KGAuthor.divideDefs(0.5, KGAuthor.subtractDefs(1, def.alpha))]; + } + return _this; + } + MinFunction.prototype.value = function (x) { + var c = this.coefficients; + return "(min((" + x[0] + ")*(" + c[0] + "),(" + x[1] + ")*(" + c[1] + ")))"; + }; + MinFunction.prototype.levelSet = function (def) { + var c = this.coefficients, level = def.level || this.value(def.point), xMin = KGAuthor.divideDefs(level, c[0]), yMin = KGAuthor.divideDefs(level, c[1]); + this.fillBelowRect = { + x1: 0, + x2: xMin, + y1: 0, + y2: yMin, + show: def.show + }; + return [ + { + "fn": KGAuthor.divideDefs(level, c[1]), + "ind": "x", + "min": xMin, + "samplePoints": 2 + }, { + "fn": KGAuthor.divideDefs(level, c[0]), + "ind": "y", + "min": yMin, + "samplePoints": 2 + } + ]; + }; + MinFunction.prototype.optimalBundle = function (budgetLine) { + var good1perBundle = KGAuthor.invertDef(this.coefficients[0]), good2perBundle = KGAuthor.invertDef(this.coefficients[1]), bundles = KGAuthor.divideDefs(budgetLine.m, KGAuthor.addDefs(KGAuthor.multiplyDefs(budgetLine.p1, good1perBundle), KGAuthor.multiplyDefs(budgetLine.p2, good2perBundle))); + return [KGAuthor.multiplyDefs(good1perBundle, bundles), KGAuthor.multiplyDefs(good2perBundle, bundles)]; + }; + MinFunction.prototype.lowestCostBundle = function (level, prices) { + var a = this.coefficients[0], b = this.coefficients[1]; + return [ + KGAuthor.divideDefs(level, a), + KGAuthor.divideDefs(level, b) + ]; + }; + return MinFunction; + }(KGAuthor.EconMultivariateFunction)); + KGAuthor.MinFunction = MinFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var LinearFunction = /** @class */ (function (_super) { + __extends(LinearFunction, _super); + function LinearFunction(def) { + var _this = _super.call(this, def) || this; + var fn = _this; + _this.interpolation = 'curveLinear'; + if (def.hasOwnProperty('alpha')) { + fn.coefficients = [def.alpha, KGAuthor.subtractDefs(1, def.alpha)]; + } + return _this; + } + LinearFunction.prototype.value = function (x) { + var c = this.coefficients; + return "((" + x[0] + ")*(" + c[0] + ")+(" + x[1] + ")*(" + c[1] + "))"; + }; + LinearFunction.prototype.levelSet = function (def) { + var c = this.coefficients, level = def.level || this.value(def.point); + return [ + { + "fn": "(" + level + " - (" + c[0] + ")*(x))/(" + c[1] + ")", + "ind": "x", + "samplePoints": 2 + } + ]; + }; + LinearFunction.prototype.optimalBundle = function (budgetLine) { + var c = this.coefficients; + var buyOnlyGood2 = "((" + c[0] + ")*(" + budgetLine.p2 + ") < (" + c[1] + ")*(" + budgetLine.p1 + "))"; + return [buyOnlyGood2 + " ? 0 : " + budgetLine.xIntercept, buyOnlyGood2 + " ? " + budgetLine.yIntercept + " : 0"]; + }; + return LinearFunction; + }(KGAuthor.EconMultivariateFunction)); + KGAuthor.LinearFunction = LinearFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var CESFunction = /** @class */ (function (_super) { + __extends(CESFunction, _super); + function CESFunction(def) { + var _this = _super.call(this, def) || this; + var fn = _this; + fn.interpolation = 'curveMonotoneX'; + if (def.hasOwnProperty('r')) { + fn.r = def.r; + fn.s = KGAuthor.divideDefs(1, KGAuthor.subtractDefs(1, def.r)); + } + else if (def.hasOwnProperty('s')) { + fn.s = def.s; + fn.r = KGAuthor.subtractDefs(1, KGAuthor.divideDefs(1, def.s)); + } + return _this; + } + CESFunction.prototype.value = function (x) { + var c = this.coefficients, r = this.r; + return KGAuthor.raiseDefToDef(KGAuthor.addDefs(KGAuthor.multiplyDefs(c[0], KGAuthor.raiseDefToDef(x[0], r)), KGAuthor.multiplyDefs(c[1], KGAuthor.raiseDefToDef(x[1], r))), KGAuthor.divideDefs(1, r)); + }; + CESFunction.prototype.levelSet = function (def) { + var u = this, a = KGAuthor.getDefinitionProperty(u.alpha), r = KGAuthor.getDefinitionProperty(u.r), b = KGAuthor.subtractDefs(1, u.alpha), level = this.extractLevel(def); + this.fillBelowRect = { + x1: 0, + x2: level, + y1: 0, + y2: level, + show: def.show + }; + return [ + { + fn: "((" + level + "^" + r + " - " + a + "*(x)^" + r + ")/" + b + ")^(1/" + r + ")", + ind: "x", + min: level + }, + { + fn: "((" + level + "^" + r + " - " + b + "*(y)^" + r + ")/" + a + ")^(1/" + r + ")", + ind: "y", + min: level + } + ]; + }; + // see http://www.gamsworld.org/mpsge/debreu/ces.pdf + CESFunction.prototype.optimalBundle = function (budgetLine) { + var s = this.s, oneMinusS = KGAuthor.subtractDefs(1, s), a = this.alpha, oneMinusA = KGAuthor.subtractDefs(1, a), theta = KGAuthor.divideDefs(budgetLine.m, KGAuthor.addDefs(KGAuthor.multiplyDefs(KGAuthor.raiseDefToDef(a, s), KGAuthor.raiseDefToDef(budgetLine.p1, oneMinusS)), KGAuthor.multiplyDefs(KGAuthor.raiseDefToDef(oneMinusA, s), KGAuthor.raiseDefToDef(budgetLine.p2, oneMinusS)))), optimalX1 = KGAuthor.multiplyDefs(KGAuthor.raiseDefToDef(KGAuthor.divideDefs(a, budgetLine.p1), s), theta), optimalX2 = KGAuthor.multiplyDefs(KGAuthor.raiseDefToDef(KGAuthor.divideDefs(oneMinusA, budgetLine.p2), s), theta); + return [optimalX1, optimalX2]; + }; + CESFunction.prototype.denominator = function (p1, p2) { + var a1 = this.alpha, a2 = KGAuthor.subtractDefs(1, a1), r = this.r, pOverA1 = KGAuthor.divideDefs(p1, a1), pOverA2 = KGAuthor.divideDefs(p2, a2), oneOverR = KGAuthor.divideDefs(1, r), rOverRminusOne = KGAuthor.divideDefs(r, KGAuthor.subtractDefs(r, 1)); + return KGAuthor.raiseDefToDef(KGAuthor.addDefs(KGAuthor.multiplyDefs(a1, KGAuthor.raiseDefToDef(pOverA1, rOverRminusOne)), KGAuthor.multiplyDefs(a2, KGAuthor.raiseDefToDef(pOverA2, rOverRminusOne))), oneOverR); + }; + // see http://personal.stthomas.edu/csmarcott/ec418/ces_cost_minimization.pdf + CESFunction.prototype.lowestCostBundle = function (level, prices) { + var a1 = this.alpha, a2 = KGAuthor.subtractDefs(1, a1), p1 = prices[0], p2 = prices[1], r = this.r, pOverA1 = KGAuthor.divideDefs(p1, a1), pOverA2 = KGAuthor.divideDefs(p2, a2), oneOverRminusOne = KGAuthor.divideDefs(1, KGAuthor.subtractDefs(r, 1)), denominator = this.denominator(p1, p2), numerator1 = KGAuthor.raiseDefToDef(pOverA1, oneOverRminusOne), numerator2 = KGAuthor.raiseDefToDef(pOverA2, oneOverRminusOne); + return [ + KGAuthor.divideDefs(KGAuthor.multiplyDefs(level, numerator1), denominator), + KGAuthor.divideDefs(KGAuthor.multiplyDefs(level, numerator2), denominator) + ]; + }; + return CESFunction; + }(KGAuthor.EconMultivariateFunction)); + KGAuthor.CESFunction = CESFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var ConcaveFunction = /** @class */ (function (_super) { + __extends(ConcaveFunction, _super); + function ConcaveFunction() { + return _super !== null && _super.apply(this, arguments) || this; + } + ConcaveFunction.prototype.value = function (x) { + var c = this.coefficients; + return "(" + c[0] + ")*(" + x[0] + ")^2+(" + c[1] + ")*(" + x[1] + ")^2"; + }; + ConcaveFunction.prototype.levelSet = function (def) { + var c = this.coefficients, level = def.level || this.value(def.point), max = "((" + level + ")/(" + c[0] + "+" + c[1] + "))^(0.5)"; + this.fillAboveRect = { + x1: max, + x2: 50, + y1: max, + y2: 50, + show: def.show + }; + return [ + { + "fn": "((" + level + "-(" + c[1] + ")*(y)*(y))/(" + c[0] + "))^(0.5)", + "ind": "y", + "min": 0, + "max": max, + "samplePoints": 30 + }, + { + "fn": "((" + level + "-(" + c[0] + ")*(x)*(x))/(" + c[1] + "))^(0.5)", + "ind": "x", + "min": 0, + "max": max, + "samplePoints": 30 + } + ]; + }; + return ConcaveFunction; + }(KGAuthor.EconMultivariateFunction)); + KGAuthor.ConcaveFunction = ConcaveFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var QuasilinearFunction = /** @class */ (function (_super) { + __extends(QuasilinearFunction, _super); + function QuasilinearFunction() { + return _super !== null && _super.apply(this, arguments) || this; + } + QuasilinearFunction.prototype.value = function (x) { + var c = this.coefficients; + return "(" + c[0] + "*log(" + x[0] + ")+" + x[1] + ")"; + }; + QuasilinearFunction.prototype.levelSet = function (def) { + var c = this.coefficients, level = this.extractLevel(def); + return [ + { + "fn": "((" + level + ")-(" + c[0] + ")*log((x)))", + "ind": "x", + "samplePoints": 100 + } + ]; + }; + QuasilinearFunction.prototype.cornerCondition = function (budgetLine) { + return "(" + this.lagrangeBundle(budgetLine)[1] + " < 0)"; + }; + QuasilinearFunction.prototype.lagrangeBundle = function (budgetLine) { + var c = this.coefficients; + return [KGAuthor.divideDefs(KGAuthor.multiplyDefs(c[0], budgetLine.p2), budgetLine.p1), KGAuthor.subtractDefs(budgetLine.yIntercept, c[0])]; + }; + QuasilinearFunction.prototype.optimalBundle = function (budgetLine) { + var lagr = this.lagrangeBundle(budgetLine), cornerCondition = this.cornerCondition(budgetLine); + return ["(" + cornerCondition + " ? " + budgetLine.xIntercept + " : " + lagr[0] + ")", "(" + cornerCondition + " ? 0 : " + lagr[1] + ")"]; + }; + return QuasilinearFunction; + }(KGAuthor.EconMultivariateFunction)); + KGAuthor.QuasilinearFunction = QuasilinearFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + function extractBudgetLine(def, graph) { + if (def.hasOwnProperty('budgetLineObject')) { + return def.budgetLineObject; + } + if (def.hasOwnProperty('budgetLine')) { + var budgetDef = JSON.parse(JSON.stringify(def.budgetLine)); + budgetDef.show = budgetDef.show || def.show; + if (!budgetDef.hasOwnProperty('m')) { + if (def.hasOwnProperty('point') && def.point.length == 2) { + budgetDef.point = def.point; + } + if (def.hasOwnProperty('coordinates') && def.coordinates.length == 2) { + budgetDef.point = def.coordinates; + } + if (def.hasOwnProperty('x') && def.hasOwnProperty('y')) { + budgetDef.x = def.x; + budgetDef.y = def.y; + } + } + budgetDef.color = budgetDef.color || def.color; + return new EconBudgetLine(budgetDef, graph); + } + //console.log('tried to instantiate a budget line without either a budget line def or object') + } + KGAuthor.extractBudgetLine = extractBudgetLine; + var EconBudgetLine = /** @class */ (function (_super) { + __extends(EconBudgetLine, _super); + function EconBudgetLine(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + def.name = def.name || 'BL' + KG.randomString(5); + // may define income either by income m or value of endowment point + if (!def.hasOwnProperty('m')) { + if (def.hasOwnProperty('x') && def.hasOwnProperty('y')) { + def.point = [def.x, def.y]; + } + if (def.hasOwnProperty('point') && def.point.length == 2) { + def.m = KGAuthor.addDefs(KGAuthor.multiplyDefs(def.p1, def.point[0]), KGAuthor.multiplyDefs(def.p2, def.point[1])); + } + } + var xIntercept = KGAuthor.divideDefs(def.m, def.p1), yIntercept = KGAuthor.divideDefs(def.m, def.p2), priceRatio = KGAuthor.divideDefs(def.p1, def.p2), endowment = { x: def.x, y: def.y }; + console.log('xIntercept', xIntercept); + if (def.inMap) { + def.strokeWidth = 1; + def.lineStyle = 'dotted'; + def.layer = 0; + def.handles = false; + def.draggable = false; + } + KG.setDefaults(def, { + a: ["calcs." + def.name + ".xIntercept", 0], + b: [0, "calcs." + def.name + ".yIntercept"], + color: 'colors.budget', + strokeWidth: 2, + lineStyle: 'solid', + buyOnly: false, + sellOnly: false + }); + if (def.sellOnly) { + def.a = [def.x, def.y]; + } + if (def.buyOnly) { + def.b = [def.x, def.y]; + } + if (def.draggable && typeof (def.m) == 'string') { + def.drag = [{ + 'directions': 'xy', + 'param': KGAuthor.paramName(def.m), + 'expression': KGAuthor.addDefs(KGAuthor.multiplyDefs('drag.x', def.p1), KGAuthor.multiplyDefs('drag.y', def.p2)) + }]; + } + if (!def.inMap) { + def.label = KG.setDefaults(def.label || {}, { + text: "BL", + location: def.sellOnly ? 0.1 : 0.9 + }); + } + _this = _super.call(this, def, graph) || this; + var bl = _this; + bl.p1 = def.p1; + bl.p2 = def.p2; + bl.m = def.m; + bl.xIntercept = xIntercept; + bl.yIntercept = yIntercept; + bl.priceRatio = priceRatio; + bl.point = def.point; + bl.endowment = endowment; + if (graph) { + var subObjects = bl.subObjects; + var xInterceptPointDef = { + coordinates: ["calcs." + bl.name + ".xIntercept", 0], + color: def.stroke, + r: 4 + }; + if (def.draggable && typeof (def.p1) == 'string') { + xInterceptPointDef['drag'] = [{ + directions: 'x', + param: KGAuthor.paramName(def.p1), + expression: KGAuthor.divideDefs("calcs." + bl.name + ".m", 'drag.x') + }]; + } + if (def.hasOwnProperty('xInterceptLabel')) { + xInterceptPointDef['droplines'] = { + vertical: def.xInterceptLabel + }; + } + bl.xInterceptPoint = new KGAuthor.Point(xInterceptPointDef, graph); + var yInterceptPointDef = { + coordinates: [0, "calcs." + bl.name + ".yIntercept"], + color: def.stroke, + r: 4 + }; + if (def.draggable && typeof (def.p2) == 'string') { + yInterceptPointDef['drag'] = [{ + directions: 'y', + param: KGAuthor.paramName(def.p2), + expression: KGAuthor.divideDefs('calcs.' + bl.name + '.m', 'drag.y') + }]; + } + if (def.hasOwnProperty('yInterceptLabel')) { + yInterceptPointDef['droplines'] = { + horizontal: def.yInterceptLabel + }; + } + bl.yInterceptPoint = new KGAuthor.Point(yInterceptPointDef, graph); + bl.budgetSetArea = new KGAuthor.Area({ + fill: "colors.budget", + univariateFunction1: { + fn: "calcs." + bl.name + ".yIntercept - calcs." + bl.name + ".priceRatio*(x)", + samplePoints: 2, + max: "calcs." + bl.name + ".xIntercept" + }, + show: def.set + }, graph); + bl.costlierArea = new KGAuthor.Area({ + fill: "colors.costlier", + univariateFunction1: { + fn: "calcs." + bl.name + ".yIntercept - calcs." + bl.name + ".priceRatio*(x)", + samplePoints: 2 + }, + show: def.costlier, + above: true + }, graph); + if (def.handles) { + subObjects.push(bl.xInterceptPoint); + subObjects.push(bl.yInterceptPoint); + } + if (def.set) { + subObjects.push(bl.budgetSetArea); + } + if (def.costlier) { + subObjects.push(bl.costlierArea); + } + } + return _this; + } + EconBudgetLine.prototype.cost = function (bundle) { + var c = "((" + this.p1 + ")*(" + bundle.x + ") + (" + this.p2 + ")*(" + bundle.y + "))"; + //console.log(c); + return c; + }; + EconBudgetLine.prototype.parseSelf = function (parsedData) { + var bl = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[bl.name] = { + xIntercept: bl.xIntercept.toString(), + yIntercept: bl.yIntercept.toString(), + m: bl.m.toString(), + p1: bl.p1.toString(), + p2: bl.p2.toString(), + priceRatio: bl.priceRatio.toString(), + endowment: bl.endowment.toString() + }; + return parsedData; + }; + return EconBudgetLine; + }(KGAuthor.Segment)); + KGAuthor.EconBudgetLine = EconBudgetLine; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + function getUtilityFunction(def) { + if (def != undefined) { + def = KGAuthor.extractTypeAndDef(def); + if (def.type == 'CobbDouglas') { + return new KGAuthor.CobbDouglasFunction(def.def); + } + else if (def.type == 'Substitutes' || def.type == 'PerfectSubstitutes') { + return new KGAuthor.LinearFunction(def.def); + } + else if (def.type == 'Complements' || def.type == 'PerfectComplements') { + return new KGAuthor.MinFunction(def.def); + } + else if (def.type == 'Concave') { + return new KGAuthor.ConcaveFunction(def.def); + } + else if (def.type == 'Quasilinear') { + return new KGAuthor.QuasilinearFunction(def.def); + } + else if (def.type == 'CESFunction' || def.type == 'CES') { + return new KGAuthor.CESFunction(def.def); + } + } + } + KGAuthor.getUtilityFunction = getUtilityFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + function extractIndifferenceCurve(def, graph) { + if (def.hasOwnProperty('indifferenceCurveObject')) { + return def.indifferenceCurveObject; + } + if (def.hasOwnProperty('indifferenceCurve')) { + var indifferenceCurveDef = KGAuthor.copyJSON(def.indifferenceCurve); + indifferenceCurveDef.show = indifferenceCurveDef.show || def.show; + indifferenceCurveDef.name = def.name + "_IC"; + return new EconIndifferenceCurve(indifferenceCurveDef, graph); + } + console.log('tried to instantiate a budget line without either a budget line def or object'); + } + KGAuthor.extractIndifferenceCurve = extractIndifferenceCurve; + var EconIndifferenceCurve = /** @class */ (function (_super) { + __extends(EconIndifferenceCurve, _super); + function EconIndifferenceCurve(def, graph) { + var _this = this; + if (def.inMap) { + def.strokeWidth = 1; + def.color = 'lightgrey'; + def.layer = 0; + } + KG.setDefaults(def, { + strokeWidth: 2, + color: 'colors.utility', + layer: 1, + showPreferred: false, + showDispreferred: false, + inMap: false, + showMapLevels: false + }); + if (def.inMap) { + if (def.showMapLevels) { + def.label = KG.setDefaults(def.label || {}, { + fontSize: 8, + x: KGAuthor.multiplyDefs(0.98, graph.xScale.max), + text: def.level + ".toFixed(0)", + color: def.color, + bgcolor: null + }); + } + } + else { + def.label = KG.setDefaults(def.label || {}, { + x: KGAuthor.multiplyDefs(0.95, graph.xScale.max), + text: "U", + color: def.color, + bgcolor: null, + position: 'bl' + }); + } + _this = _super.call(this, def, graph) || this; + var curve = _this; + var utilityFunction = KGAuthor.extractUtilityFunction(def); + curve.utilityFunction = utilityFunction; + curve.subObjects = curve.subObjects.concat(utilityFunction.levelCurve(def, graph)); + if (!def.inMap) { + if (!!def.showPreferred) { + var preferredDef = KGAuthor.copyJSON(def); + //preferredDef.fill = def.preferredColor || 'colors.preferred'; + preferredDef.fill = def.color || 'colors.preferred'; + preferredDef.show = def.showPreferred; + curve.subObjects = curve.subObjects.concat(utilityFunction.areaAboveLevelCurve(preferredDef, graph)); + } + if (!!def.showDispreferred) { + var dispreferredDef = KGAuthor.copyJSON(def); + dispreferredDef.fill = 'colors.dispreferred'; + dispreferredDef.show = def.showDispreferred; + curve.subObjects = curve.subObjects.concat(utilityFunction.areaBelowLevelCurve(dispreferredDef, graph)); + } + } + return _this; + } + return EconIndifferenceCurve; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconIndifferenceCurve = EconIndifferenceCurve; + var EconIndifferenceMap = /** @class */ (function (_super) { + __extends(EconIndifferenceMap, _super); + function EconIndifferenceMap(def, graph) { + var _this = _super.call(this, def, graph) || this; + _this.subObjects = def.levels.map(function (level) { + var icDef = KGAuthor.copyJSON(def); + icDef.inMap = true; + delete icDef.levels; + if (Array.isArray(level)) { + icDef.point = level; + } + else { + icDef.level = level; + } + return new EconIndifferenceCurve(icDef, graph); + }); + return _this; + } + return EconIndifferenceMap; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconIndifferenceMap = EconIndifferenceMap; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + function extractUtilityFunction(def) { + return def.utilityFunctionObject || KGAuthor.getUtilityFunction(def.utilityFunction); + } + KGAuthor.extractUtilityFunction = extractUtilityFunction; + var EconBundle = /** @class */ (function (_super) { + __extends(EconBundle, _super); + function EconBundle(def, graph) { + var _this = this; + KG.setDefaults(def, { + label: { text: 'X' }, + droplines: { + vertical: "x_1", + horizontal: "x_2" + }, + color: "colors.utility" + }); + KGAuthor.setFillColor(def); + _this = _super.call(this, def, graph) || this; + var bundle = _this; + bundle.budgetLine = KGAuthor.extractBudgetLine(def, graph); + if (bundle.budgetLine) { + bundle.subObjects.push(bundle.budgetLine); + } + bundle.utilityFunction = extractUtilityFunction(def); + if (bundle.utilityFunction) { + bundle.subObjects.push(bundle.utilityFunction); + if (def.hasOwnProperty('indifferenceCurve')) { + def.indifferenceCurve.level = "calcs." + bundle.name + ".level"; + def.indifferenceCurve.utilityFunction = def.utilityFunction; + bundle.subObjects.push(KGAuthor.extractIndifferenceCurve(def, graph)); + } + } + return _this; + } + EconBundle.prototype.parseSelf = function (parsedData) { + var bundle = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[bundle.name] = { + x: bundle.x, + y: bundle.y, + level: bundle.utilityFunction ? bundle.utilityFunction.value([bundle.x, bundle.y]) : '', + cost: bundle.budgetLine ? bundle.budgetLine.cost(bundle) : '', + mrs: bundle.utilityFunction ? KGAuthor.negativeDef(bundle.utilityFunction.levelCurveSlope([bundle.x, bundle.y])) : '' + }; + return parsedData; + }; + return EconBundle; + }(KGAuthor.Point)); + KGAuthor.EconBundle = EconBundle; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconOptimalBundle = /** @class */ (function (_super) { + __extends(EconOptimalBundle, _super); + function EconOptimalBundle(def, graph) { + var _this = this; + var bl = KGAuthor.extractBudgetLine(def, graph), u = KGAuthor.extractUtilityFunction(def), coords = u.optimalBundle(bl); + KG.setDefaults(def, { + coordinates: coords, + label: { text: 'X^*' }, + color: 'demand', + droplines: { + vertical: "x_1^*", + horizontal: "x_2^*" + }, + indifferenceCurve: {} + }); + console.log('coords: ', coords); + if (bl.hasOwnProperty('endowment')) { + if (bl.def.sellOnly) { + def.show = "(" + (def.show || true) + " && (" + coords[0] + " < " + bl.endowment.x + "))"; + } + if (bl.def.buyOnly) { + def.show = "(" + (def.show || true) + " && (" + coords[0] + " > " + bl.endowment.x + "))"; + } + } + def.budgetLineObject = bl; + _this = _super.call(this, def, graph) || this; + _this.level = u.value(coords); + return _this; + } + return EconOptimalBundle; + }(KGAuthor.EconBundle)); + KGAuthor.EconOptimalBundle = EconOptimalBundle; + var EconLagrangeBundle = /** @class */ (function (_super) { + __extends(EconLagrangeBundle, _super); + function EconLagrangeBundle(def, graph) { + var _this = this; + if (def.hasOwnProperty('utilityFunction') && def.hasOwnProperty('budgetLine')) { + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + coordinates: u.lagrangeBundle(bl), + color: 'colors.incomeOffer', + show: u.cornerCondition(bl), + label: { text: 'X^*_L' } + }); + } + else { + console.log('oops, need to define an EconOptimalBundle with a utility function and budget line.'); + } + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconLagrangeBundle; + }(EconOptimalBundle)); + KGAuthor.EconLagrangeBundle = EconLagrangeBundle; + var LowestCostBundle = /** @class */ (function (_super) { + __extends(LowestCostBundle, _super); + function LowestCostBundle(def, graph) { + var _this = this; + var u = KGAuthor.extractUtilityFunction(def), p1 = def.prices[0], p2 = def.prices[1], m = u.expenditure(def.level, def.prices); + delete def.prices; + delete def.level; + def.budgetLine = KG.setDefaults(def.budgetLine || {}, { + p1: p1, + p2: p2, + m: m + }); + _this = _super.call(this, def, graph) || this; + return _this; + } + return LowestCostBundle; + }(EconOptimalBundle)); + KGAuthor.LowestCostBundle = LowestCostBundle; + var EconSlutskyBundle = /** @class */ (function (_super) { + __extends(EconSlutskyBundle, _super); + function EconSlutskyBundle(def, graph) { + var _this = this; + var bl = KGAuthor.extractBudgetLine(def, graph), u = KGAuthor.extractUtilityFunction(def); + def.budgetLine = def.budgetLine || {}; + if (def.hasOwnProperty('p1')) { + def.budgetLine.p1 = def.p1; + delete def.budgetLine.m; + } + if (def.hasOwnProperty('p2')) { + def.budgetLine.p2 = def.p2; + delete def.budgetLine.m; + } + def.budgetLine.label = KG.setDefaults(def.budgetLine.label || {}, { + text: "BL_D" + }); + def.budgetLine.point = u.optimalBundle(bl); + delete def.budgetLineObject; + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconSlutskyBundle; + }(EconOptimalBundle)); + KGAuthor.EconSlutskyBundle = EconSlutskyBundle; + var EconHicksBundle = /** @class */ (function (_super) { + __extends(EconHicksBundle, _super); + function EconHicksBundle(def, graph) { + var _this = this; + var bl = KGAuthor.extractBudgetLine(def, graph), u = KGAuthor.extractUtilityFunction(def), p1 = def.hasOwnProperty('p1') ? def.p1 : def.budgetLine.p1, p2 = def.hasOwnProperty('p2') ? def.p2 : def.budgetLine.p2, level = u.value(u.optimalBundle(bl)); + def.budgetLine.p1 = p1; + def.budgetLine.p2 = p2; + def.budgetLine.m = u.expenditure(level, [p1, p2]); + def.budgetLine.label = KG.setDefaults(def.budgetLine.label || {}, { + text: "BL_C" + }); + def.coordinates = u.lowestCostBundle(level, [p1, p2]); + delete def.budgetLineObject; + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconHicksBundle; + }(EconOptimalBundle)); + KGAuthor.EconHicksBundle = EconHicksBundle; + var EconShortRunProductionBundle = /** @class */ (function (_super) { + __extends(EconShortRunProductionBundle, _super); + function EconShortRunProductionBundle(def, graph) { + var _this = this; + var u = KGAuthor.extractUtilityFunction(def), p1 = def.prices[0], p2 = def.prices[1]; + def.coordinates = [u.laborRequirement(def.level, def.capital), def.capital]; + def.budgetLine = KG.setDefaults(def.budgetLine || {}, { + p1: p1, + p2: p2 + }); + def.budgetLine.label = KG.setDefaults(def.budgetLine.label || {}, { + text: "c_s(y)" + }); + delete def.budgetLineObject; + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconShortRunProductionBundle; + }(KGAuthor.EconBundle)); + KGAuthor.EconShortRunProductionBundle = EconShortRunProductionBundle; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconDemandCurve = /** @class */ (function (_super) { + __extends(EconDemandCurve, _super); + function EconDemandCurve(def, graph) { + var _this = this; + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + stroke: 'colors.demand', + strokeWidth: 2 + }); + _this = _super.call(this, def, graph) || this; + _this.subObjects = u.demandCurve(bl, def.good, def, graph); + return _this; + } + return EconDemandCurve; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconDemandCurve = EconDemandCurve; + var EconDemandPoint = /** @class */ (function (_super) { + __extends(EconDemandPoint, _super); + function EconDemandPoint(def, graph) { + var _this = this; + if (def.hasOwnProperty('utilityFunction') && def.hasOwnProperty('budgetLine')) { + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + coordinates: [u.quantityDemanded(bl, def.good), bl['p' + def.good]], + fill: 'colors.demand', + label: { text: "x_" + def.good + "(p_" + def.good + "|p_" + (3 - def.good) + ",m)" }, + droplines: { vertical: "x_" + def.good + "^*" } + }); + } + else { + console.log('oops, need to define an EconOptimalBundle with a utility function and budget line.'); + } + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconDemandPoint; + }(KGAuthor.Point)); + KGAuthor.EconDemandPoint = EconDemandPoint; + var EconNetDemandCurve = /** @class */ (function (_super) { + __extends(EconNetDemandCurve, _super); + function EconNetDemandCurve(def, graph) { + var _this = this; + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + color: 'colors.demand', + strokeWidth: 2 + }); + _this = _super.call(this, def, graph) || this; + _this.subObjects = u.netDemandCurve(bl, def.good, def, graph); + return _this; + } + return EconNetDemandCurve; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconNetDemandCurve = EconNetDemandCurve; + var EconNetDemandPoint = /** @class */ (function (_super) { + __extends(EconNetDemandPoint, _super); + function EconNetDemandPoint(def, graph) { + var _this = this; + if (def.hasOwnProperty('utilityFunction') && def.hasOwnProperty('budgetLine')) { + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + coordinates: [KGAuthor.subtractDefs(u.quantityDemanded(bl, def.good), bl.point[def.good - 1]), bl['p' + def.good]], + fill: 'colors.demand', + label: { text: "d_" + def.good + "(p_" + def.good + "|p_" + (3 - def.good) + ")" }, + droplines: { vertical: "d_" + def.good + "^*" } + }); + } + else { + console.log('oops, need to define an EconOptimalBundle with a utility function and budget line.'); + } + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconNetDemandPoint; + }(KGAuthor.Point)); + KGAuthor.EconNetDemandPoint = EconNetDemandPoint; + var EconNetSupplyCurve = /** @class */ (function (_super) { + __extends(EconNetSupplyCurve, _super); + function EconNetSupplyCurve(def, graph) { + var _this = this; + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + color: 'colors.supply', + strokeWidth: 2 + }); + _this = _super.call(this, def, graph) || this; + _this.subObjects = u.netSupplyCurve(bl, def.good, def, graph); + return _this; + } + return EconNetSupplyCurve; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconNetSupplyCurve = EconNetSupplyCurve; + var EconNetSupplyPoint = /** @class */ (function (_super) { + __extends(EconNetSupplyPoint, _super); + function EconNetSupplyPoint(def, graph) { + var _this = this; + if (def.hasOwnProperty('utilityFunction') && def.hasOwnProperty('budgetLine')) { + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + coordinates: [KGAuthor.subtractDefs(bl.point[def.good - 1], u.quantityDemanded(bl, def.good)), bl['p' + def.good]], + fill: 'colors.supply', + label: { text: "s_" + def.good + "(p_" + def.good + "|p_" + (3 - def.good) + ")" }, + droplines: { vertical: "s_" + def.good + "^*" } + }); + } + else { + console.log('oops, need to define an EconOptimalBundle with a utility function and budget line.'); + } + _this = _super.call(this, def, graph) || this; + return _this; + } + return EconNetSupplyPoint; + }(KGAuthor.Point)); + KGAuthor.EconNetSupplyPoint = EconNetSupplyPoint; + var EconPriceOfferCurve = /** @class */ (function (_super) { + __extends(EconPriceOfferCurve, _super); + function EconPriceOfferCurve(def, graph) { + var _this = this; + var u = KGAuthor.getUtilityFunction(def.utilityFunction), bl = new KGAuthor.EconBudgetLine(def.budgetLine, graph); + KG.setDefaults(def, { + stroke: 'colors.offer', + strokeWidth: 2 + }); + _this = _super.call(this, def, graph) || this; + _this.subObjects = u.priceOfferCurve(bl, def.good, def.min, def.max, def, graph); + return _this; + } + return EconPriceOfferCurve; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconPriceOfferCurve = EconPriceOfferCurve; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconOneInputProductionFunction = /** @class */ (function (_super) { + __extends(EconOneInputProductionFunction, _super); + function EconOneInputProductionFunction(def, graph) { + var _this = this; + KG.setDefaults(def, { + coefficient: 1, + exponent: 0.5, + wage: 1, + price: 1 + }); + _this = _super.call(this, def) || this; + var f = _this; + f.coefficient = def.coefficient; + f.exponent = def.exponent; + f.wage = def.wage; + f.price = def.price; + // if y(L) = AL^b, L(y) = [A^(-1/b)] * y^[1/b] + f.laborRequirementExponent = KGAuthor.invertDef(def.exponent); + f.laborRequirementCoefficient = KGAuthor.raiseDefToDef(def.coefficient, KGAuthor.negativeDef(f.laborRequirementExponent)); + // if f(L) = AL^b, f'(L) = [bA] * L^[b-1] + f.marginalProductExponent = KGAuthor.subtractDefs(def.exponent, 1); + f.marginalProductCoefficient = KGAuthor.multiplyDefs(def.exponent, def.coefficient); + // if c(y) = wL(y) = w*LRC * y^LRE, c'(y) = [w*LRC*LRE] * y^[LRE - 1] + f.marginalCostCoefficient = KGAuthor.multiplyDefs(def.wage, KGAuthor.multiplyDefs(f.laborRequirementExponent, f.laborRequirementCoefficient)); + f.marginalCostExponent = KGAuthor.subtractDefs(f.laborRequirementExponent, 1); + // if c'(y) = MCC * y^MCE, y*(p) = MCC^(-1/MCE) * p^(1/MCE) + f.outputSupplyCoefficient = KGAuthor.raiseDefToDef(f.marginalCostCoefficient, KGAuthor.negativeDef(KGAuthor.invertDef(f.marginalCostExponent))); + f.outputSupplyExponent = KGAuthor.invertDef(f.marginalCostExponent); + // if MRPL = [p * MPC] * L^MPE, L*(w) = (p*MPC)^(-1/MPE) * w^(1/MPE) + f.laborDemandCoefficient = KGAuthor.raiseDefToDef(KGAuthor.multiplyDefs(f.price, f.marginalProductCoefficient), KGAuthor.negativeDef(KGAuthor.invertDef(f.marginalProductExponent))); + f.laborDemandExponent = KGAuthor.invertDef(f.marginalProductExponent); + return _this; + } + // output produced by L units of olabor + EconOneInputProductionFunction.prototype.f = function (L) { + var f = this; + return KGAuthor.multiplyDefs(f.coefficient, KGAuthor.raiseDefToDef(L, f.exponent)); + }; + // labor required to produce y units of output + EconOneInputProductionFunction.prototype.laborRequirement = function (y) { + var f = this; + return KGAuthor.multiplyDefs(f.laborRequirementCoefficient, KGAuthor.raiseDefToDef(y, f.laborRequirementExponent)); + }; + // marginal product of labor + EconOneInputProductionFunction.prototype.MPL = function (L) { + var f = this; + return KGAuthor.multiplyDefs(f.marginalProductCoefficient, KGAuthor.raiseDefToDef(L, f.marginalProductExponent)); + }; + // marginal revenue product of labor is price times MPL + EconOneInputProductionFunction.prototype.MRPL = function (L) { + var f = this; + return KGAuthor.multiplyDefs(f.price, f.MPL(L)); + }; + // cost is wage times labor requirement + EconOneInputProductionFunction.prototype.cost = function (y) { + var f = this; + return KGAuthor.multiplyDefs(f.wage, f.laborRequirement(y)); + }; + EconOneInputProductionFunction.prototype.marginalCost = function (y) { + var f = this; + return KGAuthor.multiplyDefs(f.marginalCostCoefficient, KGAuthor.raiseDefToDef(y, f.marginalCostExponent)); + }; + // labor demand + EconOneInputProductionFunction.prototype.laborDemand = function (w) { + var f = this; + return KGAuthor.multiplyDefs(f.laborDemandCoefficient, KGAuthor.raiseDefToDef(w, f.laborDemandExponent)); + }; + // optimal output + EconOneInputProductionFunction.prototype.optimalOutput = function (p) { + var f = this; + return KGAuthor.multiplyDefs(f.outputSupplyCoefficient, KGAuthor.raiseDefToDef(p, f.outputSupplyCoefficient)); + }; + EconOneInputProductionFunction.prototype.parseSelf = function (parsedData) { + var ppf = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[ppf.name] = { + coefficient: ppf.coefficient, + exponent: ppf.exponent, + curve: ppf.f('(x)') + }; + return parsedData; + }; + return EconOneInputProductionFunction; + }(KGAuthor.AuthoringObject)); + KGAuthor.EconOneInputProductionFunction = EconOneInputProductionFunction; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconConstantElasticityCurve = /** @class */ (function (_super) { + __extends(EconConstantElasticityCurve, _super); + function EconConstantElasticityCurve(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + KG.setDefaults(def, { + name: 'constElasticityCurve' + KG.randomString(5), + color: 'colors.demand', + strokeWidth: 2, + lineStyle: 'solid', + show: true + }); + // TODO shouldn't need to convert these to strings; it should work with numbers... + if (def.hasOwnProperty('elasticity')) { + def.elasticity = def.elasticity.toString(); + } + if (def.hasOwnProperty('normalizedElasticity')) { + def.normalizedElasticity = def.normalizedElasticity.toString(); + } + // A constant elasticity curve is defined by one point and either an elasticity, a normalized elasticity, or a second point. + var curveDef = KGAuthor.copyJSON(def); + curveDef.fn = KGAuthor.multiplyDefs("calcs." + def.name + ".coefficient", KGAuthor.raiseDefToDef("(y)", "calcs." + curveDef.name + ".elasticity")); + curveDef.ind = 'y'; + curveDef.samplePoints = 500; + curveDef.show = "((" + def.show + ") && !(calcs. " + def.name + ".elastic))"; + var invCurveDef = KGAuthor.copyJSON(def); + invCurveDef.name = def.name + "inverse"; + invCurveDef.fn = KGAuthor.multiplyDefs("calcs." + invCurveDef.name + ".coefficient", KGAuthor.raiseDefToDef("(x)", "calcs." + invCurveDef.name + ".elasticity")); + invCurveDef.samplePoints = 500; + invCurveDef.ind = 'x'; + invCurveDef.show = "((" + def.show + ") && (calcs. " + def.name + ".elastic))"; + // define the control point + var pointDef = KGAuthor.copyJSON(def.point || {}); + pointDef.color = pointDef.color || def.color; + pointDef.show = pointDef.show || def.show; + // define the second control point, if applicable + if (def.hasOwnProperty('point2')) { + var point2Def = KGAuthor.copyJSON(def.point2); + point2Def.color = point2Def.color || def.color; + point2Def.show = point2Def.show || def.show; + } + _this = _super.call(this, curveDef, graph) || this; + var c = _this; + c.subObjects.push(new KGAuthor.Curve(invCurveDef, graph)); + var p = new KGAuthor.Point(pointDef, graph); + c.subObjects.push(p); + // If defined by a second point, calculate the elasticity implied by those two points + if (def.hasOwnProperty('point2')) { + var pointDef2 = def.point2; + pointDef2.color = pointDef2.color || def.color; + var p2 = new KGAuthor.Point(pointDef2, graph); + // calculate elasticity between the two points + // we have x0 = a*y0^b, x1 = a*y1^b + // therefore a = x0y0^(-b) = x1y1^(-b) + // therefore (x0/x1) = (y0/y1)^b => b = log(x0/x1)/log(y0/y1) + var x0overx1 = KGAuthor.divideDefs(p.x, p2.x); + var y0overy1 = KGAuthor.divideDefs(p.y, p2.y); + c.elasticity = KGAuthor.divideDefs("log" + x0overx1 + "", "log" + y0overy1 + ""); + c.invElasticity = KGAuthor.divideDefs("log" + y0overy1 + "", "log" + x0overx1 + ""); + c.perfectlyElastic = "(" + p.y + " == " + p2.y + ")"; + c.perfectlyInelastic = "(" + p.x + " == " + p2.x + ")"; + c.subObjects.push(p2); + } + // If the elasticity is normalized, 0 is perfectly inelastic, and 1 or -1 is perfectly elastic. + else if (def.hasOwnProperty('normalizedElasticity')) { + var absNormalizedElasticity = "(abs(" + def.normalizedElasticity + "))"; + c.elasticity = KGAuthor.divideDefs(def.normalizedElasticity, "(1 - " + absNormalizedElasticity + ")"); + c.invElasticity = KGAuthor.divideDefs("(1 - " + absNormalizedElasticity + ")", def.normalizedElasticity); + c.perfectlyElastic = "(" + absNormalizedElasticity + " == 1)"; + c.perfectlyInelastic = "(" + def.normalizedElasticity + " == 0)"; + } + // If the elasticity is defined directly, it can't be infinite + else { + c.elasticity = def.elasticity; + c.invElasticity = KGAuthor.invertDef(def.elasticity); + c.perfectlyInelastic = "(" + def.elasticity + " == 0)"; + c.perfectlyElastic = "false"; + } + // we have a function of the form x = ay^b => a = x0/y0^(b) + c.coefficient = KGAuthor.divideDefs(p.x, KGAuthor.raiseDefToDef(p.y, c.elasticity)); + // the inverse of this function is of the form y = a'x^(b') => a' = y0/x0^(b') + c.invCoefficient = KGAuthor.divideDefs(p.y, KGAuthor.raiseDefToDef(p.x, c.invElasticity)); + // Define regions of elasticity + c.absElasticity = "(abs(" + c.elasticity + "))"; + c.elastic = "(" + c.absElasticity + " > 1)"; + c.unitElastic = "(" + c.absElasticity + " == 1)"; + c.inelastic = "(" + c.absElasticity + " < 1)"; + return _this; + } + EconConstantElasticityCurve.prototype.parseSelf = function (parsedData) { + var c = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[c.name] = { + elasticity: c.elasticity, + coefficient: c.coefficient, + elastic: c.elastic, + unitElastic: c.unitElastic, + inelastic: c.inelastic, + perfectlyElastic: c.perfectlyElastic, + perfectlyInelastic: c.perfectlyInelastic + }; + parsedData.calcs[c.name + 'inverse'] = { + elasticity: c.invElasticity, + coefficient: c.invCoefficient + }; + return parsedData; + }; + return EconConstantElasticityCurve; + }(KGAuthor.Curve)); + KGAuthor.EconConstantElasticityCurve = EconConstantElasticityCurve; + var EconConstantElasticityIntersection = /** @class */ (function (_super) { + __extends(EconConstantElasticityIntersection, _super); + function EconConstantElasticityIntersection(def, graph) { + var _this = _super.call(this, def, graph) || this; + var intersection = _this; + intersection.name = def.name; + var c1 = "(calcs." + def.curve1 + ".coefficient)", e1 = "(calcs." + def.curve1 + ".elasticity)", c2 = "(calcs." + def.curve2 + ".coefficient)", e2 = "(calcs." + def.curve2 + ".elasticity)", invc1 = "(calcs." + def.curve1 + "inverse.coefficient)", inve1 = "(calcs." + def.curve1 + "inverse.elasticity)", invc2 = "(calcs." + def.curve2 + "inverse.coefficient)", inve2 = "(calcs." + def.curve2 + "inverse.elasticity)"; + // intersection occurs at the point where c1*x^(e1) = c2*x^(e2) => x = (c1/c2)^(1/(e2 - e1)) + var P = KGAuthor.raiseDefToDef(KGAuthor.divideDefs(c1, c2), KGAuthor.invertDef(KGAuthor.subtractDefs(e2, e1))); + var QofP = KGAuthor.multiplyDefs(c1, KGAuthor.raiseDefToDef(P, e1)); + intersection.Pdirect = P; + intersection.Qcalc = QofP; + // can also use the inverse curves to calculate the Q, and the P from that. + var Q = KGAuthor.raiseDefToDef(KGAuthor.divideDefs(invc1, invc2), KGAuthor.invertDef(KGAuthor.subtractDefs(inve2, inve1))); + var PofQ = KGAuthor.multiplyDefs(invc1, KGAuthor.raiseDefToDef(Q, inve1)); + intersection.Qdirect = Q; + intersection.Pcalc = PofQ; + // want to use (P, QofP) when either supply or demand is perfectly inelastic; otherwise want to use (Q, PofQ) + var eitherPerfectlyInelastic = "(" + KGAuthor.multiplyDefs(e1, e2) + " == 0)"; + intersection.Q = "(" + eitherPerfectlyInelastic + " ? " + QofP + " : " + Q + ")"; + intersection.P = "(" + eitherPerfectlyInelastic + " ? " + P + " : " + PofQ + ")"; + return _this; + } + EconConstantElasticityIntersection.prototype.parseSelf = function (parsedData) { + var c = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[c.name] = { + Pdirect: c.Pdirect, + Pcalc: c.Pcalc, + Qdirect: c.Qdirect, + Qcalc: c.Qcalc, + Q: c.Q, + P: c.P + }; + return parsedData; + }; + return EconConstantElasticityIntersection; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconConstantElasticityIntersection = EconConstantElasticityIntersection; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconConstantElasticityEquilibrium = /** @class */ (function (_super) { + __extends(EconConstantElasticityEquilibrium, _super); + function EconConstantElasticityEquilibrium(def, graph) { + var _this = this; + KG.setDefaults(def, { + name: 'equilibrium', + showCS: false, + showPS: false + }); + _this = _super.call(this, def, graph) || this; + var cee = _this; + def.equilibrium.color = def.equilibrium.color || "colors.green"; + var equilibrium = new KGAuthor.Point(def.equilibrium, graph); + cee.Q = equilibrium.x; + cee.P = equilibrium.y; + def.demand.point = def.equilibrium; + def.demand.name = def.name + "dem"; + def.demand.color = "colors.demand"; + var demand = new KGAuthor.EconConstantElasticityCurve(def.demand, graph); + console.log("demand: ", demand); + cee.subObjects.push(demand); + def.supply.point = def.equilibrium; + def.supply.name = def.name + "sup"; + def.supply.color = "colors.supply"; + var supply = new KGAuthor.EconConstantElasticityCurve(def.supply, graph); + console.log('supply: ', supply); + cee.subObjects.push(supply); + return _this; + } + EconConstantElasticityEquilibrium.prototype.parseSelf = function (parsedData) { + var cee = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[cee.name] = { + Q: cee.Q.toString(), + P: cee.P.toString() + }; + return parsedData; + }; + return EconConstantElasticityEquilibrium; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconConstantElasticityEquilibrium = EconConstantElasticityEquilibrium; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconLinearDemand = /** @class */ (function (_super) { + __extends(EconLinearDemand, _super); + function EconLinearDemand(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + KG.setDefaults(def, { + name: "demand", + point: [0, def.yIntercept], + slope: 0, + color: 'colors.demand', + strokeWidth: 2, + lineStyle: 'solid', + pts: [] + }); + if (def.draggable && typeof (def.xIntercept) == 'string') { + def.drag = [{ + 'directions': 'x', + 'param': KGAuthor.paramName(def.xIntercept), + 'expression': KGAuthor.addDefs(def.xIntercept, 'drag.dx') + }]; + } + else if (def.draggable && typeof (def.yIntercept) == 'string') { + def.drag = [{ + 'directions': 'y', + 'param': KGAuthor.paramName(def.yIntercept), + 'expression': KGAuthor.addDefs(def.yIntercept, 'drag.dy') + }]; + } + //def.max = def.xIntercept; + if (def.hasOwnProperty("price")) { + def.pts.push({ + name: "PQ", + y: def.price + }); + } + if (def.hasOwnProperty("surplus")) { + if (!def.hasOwnProperty("price") && def.surplus.hasOwnProperty("quantity")) { + def.pts.push({ + name: "PQ", + x: def.surplus.quantity + }); + } + } + _this = _super.call(this, def, graph) || this; + var ld = _this; + if (graph) { + var subObjects = ld.subObjects; + var xInterceptPointDef = { + coordinates: [ld.xIntercept, 0], + color: def.color, + r: 4 + }; + if (def.draggable && typeof (ld.xIntercept) == 'string') { + xInterceptPointDef['drag'] = [{ + directions: 'x', + param: KGAuthor.paramName(ld.xIntercept), + expression: KGAuthor.addDefs(ld.xIntercept, 'drag.dx') + }]; + } + if (def.hasOwnProperty('xInterceptLabel')) { + xInterceptPointDef['droplines'] = { + vertical: def.xInterceptLabel + }; + } + ld.xInterceptPoint = new KGAuthor.Point(xInterceptPointDef, graph); + var yInterceptPointDef = { + coordinates: [0, ld.yIntercept], + color: def.color, + r: 4 + }; + if (def.draggable && typeof (ld.yIntercept) == 'string') { + yInterceptPointDef['drag'] = [{ + directions: 'y', + param: KGAuthor.paramName(ld.invSlope), + expression: KGAuthor.negativeDef(KGAuthor.divideDefs(ld.xIntercept, 'max(drag.y,0.01)')) + }]; + } + if (def.hasOwnProperty('yInterceptLabel')) { + yInterceptPointDef['droplines'] = { + horizontal: def.yInterceptLabel + }; + } + ld.yInterceptPoint = new KGAuthor.Point(yInterceptPointDef, graph); + if (def.handles) { + subObjects.push(ld.xInterceptPoint); + subObjects.push(ld.yInterceptPoint); + } + if (def.hasOwnProperty('marginalRevenue')) { + var marginalRevenueDef = KG.setDefaults(def.marginalRevenue || {}, { + "color": "colors.marginalRevenue", + "yIntercept": ld.yIntercept, + "slope": KGAuthor.multiplyDefs(2, ld.slope), + "label": { + "text": "MR", + "x": KGAuthor.multiplyDefs(0.6, ld.xIntercept) + } + }); + ld.marginalRevenue = new KGAuthor.Line(marginalRevenueDef, graph); + ld.subObjects.push(ld.marginalRevenue); + } + if (def.hasOwnProperty('surplus')) { + var surplusDef = KG.setDefaults(def.surplus || {}, { + "fill": "colors.demand" + }); + var price = surplusDef.price || "calcs." + ld.name + ".PQ.y", quantity = surplusDef.quantity || "calcs." + ld.name + ".PQ.x"; + surplusDef.univariateFunction1 = { + fn: ld.def.univariateFunction.fn, + min: 0, + max: quantity, + samplePoints: 2 + }; + surplusDef.univariateFunction2 = { + fn: price, + min: 0, + max: quantity, + samplePoints: 2 + }; + ld.subObjects.push(new KGAuthor.Area(surplusDef, graph)); + } + } + return _this; + } + return EconLinearDemand; + }(KGAuthor.Line)); + KGAuthor.EconLinearDemand = EconLinearDemand; + var EconCompetitiveDemand = /** @class */ (function (_super) { + __extends(EconCompetitiveDemand, _super); + function EconCompetitiveDemand() { + return _super !== null && _super.apply(this, arguments) || this; + } + return EconCompetitiveDemand; + }(EconLinearDemand)); + KGAuthor.EconCompetitiveDemand = EconCompetitiveDemand; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconLinearSupply = /** @class */ (function (_super) { + __extends(EconLinearSupply, _super); + function EconLinearSupply(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + KG.setDefaults(def, { + name: 'supply', + color: 'colors.supply', + strokeWidth: 2, + lineStyle: 'solid', + pts: [] + }); + if (def.draggable && typeof (def.slope) == 'string') { + def.drag = [{ + 'directions': 'xy', + 'param': KGAuthor.paramName(def.slope), + 'expression': KGAuthor.divideDefs(KGAuthor.subtractDefs('drag.y', def.yIntercept), 'drag.x') + }]; + } + else if (def.draggable && typeof (def.invSlope) == 'string') { + def.drag = [{ + 'directions': 'xy', + 'param': KGAuthor.paramName(def.invSlope), + 'expression': KGAuthor.divideDefs('drag.x', KGAuthor.subtractDefs('drag.y', def.yIntercept)) + }]; + } + else if (def.draggable && typeof (def.yIntercept) == 'string') { + def.drag = [{ + 'directions': 'y', + 'param': KGAuthor.paramName(def.yIntercept), + 'expression': KGAuthor.addDefs(def.yIntercept, 'drag.dy') + }]; + } + if (def.hasOwnProperty("price")) { + def.pts.push({ + name: "PQ", + y: def.price + }); + } + _this = _super.call(this, def, graph) || this; + var ls = _this; + if (graph) { + var subObjects = ls.subObjects; + var yInterceptPointDef = { + coordinates: [0, ls.yIntercept], + color: def.color, + r: 4, + show: def.show + }; + if (def.draggable && typeof (ls.yIntercept) == 'string') { + yInterceptPointDef['drag'] = [{ + directions: 'y', + param: KGAuthor.paramName(ls.yIntercept), + expression: KGAuthor.addDefs(ls.yIntercept, 'drag.dy') + }]; + } + if (def.hasOwnProperty('yInterceptLabel')) { + yInterceptPointDef['droplines'] = { + horizontal: def.yInterceptLabel + }; + } + ls.yInterceptPoint = new KGAuthor.Point(yInterceptPointDef, graph); + if (def.handles) { + subObjects.push(ls.yInterceptPoint); + } + if (def.hasOwnProperty('surplus')) { + var surplusDef = KG.setDefaults(def.surplus || {}, { + "fill": "colors.supply" + }); + var price = surplusDef.price || "calcs." + ls.name + ".PQ.y", quantity = surplusDef.quantity || "calcs." + ls.name + ".PQ.x"; + surplusDef.univariateFunction1 = { + fn: ls.def.univariateFunction.fn, + min: 0, + max: quantity, + samplePoints: 2 + }; + surplusDef.univariateFunction2 = { + fn: price, + min: 0, + max: quantity, + samplePoints: 2 + }; + ls.subObjects.push(new KGAuthor.Area(surplusDef, graph)); + } + } + return _this; + } + return EconLinearSupply; + }(KGAuthor.Line)); + KGAuthor.EconLinearSupply = EconLinearSupply; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconLinearEquilibrium = /** @class */ (function (_super) { + __extends(EconLinearEquilibrium, _super); + function EconLinearEquilibrium(def, graph) { + var _this = this; + KG.setDefaults(def, { + name: 'equilibrium', + showCS: false, + showPS: false + }); + _this = _super.call(this, def, graph) || this; + var le = _this; + def.demand.price = "calcs." + le.name + ".P"; + def.supply.price = "calcs." + le.name + ".P"; + le.demand = new KGAuthor.EconLinearDemand(def.demand, graph); + le.supply = new KGAuthor.EconLinearSupply(def.supply, graph); + le.subObjects.push(_this.demand); + le.subObjects.push(_this.supply); + var eq = KGAuthor.lineIntersection(le.demand, le.supply); + le.Q = eq[0]; + le.P = eq[1]; + if (graph) { + if (def.hasOwnProperty('equilibrium')) { + def.equilibrium = KG.setDefaults(def.equilibrium, { + "color": "colors.equilibriumPrice", + "x": le.Q, + "y": le.P, + "droplines": { + "vertical": "Q^*", + "horizontal": "P^*" + } + }); + le.subObjects.push(new KGAuthor.Point(def.equilibrium, graph)); + } + } + return _this; + } + EconLinearEquilibrium.prototype.parseSelf = function (parsedData) { + var le = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[le.name] = { + Q: le.Q.toString(), + P: le.P.toString() + }; + return parsedData; + }; + return EconLinearEquilibrium; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconLinearEquilibrium = EconLinearEquilibrium; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconPPF = /** @class */ (function (_super) { + __extends(EconPPF, _super); + function EconPPF(def, graph) { + var _this = this; + def = KGAuthor.setStrokeColor(def); + KG.setDefaults(def, { + name: 'ppf', + color: 'colors.supply', + strokeWidth: 2, + lineStyle: 'solid', + labor: 100, + L1: 50, + p1: 1, + p2: 1, + max1: 100, + max2: 100, + curvature: 0.5 + }); + if (def.linear) { + def.curvature = 1; + } + var fn1coeff = KGAuthor.divideDefs(def.max1, KGAuthor.raiseDefToDef(def.labor, def.curvature)), fn2coeff = KGAuthor.divideDefs(def.max2, KGAuthor.raiseDefToDef(def.labor, def.curvature)); + var fn1 = new KGAuthor.EconOneInputProductionFunction({ + name: def.name + '_prodFn1', + coefficient: fn1coeff, + exponent: def.curvature + }), fn2 = new KGAuthor.EconOneInputProductionFunction({ + name: def.name + '_prodFn2', + coefficient: fn2coeff, + exponent: def.curvature + }); + def.parametricFunction = { + xFunction: fn1.f("(t)"), + yFunction: fn2.f(KGAuthor.subtractDefs(def.labor, "(t)")), + max: def.labor + }; + if (def.draggable) { + var dragLaborRequirement = KGAuthor.addDefs(fn1.laborRequirement('drag.x'), fn2.laborRequirement('drag.y')); + def.drag = [{ + 'directions': 'xy', + 'param': KGAuthor.paramName(def.max1), + 'expression': fn1.f(dragLaborRequirement) + }, + { + 'directions': 'xy', + 'param': KGAuthor.paramName(def.max2), + 'expression': fn2.f(dragLaborRequirement) + }]; + } + _this = _super.call(this, def, graph) || this; + var ppf = _this; + ppf.labor = def.labor; + ppf.prodFn1 = fn1; + ppf.prodFn2 = fn2; + ppf.subObjects.push(fn1); + ppf.subObjects.push(fn2); + ppf.L1 = def.L1; + ppf.L2 = KGAuthor.subtractDefs(def.labor, def.L1); + ppf.y1 = ppf.prodFn1.f(ppf.L1); + ppf.y2 = ppf.prodFn2.f(ppf.L2); + var coefficientRatio = KGAuthor.divideDefs(def.max2, def.max1), laborRatio = KGAuthor.divideDefs(ppf.L2, def.L1), priceRatio = KGAuthor.divideDefs(def.p1, def.p2); + if (def.curvature == 1) { + ppf.mrt = coefficientRatio; + ppf.optimalL1 = "((" + coefficientRatio + " > " + priceRatio + ") ? 0 : " + ppf.labor + ")"; + ppf.optimalL1 = "((" + coefficientRatio + " > " + priceRatio + ") ? " + ppf.labor + " : 0)"; + } + else { + ppf.mrt = KGAuthor.multiplyDefs(coefficientRatio, KGAuthor.raiseDefToDef(laborRatio, KGAuthor.subtractDefs(def.curvature, 1))); + var theta = KGAuthor.raiseDefToDef(KGAuthor.divideDefs(coefficientRatio, priceRatio), KGAuthor.invertDef(KGAuthor.subtractDefs(def.curvature, 1))); + ppf.optimalL1 = KGAuthor.multiplyDefs(KGAuthor.divideDefs(theta, KGAuthor.addDefs(1, theta)), ppf.labor); + ppf.optimalL2 = KGAuthor.multiplyDefs(KGAuthor.divideDefs(1, KGAuthor.addDefs(1, theta)), ppf.labor); + } + ppf.optimaly1 = ppf.prodFn1.f(ppf.optimalL1); + ppf.optimaly2 = ppf.prodFn2.f(ppf.optimalL2); + if (graph) { + var subObjects = ppf.subObjects; + var xInterceptPointDef = { + coordinates: [def.max1, 0], + fill: def.stroke, + r: 4 + }; + if (def.draggable && typeof (def.max1) == 'string') { + xInterceptPointDef['drag'] = [{ + directions: 'x', + param: KGAuthor.paramName(def.max1), + expression: KGAuthor.addDefs(def.max1, 'drag.dx') + }]; + } + if (def.hasOwnProperty('xInterceptLabel')) { + xInterceptPointDef['droplines'] = { + vertical: def.xInterceptLabel + }; + } + ppf.xInterceptPoint = new KGAuthor.Point(xInterceptPointDef, graph); + var yInterceptPointDef = { + coordinates: [0, def.max2], + fill: def.stroke, + r: 4 + }; + if (def.draggable && typeof (def.max2) == 'string') { + yInterceptPointDef['drag'] = [{ + directions: 'y', + param: KGAuthor.paramName(def.max2), + expression: KGAuthor.addDefs(def.max2, 'drag.dy') + }]; + } + if (def.hasOwnProperty('yInterceptLabel')) { + yInterceptPointDef['droplines'] = { + horizontal: def.yInterceptLabel + }; + } + ppf.yInterceptPoint = new KGAuthor.Point(yInterceptPointDef, graph); + if (def.handles) { + subObjects.push(ppf.xInterceptPoint); + subObjects.push(ppf.yInterceptPoint); + } + } + return _this; + } + EconPPF.prototype.parseSelf = function (parsedData) { + var ppf = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[ppf.name] = { + L1: ppf.L1, + L2: ppf.L2, + y1: ppf.y1, + y2: ppf.y2, + optimalL1: ppf.optimalL1, + optimalL2: ppf.optimalL2, + optimaly1: ppf.optimaly1, + optimaly2: ppf.optimaly2, + mrt: ppf.mrt + }; + return parsedData; + }; + return EconPPF; + }(KGAuthor.Curve)); + KGAuthor.EconPPF = EconPPF; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconLinearMC = /** @class */ (function (_super) { + __extends(EconLinearMC, _super); + function EconLinearMC(def, graph) { + return _super.call(this, def, graph) || this; + } + return EconLinearMC; + }(KGAuthor.EconLinearSupply)); + KGAuthor.EconLinearMC = EconLinearMC; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconLinearMonopoly = /** @class */ (function (_super) { + __extends(EconLinearMonopoly, _super); + function EconLinearMonopoly(def, graph) { + var _this = this; + KG.setDefaults(def, { + name: 'monopoly', + showCS: false, + showPS: false, + showProfit: false, + showDWL: false + }); + _this = _super.call(this, def, graph) || this; + var lm = _this; + def.demand.surplus = { show: def.showCS, price: "calcs." + lm.name + ".P", quantity: "calcs." + lm.name + ".Q" }; + def.cost.surplus = { show: def.showPS, price: "calcs." + lm.name + ".P", quantity: "calcs." + lm.name + ".Q" }; + lm.demand = new KGAuthor.EconLinearDemand(def.demand, graph); + lm.cost = new KGAuthor.EconLinearMC(def.cost, graph); + var intersectMRMC = KGAuthor.lineIntersection(lm.demand.marginalRevenue, lm.cost); + lm.Q = intersectMRMC[0]; + lm.P = lm.demand.yOfX(lm.Q); + lm.MRMC = lm.cost.yOfX(lm.Q); + var intersectDMC = KGAuthor.lineIntersection(lm.demand, lm.cost); + lm.competitiveQ = intersectDMC[0]; + lm.competitiveP = lm.demand.yOfX(lm.competitiveQ); + if (def.hasOwnProperty('showDWL')) { + var DWLDef = { + show: def.showDWL, + fill: "colors.dwl" + }; + DWLDef.univariateFunction1 = { + fn: lm.demand.def.univariateFunction.fn, + min: lm.Q, + max: lm.competitiveQ, + samplePoints: 2 + }; + DWLDef.univariateFunction2 = { + fn: lm.cost.def.univariateFunction.fn, + min: lm.Q, + max: lm.competitiveQ, + samplePoints: 2 + }; + lm.subObjects.push(new KGAuthor.Area(DWLDef, graph)); + } + lm.subObjects.push(_this.demand); + lm.subObjects.push(_this.cost); + return _this; + } + EconLinearMonopoly.prototype.parseSelf = function (parsedData) { + var lm = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs[lm.name] = { + Q: lm.Q.toString(), + P: lm.P.toString(), + competitiveQ: lm.competitiveQ.toString(), + competitiveP: lm.competitiveP.toString() + }; + return parsedData; + }; + return EconLinearMonopoly; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconLinearMonopoly = EconLinearMonopoly; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var ExchangeEquilibriumBundle = /** @class */ (function (_super) { + __extends(ExchangeEquilibriumBundle, _super); + function ExchangeEquilibriumBundle(def, graph) { + var _this = this; + var agentA = new KGAuthor.EconBundle(def.agentA, graph), agentB = new KGAuthor.EconBundle(def.agentB, graph); + var p; + if (def.agentA.utilityFunction.type == 'CobbDouglas' && def.agentB.utilityFunction.type == 'CobbDouglas') { + var alphaW2 = function (agent) { + return KGAuthor.multiplyDefs(agent.y, agent.utilityFunction.alpha); + }, oneMinusAlphaW1 = function (agent) { + return KGAuthor.multiplyDefs(agent.x, KGAuthor.subtractDefs(1, agent.utilityFunction.alpha)); + }; + p = KGAuthor.divideDefs(KGAuthor.addDefs(alphaW2(agentA), alphaW2(agentB)), KGAuthor.addDefs(oneMinusAlphaW1(agentA), oneMinusAlphaW1(agentB))); + } + else { + console.log("We're just handling Edgeworth equilibrium with Cobb-Douglas so far..."); + } + KG.setDefaults(def, { + label: { text: 'E' }, + color: "colors.budget" + }); + def.utilityFunctionObject = agentA.utilityFunction; + def.budgetLine = { + p1: p, + p2: 1, + point: [agentA.x, agentA.y] + }; + _this = _super.call(this, def, graph) || this; + return _this; + } + return ExchangeEquilibriumBundle; + }(KGAuthor.EconOptimalBundle)); + KGAuthor.ExchangeEquilibriumBundle = ExchangeEquilibriumBundle; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconContractCurve = /** @class */ (function (_super) { + __extends(EconContractCurve, _super); + function EconContractCurve(def, graph) { + var _this = this; + var a = def.a, b = def.b, ab = KGAuthor.multiplyDefs(a, b), aMinusABtimesX = KGAuthor.multiplyDefs(KGAuthor.subtractDefs(a, ab), def.totalGood1), bMinusABtimesY = KGAuthor.multiplyDefs(KGAuthor.subtractDefs(b, ab), def.totalGood2), bMinusA = KGAuthor.subtractDefs(b, a), fnString = bMinusABtimesY + "*(x)/(" + aMinusABtimesX + " + " + bMinusA + "*(x))"; + def.univariateFunction = { fn: fnString }; + KG.setDefaults(def, { + interpolation: 'curveMonotoneX', + color: 'colors.budget' + }); + _this = _super.call(this, def, graph) || this; + _this.fnString = fnString; + return _this; + } + EconContractCurve.prototype.parseSelf = function (parsedData) { + var cc = this; + parsedData = _super.prototype.parseSelf.call(this, parsedData); + parsedData.calcs['cc'] = cc.fnString; + return parsedData; + }; + return EconContractCurve; + }(KGAuthor.Curve)); + KGAuthor.EconContractCurve = EconContractCurve; +})(KGAuthor || (KGAuthor = {})); +/// +var KGAuthor; +(function (KGAuthor) { + var EconParetoLens = /** @class */ (function (_super) { + __extends(EconParetoLens, _super); + function EconParetoLens(def, graph) { + var _this = _super.call(this, def, graph) || this; + _this.subObjects.push(new KGAuthor.Rectangle({ + clipPathName: def.bundleA + "_IC_above", + clipPathName2: def.bundleB + "_IC_above", + x1: graph.def.xAxis.min, + x2: graph.def.xAxis.max, + y1: graph.def.yAxis.min, + y2: graph.def.yAxis.max, + fill: "colors.paretoLens", + opacity: "0.8", + show: def.show + }, graph)); + return _this; + } + return EconParetoLens; + }(KGAuthor.GraphObjectGenerator)); + KGAuthor.EconParetoLens = EconParetoLens; +})(KGAuthor || (KGAuthor = {})); +/// +/* SCHEMAS */ +/// +/// +/* LAYOUTS */ +/// +/// +/* FUNCTIONAL FORMS */ +/// +/// +/// +/// +/// +/// +/// +/* MICRO */ +/* Consumer Theory */ +/// +/// +/// +/// +/// +/// +/* Producer Theory */ +/// +/* Equilibrium */ +/// +/// +/// +/// +/// +/// +/* Monopoly */ +/// +/// +/* Exchange */ +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +var KG; +(function (KG) { + var Model = /** @class */ (function () { + function Model(parsedData) { + var model = this; + model.params = parsedData.params.map(function (def) { + return new KG.Param(def); + }); + model.initialParams = parsedData.params; + model.calcs = parsedData.calcs; + model.colors = parsedData.colors; + model.idioms = parsedData.idioms; + model.clearColor = parsedData.clearColor; + model.restrictions = (parsedData.restrictions || []).map(function (def) { + return new KG.Restriction(def); + }); + model.updateListeners = []; + model.currentParamValues = model.evalParams(); + model.evalCalcs(); + model.currentColors = model.evalObject(model.colors); + model.currentIdioms = model.evalObject(model.idioms); + } + Model.prototype.addUpdateListener = function (updateListener) { + this.updateListeners.push(updateListener); + return this; + }; + Model.prototype.resetParams = function () { + console.log("resetting model parameters"); + var model = this; + console.log('initial parameters are: ', model.initialParams); + model.initialParams.forEach(function (p) { + console.log('setting ', p.name, ' to ', p.value); + model.updateParam(p.name, p.value); + }); + model.update(true); + }; + Model.prototype.evalParams = function () { + var p = {}; + this.params.forEach(function (param) { + p[param.name] = param.value; + }); + return p; + }; + // evaluates the calcs object; then re-evaluates to capture calcs that depend on other calcs + Model.prototype.evalCalcs = function () { + var model = this; + // clear calculations so old values aren't used; + model.currentCalcValues = {}; + // generate as many calculations from params as possible + model.currentCalcValues = model.evalObject(model.calcs, true); + // calculate values based on other calculations (up to a depth of 5) + for (var i = 0; i < 5; i++) { + for (var calcName in model.currentCalcValues) { + if (typeof model.calcs[calcName] == 'object') { + model.currentCalcValues[calcName] = model.evalObject(model.calcs[calcName], true); + } + else if (isNaN(model.currentCalcValues[calcName]) && typeof model.calcs[calcName] == 'string') { + model.currentCalcValues[calcName] = model.evaluate(model.calcs[calcName], true); + } + } + } + return model.currentCalcValues; + }; + Model.prototype.evalObject = function (obj, onlyJSMath) { + var model = this; + var newObj = {}; + for (var stringOrObj in obj) { + var def = obj[stringOrObj]; + if (typeof def === 'number') { + newObj[stringOrObj] = def; + } + else if (typeof def === 'string') { + newObj[stringOrObj] = model.evaluate(def, onlyJSMath); + } + else { + newObj[stringOrObj] = model.evalObject(def, onlyJSMath); + } + } + return newObj; + }; + // the model serves as a model, and can evaluate expressions within the context of that model + // if onlyJSMath is selected, it will only try to evaluate using JSMath; this is especially important for calculations. + Model.prototype.evaluate = function (name, onlyJSMath) { + var model = this; + // don't just evaluate numbers + if (!isNaN(parseFloat(name))) { + //console.log('interpreted ', name, 'as a number.'); + return parseFloat(name); + } + // collect current values in a scope object + var params = model.currentParamValues, calcs = model.currentCalcValues, colors = model.currentColors, idioms = model.currentIdioms; + //console.log('trying to parse ', name); + // try to evaluate using mathjs + try { + var compiledMath = math.compile(name); + var result = compiledMath.evaluate({ + params: params, + calcs: calcs, + idioms: idioms, + colors: colors + }); + //onsole.log('parsed', name, 'as ', result); + return result; + } + catch (err) { + // if that doesn't work, try to evaluate using native js eval + //console.log('unable to parse', name, 'as a pure math function, trying general eval'); + //console.log('parsing did not work'); + if (onlyJSMath) { + return name; + } + else { + try { + var result = eval(name); + //console.log('parsed', name, 'as an expression with value', result); + return result; + } + catch (err) { + //console.log('unable to parse', name, 'as a valid expression; generates error:', err.message); + return name; + } + } + } + }; + // This is a utility for exporting currently used colors for use in LaTex documents. + Model.prototype.latexColors = function () { + var result = '%% econ colors %%\n', model = this; + for (var color in model.colors) { + result += "\\definecolor{" + color + "}{HTML}{" + model.evaluate(model.colors[color]).replace('#', '') + "}\n"; + } + console.log(result); + }; + Model.prototype.getParam = function (paramName) { + var params = this.params; + for (var i = 0; i < params.length; i++) { + if (params[i].name == paramName) { + return params[i]; + } + } + }; + // method exposed to viewObjects to allow them to try to change a parameter + Model.prototype.updateParam = function (name, newValue) { + var model = this, param = model.getParam(name); + var oldValue = param.value; + param.update(newValue); + // if param has changed, check to make sure the change is val + if (oldValue != param.value) { + //restrictions aren't working right now + var valid_1 = true; + model.restrictions.forEach(function (r) { + if (!r.valid(model)) { + valid_1 = false; + } + }); + if (valid_1) { + model.update(false); + } + else { + param.update(oldValue); + } + model.update(false); + } + }; + // method exposed to viewObjects to allow them to toggle a binary param + Model.prototype.toggleParam = function (name) { + var currentValue = this.getParam(name).value; + this.updateParam(name, !currentValue); + }; + // method exposed to viewObjects to allow them to cycle a discrete param + // increments by 1 if below max value, otherwise sets to zero + Model.prototype.cycleParam = function (name) { + var param = this.getParam(name); + this.updateParam(name, param.value < param.max ? param.value++ : 0); + }; + Model.prototype.update = function (force) { + var model = this; + model.currentParamValues = model.evalParams(); + model.evalCalcs(); + console.log('calcs', model.currentCalcValues); + model.currentColors = model.evalObject(model.colors); + model.updateListeners.forEach(function (listener) { + listener.update(force); + }); + }; + return Model; + }()); + KG.Model = Model; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Param = /** @class */ (function () { + function Param(def) { + function decimalPlaces(numAsString) { + var match = ('' + numAsString).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); + if (!match) { + return 0; + } + return Math.max(0, + // Number of digits right of decimal point. + (match[1] ? match[1].length : 0) + // Adjust for scientific notation. + - (match[2] ? +match[2] : 0)); + } + KG.setDefaults(def, { min: 0, max: 10, round: 1, label: '' }); + this.name = def.name; + this.label = def.label; + if (typeof def.value == 'boolean') { + this.value = +def.value; + this.min = 0; + this.max = 100; + this.round = 1; + } + else { + this.value = parseFloat(def.value); + this.min = parseFloat(def.min); + this.max = parseFloat(def.max); + this.round = parseFloat(def.round); + this.precision = parseInt(def.precision) || decimalPlaces(this.round.toString()); + } + } + // Receives an instruction to update the parameter to a new value + // Updates to the closest rounded value to the desired newValue within accepted range + Param.prototype.update = function (newValue) { + var param = this; + if (newValue < param.min) { + param.value = param.min; + } + else if (newValue > param.max) { + param.value = param.max; + } + else { + param.value = Math.round(newValue / param.round) * param.round; + } + return param.value; + }; + // Displays current value of the parameter to desired precision + // If no precision is given, uses the implied precision given by the rounding parameter + Param.prototype.formatted = function (precision) { + precision = precision || this.precision; + return d3.format("." + precision + "f")(this.value); + }; + return Param; + }()); + KG.Param = Param; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Restriction = /** @class */ (function () { + function Restriction(def) { + this.expression = def.expression; + this.type = def.type; + this.min = def.min; + this.max = def.max; + } + Restriction.prototype.valid = function (model) { + var r = this, value = model.evaluate(r.expression), min = model.evaluate(r.min), max = model.evaluate(r.max); + // restrictions aren't working right now + return true; + //return (value >= min && value <= max); + }; + return Restriction; + }()); + KG.Restriction = Restriction; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + function randomString(length) { + var text = "KGID_"; + var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + for (var i = 0; i < length; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; + } + KG.randomString = randomString; + var UpdateListener = /** @class */ (function () { + function UpdateListener(def) { + def.constants = (def.constants || []).concat(['model', 'updatables', 'name']); + var ul = this; + ul.def = def; + def.constants.forEach(function (c) { + ul[c] = isNaN(parseFloat(def[c])) ? def[c] : +def[c]; + }); + ul.id = randomString(10); + ul.model.addUpdateListener(this); + } + UpdateListener.prototype.updateArray = function (a) { + var u = this; + return a.map(function (d) { + if (Array.isArray(d)) { + return u.updateArray(d); + } + else { + var initialValue = d; + var newValue = u.model.evaluate(d); + if (initialValue != newValue) { + u.hasChanged = true; + } + return newValue; + } + }); + }; + UpdateListener.prototype.updateDef = function (name) { + var u = this; + if (u.def.hasOwnProperty(name)) { + var d = u.def[name], initialValue = u[name]; + if (Array.isArray(d)) { + u[name] = u.updateArray(d); + } + else { + var newValue = u.model.evaluate(d); + if (initialValue != newValue) { + u.hasChanged = true; + u[name] = newValue; + } + } + //console.log(u.constructor['name'],name,'changed from',initialValue,'to',u[name]); + } + return u; + }; + UpdateListener.prototype.update = function (force) { + var u = this; + u.hasChanged = !!force; + if (u.hasOwnProperty('updatables') && u.updatables != undefined) { + u.updatables.forEach(function (name) { + u.updateDef(name); + }); + } + return u; + }; + return UpdateListener; + }()); + KG.UpdateListener = UpdateListener; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var MathFunction = /** @class */ (function (_super) { + __extends(MathFunction, _super); + function MathFunction(def) { + var _this = this; + KG.setDefaults(def, { + samplePoints: 50 + }); + KG.setProperties(def, 'constants', ['samplePoints']); + KG.setProperties(def, 'updatables', ['min', 'max']); + _this = _super.call(this, def) || this; + return _this; + } + MathFunction.prototype.updateFunctionString = function (str, scope) { + function getCalc(o, s) { + s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties + s = s.replace(/^\./, ''); // strip a leading dot + var a = s.split('.'); + for (var i = 0, n = a.length; i < n; ++i) { + var k = a[i]; + if (k in o) { + o = o[k]; + } + else { + return; + } + } + return o; + } + str = str.toString(); + if (str.indexOf('null') > -1 || str.indexOf('Infinity') > -1) { + return null; + } + var re = /((calcs|params).[.\w]*)+/g; + var references = str.match(re); + if (references) { + references.forEach(function (name) { + str = KGAuthor.replaceVariable(str, name, getCalc(scope, name)); + }); + } + //console.log('updated function to ',str); + return str; + }; + return MathFunction; + }(KG.UpdateListener)); + KG.MathFunction = MathFunction; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var MathFunction = KG.MathFunction; + var UnivariateFunction = /** @class */ (function (_super) { + __extends(UnivariateFunction, _super); + function UnivariateFunction(def) { + var _this = this; + KG.setDefaults(def, { + ind: 'x' + }); + KG.setProperties(def, 'constants', ['fn', 'yFn']); + KG.setProperties(def, 'updatables', ['ind', 'min', 'max']); + _this = _super.call(this, def) || this; + _this.fnStringDef = def.fn; + _this.fnZStringDef = def.fnZ; + _this.yFnStringDef = def.yFn; + _this.yFnZStringDef = def.yFnZ; + return _this; + } + UnivariateFunction.prototype.evaluate = function (input, z) { + var fn = this; + if (z) { + if (fn.hasOwnProperty('yzCompiledFunction') && fn.ind == 'y') { + return fn.yzCompiledFunction.evaluate({ y: input }); + } + else if (fn.hasOwnProperty('zCompiledFunction') && fn.ind == 'y') { + return fn.zCompiledFunction.evaluate({ y: input }); + } + else if (fn.hasOwnProperty('zCompiledFunction')) { + return fn.zCompiledFunction.evaluate({ x: input }); + } + } + else { + if (fn.hasOwnProperty('yCompiledFunction') && fn.ind == 'y') { + return fn.yCompiledFunction.evaluate({ y: input }); + } + else if (fn.hasOwnProperty('compiledFunction') && fn.ind == 'y') { + return fn.compiledFunction.evaluate({ y: input }); + } + else if (fn.hasOwnProperty('compiledFunction')) { + return fn.compiledFunction.evaluate({ x: input }); + } + } + }; + UnivariateFunction.prototype.generateData = function (min, max) { + var fn = this, data = []; + if (undefined != fn.min) { + min = fn.min; + } + if (undefined != fn.max) { + max = fn.max; + } + for (var i = 0; i < fn.samplePoints + 1; i++) { + var a = i / fn.samplePoints, input = a * min + (1 - a) * max, output = fn.evaluate(input); + if (!isNaN(output) && output != Infinity && output != -Infinity) { + data.push((fn.ind == 'x') ? { x: input, y: output } : { x: output, y: input }); + } + } + this.data = data; + return data; + }; + UnivariateFunction.prototype.mathboxFn = function (mathbox) { + var fn = this; + if (fn.ind == 'y') { + return function (emit, y) { + var x = fn.evaluate(y), z = fn.evaluate(y, true); + if (x >= mathbox.xAxis.min && x <= mathbox.xAxis.max && z >= mathbox.zAxis.min && z <= mathbox.zAxis.max) { + emit(y, z, x); + } + }; + } + else { + return function (emit, x) { + var y = fn.evaluate(x), z = fn.evaluate(x, true); + if (y >= mathbox.yAxis.min && y <= mathbox.yAxis.max && z >= mathbox.zAxis.min && z <= mathbox.zAxis.max) { + emit(y, z, x); + } + }; + } + }; + UnivariateFunction.prototype.update = function (force) { + var fn = _super.prototype.update.call(this, force); + //console.log('updating; currently ', fn.fnString); + fn.scope = { + params: fn.model.currentParamValues, + calcs: fn.model.currentCalcValues, + colors: fn.model.currentColors + }; + var originalString = fn.fnString; + if (originalString != fn.updateFunctionString(fn.fnStringDef, fn.scope)) { + fn.hasChanged = true; + fn.fnString = fn.updateFunctionString(fn.fnStringDef, fn.scope); + fn.compiledFunction = math.compile(fn.fnString); + } + if (fn.def.hasOwnProperty('yFn')) { + if (fn.yFnString != fn.updateFunctionString(fn.yFnStringDef, fn.scope)) { + fn.hasChanged = true; + fn.yFnString = fn.updateFunctionString(fn.yFnStringDef, fn.scope); + fn.yCompiledFunction = math.compile(fn.yFnString); + } + } + if (fn.def.hasOwnProperty('fnZ')) { + if (fn.fnZString != fn.updateFunctionString(fn.fnZStringDef, fn.scope)) { + fn.hasChanged = true; + fn.fnZString = fn.updateFunctionString(fn.fnZStringDef, fn.scope); + fn.zCompiledFunction = math.compile(fn.fnZString); + } + } + if (fn.def.hasOwnProperty('yFnZ')) { + if (fn.yFnZString != fn.updateFunctionString(fn.yFnZStringDef, fn.scope)) { + fn.hasChanged = true; + fn.yFnZString = fn.updateFunctionString(fn.yFnZStringDef, fn.scope); + fn.yzCompiledFunction = math.compile(fn.yFnZString); + } + } + return fn; + }; + return UnivariateFunction; + }(MathFunction)); + KG.UnivariateFunction = UnivariateFunction; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var ParametricFunction = /** @class */ (function (_super) { + __extends(ParametricFunction, _super); + function ParametricFunction(def) { + var _this = this; + KG.setDefaults(def, { + min: 0, + max: 10 + }); + _this = _super.call(this, def) || this; + _this.xFunctionStringDef = def.xFunction; + _this.yFunctionStringDef = def.yFunction; + return _this; + } + ParametricFunction.prototype.evaluate = function (input) { + var fn = this; + fn.scope = fn.scope || { params: fn.model.currentParamValues }; + fn.scope.t = input; + return { x: fn.xCompiledFunction.evaluate(fn.scope), y: fn.yCompiledFunction.evaluate(fn.scope) }; + }; + ParametricFunction.prototype.generateData = function (min, max) { + var fn = this, data = []; + if (undefined != fn.min) { + min = fn.min; + } + if (undefined != fn.max) { + max = fn.max; + } + for (var i = 0; i < fn.samplePoints + 1; i++) { + var a = i / fn.samplePoints, input = a * min + (1 - a) * max, output = fn.evaluate(input); + if (!isNaN(output.x) && output.x != Infinity && output.x != -Infinity && !isNaN(output.y) && output.y != Infinity && output.y != -Infinity) { + data.push(output); + } + } + this.data = data; + return data; + }; + ParametricFunction.prototype.update = function (force) { + var fn = _super.prototype.update.call(this, force); + //console.log('updating; currently ', fn.fnString); + fn.scope = { + params: fn.model.currentParamValues, + calcs: fn.model.currentCalcValues, + colors: fn.model.currentColors + }; + var originalXFunctionString = fn.xFunctionString; + if (originalXFunctionString != fn.updateFunctionString(fn.xFunctionStringDef, fn.scope)) { + fn.hasChanged = true; + fn.xFunctionString = fn.updateFunctionString(fn.xFunctionStringDef, fn.scope); + fn.xCompiledFunction = math.compile(fn.xFunctionString); + } + var originalYFunctionString = fn.yFunctionString; + if (originalYFunctionString != fn.updateFunctionString(fn.yFunctionStringDef, fn.scope)) { + fn.hasChanged = true; + fn.yFunctionString = fn.updateFunctionString(fn.yFunctionStringDef, fn.scope); + fn.yCompiledFunction = math.compile(fn.yFunctionString); + } + return fn; + }; + return ParametricFunction; + }(KG.MathFunction)); + KG.ParametricFunction = ParametricFunction; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var MathFunction = KG.MathFunction; + var MultivariateFunction = /** @class */ (function (_super) { + __extends(MultivariateFunction, _super); + function MultivariateFunction(def) { + var _this = this; + def.samplePoints = 100; + KG.setProperties(def, 'constants', ['fn']); + _this = _super.call(this, def) || this; + _this.fnStringDef = def.fn; + _this.domainConditionStringDef = def.domainCondition; + return _this; + } + MultivariateFunction.prototype.inDomain = function (x, y, z) { + var fn = this; + if (fn.hasOwnProperty('compiledDomainCondition')) { + return fn.compiledDomainCondition.evaluate({ x: x, y: y, z: z }); + } + else { + return true; + } + }; + MultivariateFunction.prototype.evaluate = function (x, y) { + var fn = this; + if (fn.hasOwnProperty('compiledFunction')) { + var z = fn.compiledFunction.evaluate({ x: x, y: y }); + if (fn.inDomain(x, y, z)) { + return z; + } + } + }; + MultivariateFunction.prototype.mathboxFn = function () { + var fn = this; + return function (emit, x, y) { + emit(y, fn.evaluate(x, y), x); + }; + }; + MultivariateFunction.prototype.contour = function (level, xScale, yScale, bounds) { + var fn = this; + bounds = KG.setDefaults(bounds || {}, { + xMin: xScale.domainMin, + xMax: xScale.domainMax, + yMin: yScale.domainMin, + yMax: yScale.domainMax + }); + var n = 100, m = 100, values = new Array(n * m); + for (var j = 0.5, k = 0; j < m; ++j) { + for (var i = 0.5; i < n; ++i, ++k) { + var x = bounds.xMin + i * (bounds.xMax - bounds.xMin) / n, y = bounds.yMin + j * (bounds.yMax - bounds.yMin) / m; + values[k] = fn.evaluate(x, y); + } + } + var transform = function (_a) { + var type = _a.type, value = _a.value, coordinates = _a.coordinates; + return { + type: type, value: value, coordinates: coordinates.map(function (rings) { + return rings.map(function (points) { + return points.map(function (_a) { + var x = _a[0], y = _a[1]; + return ([xScale.scale(bounds.xMin + x * (bounds.xMax - bounds.xMin) / 100), yScale.scale(bounds.yMin + y * (bounds.yMax - bounds.yMin) / 100)]); + }); + }); + }) + }; + }; + var p = d3.geoPath(); + // Compute the contour polygons at log-spaced intervals; returns an array of MultiPolygon. + var contourLine = d3.contours().size([n, m]).contour(values, level); + return p(transform(contourLine)); + }; + MultivariateFunction.prototype.update = function (force) { + var fn = _super.prototype.update.call(this, force); + //console.log('updating; currently ', fn.fnString); + fn.scope = { + params: fn.model.currentParamValues, + calcs: fn.model.currentCalcValues, + colors: fn.model.currentColors + }; + var originalString = fn.fnString, originalDomainCondition = fn.domainConditionString; + if (originalString != fn.updateFunctionString(fn.fnStringDef, fn.scope)) { + fn.hasChanged = true; + fn.fnString = fn.updateFunctionString(fn.fnStringDef, fn.scope); + fn.compiledFunction = math.compile(fn.fnString); + } + if (fn.domainConditionStringDef != undefined) { + if (originalDomainCondition != fn.updateFunctionString(fn.domainConditionStringDef, fn.scope)) { + fn.hasChanged = true; + fn.domainConditionString = fn.updateFunctionString(fn.domainConditionStringDef, fn.scope); + fn.compiledDomainCondition = math.compile(fn.domainConditionString); + } + } + return fn; + }; + return MultivariateFunction; + }(MathFunction)); + KG.MultivariateFunction = MultivariateFunction; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + /* + + A listener is defined by a param and an expression. + When the interactionHandler senses a change, it generates a scope of the current state of the model. + The listener then determines the current value of its expression within the context of that scope, + and sends a signal to the model to update its param. + + */ + var Listener = /** @class */ (function (_super) { + __extends(Listener, _super); + function Listener(def) { + var _this = this; + KG.setProperties(def, 'updatables', ['expression']); + KG.setProperties(def, 'constants', ['param']); + _this = _super.call(this, def) || this; + return _this; + } + Listener.prototype.onChange = function (scope) { + var l = this, compiledMath = math.compile(l.expression); + var parsedMath = compiledMath.evaluate(scope); + l.model.updateParam(l.param, parsedMath); + }; + return Listener; + }(KG.UpdateListener)); + KG.Listener = Listener; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + /* + + A DragListener is a special kind of Listener that listens for drag events. + In addition to a param and an expression, it has properties for whether it is draggable + and, if so, in which directions it is draggable. + + */ + var DragListener = /** @class */ (function (_super) { + __extends(DragListener, _super); + function DragListener(def) { + var _this = this; + if (def.hasOwnProperty('vertical')) { + def.directions = 'y'; + def.param = def.vertical; + def.expression = "params." + def.vertical + " + drag.dy"; + } + if (def.hasOwnProperty('horizontal')) { + def.directions = 'x'; + def.param = def.horizontal; + def.expression = "params." + def.horizontal + " + drag.dx"; + } + KG.setDefaults(def, { + directions: "xy" + }); + KG.setProperties(def, 'updatables', ['draggable', 'directions']); + _this = _super.call(this, def) || this; + return _this; + } + DragListener.prototype.update = function (force) { + var dl = _super.prototype.update.call(this, force); + if (!dl.def.hasOwnProperty('draggable')) { + dl.draggable = (dl.directions.length > 0); + } + return dl; + }; + return DragListener; + }(KG.Listener)); + KG.DragListener = DragListener; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var ClickListener = /** @class */ (function (_super) { + __extends(ClickListener, _super); + function ClickListener(def) { + var _this = this; + KG.setDefaults(def, { transitions: [1, 0] }); // default to toggle on/off + _this = _super.call(this, def) || this; + _this.transitions = def.transitions; + return _this; + } + ClickListener.prototype.click = function () { + var c = this; + console.log("clicking", c); + var current = c.model.currentParamValues[c.param]; + var newvalue = c.transitions[current]; + c.model.updateParam(c.param, newvalue); + }; + return ClickListener; + }(KG.Listener)); + KG.ClickListener = ClickListener; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var InteractionHandler = /** @class */ (function (_super) { + __extends(InteractionHandler, _super); + function InteractionHandler(def) { + var _this = this; + KG.setDefaults(def, { dragListeners: [], clickListeners: [] }); + KG.setProperties(def, 'constants', ["viewObject", "dragListeners", "clickListeners"]); + _this = _super.call(this, def) || this; + _this.update(true); + _this.scope = { params: {}, calcs: {}, colors: {}, drag: {} }; + return _this; + } + InteractionHandler.prototype.update = function (force) { + var ih = _super.prototype.update.call(this, force); + // first update dragListeners + if (ih.hasChanged && ih.hasOwnProperty('dragListeners') && (ih.element != undefined)) { + var xDrag_1 = false, yDrag_1 = false; + ih.dragListeners.forEach(function (dul) { + dul.update(force); + if (dul.directions == "x") { + xDrag_1 = true; + } + else if (dul.directions == "y") { + yDrag_1 = true; + } + else if (dul.directions == "xy") { + xDrag_1 = true; + yDrag_1 = true; + } + }); + ih.element.style("pointer-events", (xDrag_1 || yDrag_1) ? "all" : "none"); + ih.element.style("cursor", (xDrag_1 && yDrag_1) ? "move" : xDrag_1 ? "ew-resize" : "ns-resize"); + } + if (ih.hasOwnProperty('clickListeners') && (ih.element != undefined)) { + if (ih.clickListeners.length > 0) { + ih.element.style("pointer-events", "all"); + ih.element.style("cursor", "pointer"); + } + } + return ih; + }; + InteractionHandler.prototype.addTrigger = function (element) { + var handler = this; + handler.element = element; + // add click listeners + if (handler.clickListeners.length > 0) { + element.on("click", function () { + handler.clickListeners.forEach(function (c) { c.click(); }); + }); + } + // add drag listeners + if (handler.dragListeners.length > 0) { + element.call(d3.drag() + .on('start', function () { + handler.scope.params = handler.model.currentParamValues; + handler.scope.calcs = handler.model.currentCalcValues; + handler.scope.colors = handler.model.currentColors; + handler.scope.drag.x0 = handler.viewObject.xScale.scale.invert(d3.event.x); + handler.scope.drag.y0 = handler.viewObject.yScale.scale.invert(d3.event.y); + }) + .on('drag', function () { + var drag = handler.scope.drag; + drag.x = handler.viewObject.xScale.scale.invert(d3.event.x); + drag.y = handler.viewObject.yScale.scale.invert(d3.event.y); + drag.dx = drag.x - drag.x0; + drag.dy = drag.y - drag.y0; + handler.dragListeners.forEach(function (d) { + d.onChange(handler.scope); + }); + }) + .on('end', function () { + //handler.element.style("cursor","default"); + })); + } + handler.update(true); + }; + return InteractionHandler; + }(KG.UpdateListener)); + KG.InteractionHandler = InteractionHandler; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + KG.viewData = {}; + function addView(name, def) { + KG.viewData[name] = def; + } + KG.addView = addView; + var View = /** @class */ (function () { + function View(div, data) { + this.render(data, div); + } + View.prototype.parse = function (data, div) { + if (data.hasOwnProperty('templateDefaults')) { + // Any terms not defined in the user's overrides should revert to the template defaults + var defaults = data.templateDefaults; + var dataString = JSON.stringify(data); + for (var key in defaults) { + var searchTerm = new RegExp("template.\\b" + key + "\\b", "g"); + var replaceTerm = defaults[key]; + dataString = dataString.replace(searchTerm, replaceTerm); + } + data = JSON.parse(dataString); + } + data.schema = data.schema || "Schema"; + // allow user to specify param overrides or select idioms in methods + var urlParams = new URLSearchParams(window.location.search); + // override params + data.params = (data.params || []).map(function (paramData) { + // allow author to override initial parameter values by specifying them as div attributes + if (div.hasAttribute(paramData.name)) { + paramData.value = div.getAttribute(paramData.name); + } + // allow user to override parameter values by specifying them in the URL + var urlParamValue = urlParams.get(paramData.name); + /* console.log("Searching for ", paramData.name) + if (urlParamValue) { + console.log(urlParamValue) + } else { + console.log('not found') + }*/ + if (urlParamValue) { + paramData.value = urlParamValue; + } + // convert boolean params from strings to numbers + if (paramData.value == 'true') { + paramData.value = 1; + } + if (paramData.value == 'false') { + paramData.value = 0; + } + // convert numerical params from strings to numbers + paramData.value = isNaN(+paramData.value) ? paramData.value : +paramData.value; + return paramData; + }); + // allow author to set clear color as div attribute + if (div.hasAttribute("clearColor")) { + data.clearColor = div.getAttribute("clearColor"); + } + var parsedData = { + templateDefaults: data.templateDefaults || {}, + aspectRatio: data.aspectRatio || 1, + clearColor: data.clearColor || "#FFFFFF", + params: data.params || [], + calcs: data.calcs || {}, + colors: data.colors || {}, + custom: data.custom || "", + idioms: {}, + restrictions: data.restrictions, + clipPaths: data.clipPaths || [], + markers: data.markers || [], + scales: data.scales || [{ + name: 'x', + axis: 'x', + rangeMin: 0, + rangeMax: 1, + domainMin: 0, + domainMax: 1 + }, + { + name: 'y', + axis: 'y', + rangeMin: 0, + rangeMax: 1, + domainMin: 0, + domainMax: 1 + }], + layers: data.layers || [[], [], [], []], + divs: data.divs || [] + }; + data.objects = data.objects || []; + if (data.hasOwnProperty('layout')) { + if (data.layout.hasOwnProperty('type')) { + data.objects.push(data.layout); + } + else { + var layoutType = Object.keys(data.layout)[0], layoutDef = data.layout[layoutType]; + data.objects.push({ type: layoutType, def: layoutDef }); + } + } + if (data.hasOwnProperty('explanation')) { + data.objects.push({ type: "Explanation", def: data.explanation }); + } + if (data.hasOwnProperty('schema')) { + if (urlParams.get('custom')) { + parsedData.custom = urlParams.get('custom'); + } + data.objects.push({ type: data.schema, def: { custom: parsedData.custom } }); + } + console.log('parsed data: ', parsedData); + return KGAuthor.parse(data.objects, parsedData); + }; + View.prototype.render = function (data, div) { + var view = this; + var parsedData = view.parse(data, div); + console.log('parsedData: ', parsedData); + div.innerHTML = ""; + view.aspectRatio = data.aspectRatio || parsedData.aspectRatio || 1; + view.model = new KG.Model(parsedData); + // create scales + view.scales = parsedData.scales.map(function (def) { + def.model = view.model; + return new KG.Scale(def); + }); + // create the div for the view + view.div = d3.select(div) + .style('position', 'relative'); + // create a spacer div to make sure text flows properly around the graph + view.svgContainerDiv = view.div.append('div') + .style('position', 'absolute') + .style('left', '0px') + .style('top', '0px'); + // create the SVG element for the view + if (!parsedData.nosvg) { + view.svg = view.svgContainerDiv.append('svg') + .style('overflow', 'visible') + .style('pointer-events', 'none'); + } + view.addViewObjects(parsedData); + view.parsedData = parsedData; + }; + // add view information (model, layer, scales) to an object + View.prototype.addViewToDef = function (def, layer) { + var view = this; + function getScale(name) { + var result = null; + view.scales.forEach(function (scale) { + if (scale.name == name) { + result = scale; + } + }); + return result; + } + def.model = view.model; + def.layer = layer; + def.xScale = getScale(def['xScaleName']); + def.yScale = getScale(def['yScaleName']); + if (def.hasOwnProperty('xScale2Name')) { + def.xScale2 = getScale(def['xScale2Name']); + def.yScale2 = getScale(def['yScale2Name']); + } + return def; + }; + // create view objects + View.prototype.addViewObjects = function (data) { + var view = this; + var defURLS = {}; + if (view.svg) { + var defLayer_1 = view.svg.append('defs'); + // create ClipPaths, generate their URLs, and add their paths to the SVG defs element. + if (data.clipPaths.length > 0) { + data.clipPaths.forEach(function (def) { + var clipPathURL = KG.randomString(10); + var clipPathLayer = defLayer_1.append('clipPath').attr('id', clipPathURL); + def.paths.forEach(function (td) { + td.def.inDef = true; + new KG[td.type](view.addViewToDef(td.def, clipPathLayer)); + }); + defURLS[def.name] = clipPathURL; + }); + } + // create Markers, generate their URLs, and add their paths to the SVG defs element. + if (data.markers.length > 0) { + data.markers.forEach(function (def) { + var markerURL = KG.randomString(10); + def.url = markerURL; + defURLS[def.name] = markerURL; + var markerLayer = defLayer_1.append('marker') + .attr('id', markerURL) + .attr("refX", def.refX) + .attr("refY", 6) + .attr("markerWidth", 13) + .attr("markerHeight", 13) + .attr("orient", "auto") + .attr("markerUnits", "userSpaceOnUse"); + view.addViewToDef(def, markerLayer); + new KG.Marker(def); + }); + } + // add layers of objects + data.layers.forEach(function (layerTds) { + if (layerTds.length > 0) { + var layer_1 = view.svg.append('g'); + layerTds.forEach(function (td) { + var def = td.def; + if (def.hasOwnProperty('clipPathName')) { + def.clipPath = defURLS[def['clipPathName']]; + } + if (def.hasOwnProperty('clipPathName2')) { + def.clipPath2 = defURLS[def['clipPathName2']]; + } + if (def.hasOwnProperty('startArrowName')) { + def.startArrow = defURLS[def['startArrowName']]; + } + if (def.hasOwnProperty('endArrowName')) { + def.endArrow = defURLS[def['endArrowName']]; + } + def = view.addViewToDef(def, layer_1); + new KG[td.type](def); + }); + } + }); + } + // add divs + if (data.divs.length > 0) { + data.divs.forEach(function (td) { + var def = view.addViewToDef(td.def, view.div), newDiv = new KG[td.type](def); + if (td.type == 'Sidebar') { + view.sidebar = newDiv; + } + if (td.type == 'Explanation') { + view.explanation = newDiv; + } + }); + } + view.updateDimensions(); + }; + // update dimensions, either when first rendering or when the window is resized + View.prototype.updateDimensions = function (printing) { + var view = this; + printing = !!printing; + //console.log('printing is ', printing); + var width = 0, height = 0, displayHeight = 0; + if (printing) { + width = 600; + height = width / view.aspectRatio; + displayHeight = height + 20; + } + else { + // read the client width of the enclosing div and calculate the height using the aspectRatio + var clientWidth = view.div.node().clientWidth; + width = clientWidth - 10; + height = width / view.aspectRatio; + var sidebarHeight = 0, explanationHeight = 0; + // position the sidebar to the right if the screen is wide enough, or below if it isn't + if (view.sidebar) { + if (width > view.sidebar.triggerWidth) { + height = height * 77 / 126; + var s_height = void 0; + if (view.explanation) { + s_height = height + view.explanation.rootElement.node().clientHeight + 10; + } + else { + s_height = height; + } + view.sidebar.positionRight(width, s_height); + width = width * 77 / 126; // make width of graph the same width as main Tufte column + } + else { + view.sidebar.positionBelow(width, height); + sidebarHeight = view.sidebar.rootElement.node().clientHeight + 30; + } + } + // position the explanation below + if (view.explanation) { + view.explanation.position(width, height + sidebarHeight + 10); + explanationHeight = view.explanation.rootElement.node().clientHeight + 20; + } + displayHeight = height + sidebarHeight + explanationHeight + 10; + } + view.div.style('height', displayHeight + 'px'); + // set the height of the div + view.svgContainerDiv.style('width', width); + view.svgContainerDiv.style('height', height); + if (view.svg) { + // set the dimensions of the svg + view.svg.style('width', width); + view.svg.style('height', height); + view.svg.attr('width', width); + view.svg.attr('height', height); + } + // adjust all of the scales to be proportional to the new dimensions + view.scales.forEach(function (scale) { + scale.updateDimensions(width, height); + }); + // once the scales are updated, update the coordinates of all view objects + view.model.update(true); + }; + return View; + }()); + KG.View = View; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Scale = /** @class */ (function (_super) { + __extends(Scale, _super); + function Scale(def) { + var _this = this; + KG.setDefaults(def, { + log: false + }); + def.constants = ['rangeMin', 'rangeMax', 'axis', 'name']; + def.updatables = ['domainMin', 'domainMax', 'intercept']; + _this = _super.call(this, def) || this; + _this.scale = def.log ? d3.scaleLog() : d3.scaleLinear(); + _this.update(true); + return _this; + } + Scale.prototype.update = function (force) { + var s = _super.prototype.update.call(this, force); + if (s.extent != undefined) { + var rangeMin = s.rangeMin * s.extent, rangeMax = s.rangeMax * s.extent; + s.scale.domain([s.domainMin, s.domainMax]); + s.scale.range([rangeMin, rangeMax]); + } + return s; + }; + Scale.prototype.updateDimensions = function (width, height) { + var s = this; + s.extent = (s.axis == 'x') ? width : height; + return s.update(true); + }; + return Scale; + }(KG.UpdateListener)); + KG.Scale = Scale; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var ViewObject = /** @class */ (function (_super) { + __extends(ViewObject, _super); + function ViewObject(def) { + var _this = this; + KG.setDefaults(def, { + alwaysUpdate: false, + interactive: true, + fill: 'colors.blue', + fillOpacity: 0.2, + stroke: 'colors.blue', + strokeWidth: 1, + stokeOpacity: 1, + show: true, + inDef: false, + lineStyle: 'solid', + checkOnGraph: true + }); + KG.setProperties(def, 'updatables', ['xScaleMin', 'xScaleMax', 'yScaleMin', 'yScaleMax', 'fill', 'stroke', 'strokeWidth', 'opacity', 'strokeOpacity', 'show', 'lineStyle']); + KG.setProperties(def, 'constants', ['xScale', 'yScale', 'clipPath', 'clipPath2', 'interactive', 'alwaysUpdate', 'inDef', 'checkOnGraph']); + KG.setProperties(def, 'colorAttributes', ['stroke', 'fill', 'color']); + if (def.inDef) { + def.show = true; + } + _this = _super.call(this, def) || this; + var vo = _this; + if (vo.hasOwnProperty('xScale') && vo.xScale) { + def.xScaleMin = vo.xScale.def.domainMin; + def.xScaleMax = vo.xScale.def.domainMax; + def.yScaleMin = vo.yScale.def.domainMin; + def.yScaleMax = vo.yScale.def.domainMax; + } + def.colorAttributes.forEach(function (attr) { + var c = def[attr]; + if (vo.model.colors.hasOwnProperty(c)) { + def[attr] = vo.model.colors[c]; + } + }); + // the interaction handler manages drag and hover events + if (def.interactive) { + def.drag = def.drag || []; + var dragListeners = def.drag.map(function (dragDef) { + dragDef.model = vo.model; + return new KG.DragListener(dragDef); + }); + def.click = def.click || []; + var clickListeners = def.click.map(function (clickDef) { + clickDef.model = vo.model; + return new KG.ClickListener(clickDef); + }); + vo.interactionHandler = new KG.InteractionHandler({ + viewObject: vo, + model: vo.model, + dragListeners: dragListeners, + clickListeners: clickListeners + }); + } + // the draw method creates the DOM elements for the view object + // the update method updates their attributes + if (def.hasOwnProperty('layer')) { + vo.draw(def.layer).update(true).init(); + } + return _this; + } + ViewObject.prototype.init = function () { + return this; //defined at subclass level + }; + ViewObject.prototype.addClipPathAndArrows = function () { + var vo = this; + if (vo.hasOwnProperty('clipPath') && vo.clipPath != undefined) { + vo.rootElement.attr('clip-path', "url(#" + vo.clipPath + ")"); + } + if (vo.hasOwnProperty('clipPath2') && vo.clipPath2 != undefined) { + vo.rootElement2.attr('clip-path', "url(#" + vo.clipPath2 + ")"); + } + if (vo.hasOwnProperty('endArrow') && vo.endArrow != undefined) { + vo.markedElement.attr("marker-end", "url(#" + vo.endArrow + ")"); + } + if (vo.hasOwnProperty('startArrow') && vo.endArrow != undefined) { + vo.markedElement.attr("marker-start", "url(#" + vo.startArrow + ")"); + } + return vo; + }; + ViewObject.prototype.addInteraction = function () { + var vo = this; + vo.interactionHandler.addTrigger(vo.rootElement); + return vo; + }; + ViewObject.prototype.draw = function (layer, inDef) { + return this; + }; + ViewObject.prototype.redraw = function () { + return this; + }; + ViewObject.prototype.drawStroke = function (el) { + var vo = this; + el.attr('stroke', vo.stroke); + el.attr('stroke-width', vo.strokeWidth); + el.style('stroke-opacity', vo.strokeOpacity); + if (vo.lineStyle == 'dashed') { + el.style('stroke-dashArray', '10,10'); + } + else if (vo.lineStyle == 'dotted') { + el.style('stroke-dashArray', '1,2'); + } + else { + el.style('stroke-dashArray', '10,0'); + } + }; + ViewObject.prototype.drawFill = function (el) { + var vo = this; + el.style('fill', vo.fill); + el.style('fill-opacity', vo.opacity); + }; + ViewObject.prototype.displayElement = function (show) { + var vo = this; + if (vo.hasOwnProperty('rootElement')) { + vo.rootElement.style('display', show ? null : 'none'); + } + }; + ViewObject.prototype.onGraph = function () { + var vo = this; + if (vo.checkOnGraph) { + var notBetween = function (x, a, b) { + var min = Math.min(a, b); + var max = Math.max(a, b); + return ((x < min) || (x > max)); + }; + if (vo.hasOwnProperty('x')) { + if (notBetween(vo.x, vo.xScale.domainMin, vo.xScale.domainMax)) { + return false; + } + } + if (vo.hasOwnProperty('y')) { + if (notBetween(vo.y, vo.yScale.domainMin, vo.yScale.domainMax)) { + return false; + } + } + } + return true; + }; + ViewObject.prototype.update = function (force) { + var vo = _super.prototype.update.call(this, force); + if ((vo.show && vo.onGraph()) || vo.inDef) { + vo.displayElement(true); + if (vo.hasChanged) { + vo.redraw(); + } + } + else { + vo.displayElement(false); + } + return vo; + }; + return ViewObject; + }(KG.UpdateListener)); + KG.ViewObject = ViewObject; +})(KG || (KG = {})); +var KG; +(function (KG) { + var Marker = /** @class */ (function (_super) { + __extends(Marker, _super); + function Marker(def) { + var _this = this; + KG.setProperties(def, 'constants', ['maskPath', 'arrowPath']); + KG.setProperties(def, 'updatables', ['color']); + _this = _super.call(this, def) || this; + return _this; + } + Marker.prototype.draw = function (layer) { + var m = this; + layer.append("svg:path") + .attr("d", m.maskPath) + .attr("fill", "white"); + m.arrowElement = layer.append("svg:path") + .attr("d", m.arrowPath); + return m; + }; + Marker.prototype.redraw = function () { + var m = this; + m.arrowElement.attr("fill", m.color); + return m; + }; + return Marker; + }(KG.ViewObject)); + KG.Marker = Marker; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Segment = /** @class */ (function (_super) { + __extends(Segment, _super); + function Segment(def) { + var _this = this; + KG.setDefaults(def, { + xScale2: def.xScale, + yScale2: def.yScale, + strokeWidth: 2 + }); + KG.setProperties(def, 'constants', ['xScale2', 'yScale2', 'startArrow', 'endArrow']); + KG.setProperties(def, 'updatables', ['x1', 'y1', 'x2', 'y2']); + _this = _super.call(this, def) || this; + return _this; + } + // create SVG elements + Segment.prototype.draw = function (layer) { + var segment = this; + segment.rootElement = layer.append('g'); + segment.dragLine = segment.rootElement.append('line').attr('stroke-width', '20px').style('stroke-opacity', 0); + segment.line = segment.rootElement.append('line'); + segment.markedElement = segment.line; + return segment.addClipPathAndArrows().addInteraction(); + }; + // update properties + Segment.prototype.redraw = function () { + var segment = this; + var x1 = segment.xScale.scale(segment.x1), x2 = segment.xScale.scale(segment.x2), y1 = segment.yScale2.scale(segment.y1), y2 = segment.yScale2.scale(segment.y2); + segment.dragLine + .attr("x1", x1) + .attr("y1", y1) + .attr("x2", x2) + .attr("y2", y2); + segment.line + .attr("x1", x1) + .attr("y1", y1) + .attr("x2", x2) + .attr("y2", y2); + segment.drawStroke(segment.line); + return segment; + }; + return Segment; + }(KG.ViewObject)); + KG.Segment = Segment; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Curve = /** @class */ (function (_super) { + __extends(Curve, _super); + function Curve(def) { + var _this = this; + var univariateFunction, parametricFunction; + KG.setDefaults(def, { + interpolation: 'curveBasis', + strokeWidth: 2 + }); + KG.setProperties(def, 'constants', ['interpolation']); + if (def.hasOwnProperty('univariateFunction')) { + def.univariateFunction.model = def.model; + univariateFunction = new KG.UnivariateFunction(def.univariateFunction); + KG.setProperties(def, 'updatables', []); + } + else if (def.hasOwnProperty('parametricFunction')) { + def.parametricFunction.model = def.model; + parametricFunction = new KG.ParametricFunction(def.parametricFunction); + KG.setProperties(def, 'updatables', []); + } + _this = _super.call(this, def) || this; + var curve = _this; + if (def.hasOwnProperty('univariateFunction')) { + curve.univariateFunction = univariateFunction; + } + else if (def.hasOwnProperty('parametricFunction')) { + def.parametricFunction.model = def.model; + curve.parametricFunction = parametricFunction; + } + return _this; + } + // create SVG elements + Curve.prototype.draw = function (layer) { + var curve = this; + curve.dataLine = d3.line() + .curve(d3[curve.interpolation]) + .x(function (d) { + return curve.xScale.scale(d.x); + }) + .y(function (d) { + return curve.yScale.scale(d.y); + }); + curve.rootElement = layer.append('g'); + curve.dragPath = curve.rootElement.append('path').attr('stroke-width', '20px').style('stroke-opacity', 0).style('fill', 'none'); + curve.path = curve.rootElement.append('path').style('fill', 'none'); + return curve.addClipPathAndArrows().addInteraction(); + }; + // update properties + Curve.prototype.redraw = function () { + var curve = this; + if (curve.hasOwnProperty('univariateFunction')) { + var fn = curve.univariateFunction, scale = fn.ind == 'y' ? curve.yScale : curve.xScale; + fn.generateData(scale.domainMin, scale.domainMax); + curve.dragPath.data([fn.data]).attr('d', curve.dataLine); + curve.path.data([fn.data]).attr('d', curve.dataLine); + } + if (curve.hasOwnProperty('parametricFunction')) { + var fn = curve.parametricFunction; + fn.generateData(); + curve.dragPath.data([fn.data]).attr('d', curve.dataLine); + curve.path.data([fn.data]).attr('d', curve.dataLine); + } + curve.drawStroke(curve.path); + return curve; + }; + // update self and functions + Curve.prototype.update = function (force) { + var curve = _super.prototype.update.call(this, force); + if (!curve.hasChanged) { + if (curve.hasOwnProperty('univariateFunction')) { + if (curve.univariateFunction.hasChanged) { + curve.redraw(); + } + } + if (curve.hasOwnProperty('parametricFunction')) { + if (curve.parametricFunction.hasChanged) { + curve.redraw(); + } + } + } + return curve; + }; + return Curve; + }(KG.ViewObject)); + KG.Curve = Curve; +})(KG || (KG = {})); +var KG; +(function (KG) { + var Axis = /** @class */ (function (_super) { + __extends(Axis, _super); + function Axis(def) { + var _this = this; + KG.setDefaults(def, { + ticks: 5, + intercept: 0 + }); + KG.setProperties(def, 'constants', ['orient']); + KG.setProperties(def, 'updatables', ['ticks', 'intercept', 'label', 'min', 'max', 'otherMin', 'otherMax', 'tickPrepend', 'tickPrecision']); + _this = _super.call(this, def) || this; + return _this; + } + Axis.prototype.draw = function (layer) { + var a = this; + a.rootElement = layer.append('g').attr('class', 'axis'); + return a; + }; + Axis.prototype.redraw = function () { + var a = this; + function formatTick(d) { + if (a.tickPrecision) { + d = d.toFixed(a.tickPrecision); + } + if (a.tickPrepend) { + return "" + a.tickPrepend + d; + } + else { + return d; + } + } + switch (a.orient) { + case 'bottom': + a.rootElement.attr('transform', "translate(0, " + a.yScale.scale(a.intercept) + ")"); + a.rootElement.call(d3.axisBottom(a.xScale.scale).ticks(a.ticks).tickFormat(formatTick)); + return a; + case 'left': + a.rootElement.attr('transform', "translate(" + a.xScale.scale(a.intercept) + ",0)"); + a.rootElement.call(d3.axisLeft(a.yScale.scale).ticks(a.ticks).tickFormat(formatTick)); + return a; + case 'top': + a.rootElement.attr('transform', "translate(0, " + a.yScale.scale(a.intercept) + ")"); + a.rootElement.call(d3.axisTop(a.xScale.scale).ticks(a.ticks).tickFormat(formatTick)); + return a; + case 'right': + a.rootElement.attr('transform', "translate(" + a.xScale.scale(a.intercept) + ",0)"); + a.rootElement.call(d3.axisRight(a.yScale.scale).ticks(a.ticks).tickFormat(formatTick)); + return a; + } + return a; + }; + return Axis; + }(KG.ViewObject)); + KG.Axis = Axis; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Point = /** @class */ (function (_super) { + __extends(Point, _super); + function Point(def) { + var _this = this; + KG.setDefaults(def, { + fill: 'colors.blue', + opacity: 1, + stroke: 'white', + strokeWidth: 1, + strokeOpacity: 1, + r: 6 + }); + KG.setProperties(def, 'updatables', ['x', 'y', 'r']); + _this = _super.call(this, def) || this; + return _this; + } + // create SVG elements + Point.prototype.draw = function (layer) { + var p = this; + p.rootElement = layer.append('g'); // SVG group + p.dragCircle = p.rootElement.append('circle').style('fill-opacity', 0).attr('r', 20); + p.circle = p.rootElement.append('circle'); + //p.addClipPathAndArrows() + return p.addInteraction(); + }; + // update properties + Point.prototype.redraw = function () { + var p = this; + p.rootElement.attr('transform', "translate(" + p.xScale.scale(p.x) + " " + p.yScale.scale(p.y) + ")"); + p.circle.attr('r', p.r); + p.circle.style('fill', p.fill); + p.circle.style('fill-opacity', p.opacity); + p.circle.style('stroke', p.stroke); + p.circle.style('stroke-width', p.strokeWidth + "px"); + p.circle.style('stroke-opacity', p.strokeOpacity); + return p; + }; + return Point; + }(KG.ViewObject)); + KG.Point = Point; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Ellipse = /** @class */ (function (_super) { + __extends(Ellipse, _super); + function Ellipse(def) { + var _this = this; + KG.setDefaults(def, { + fill: 'colors.blue', + opacity: 1, + stroke: 'colors.blue', + strokeWidth: 1, + strokeOpacity: 1, + rx: 1, + ry: 1, + checkOnGraph: false + }); + KG.setProperties(def, 'updatables', ['x', 'y', 'rx', 'ry']); + _this = _super.call(this, def) || this; + return _this; + } + // create SVG elements + Ellipse.prototype.draw = function (layer) { + var c = this; + c.rootElement = layer.append('ellipse'); + return c.addClipPathAndArrows().addInteraction(); + }; + // update properties + Ellipse.prototype.redraw = function () { + var c = this; + c.rootElement.attr('cx', c.xScale.scale(c.x)); + c.rootElement.attr('cy', c.yScale.scale(c.y)); + c.rootElement.attr('rx', Math.abs(c.xScale.scale(c.rx) - c.xScale.scale(0))); + c.rootElement.attr('ry', Math.abs(c.yScale.scale(c.ry) - c.yScale.scale(0))); + c.drawFill(c.rootElement); + c.drawStroke(c.rootElement); + return c; + }; + return Ellipse; + }(KG.ViewObject)); + KG.Ellipse = Ellipse; + var Circle = /** @class */ (function (_super) { + __extends(Circle, _super); + function Circle(def) { + return _super.call(this, def) || this; + } + return Circle; + }(Ellipse)); + KG.Circle = Circle; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Rectangle = /** @class */ (function (_super) { + __extends(Rectangle, _super); + function Rectangle(def) { + var _this = this; + KG.setDefaults(def, { + opacity: 0.2, + stroke: "none" + }); + KG.setProperties(def, 'updatables', ['x1', 'x2', 'y1', 'y2']); + _this = _super.call(this, def) || this; + return _this; + } + // create SVG elements + Rectangle.prototype.draw = function (layer) { + var rect = this; + if (rect.inDef) { + rect.rootElement = layer; + } + else { + rect.rootElement = layer.append('g'); + } + rect.rootElement2 = rect.rootElement.append('rect'); + //rect.interactionHandler.addTrigger(rect.rootElement); + return rect.addClipPathAndArrows().addInteraction(); + }; + // update properties + Rectangle.prototype.redraw = function () { + var rect = this; + var x1 = rect.xScale.scale(rect.x1); + var y1 = rect.yScale.scale(rect.y1); + var x2 = rect.xScale.scale(rect.x2); + var y2 = rect.yScale.scale(rect.y2); + rect.rootElement2 + .attr('x', Math.min(x1, x2)) + .attr('y', Math.min(y1, y2)) + .attr('width', Math.abs(x2 - x1)) + .attr('height', Math.abs(y2 - y1)) + .style('fill', rect.fill) + .style('fill-opacity', rect.opacity) + .style('stroke', rect.stroke) + .style('stroke-width', rect.strokeWidth + "px") + .style('stroke-opacity', rect.strokeOpacity); + return rect; + }; + return Rectangle; + }(KG.ViewObject)); + KG.Rectangle = Rectangle; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Area = /** @class */ (function (_super) { + __extends(Area, _super); + function Area(def) { + var _this = this; + var minValue = def.univariateFunction1.ind == 'x' ? def.yScale.domainMin : def.xScale.domainMin; + var maxValue = def.univariateFunction1.ind == 'x' ? def.yScale.domainMax : def.xScale.domainMax; + KG.setDefaults(def, { + interpolation: 'curveBasis', + ind: 'x', + fill: 'lightsteelblue', + opacity: 0.2, + univariateFunction2: { + "fn": ((def.above && !def.useTopScale) || (!def.above && def.useTopScale)) ? maxValue : minValue, + "ind": def.univariateFunction1['ind'], + "min": def.univariateFunction1['min'], + "max": def.univariateFunction1['max'], + "samplePoints": def.univariateFunction1['samplePoints'] + } + }); + KG.setProperties(def, 'constants', ['interpolation']); + def.univariateFunction1.model = def.model; + def.univariateFunction2.model = def.model; + // need to initialize the functions before the area, so they exist when it's time to draw the area + var univariateFunction1 = new KG.UnivariateFunction(def.univariateFunction1), univariateFunction2 = new KG.UnivariateFunction(def.univariateFunction2); + _this = _super.call(this, def) || this; + _this.univariateFunction1 = univariateFunction1; + _this.univariateFunction2 = univariateFunction2; + return _this; + } + // create SVG elements + Area.prototype.draw = function (layer) { + var ab = this; + ab.rootElement = layer.append('path'); + ab.areaShape = d3.area() + .x0(function (d) { + return ab.xScale.scale(d[0].x); + }) + .y0(function (d) { + return ab.yScale.scale(d[0].y); + }) + .x1(function (d) { + return ab.xScale.scale(d[1].x); + }) + .y1(function (d) { + return ab.yScale.scale(d[1].y); + }); + ab.areaPath = ab.rootElement; + return ab.addClipPathAndArrows(); + }; + // update properties + Area.prototype.redraw = function () { + var area = this; + if (area.univariateFunction1 != undefined && area.univariateFunction2 != undefined) { + var fn1 = area.univariateFunction1, fn2 = area.univariateFunction2, scale = fn1.ind == 'y' ? area.yScale : area.xScale; + fn1.generateData(scale.domainMin, scale.domainMax); + fn2.generateData(scale.domainMin, scale.domainMax); + area.areaPath + .data([d3.zip(fn1.data, fn2.data)]) + .attr('d', area.areaShape); + area.drawFill(area.areaPath); + } + else { + //console.log('area functions undefined') + } + return area; + }; + // update self and functions + Area.prototype.update = function (force) { + var area = _super.prototype.update.call(this, force); + if (!area.hasChanged) { + if (area.univariateFunction1.hasChanged || area.univariateFunction2.hasChanged) { + area.redraw(); + } + } + return area; + }; + return Area; + }(KG.ViewObject)); + KG.Area = Area; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var GeoGebraObject = /** @class */ (function (_super) { + __extends(GeoGebraObject, _super); + function GeoGebraObject(def) { + var _this = this; + KG.setDefaults(def, { + color: '#999999', + lineThickness: 1, + lineStyle: 0 + }); + KG.setProperties(def, 'constants', ['command', 'color', 'lineThickness', 'lineStyle']); + _this = _super.call(this, def) || this; + return _this; + } + GeoGebraObject.prototype.establishGGB = function (applet) { + // from https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb + function hexToRgb(hex) { + var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + return result ? { + r: parseInt(result[1], 16), + g: parseInt(result[2], 16), + b: parseInt(result[3], 16) + } : null; + } + var obj = this; + //console.log('sending commands to applet', applet); + // set command + var command = obj.name + " = " + obj.command; + //console.log('sending command ', obj.name + " = " + obj.command); + applet.evalCommand(command); + if (obj.hasOwnProperty('opacity')) { + applet.setFilling(obj.opacity); + } + var color = hexToRgb(obj.color); + //console.log('sending command setColor(', obj.name, ', ', color.r, ',', color.g, ', ', color.b, ')'); + applet.setColor(obj.name, color.r, color.g, color.b); + //console.log('sending command setLineThickness(', obj.name, ', ', obj.lineThickness, ')') + applet.evalCommand('SetLineThickness[' + obj.name + ', ' + obj.lineThickness + ']'); + //console.log('sending command setLineStyle(', obj.name, ', ', obj.lineStyle, ')') + applet.setLineStyle(obj.name, obj.lineStyle); + }; + return GeoGebraObject; + }(KG.ViewObject)); + KG.GeoGebraObject = GeoGebraObject; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Contour = /** @class */ (function (_super) { + __extends(Contour, _super); + function Contour(def) { + var _this = this; + KG.setDefaults(def, { + opacity: 0.2, + stroke: "grey", + fillAbove: "none", + fillBelow: "none", + strokeOpacity: 1 + }); + KG.setProperties(def, 'colorAttributes', ['fillAbove', 'fillBelow']); + KG.setProperties(def, 'updatables', ['level', 'fillBelow', 'fillAbove', 'xMin', 'xMax', 'yMin', 'yMax']); + _this = _super.call(this, def) || this; + // used for shading area above + _this.fn = new KG.MultivariateFunction({ + fn: def.fn, + model: def.model + }).update(true); + // used for shading area below + _this.negativeFn = new KG.MultivariateFunction({ + fn: "-1*(" + def.fn + ")", + model: def.model + }).update(true); + return _this; + } + Contour.prototype.draw = function (layer) { + var c = this; + if (c.inDef) { + c.rootElement = layer.append('path'); + c.path = c.rootElement; + } + else { + c.rootElement = layer.append('g'); + c.negativePath = c.rootElement.append('path'); + c.path = c.rootElement.append('path'); + } + return c.addClipPathAndArrows(); + }; + Contour.prototype.redraw = function () { + var c = this; + if (undefined != c.fn) { + var bounds_1 = {}; + ['xMin', 'xMax', 'yMin', 'yMax'].forEach(function (p) { + if (c.hasOwnProperty(p) && c[p] != undefined) { + bounds_1[p] = c[p]; + } + }); + c.path.attr("d", c.fn.contour(c.level, c.xScale, c.yScale, { + xMin: c.xMin, + xMax: c.xMax, + yMin: c.yMin, + yMax: c.yMax + })); + if (!c.inDef) { + c.path.style('fill', c.fillAbove); + c.path.style('fill-opacity', c.opacity); + c.path.style('stroke', c.stroke); + c.path.style('stroke-width', c.strokeWidth); + c.path.style('stroke-opacity', c.strokeOpacity); + c.negativePath.attr("d", c.negativeFn.contour(-1 * c.level, c.xScale, c.yScale)); + c.negativePath.style('fill', c.fillBelow); + c.negativePath.style('fill-opacity', c.opacity); + } + } + return c; + }; + // update self and functions + Contour.prototype.update = function (force) { + var c = _super.prototype.update.call(this, force); + if (!c.hasChanged) { + if (c.fn.hasChanged) { + c.redraw(); + } + } + return c; + }; + return Contour; + }(KG.ViewObject)); + KG.Contour = Contour; + var ContourMap = /** @class */ (function (_super) { + __extends(ContourMap, _super); + function ContourMap(def) { + return _super.call(this, def) || this; + } + return ContourMap; + }(KG.ViewObject)); + KG.ContourMap = ContourMap; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Label = /** @class */ (function (_super) { + __extends(Label, _super); + function Label(def) { + var _this = this; + var xAxisReversed = (def.xScale.rangeMin > def.xScale.rangeMax), yAxisReversed = (def.yScale.rangeMin < def.yScale.rangeMax); + var xOffset = xAxisReversed ? 1 : -1, yOffset = yAxisReversed ? 12 : -12; + if (def.x == 'AXIS') { + def.x = def.yScale.intercept; + def.align = xAxisReversed ? 'left' : 'right'; + def.xPixelOffset = xOffset; + } + if (def.x == 'OPPAXIS') { + def.x = def.xScale.domainMax; + def.align = xAxisReversed ? 'right' : 'left'; + def.xPixelOffset = -xOffset; + } + if (def.y == 'AXIS') { + def.y = def.yScale.intercept; + def.yPixelOffset = yOffset; + } + if (def.y == 'OPPAXIS') { + def.y = def.yScale.domainMax; + def.yPixelOffset = -yOffset; + } + //establish property defaults + KG.setDefaults(def, { + xPixelOffset: 0, + yPixelOffset: 0, + fontSize: 12, + align: 'center', + valign: 'middle', + rotate: 0, + color: 'black' + }); + // define constant and updatable properties + KG.setProperties(def, 'constants', ['xPixelOffset', 'yPixelOffset', 'fontSize', 'plainText']); + KG.setProperties(def, 'updatables', ['x', 'y', 'text', 'align', 'valign', 'rotate', 'color', 'bgcolor']); + _this = _super.call(this, def) || this; + _this.bgcolor = def.model.clearColor; + return _this; + } + // create div for text + Label.prototype.draw = function (layer) { + var label = this; + label.rootElement = layer.append('div') + .attr('class', 'draggable') + .style('position', 'absolute') + .style('font-size', label.fontSize + 'pt') + .style('text-align', 'center') + .style('padding-left', '3px') + .style('padding-right', '3px'); + return label.addInteraction(); + }; + // update properties + Label.prototype.redraw = function () { + var label = this; + label.rootElement.style('color', label.color).style('background-color', label.bgcolor); + var x = label.xScale.scale(label.x) + (+label.xPixelOffset), y = label.yScale.scale(label.y) - (+label.yPixelOffset); + if (undefined != label.text) { + if (label.plainText) { + //console.log('rendering label as plain text: ', label.text) + label.text = "\\text{" + label.text + "}"; + } + else { + //console.log('rendering label as LaTeX: ', label.text) + } + try { + katex.render(label.text.toString(), label.rootElement.node()); + } + catch (e) { + console.log("Error rendering KaTeX: ", label.text); + } + } + label.rootElement.style('left', x + 'px'); + label.rootElement.style('top', y + 'px'); + var width = label.rootElement.node().clientWidth, height = label.rootElement.node().clientHeight; + // Set left pixel margin; default to centered on x coordinate + var alignDelta = width * 0.5; + if (label.align == 'left') { + alignDelta = 0; + } + else if (label.align == 'right') { + // move left by half the width of the div if right aligned + alignDelta = width; + } + label.rootElement.style('left', (x - alignDelta) + 'px'); + // Set top pixel margin; default to centered on y coordinate + var vAlignDelta = height * 0.5; + // Default to centered on x coordinate + if (label.valign == 'top') { + vAlignDelta = 0; + } + else if (label.valign == 'bottom') { + vAlignDelta = height; + } + label.rootElement.style('top', (y - vAlignDelta) + 'px'); + var rotate = "rotate(-" + label.rotate + "deg)"; + label.rootElement.style('-webkit-transform', rotate) + .style('transform', rotate); + return label; + }; + return Label; + }(KG.ViewObject)); + KG.Label = Label; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var DivObject = /** @class */ (function (_super) { + __extends(DivObject, _super); + function DivObject() { + return _super !== null && _super.apply(this, arguments) || this; + } + DivObject.prototype.redraw = function () { + var div = this; + var width = Math.abs(div.xScale.scale(1) - div.xScale.scale(0)), height = Math.abs(div.yScale.scale(1) - div.yScale.scale(0)); + div.rootElement.style('left', div.xScale.scale(0) + 'px'); + div.rootElement.style('top', div.yScale.scale(1) + 'px'); + div.rootElement.style('width', width + 'px'); + div.rootElement.style('height', height + 'px'); + return div; + }; + return DivObject; + }(KG.ViewObject)); + KG.DivObject = DivObject; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var PositionedDiv = /** @class */ (function (_super) { + __extends(PositionedDiv, _super); + function PositionedDiv() { + return _super !== null && _super.apply(this, arguments) || this; + } + PositionedDiv.prototype.draw = function (layer) { + var div = this; + div.rootElement = layer.append('div'); + div.rootElement.style('position', 'absolute'); + if (div.def.hasOwnProperty('children')) { + div.def['children'].forEach(function (child) { + child.def.layer = div.rootElement; + child.def.model = div.model; + new KG[child.type](child.def); + }); + } + return div; + }; + PositionedDiv.prototype.redraw = function () { + var div = this; + var width = Math.abs(div.xScale.scale(1) - div.xScale.scale(0)), height = Math.abs(div.yScale.scale(1) - div.yScale.scale(0)); + div.rootElement.style('left', div.xScale.scale(0) + 'px'); + div.rootElement.style('top', div.yScale.scale(1) + 'px'); + div.rootElement.style('width', width + 'px'); + div.rootElement.style('height', height + 'px'); + return div; + }; + return PositionedDiv; + }(KG.DivObject)); + KG.PositionedDiv = PositionedDiv; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Div = /** @class */ (function (_super) { + __extends(Div, _super); + function Div(def) { + var _this = this; + //establish property defaults + KG.setDefaults(def, { + xPixelOffset: 0, + yPixelOffset: 0, + fontSize: 12 + }); + // define constant and updatable properties + KG.setProperties(def, 'constants', ['fontSize']); + KG.setProperties(def, 'updatables', ['html']); + _this = _super.call(this, def) || this; + return _this; + } + // create div for text + Div.prototype.draw = function (layer) { + var div = this; + div.rootElement = layer.append('div') + .style('font-size', div.fontSize + 'pt') + .style('padding-top', '2px') + .style('padding-bottom', '2px'); + return div; + }; + // update properties + Div.prototype.redraw = function () { + var div = this; + if (div.show) { + div.rootElement.html(div.html); + renderMathInElement(div.rootElement.node(), { + delimiters: [ + { left: "$$", right: "$$", display: true }, + { left: "\\[", right: "\\]", display: true }, + { left: "$", right: "$", display: false }, + { left: "\\(", right: "\\)", display: false } + ] + }); + } + else { + div.rootElement.html(null); + } + return div; + }; + return Div; + }(KG.DivObject)); + KG.Div = Div; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var ParamControl = /** @class */ (function (_super) { + __extends(ParamControl, _super); + function ParamControl(def) { + var _this = this; + // establish property defaults + KG.setDefaults(def, { + value: 'params.' + def.param, + alwaysUpdate: true, + plainText: false + }); + // define constant and updatable properties + KG.setProperties(def, 'constants', ['param', 'plainText']); + KG.setProperties(def, 'updatables', ['label', 'value']); + _this = _super.call(this, def) || this; + return _this; + } + return ParamControl; + }(KG.DivObject)); + KG.ParamControl = ParamControl; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Slider = /** @class */ (function (_super) { + __extends(Slider, _super); + function Slider(def) { + var _this = this; + // establish property defaults + KG.setDefaults(def, { + noAxis: false, + showNumber: true + }); + // define constant and updatable properties + KG.setProperties(def, 'constants', ['noAxis', 'label', 'digits']); + KG.setProperties(def, 'updatables', ['showNumber']); + _this = _super.call(this, def) || this; + // calculate maximum number of digits + var slider = _this; + var paramObject = slider.model.getParam(slider.param); + // number of digits for decimals + var decimalPlaces = paramObject.precision; + function maxMinDigits(x) { + if (x > 0) { + return Math.trunc(Math.log10(x) + 1); + } + else { + return Math.trunc(Math.log10(-1 * x) + 2); + } + } + // number of digits for minimum + slider.digits = Math.max(maxMinDigits(paramObject.min), maxMinDigits(paramObject.max)) + decimalPlaces; + return _this; + } + Slider.prototype.draw = function (layer) { + var slider = this; + slider.rootElement = layer.append('tr'); + var param = slider.model.getParam(slider.param); + slider.labelElement = slider.rootElement.append('td') + .style('font-size', '14pt') + .style('text-align', 'right') + .style('padding', '0px') + .style('margin', '0px') + .style('border', 'none'); + function inputUpdate() { + slider.model.updateParam(slider.param, +this.value); + } + slider.numberCell = slider.rootElement.append('td') + .style('padding', '0px') + .style('margin', '0px') + .style('border', 'none'); + slider.numberInput = slider.numberCell.append('input') + .attr('type', 'number') + .attr('min', param.min) + .attr('max', param.max) + .attr('step', param.round) + .style('font-size', '14pt') + .style('border', 'none') + .style('background', 'none') + .style('font-family', 'KaTeX_Main') + .style('margin', '0px') + .style('padding-top', '0px') + .style('padding-bottom', '0px'); + slider.numberInput.on("blur", inputUpdate); + slider.numberInput.on("click", inputUpdate); + slider.numberInput.on("keyup", function () { + if (event['keyCode'] == 13) { + slider.model.updateParam(slider.param, +this.value); + } + }); + var rangeCell = slider.rootElement.append('td') + .style('padding', '0px') + .style('margin', '0px') + .style('border', 'none'); + slider.rangeInput = rangeCell.append('input') + .attr('type', 'range') + .attr('min', param.min) + .attr('max', param.max) + .attr('step', param.round) + .style('padding', '0px') + .style('width', '100%') + .style('margin', '0px'); + slider.rangeInput.on("input", inputUpdate); + return slider; + }; + // update properties + Slider.prototype.redraw = function () { + var slider = this; + if (slider.showNumber) { + katex.render(slider.label + " = ", slider.labelElement.node()); + slider.numberInput.property('value', slider.value.toFixed(slider.model.getParam(slider.param).precision)); + slider.numberInput.style('width', 20 + slider.digits * 10 + "px"); + slider.numberInput.style('display', 'inline-block'); + } + else { + katex.render(slider.label, slider.labelElement.node()); + slider.numberCell.style('width', '10px'); + slider.numberInput.style('display', 'none'); + } + slider.rangeInput.property('value', slider.value); + return slider; + }; + return Slider; + }(KG.ParamControl)); + KG.Slider = Slider; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Checkbox = /** @class */ (function (_super) { + __extends(Checkbox, _super); + function Checkbox() { + return _super !== null && _super.apply(this, arguments) || this; + } + Checkbox.prototype.draw = function (layer) { + var checkbox = this; + checkbox.rootElement = layer.append('div').append('label'); + checkbox.inputElement = checkbox.rootElement.append('input'); + checkbox.inputElement + .attr('type', 'checkbox'); + checkbox.inputElement.on("change", function () { + checkbox.model.toggleParam(checkbox.param); + }); + checkbox.labelElement = checkbox.rootElement.append('span'); + checkbox.labelElement.style('padding-left', '10px'); + return checkbox; + }; + Checkbox.prototype.redraw = function () { + var checkbox = this; + if (checkbox.plainText) { + //console.log('rendering label as plain text: ', label.text) + checkbox.label = "\\text{" + checkbox.label + "}"; + } + else { + //console.log('rendering label as LaTeX: ', label.text) + } + checkbox.inputElement.property('checked', Boolean(checkbox.value)); + katex.render(checkbox.label, checkbox.labelElement.node()); + return checkbox; + }; + return Checkbox; + }(KG.ParamControl)); + KG.Checkbox = Checkbox; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Radio = /** @class */ (function (_super) { + __extends(Radio, _super); + function Radio(def) { + var _this = this; + KG.setProperties(def, 'constants', ['figure_id']); + KG.setProperties(def, 'updatables', ['optionValue']); + _this = _super.call(this, def) || this; + return _this; + } + Radio.prototype.draw = function (layer) { + var radio = this; + radio.rootElement = layer.append('div').append('label'); + radio.inputElement = radio.rootElement.append('input'); + radio.inputElement + .attr('type', 'radio') + .attr('name', radio.figure_id + '_' + radio.param) + .attr('value', radio.optionValue); + radio.inputElement.on("change", function () { + radio.model.updateParam(radio.param, radio.optionValue); + }); + radio.labelElement = radio.rootElement.append('span'); + radio.labelElement.style('padding-left', '10px'); + return radio; + }; + Radio.prototype.redraw = function () { + var radio = this; + radio.inputElement.property('checked', radio.value == radio.optionValue); + katex.render(radio.label, radio.labelElement.node()); + return radio; + }; + return Radio; + }(KG.ParamControl)); + KG.Radio = Radio; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Controls = /** @class */ (function (_super) { + __extends(Controls, _super); + function Controls(def) { + var _this = this; + KG.setDefaults(def, { + title: '', + description: '', + sliders: [], + checkboxes: [], + radios: [], + divs: [] + }); + KG.setProperties(def, 'constants', ['sliders', 'checkboxes', 'radios', 'divs']); + KG.setProperties(def, 'updatables', ['title', 'description']); + _this = _super.call(this, def) || this; + return _this; + } + // create div for text + Controls.prototype.draw = function (layer) { + var controls = this; + var controls_id = KG.randomString(5); + controls.rootElement = layer.append('div').style('padding-top', '10px').style('padding-bottom', '10px'); + controls.titleElement = controls.rootElement.append('div').style('font-size', '10pt').style('padding-bottom', 10); + controls.rootElement.append('hr'); + controls.descriptionElement = controls.rootElement.append('div'); + controls.descriptionElement.style('margin-bottom', '10px'); + if (controls.sliders.length > 0) { + var sliderTable_1 = controls.rootElement.append('table').style('padding', '10px').style('width', '100%').style('margin', '0px 0px 10px 0px'); + controls.sliders.forEach(function (slider) { + new KG.Slider({ layer: sliderTable_1, param: slider.param, label: slider.label, digits: slider.digits, showNumber: slider.showNumber, model: controls.model, show: slider.show }); + }); + } + controls.radios.forEach(function (radio) { + radio = KG.setDefaults(radio, { + layer: controls.rootElement, + model: controls.model, + figure_id: controls_id + }); + new KG.Radio(radio); + }); + if (controls.checkboxes.length > 0) { + if (controls.radios.length > 0) { + controls.rootElement.append('div').style('margin-bottom', '10px'); + } + controls.checkboxes.forEach(function (checkbox) { + checkbox = KG.setDefaults(checkbox, { + layer: controls.rootElement, + model: controls.model + }); + new KG.Checkbox(checkbox); + }); + } + controls.divs.forEach(function (div) { + div = KG.setDefaults(div, { + layer: controls.rootElement, + model: controls.model, + fontSize: 14 + }); + if (div.hasOwnProperty('html')) { + new KG.Div(div); + } + else if (div.hasOwnProperty('table')) { + div.rows = div.table.rows; + div.columns = div.table.columns; + div.lines = div.table.lines; + div.fontSize = 10; + delete div.table; + new KG.Table(div); + } + }); + return controls; + }; + // update properties + Controls.prototype.redraw = function () { + var controls = this; + if (controls.title.length > 0) { + controls.titleElement.text(controls.title.toUpperCase()); + } + controls.descriptionElement.html(controls.description); + return controls; + }; + return Controls; + }(KG.DivObject)); + KG.Controls = Controls; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var GameMatrix = /** @class */ (function (_super) { + __extends(GameMatrix, _super); + function GameMatrix(def) { + var _this = this; + KG.setDefaults(def, { + players: ["Player 1", "Player 2"] + }); + KG.setProperties(def, 'constants', ['players', 'strategies']); + KG.setProperties(def, 'updatables', ['payoffs']); + _this = _super.call(this, def) || this; + return _this; + } + // create div for text + GameMatrix.prototype.draw = function (layer) { + var gameMatrix = this; + var numStrategies1 = gameMatrix.strategies[0].length, numStrategies2 = gameMatrix.strategies[1].length; + gameMatrix.rootElement = layer.append('div'); + var table = gameMatrix.rootElement.append('table').attr('class', 'gameMatrix'); + var topRow = table.append('tr'); + topRow.append('td').attr('colspan', '2').attr('class', 'empty'); + topRow.append('td') + .attr('colspan', numStrategies2 * 2) + .attr('class', 'player2 strategy empty') + .text(gameMatrix.players[1]); + var secondRow = table.append('tr'); + secondRow.append('td').attr('colspan', '2').attr('class', 'empty'); + gameMatrix.strategies[1].forEach(function (s) { + secondRow.append('td').attr('colspan', '2').attr('class', 'player2 strategy').text(s); + }); + gameMatrix.payoffNodes = []; + for (var i = 0; i < numStrategies1; i++) { + var row = table.append('tr'); + var payoffRow = []; + if (i == 0) { + row.append('td') + .attr('rowSpan', numStrategies1) + .attr('class', 'player1 strategy empty') + .text(gameMatrix.players[0]); + } + row.append('td').text(gameMatrix.strategies[0][i]).attr('class', 'player1 strategy'); + for (var j = 0; j < numStrategies2; j++) { + var payoff1 = row.append('td').attr('class', 'player1 payoff'); + var payoff2 = row.append('td').attr('class', 'player2 payoff'); + payoffRow.push([payoff1, payoff2]); + } + gameMatrix.payoffNodes.push(payoffRow); + } + return gameMatrix; + }; + GameMatrix.prototype.redraw = function () { + var gameMatrix = this; + var strategies1 = gameMatrix.strategies[0], strategies2 = gameMatrix.strategies[1]; + var numStrategies1 = strategies1.length, numStrategies2 = strategies2.length; + for (var i = 0; i < numStrategies1; i++) { + for (var j = 0; j < numStrategies2; j++) { + var cell = gameMatrix.payoffNodes[i][j]; + katex.render(gameMatrix.payoffs[i][j][0].toString(), cell[0].node()); + katex.render(gameMatrix.payoffs[i][j][1].toString(), cell[1].node()); + } + } + return gameMatrix; + }; + return GameMatrix; + }(KG.DivObject)); + KG.GameMatrix = GameMatrix; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var GeoGebraApplet = /** @class */ (function (_super) { + __extends(GeoGebraApplet, _super); + function GeoGebraApplet(def) { + var _this = this; + KG.setDefaults(def, { + params: [], + objects: [], + axisLabels: [] + }); + def.params.forEach(function (param) { + def[param] = 'params.' + param; + }); + KG.setProperties(def, 'updatables', def.params); + KG.setProperties(def, 'constants', ['axes', 'params']); + _this = _super.call(this, def) || this; + var div = _this; + div.objects = def.objects.map(function (objDef) { + objDef.model = def.model; + return new KG.GeoGebraObject(objDef); + }); + //console.log('created GGB javascript object ', this) + div.axesEstablished = false; + return _this; + } + // create div for text + GeoGebraApplet.prototype.draw = function (layer) { + var div = _super.prototype.draw.call(this, layer); + var id = KG.randomString(10); + div.rootElement.append('div').attr('id', id); + var applet = new GGBApplet({ + allowStyleBar: true, + perspective: "T", + borderColor: "#FFFFFF", + dataParamId: id + }, true); + applet.setHTML5Codebase('../../../../GeoGebra/HTML5/5.0/web3d/'); + applet.inject(id); + return div; + }; + GeoGebraApplet.prototype.establishGGB = function (width, height) { + var div = this; + //console.log('called establishGGB'); + if (undefined != document['ggbApplet']) { + //console.log('applet exists'); + div.applet = document['ggbApplet']; + div.params.forEach(function (p) { + var establishParamCommand = p + " = " + div.model.currentParamValues[p]; + //console.log('setting param using command ', establishParamCommand); + div.applet.evalCommand(establishParamCommand); + }); + div.objects.forEach(function (obj) { + obj.establishGGB(div.applet); + }); + div.updateGGB(div.applet, width, height); + } + else { + //console.log('applet does not exist') + } + }; + GeoGebraApplet.prototype.updateGGB = function (applet, width, height) { + var div = this; + console.log('called updateGGB'); + if (undefined != applet) { + //console.log('applet exists'); + //console.log('setting width to ', width); + applet.setWidth(width); + //console.log('setting height to ', height); + applet.setHeight(height); + if (div.axes.length == 3) { + //console.log('setting coordinate system ', div.axes[0].min, div.axes[0].max, div.axes[1].min, div.axes[1].max, div.axes[2].min, div.axes[2].max) + applet.setCoordSystem(div.axes[0].min, div.axes[0].max, div.axes[1].min, div.axes[1].max, div.axes[2].min, div.axes[2].max); + //console.log('setting axis steps ', div.axes[0].step, div.axes[1].step, div.axes[2].step); + applet.setAxisSteps(3, div.axes[0].step, div.axes[1].step, div.axes[2].step); + //console.log('setting axis labels ', div.axes[0].label, div.axes[1].label, div.axes[2].label); + applet.setAxisLabels(3, div.axes[0].label, div.axes[1].label, div.axes[2].label); + applet.setColor('xAxis', 0, 0, 0); + applet.setColor('yAxis', 0, 0, 0); + applet.setColor('zAxis', 0, 0, 0); + } + else { + applet.setCoordSystem(div.axes[0].scale.domainMin, div.axes[0].scale.domainMax, div.axes[1].scale.domainMin, div.axes[1].scale.domainMax); + applet.setAxisSteps(2, div.axes[0].step, div.axes[1].step); + applet.setAxisLabels(2, div.axes[0].label, div.axes[1].label); + applet.setColor('xAxis', 0, 0, 0); + applet.setColor('yAxis', 0, 0, 0); + } + if (div.hasOwnProperty('params')) { + div.params.forEach(function (param) { + applet.setValue(param, div[param]); + }); + } + } + else { + //console.log('applet does not exist') + } + }; + // update properties + GeoGebraApplet.prototype.redraw = function () { + var div = _super.prototype.redraw.call(this); + var width = Math.abs(div.xScale.scale(1) - div.xScale.scale(0)), height = Math.abs(div.yScale.scale(1) - div.yScale.scale(0)); + var checkExist = setInterval(function () { + if (undefined != div.applet) { + div.updateGGB(div.applet, width, height); + clearInterval(checkExist); + } + else { + div.establishGGB(width, height); + } + }, 100); // check every 100ms + return div; + }; + return GeoGebraApplet; + }(KG.PositionedDiv)); + KG.GeoGebraApplet = GeoGebraApplet; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Mathbox = /** @class */ (function (_super) { + __extends(Mathbox, _super); + function Mathbox(def) { + var _this = this; + KG.setDefaults(def, { + objects: [] + }); + _this = _super.call(this, def) || this; + var mb = _this; + mb.objectDefs = def.objects; + mb.objects = []; + mb.objectDefs.forEach(function (td) { + td.def.mathbox = mb; + td.def.model = mb.model; + if (td.type.indexOf('Mathbox') < 0) { + td.type = 'Mathbox' + td.type; + } + try { + mb.objects.push(new KG[td.type](td.def)); + } + catch (e) { + console.log("There's no object called ", td.type); + } + }); + mb.clearColor = mb.model.clearColor; + return _this; + //console.log('created mathbox', mb); + } + Mathbox.prototype.initMathbox = function () { + var mb = this; + mb.mathbox = mathBox({ + plugins: ['core', 'controls', 'cursor', 'mathbox'], + controls: { klass: THREE.OrbitControls }, + element: mb.rootElement.node() + }); + if (mb.mathbox.fallback) + throw "WebGL not supported"; + mb.three = mb.mathbox.three; + mb.three.renderer.setClearColor(new THREE.Color(mb.clearColor), 1.0); + mb.mathbox.camera({ proxy: true, position: [-5, 0.5, 0.8], eulerOrder: "yzx" }); + mb.mathboxView = mb.mathbox.cartesian({ scale: [1.6, 1.6, 1.6] }); + mb.mathboxView.grid({ axes: [1, 3], width: 2, divideX: 10, divideY: 10, opacity: 0.3 }); + mb.xAxis.redraw(); + mb.yAxis.redraw(); + mb.zAxis.redraw(); + mb.objects.forEach(function (o) { o.draw().update(); }); + return mb; + }; + // create mb for mathbox + Mathbox.prototype.draw = function (layer) { + //console.log('creating mathbox container'); + var mb = this; + mb.rootElement = layer.append('div').style('position', 'absolute'); + return mb; + }; + Mathbox.prototype.redraw = function () { + var mb = _super.prototype.redraw.call(this); + //console.log('called redraw'); + if (mb.mathbox == undefined && mb.rootElement.node().clientWidth > 10 && mb.zAxis != undefined) { + mb.initMathbox(); + } + else { + return mb; + } + return mb; + }; + return Mathbox; + }(KG.PositionedDiv)); + KG.Mathbox = Mathbox; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Sidebar = /** @class */ (function (_super) { + __extends(Sidebar, _super); + function Sidebar(def) { + var _this = this; + KG.setDefaults(def, { + controls: [], + triggerWidth: 563 + }); + KG.setProperties(def, 'constants', ['controls', 'triggerWidth']); + _this = _super.call(this, def) || this; + return _this; + } + Sidebar.prototype.positionRight = function (width, height) { + var sidebar = this; + sidebar.rootElement + .style('left', width * 847 / 1260 + 'px') + .style('top', '0px') + .style('width', (width * 413 / 1260 - 10) + 'px') + .style('height', height + 'px') + .style('overflow-y', 'scroll') + .style('right', '-17px'); + }; + Sidebar.prototype.positionBelow = function (width, height) { + var sidebar = this; + sidebar.rootElement + .style('left', '10px') + .style('top', height + 20 + 'px') + .style('width', width - 20 + 'px') + .style('height', null); + }; + Sidebar.prototype.draw = function (layer) { + var sidebar = this; + sidebar.rootElement = layer.append('div').style('position', 'absolute').attr('class', 'sidebar'); + sidebar.controls.forEach(function (controlsDef) { + controlsDef.layer = sidebar.rootElement; + controlsDef.model = sidebar.model; + new KG.Controls(controlsDef); + }); + return sidebar; + }; + return Sidebar; + }(KG.ViewObject)); + KG.Sidebar = Sidebar; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Explanation = /** @class */ (function (_super) { + __extends(Explanation, _super); + function Explanation(def) { + var _this = this; + KG.setDefaults(def, { + height: 0, + divs: [], + border: 'none' + }); + KG.setProperties(def, 'constants', ['divs', 'height', 'border']); + _this = _super.call(this, def) || this; + return _this; + } + Explanation.prototype.position = function (width, height) { + var explanation = this; + explanation.rootElement + .style('left', '10px') + .style('top', height + 20 + 'px') + .style('width', width - 20 + 'px'); + }; + Explanation.prototype.draw = function (layer) { + var explanation = this; + explanation.rootElement = layer.append('div') + .style('position', 'absolute') + .style('height', explanation.height == 0 ? null : explanation.height + 'px') + .style('overflow-y', 'scroll') + .style('border', explanation.border); + explanation.divs.forEach(function (div) { + div = KG.setDefaults(div, { + layer: explanation.rootElement, + model: explanation.model, + fontSize: 12 + }); + if (div.hasOwnProperty('html')) { + new KG.Div(div); + } + else if (div.hasOwnProperty('table')) { + div.rows = div.table.rows; + div.columns = div.table.columns; + div.fontSize = 10; + delete div.table; + new KG.Table(div); + } + }); + return explanation; + }; + return Explanation; + }(KG.ViewObject)); + KG.Explanation = Explanation; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var Table = /** @class */ (function (_super) { + __extends(Table, _super); + function Table(def) { + var _this = this; + KG.setDefaults(def, { + columns: [], + rows: [], + fontSize: 8, + lines: true + }); + KG.setProperties(def, 'constants', ['fontSize', 'lines']); + KG.setProperties(def, 'updatables', ['rows', 'columns']); + _this = _super.call(this, def) || this; + return _this; + } + // create div for text + Table.prototype.draw = function (layer) { + var t = this; + console.log('table is ', t); + var hasColumnHeaders = (t.def['columns'].length > 0), numColumns = t.def['rows'][0].length, numRows = t.def['rows'].length; + t.rootElement = layer.append('div'); + var table = t.rootElement.append('table').attr('class', 'table'); + table + .style('margin-left', 'auto') + .style('margin-right', 'auto') + .style('font-size', t.fontSize + 'pt') + .style('text-align', 'center') + .style('border-collapse', 'collapse') + .style('margin-top', '15pt') + .attr('cell-padding', '5px') + .style('width', '80%'); + t.columnCells = []; + if (hasColumnHeaders) { + var columnRow = table.append('thead').append('tr'); + for (var c = 0; c < numColumns; c++) { + var columnCell = columnRow.append('td'); + columnCell + .style('font-size', t.fontSize + 'pt') + .style('font-weight', 'bold') + .style('border-bottom', '1px solid black') + .style('text-align', 'center') + .style('padding', '0px 10px 0px 10px'); + t.columnCells.push(columnCell); + } + } + t.rowCells = []; + var tableBody = table.append('tbody'); + for (var r = 0; r < numRows; r++) { + var dataRow = []; + var tableRow = tableBody.append('tr'); + for (var c = 0; c < numColumns; c++) { + var rowCell = tableRow.append('td'); + rowCell + .style('font-size', t.fontSize + 'pt') + .style('text-align', 'center'); + if (t.lines) { + rowCell.style('border-bottom', '0.5px solid grey'); + } + dataRow.push(rowCell); + } + t.rowCells.push(dataRow); + } + return t; + }; + Table.prototype.redraw = function () { + var t = this; + var hasColumnHeaders = (t.def['columns'].length > 0), numColumns = t.rows[0].length, numRows = t.rows.length; + if (hasColumnHeaders) { + for (var c = 0; c < numColumns; c++) { + katex.render("\\text{" + t.columns[c].toString() + "}", t.columnCells[c].node()); + } + } + for (var r = 0; r < numRows; r++) { + for (var c = 0; c < numColumns; c++) { + katex.render("\\text{" + t.rows[r][c].toString() + "}", t.rowCells[r][c].node()); + } + } + return t; + }; + return Table; + }(KG.DivObject)); + KG.Table = Table; +})(KG || (KG = {})); +/// +var KG; +(function (KG) { + var MathboxObject = /** @class */ (function (_super) { + __extends(MathboxObject, _super); + function MathboxObject(def) { + var _this = this; + KG.setProperties(def, 'constants', ['mathbox']); + _this = _super.call(this, def) || this; + return _this; + } + MathboxObject.prototype.onGraph = function () { + return true; // we won't check yet to see if it's on the graph... + }; + MathboxObject.prototype.displayElement = function (show) { + var mbo = this; + if (mbo.hasOwnProperty("mo")) { + this.mo.set("visible", show); + } + }; + return MathboxObject; + }(KG.ViewObject)); + KG.MathboxObject = MathboxObject; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxAxis = /** @class */ (function (_super) { + __extends(MathboxAxis, _super); + function MathboxAxis(def) { + var _this = this; + KG.setDefaults(def, { + ticks: 5, + min: 0, + max: 10 + }); + KG.setProperties(def, 'constants', ['axisNumber', 'ticks']); + KG.setProperties(def, 'updatables', ['ticks', 'label', 'min', 'max']); + _this = _super.call(this, def) || this; + return _this; + } + MathboxAxis.prototype.redraw = function () { + var a = this; + var view = a.mathbox.mathboxView; + if (view == undefined) { + return a; + } + view.set("range", [[a.mathbox.yAxis.min, a.mathbox.yAxis.max], [a.mathbox.zAxis.min, a.mathbox.zAxis.max], [a.mathbox.xAxis.min, a.mathbox.xAxis.max]]); + var axis = view.axis({ axis: a.axisNumber, width: 8, detail: 40, color: "black" }); + var scale = view.scale({ axis: a.axisNumber, divide: a.ticks, nice: false, zero: true }); + var ticks = view.ticks({ width: 5, size: 5, color: "gray", zBias: 2 }); + var format = view.format({ digits: 2, classes: ["tick"], style: "normal", source: scale }); + var ticklabel = view.label({ color: "gray", zIndex: 1, offset: [0, 0], points: scale, text: format, size: 10 }); + return a; + }; + return MathboxAxis; + }(KG.MathboxObject)); + KG.MathboxAxis = MathboxAxis; + var MathboxXAxis = /** @class */ (function (_super) { + __extends(MathboxXAxis, _super); + function MathboxXAxis(def) { + var _this = this; + def.axisNumber = 3; + _this = _super.call(this, def) || this; + var xAxis = _this; + xAxis.mathbox.xAxis = xAxis; + return _this; + } + return MathboxXAxis; + }(MathboxAxis)); + KG.MathboxXAxis = MathboxXAxis; + var MathboxYAxis = /** @class */ (function (_super) { + __extends(MathboxYAxis, _super); + function MathboxYAxis(def) { + var _this = this; + def.axisNumber = 1; + _this = _super.call(this, def) || this; + var yAxis = _this; + yAxis.mathbox.yAxis = yAxis; + return _this; + } + return MathboxYAxis; + }(MathboxAxis)); + KG.MathboxYAxis = MathboxYAxis; + var MathboxZAxis = /** @class */ (function (_super) { + __extends(MathboxZAxis, _super); + function MathboxZAxis(def) { + var _this = this; + def.axisNumber = 2; + _this = _super.call(this, def) || this; + var zAxis = _this; + zAxis.mathbox.zAxis = zAxis; + return _this; + } + return MathboxZAxis; + }(MathboxAxis)); + KG.MathboxZAxis = MathboxZAxis; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxPoint = /** @class */ (function (_super) { + __extends(MathboxPoint, _super); + function MathboxPoint(def) { + var _this = this; + KG.setDefaults(def, { + x: 0, + y: 0, + z: 0 + }); + KG.setProperties(def, 'updatables', ['x', 'y', 'z']); + _this = _super.call(this, def) || this; + return _this; + } + MathboxPoint.prototype.draw = function () { + var p = this; + p.pointData = p.mathbox.mathboxView.array({ + width: 1, + channels: 3 + }); + p.mo = p.mathbox.mathboxView.point({ + size: 20, + points: p.pointData, + zIndex: 4 + }); + return p; + }; + MathboxPoint.prototype.redraw = function () { + var p = this; + //console.log(p); + p.pointData.set("data", [[p.y, p.z, p.x]]); + p.mo.set("color", p.stroke); + return p; + }; + return MathboxPoint; + }(KG.MathboxObject)); + KG.MathboxPoint = MathboxPoint; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxCurve = /** @class */ (function (_super) { + __extends(MathboxCurve, _super); + function MathboxCurve(def) { + var _this = this; + KG.setDefaults(def, { + text: "#666666", + strokeWidth: 10 + }); + _this = _super.call(this, def) || this; + def.fn = KG.setDefaults(def.fn, { + model: def.model, + samplePoints: 100 + }); + _this.fn = new KG.UnivariateFunction(def.fn).update(true); + return _this; + } + MathboxCurve.prototype.draw = function () { + var c = this; + c.curveData = c.mathbox.mathboxView.interval({ + axis: 1, + channels: 3, + width: c.fn.samplePoints + }); + c.mo = c.mathbox.mathboxView.line({ + points: c.curveData, + zIndex: 3 + }); + return c; + }; + MathboxCurve.prototype.redraw = function () { + var c = this; + //console.log(c); + c.curveData.set("expr", c.fn.mathboxFn(c.mathbox)); + c.mo.set("color", c.stroke); + c.mo.set("width", c.strokeWidth); + c.mo.set("stroke", c.lineStyle); + return c; + }; + return MathboxCurve; + }(KG.MathboxObject)); + KG.MathboxCurve = MathboxCurve; + var CurveThreeD = /** @class */ (function (_super) { + __extends(CurveThreeD, _super); + function CurveThreeD(def) { + return _super.call(this, def) || this; + } + return CurveThreeD; + }(MathboxCurve)); + KG.CurveThreeD = CurveThreeD; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxSurface = /** @class */ (function (_super) { + __extends(MathboxSurface, _super); + function MathboxSurface(def) { + var _this = this; + KG.setDefaults(def, { + fill: "#666666", + strokeWidth: 10, + opacity: 0.2, + meshWidth: 1, + samplePoints: 100, + axis1: "x", + axis2: "y" + }); + KG.setProperties(def, 'constants', ['meshWidth', 'samplePoints']); + _this = _super.call(this, def) || this; + var s = _this; + var axis1 = [0, "y", "z", "x"].indexOf(def.axis1); + var axis2 = [0, "y", "z", "x"].indexOf(def.axis2); + s.axes = [axis1, axis2]; + return _this; + } + MathboxSurface.prototype.draw = function () { + var s = this; + s.surfaceData = s.mathbox.mathboxView.area({ + axes: s.axes, + channels: 3, + width: s.samplePoints, + height: s.samplePoints + }); + console.log('surface data: ', s.surfaceData); + /* + + #TODO Someday we'll improve shading + + var graphColors = s.mathbox.mathboxView.area({ + expr: function (emit, x, y, i, j, t) { + if (x < 0) + emit(1.0, 0.0, 0.0, 1.0); + else + emit(0.0, 1.0, 0.0, 1.0); + }, + axes: [1, 3], + width: 64, height: 64, + channels: 4, // RGBA + }); + + graphColors.set("expr", + function (emit, x, y, i, j, t) + { + var z = x*x + y*y; + const zMin = 0, zMax=200; + var percent = (z - zMin) / (zMax - zMin); + emit( percent, percent, percent, 1.0 ); + } + );*/ + s.mo = s.mathbox.mathboxView.surface({ + points: s.surfaceData, + shaded: true, + fill: true, + lineX: true, + lineY: true, + width: s.meshWidth, + zIndex: 2 + }); + return s; + }; + MathboxSurface.prototype.redraw = function () { + var c = this; + //console.log(c); + c.surfaceData.set("expr", c.mathboxFn()); + c.mo.set("color", c.fill); + c.mo.set("opacity", c.opacity); + return c; + }; + return MathboxSurface; + }(KG.MathboxObject)); + KG.MathboxSurface = MathboxSurface; + var MathboxFunctionSurface = /** @class */ (function (_super) { + __extends(MathboxFunctionSurface, _super); + function MathboxFunctionSurface(def) { + var _this = this; + def.fn = KG.setDefaults(def.fn, { + model: def.model, + samplePoints: 100 + }); + KG.setDefaults(def, { + samplePoints: def.fn.samplePoints + }); + _this = _super.call(this, def) || this; + _this.fn = new KG.MultivariateFunction(def.fn).update(true); + return _this; + } + MathboxFunctionSurface.prototype.mathboxFn = function () { + var s = this; + return function (emit, x, y) { + emit(y, s.fn.evaluate(x, y), x); + }; + }; + return MathboxFunctionSurface; + }(MathboxSurface)); + KG.MathboxFunctionSurface = MathboxFunctionSurface; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxDataSurface = /** @class */ (function (_super) { + __extends(MathboxDataSurface, _super); + function MathboxDataSurface(def) { + var _this = this; + KG.setDefaults(def, { + fill: "#666666", + strokeWidth: 10, + opacity: 0.2, + meshWidth: 1, + samplePoints: 100, + axis1: "x", + axis2: "y" + }); + KG.setProperties(def, 'constants', ['meshWidth', 'samplePoints']); + _this = _super.call(this, def) || this; + var s = _this; + var axis1 = [0, "y", "z", "x"].indexOf(def.axis1); + var axis2 = [0, "y", "z", "x"].indexOf(def.axis2); + s.axes = [axis1, axis2]; + return _this; + } + MathboxDataSurface.prototype.draw = function () { + var s = this; + s.surfaceData = s.mathbox.mathboxView.area({ + axes: s.axes, + channels: 3, + width: s.samplePoints, + height: s.samplePoints + }); + /* + + #TODO Someday we'll improve shading + + var graphColors = s.mathbox.mathboxView.area({ + expr: function (emit, x, y, i, j, t) { + if (x < 0) + emit(1.0, 0.0, 0.0, 1.0); + else + emit(0.0, 1.0, 0.0, 1.0); + }, + axes: [1, 3], + width: 64, height: 64, + channels: 4, // RGBA + }); + + graphColors.set("expr", + function (emit, x, y, i, j, t) + { + var z = x*x + y*y; + const zMin = 0, zMax=200; + var percent = (z - zMin) / (zMax - zMin); + emit( percent, percent, percent, 1.0 ); + } + );*/ + s.mo = s.mathbox.mathboxView.surface({ + points: s.surfaceData, + shaded: true, + fill: true, + lineX: true, + lineY: true, + width: s.meshWidth, + zIndex: 2 + }); + return s; + }; + MathboxDataSurface.prototype.redraw = function () { + var c = this; + //console.log(c); + c.surfaceData.set("expr", c.mathboxFn()); + c.mo.set("color", c.fill); + c.mo.set("opacity", c.opacity); + return c; + }; + return MathboxDataSurface; + }(KG.MathboxSurface)); + KG.MathboxDataSurface = MathboxDataSurface; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxPlane = /** @class */ (function (_super) { + __extends(MathboxPlane, _super); + function MathboxPlane(def) { + var _this = this; + var planeType = 'z'; + if (def.hasOwnProperty('x')) { + def.axis1 = "y"; + def.axis2 = "z"; + planeType = "x"; + } + else if (def.hasOwnProperty('y')) { + def.axis1 = "x"; + def.axis2 = "z"; + planeType = "y"; + } + else { + def.axis1 = "x"; + def.axis2 = "y"; + } + def.samplePoints = 2; + KG.setProperties(def, 'updatables', ['x', 'y', 'z']); + _this = _super.call(this, def) || this; + _this.planeType = planeType; + return _this; + } + MathboxPlane.prototype.mathboxFn = function () { + var p = this; + if (p.planeType == "x") { + return function (emit, y, z) { + emit(y, z, p.x); + }; + } + else if (p.planeType == "y") { + return function (emit, x, z) { + emit(p.y, z, x); + }; + } + else { + return function (emit, x, y) { + emit(y, p.z, x); + }; + } + }; + return MathboxPlane; + }(KG.MathboxSurface)); + KG.MathboxPlane = MathboxPlane; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxShape = /** @class */ (function (_super) { + __extends(MathboxShape, _super); + function MathboxShape(def) { + var _this = this; + KG.setDefaults(def, { + fill: "#666666", + strokeWidth: 10, + opacity: 0.2 + }); + _this = _super.call(this, def) || this; + return _this; + } + MathboxShape.prototype.draw = function () { + var s = this; + s.surfaceData = s.mathbox.mathboxView.area({ + axes: [1, 3], + channels: 3, + width: s.fn.samplePoints, + height: s.fn.samplePoints + }); + s.mo = s.mathbox.mathboxView.surface({ + points: s.surfaceData, + shaded: true, + fill: true, + lineX: false, + lineY: false, + width: 0, + zIndex: 2 + }); + return s; + }; + MathboxShape.prototype.redraw = function () { + var c = this; + //console.log(c); + c.surfaceData.set("expr", c.fn.mathboxFn()); + c.mo.set("color", c.fill); + c.mo.set("opacity", c.opacity); + return c; + }; + return MathboxShape; + }(KG.MathboxObject)); + KG.MathboxShape = MathboxShape; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxLabel = /** @class */ (function (_super) { + __extends(MathboxLabel, _super); + function MathboxLabel(def) { + var _this = this; + KG.setDefaults(def, { + text: "foo" + }); + KG.setProperties(def, 'updatables', ['text']); + _this = _super.call(this, def) || this; + return _this; + } + MathboxLabel.prototype.draw = function () { + var l = this; + l.pointData = l.mathbox.mathboxView.array({ + width: 1, + channels: 3 + }); + l.labelData = l.mathbox.mathboxView.format({ + font: "KaTeX_Main", + style: "normal" + }); + l.mo = l.mathbox.mathboxView.label({ + points: l.pointData, + zIndex: 4, + text: l.labelData + }); + return l; + }; + MathboxLabel.prototype.redraw = function () { + var l = _super.prototype.redraw.call(this); + l.labelData.set("data", [l.text]); + return l; + }; + return MathboxLabel; + }(KG.MathboxPoint)); + KG.MathboxLabel = MathboxLabel; +})(KG || (KG = {})); +var KG; +(function (KG) { + var MathboxLine = /** @class */ (function (_super) { + __extends(MathboxLine, _super); + function MathboxLine(def) { + var _this = this; + KG.setDefaults(def, { + x1: 0, + y1: 0, + z1: 0, + x2: 0, + y2: 0, + z2: 0, + lineStyle: "solid" + }); + KG.setProperties(def, 'updatables', ['x1', 'y1', 'z1', 'x2', 'y2', 'z2']); + KG.setProperties(def, 'constants', ['start', 'end']); + _this = _super.call(this, def) || this; + return _this; + } + MathboxLine.prototype.draw = function () { + var p = this; + p.pointData = p.mathbox.mathboxView.array({ + width: 2, + channels: 3 + }); + p.mo = p.mathbox.mathboxView.line({ + points: p.pointData, + zIndex: 4 + }); + return p; + }; + MathboxLine.prototype.redraw = function () { + var p = this; + //console.log(p); + p.pointData.set("data", [[p.y1, p.z1, p.x1], [p.y2, p.z2, p.x2]]); + p.mo.set("color", p.stroke); + p.mo.set("stroke", p.lineStyle); + p.mo.set("width", p.strokeWidth); + p.mo.set("start", p.start); + p.mo.set("end", p.end); + return p; + }; + return MathboxLine; + }(KG.MathboxObject)); + KG.MathboxLine = MathboxLine; +})(KG || (KG = {})); +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +// this file provides the interface with the overall web page +var views = []; +// initialize the diagram from divs with class kg-container +function loadGraphs() { + views = []; + var viewDivs = document.getElementsByClassName('kg-container'); + var _loop_1 = function (i) { + var d = viewDivs[i], src = d.getAttribute('src'), tmp = d.getAttribute('template'), fmt = d.getAttribute('format'); + //greenscreen = d.getAttribute('greenscreen') || false; + if (d.innerHTML.indexOf('svg') > -1) { + //console.log('already loaded'); + } + else { + // if there is no src attribute + if (!src || src.indexOf('.yml') > -1) { + try { + function generateViewFromYamlText(t) { + var y = jsyaml.safeLoad(t); + var j = JSON.parse(JSON.stringify(y).replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&')); + //j.greenscreen = greenscreen; + // If there is a template file, then load that and use the yml in the description to replace terms defined by "macro" + var custom = ""; + if (tmp) { + d3.text(tmp).then(function (template_file) { + var yt = jsyaml.safeLoad(template_file); + var yts = JSON.stringify(yt).replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&'); + for (var key in j) { + if (key == "custom") { + custom = j[key]; + } + var searchTerm = new RegExp("template.\\b" + key + "\\b", "g"); + var replaceTerm = j[key]; + yts = yts.replace(searchTerm, replaceTerm); + } + var jt = JSON.parse(yts); + jt.custom = custom; + views.push(new KG.View(d, jt)); + }); + } + else { + views.push(new KG.View(d, j)); + } + } + if (src) { + // load YAML from source file + d3.text(src).then(function (yaml_file) { + generateViewFromYamlText(yaml_file); + }); + } + else { + // read inner HTML of div as YAML + var inlineDef = d.innerHTML; + d.innerHTML = ""; + generateViewFromYamlText(inlineDef); + } + } + catch (e) { + console.log('Error reading YAML: ', e.message); + } + } + // first look to see if there's a definition in the KG.viewData object + else if (KG['viewData'].hasOwnProperty(src)) { + viewDivs[i].innerHTML = ""; + views.push(new KG.View(viewDivs[i], KG['viewData'][src])); + } + else { + // then look to see if the src is available by a URL + d3.json(src + "?update=true").then(function (data) { + if (!data) { + d.innerHTML = "

oops, " + src + " doesn't seem to exist.

"; + } + else { + d.innerHTML = ""; + //data.greenscreen = greenscreen; + views.push(new KG.View(d, data)); + } + }); + } + d.classList.add('kg-loaded'); + } + }; + // for each div, fetch the JSON definition and create a View object with that div and data + for (var i = 0; i < viewDivs.length; i++) { + _loop_1(i); + } +} +; +// When the page loads, load the graphs +window.addEventListener("load", loadGraphs); +// if the window changes size, update the dimensions of the containers +window.onresize = function () { + views.forEach(function (c) { + c.updateDimensions(); + }); +}; +(function () { + var beforePrint = function () { + views.forEach(function (c) { + c.updateDimensions(true); + }); + }; + var afterPrint = function () { + views.forEach(function (c) { + c.updateDimensions(false); + }); + }; + if (window.matchMedia) { + var mediaQueryList = window.matchMedia('print'); + mediaQueryList.addListener(function (mql) { + if (mql.matches) { + beforePrint(); + } + else { + afterPrint(); + } + }); + } + window.onbeforeprint = beforePrint; + window.onafterprint = afterPrint; +}()); +// if embedded within a slide, send slide transitions to the parent +document.addEventListener("keyup", function (event) { + if (event.key == 'PageDown') { + event.preventDefault(); + console.log('trigger next page'); + if (window != window.parent) { + window.parent.postMessage(JSON.stringify({ + method: 'next' + }), '*'); + } + } + if (event.key == 'PageUp') { + event.preventDefault(); + if (window != window.parent) { + window.parent.postMessage(JSON.stringify({ + method: 'prev' + }), '*'); + } + } +}); +var KG; +(function (KG) { + function resetAllParams() { + console.log("Resetting parameters on all views"); + views.forEach(function (v) { + v.model.resetParams(); + }); + } + KG.resetAllParams = resetAllParams; +})(KG || (KG = {})); + +