text:
module FVGQ20
using LinearAlgebra, SymbolicUtils, LaTeXStrings
const max_order = 2
const n_y = 24
const n_x = 14
const n_p = 28
const n_ϵ = 6
const n_z = 6
const η = [0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0; 1.0 0.0 0.0 0.0 0.0 0.0; 0.0 1.0 0.0 0.0 0.0 0.0; 0.0 0.0 1.0 0.0 0.0 0.0; 0.0 0.0 0.0 1.0 0.0 0.0; 0.0 0.0 0.0 0.0 1.0 0.0; 0.0 0.0 0.0 0.0 0.0 1.0]
const Q = [0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0]
const has_Ω = true
# Display definitions
const x_symbols = [:c_m, :x_m, :Π_m, :w_m, :R_m, :yd_m, :vp_m, :k, :d, :φ, :μ_I, :μ_A, :mshock, :g]
const y_symbols = [:c, :x, :Π, :w, :R, :yd, :vp, :Πstar, :u, :q, :λ, :μ_z, :r, :l, :mc, :g1, :g2, :ob_μz, :ob_Π, :ob_R, :ob_dw, :ob_dy, :ob_l, :ob_μ]
const u_symbols = [:c, :x, :Π, :w, :R, :yd, :vp, :Πstar, :u, :q, :λ, :μ_z, :r, :l, :mc, :g1, :g2, :ob_μz, :ob_Π, :ob_R, :ob_dw, :ob_dy, :ob_l, :ob_μ, :c_m, :x_m, :Π_m, :w_m, :R_m, :yd_m, :vp_m, :k, :d, :φ, :μ_I, :μ_A, :mshock, :g]
const p_symbols = [:β, :h, :ϑ, :κ, :α, :θp, :χ, :γR, :γy, :γΠ, :Πbar, :ρd, :ρφ, :ρg, :g_bar, :σ_A, :σ_d, :σ_φ, :σ_μ, :σ_m, :σ_g, :Λμ, :ΛA, :δ, :ε, :ϕ, :γ2, :Ω_ii]
const H_latex = L"\begin{equation}
\left[
\begin{array}{c}
\frac{ - h \beta d\left( 1 + t \right)}{c\left( 1 + t \right) \mathrm{\mu\_z}\left( 1 + t \right) - h c\left( t \right)} + \frac{d\left( t \right)}{\frac{ - h \mathrm{c\_m}\left( t \right)}{\mathrm{\mu\_z}\left( t \right)} + c\left( t \right)} - \lambda\left( t \right) \\
\frac{\left( l\left( t \right) \right)^{\vartheta} \left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \left( 1 - \alpha \right) \left( 1 + \frac{ - h \beta}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right) \varphi\left( t \right)}{\left( 1 + \frac{ - h}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right) \left( \frac{\left( 1 - g_{bar} \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p \right) \left(  - \phi + \frac{\left( \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right)} \right)^{\alpha} e^{{\Lambda}A}}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)}{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \left( 1 - {\theta}p \right)} + \frac{ - \left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) \left( -1 + \delta + e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)} - w\left( t \right) \lambda\left( t \right) \\
\frac{ - \beta R\left( t \right) \lambda\left( 1 + t \right)}{\Pi\left( 1 + t \right) \mathrm{\mu\_z}\left( 1 + t \right)} + \lambda\left( t \right) \\
-1 + \delta + {\gamma}2 \left( -1 + u\left( t \right) \right) + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} - r\left( t \right) \\
\frac{ - \beta \left( \left( 1 - \delta \right) q\left( 1 + t \right) + r\left( 1 + t \right) u\left( 1 + t \right) - \frac{1}{2} \left( -1 + u\left( 1 + t \right) \right)^{2} {\gamma}2 - \left( -1 + u\left( 1 + t \right) \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right) \right) \lambda\left( 1 + t \right)}{\lambda\left( t \right) \mathrm{\mu\_I}\left( 1 + t \right) \mathrm{\mu\_z}\left( 1 + t \right)} + q\left( t \right) \\
-1 + \left( 1 + \frac{ - \kappa \left( \frac{x\left( t \right) \mathrm{\mu\_z}\left( t \right)}{\mathrm{x\_m}\left( t \right)} - e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}} \right) x\left( t \right) \mathrm{\mu\_z}\left( t \right)}{\mathrm{x\_m}\left( t \right)} - \frac{1}{2} \left( \frac{x\left( t \right) \mathrm{\mu\_z}\left( t \right)}{\mathrm{x\_m}\left( t \right)} - e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}} \right)^{2} \kappa \right) q\left( t \right) + \frac{\left( \frac{x\left( 1 + t \right) \mathrm{\mu\_z}\left( 1 + t \right)}{x\left( t \right)} \right)^{2} \beta \kappa \left( \frac{x\left( 1 + t \right) \mathrm{\mu\_z}\left( 1 + t \right)}{x\left( t \right)} - e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}} \right) q\left( 1 + t \right) \lambda\left( 1 + t \right)}{\lambda\left( t \right) \mathrm{\mu\_z}\left( 1 + t \right)} \\
 - \mathrm{g1}\left( t \right) + \mathrm{mc}\left( t \right) \mathrm{yd}\left( t \right) \lambda\left( t \right) + \left( \frac{\left( \Pi\left( t \right) \right)^{\chi}}{\Pi\left( 1 + t \right)} \right)^{ - \varepsilon} \beta {\theta}p \mathrm{g1}\left( 1 + t \right) \\
\frac{\left( \frac{\left( \Pi\left( t \right) \right)^{\chi}}{\Pi\left( 1 + t \right)} \right)^{1 - \varepsilon} \beta {\theta}p \mathrm{{\Pi}star}\left( t \right) \mathrm{g2}\left( 1 + t \right)}{\mathrm{{\Pi}star}\left( 1 + t \right)} - \mathrm{g2}\left( t \right) + \mathrm{yd}\left( t \right) \mathrm{{\Pi}star}\left( t \right) \lambda\left( t \right) \\
\varepsilon \mathrm{g1}\left( t \right) - \left( -1 + \varepsilon \right) \mathrm{g2}\left( t \right) \\
\frac{k\left( t \right) u\left( t \right)}{l\left( t \right)} + \frac{ - \alpha w\left( t \right) \mathrm{\mu\_I}\left( t \right) \mathrm{\mu\_z}\left( t \right)}{\left( 1 - \alpha \right) r\left( t \right)} \\
 - \mathrm{mc}\left( t \right) + \left( w\left( t \right) \right)^{1 - \alpha} \left( r\left( t \right) \right)^{\alpha} \left( \frac{1}{1 - \alpha} \right)^{1 - \alpha} \left( \frac{1}{\alpha} \right)^{\alpha} \\
-1 + \left( \frac{\left( \mathrm{\Pi\_m}\left( t \right) \right)^{\chi}}{\Pi\left( t \right)} \right)^{1 - \varepsilon} {\theta}p + \left( \mathrm{{\Pi}star}\left( t \right) \right)^{1 - \varepsilon} \left( 1 - {\theta}p \right) \\
\frac{\beta R\left( t \right)}{{\Pi}bar e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} - \left( \left( \frac{\Pi\left( t \right)}{{\Pi}bar} \right)^{\gamma\Pi} \left( \frac{\mathrm{yd}\left( t \right) \mathrm{\mu\_z}\left( t \right)}{\mathrm{yd\_m}\left( t \right) e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)^{{\gamma}y} \right)^{1 - {\gamma}R} \left( \frac{\beta \mathrm{R\_m}\left( t \right)}{{\Pi}bar e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)^{{\gamma}R} \mathrm{mshock}\left( t \right) \\
\frac{\left( \left( -1 + u\left( t \right) \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right) + \frac{1}{2} \left( -1 + u\left( t \right) \right)^{2} {\gamma}2 \right) k\left( t \right)}{\mathrm{\mu\_I}\left( t \right) \mathrm{\mu\_z}\left( t \right)} - \mathrm{yd}\left( t \right) + c\left( t \right) + g\left( t \right) + x\left( t \right) \\
\frac{ - \phi + \frac{\left( l\left( t \right) \right)^{1 - \alpha} \left( k\left( t \right) u\left( t \right) \right)^{\alpha} \mathrm{\mu\_A}\left( t \right)}{\mathrm{\mu\_z}\left( t \right)}}{\mathrm{vp}\left( t \right)} - \mathrm{yd}\left( t \right) \\
 - \mathrm{vp}\left( t \right) + \left( \mathrm{{\Pi}star}\left( t \right) \right)^{ - \varepsilon} \left( 1 - {\theta}p \right) + \left( \frac{\left( \mathrm{\Pi\_m}\left( t \right) \right)^{\chi}}{\Pi\left( t \right)} \right)^{ - \varepsilon} {\theta}p \mathrm{vp\_m}\left( t \right) \\
 - \left( 1 - \delta \right) k\left( t \right) + \mathrm{\mu\_I}\left( t \right) \mathrm{\mu\_z}\left( t \right) k\left( 1 + t \right) - \left( 1 - \frac{1}{2} \left( \frac{x\left( t \right) \mathrm{\mu\_z}\left( t \right)}{\mathrm{x\_m}\left( t \right)} - e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}} \right)^{2} \kappa \right) x\left( t \right) \mathrm{\mu\_I}\left( t \right) \mathrm{\mu\_z}\left( t \right) \\
 - \mathrm{c\_m}\left( 1 + t \right) + c\left( t \right) \\
 - \mathrm{x\_m}\left( 1 + t \right) + x\left( t \right) \\
 - \mathrm{\Pi\_m}\left( 1 + t \right) + \Pi\left( t \right) \\
 - \mathrm{w\_m}\left( 1 + t \right) + w\left( t \right) \\
 - \mathrm{R\_m}\left( 1 + t \right) + R\left( t \right) \\
 - \mathrm{yd\_m}\left( 1 + t \right) + \mathrm{yd}\left( t \right) \\
 - \mathrm{vp\_m}\left( 1 + t \right) + \mathrm{vp}\left( t \right) \\
 - \left( \mathrm{\mu\_I}\left( t \right) \right)^{\frac{\alpha}{1 - \alpha}} \left( \mathrm{\mu\_A}\left( t \right) \right)^{\frac{1}{1 - \alpha}} + \mathrm{\mu\_z}\left( t \right) \\
 - {\rho}d \log\left( d\left( t \right) \right) + \log\left( d\left( 1 + t \right) \right) \\
 - \rho\varphi \log\left( \varphi\left( t \right) \right) + \log\left( \varphi\left( 1 + t \right) \right) \\
 - \Lambda\mu + \log\left( \mathrm{\mu\_I}\left( 1 + t \right) \right) \\
 - {\Lambda}A + \log\left( \mathrm{\mu\_A}\left( 1 + t \right) \right) \\
\log\left( \mathrm{mshock}\left( 1 + t \right) \right) \\
 - {\rho}g \log\left( g\left( t \right) \right) - \left( 1 - {\rho}g \right) \log\left( \frac{g_{bar} \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p \right) \left(  - \phi + \frac{\left( \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right)} \right)^{\alpha} e^{{\Lambda}A}}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)}{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \left( 1 - {\theta}p \right)} \right) + \log\left( g\left( 1 + t \right) \right) \\
 - \log\left( \mathrm{\mu\_z}\left( t \right) \right) + \mathrm{ob\_{\mu}z}\left( t \right) \\
 - \log\left( \Pi\left( t \right) \right) + \mathrm{ob\_\Pi}\left( t \right) \\
 - \log\left( R\left( t \right) \right) + \mathrm{ob\_R}\left( t \right) \\
 - \log\left( w\left( t \right) \right) + \mathrm{ob\_dw}\left( t \right) + \log\left( \mathrm{w\_m}\left( t \right) \right) \\
 - \log\left( \mathrm{yd}\left( t \right) \right) + \mathrm{ob\_dy}\left( t \right) + \log\left( \mathrm{yd\_m}\left( t \right) \right) \\
 - \log\left( l\left( t \right) \right) + \mathrm{ob\_l}\left( t \right) \\
 - \log\left( \mathrm{\mu\_I}\left( t \right) \right) + \mathrm{ob\_\mu}\left( t \right) \\
\end{array}
\right]
\end{equation}
"
const steady_states_latex = L"\begin{align}
\mathrm{c\_m}\left( \infty \right) =& \frac{\left( 1 - g_{bar} \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p \right) \left(  - \phi + \frac{\left( \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right)} \right)^{\alpha} e^{{\Lambda}A}}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)}{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \left( 1 - {\theta}p \right)} + \frac{ - \left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) \left( -1 + \delta + e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \\
\mathrm{x\_m}\left( \infty \right) =& \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) \left( -1 + \delta + e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \\
\mathrm{\Pi\_m}\left( \infty \right) =& {\Pi}bar \\
\mathrm{w\_m}\left( \infty \right) =& \left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \left( 1 - \alpha \right) \\
\mathrm{R\_m}\left( \infty \right) =& \frac{{\Pi}bar e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \\
\mathrm{yd\_m}\left( \infty \right) =& \frac{\left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p \right) \left(  - \phi + \frac{\left( \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right)} \right)^{\alpha} e^{{\Lambda}A}}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)}{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \left( 1 - {\theta}p \right)} \\
\mathrm{vp\_m}\left( \infty \right) =& \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \left( 1 - {\theta}p \right)}{1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p} \\
k\left( \infty \right) =& \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right)} \\
d\left( \infty \right) =& 1.0 \\
\varphi\left( \infty \right) =& 1.0 \\
\mathrm{\mu\_I}\left( \infty \right) =& e^{\Lambda\mu} \\
\mathrm{\mu\_A}\left( \infty \right) =& e^{{\Lambda}A} \\
\mathrm{mshock}\left( \infty \right) =& 1.0 \\
g\left( \infty \right) =& \frac{g_{bar} \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p \right) \left(  - \phi + \frac{\left( \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right)} \right)^{\alpha} e^{{\Lambda}A}}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)}{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \left( 1 - {\theta}p \right)} \\
c\left( \infty \right) =& \frac{\left( 1 - g_{bar} \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p \right) \left(  - \phi + \frac{\left( \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right)} \right)^{\alpha} e^{{\Lambda}A}}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)}{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \left( 1 - {\theta}p \right)} + \frac{ - \left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) \left( -1 + \delta + e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \\
x\left( \infty \right) =& \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) \left( -1 + \delta + e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \\
\Pi\left( \infty \right) =& {\Pi}bar \\
w\left( \infty \right) =& \left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \left( 1 - \alpha \right) \\
R\left( \infty \right) =& \frac{{\Pi}bar e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \\
\mathrm{yd}\left( \infty \right) =& \frac{\left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p \right) \left(  - \phi + \frac{\left( \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right)} \right)^{\alpha} e^{{\Lambda}A}}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)}{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \left( 1 - {\theta}p \right)} \\
\mathrm{vp}\left( \infty \right) =& \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \left( 1 - {\theta}p \right)}{1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p} \\
\mathrm{{\Pi}star}\left( \infty \right) =& \left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \\
u\left( \infty \right) =& 1.0 \\
q\left( \infty \right) =& 1.0 \\
\lambda\left( \infty \right) =& \frac{1 + \frac{ - h \beta}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}}{\left( 1 + \frac{ - h}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right) \left( \frac{\left( 1 - g_{bar} \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p \right) \left(  - \phi + \frac{\left( \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right)} \right)^{\alpha} e^{{\Lambda}A}}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)}{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \left( 1 - {\theta}p \right)} + \frac{ - \left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) \left( -1 + \delta + e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)} \\
\mathrm{\mu\_z}\left( \infty \right) =& e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}} \\
r\left( \infty \right) =& -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \\
l\left( \infty \right) =& 1.0 \\
\mathrm{mc}\left( \infty \right) =& \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \\
\mathrm{g1}\left( \infty \right) =& \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( -1 + \varepsilon \right) \left(  - \phi + \frac{\left( \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right)} \right)^{\alpha} e^{{\Lambda}A}}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right) \left( 1 + \frac{ - h \beta}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p \right)}{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \varepsilon \left( 1 - {\theta}p \right) \left( 1 + \frac{ - h}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right) \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right) \left( \frac{\left( 1 - g_{bar} \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p \right) \left(  - \phi + \frac{\left( \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right)} \right)^{\alpha} e^{{\Lambda}A}}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)}{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \left( 1 - {\theta}p \right)} + \frac{ - \left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) \left( -1 + \delta + e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)} \\
\mathrm{g2}\left( \infty \right) =& \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left(  - \phi + \frac{\left( \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right)} \right)^{\alpha} e^{{\Lambda}A}}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right) \left( 1 + \frac{ - h \beta}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p \right)}{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \left( 1 - {\theta}p \right) \left( 1 + \frac{ - h}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right) \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right) \left( \frac{\left( 1 - g_{bar} \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} {\theta}p \right) \left(  - \phi + \frac{\left( \frac{\left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right)} \right)^{\alpha} e^{{\Lambda}A}}{e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)}{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{ - \varepsilon}{1 - \varepsilon}} \left( 1 - {\theta}p \right)} + \frac{ - \left( \frac{\left( \frac{1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} {\theta}p}{1 - {\theta}p} \right)^{\frac{1}{1 - \varepsilon}} \left( \frac{\alpha}{-1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta}} \right)^{\alpha} \left( -1 + \varepsilon \right) \left( 1 - {\Pi}bar^{\varepsilon \left( 1 - \chi \right)} \beta {\theta}p \right)}{\varepsilon \left( 1 - {\Pi}bar^{\left( -1 + \varepsilon \right) \left( 1 - \chi \right)} \beta {\theta}p \right)} \right)^{\frac{1}{1 - \alpha}} \alpha \left( 1 - \alpha \right) \left( -1 + \delta + e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\left( 1 - \alpha \right) \left( -1 + \delta + \frac{e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right) e^{\Lambda\mu} e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}} \right)} \\
\mathrm{ob\_{\mu}z}\left( \infty \right) =& \frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha} \\
\mathrm{ob\_\Pi}\left( \infty \right) =& \log\left( {\Pi}bar \right) \\
\mathrm{ob\_R}\left( \infty \right) =& \log\left( \frac{{\Pi}bar e^{\frac{{\Lambda}A + \Lambda\mu \alpha}{1 - \alpha}}}{\beta} \right) \\
\mathrm{ob\_dw}\left( \infty \right) =& 0.0 \\
\mathrm{ob\_dy}\left( \infty \right) =& 0.0 \\
\mathrm{ob\_l}\left( \infty \right) =& 0.0 \\
\mathrm{ob\_\mu}\left( \infty \right) =& \Lambda\mu
\end{align}
"
const steady_states_iv_latex = L"$$"
# Function definitions
include("FVGQ20/zero_order_ip.jl")
include("FVGQ20/first_order_ip.jl")
include("FVGQ20/second_order_ip.jl")
end


text:
using BinanceHistoricalData
using Test

@testset "BinanceHistoricalData.jl" begin
    # Write your tests here.
end

ext: jl


text:
using ChainRulesCore
using ZygoteRules: @adjoint

using ..ITensorAutoHOOT
using ..ITensorAutoHOOT: AbstractNetwork

struct TreeTensor <: AbstractNetwork
  tensors::Vector{ITensor}
end

function Base.show(io::IO, tree::TreeTensor)
  out_str = "\n"
  for (i, t) in enumerate(tree.tensors)
    out_str = out_str * "[" * string(i) * "] " * string(inds(t)) * "\n"
  end
  return print(io, out_str)
end

TreeTensor(tensors::ITensor...; kwargs...) = TreeTensor(collect(tensors))

@adjoint function TreeTensor(tensor::ITensor)
  treetensor_pullback(dtensor) = (ITensor(dtensor),)
  return TreeTensor(tensor), treetensor_pullback
end

ITensors.inds(tree::TreeTensor) = tuple(noncommoninds(tree.tensors...)...)

function Base.getindex(t::TreeTensor)
  @assert length(t.tensors) == 1
  @assert order(t.tensors[1]) == 0
  return t.tensors[1][]
end

function ChainRulesCore.rrule(::typeof(getindex), x::TreeTensor)
  y = x[]
  function getindex_pullback(ȳ)
    x̄ = TreeTensor([ITensor(ȳ)])
    return (NoTangent(), x̄)
  end
  return y, getindex_pullback
end

function Base.:+(A::TreeTensor, B::TreeTensor; kwargs...)
  if length(A.tensors) == 1 && length(B.tensors) == 1
    return TreeTensor(A.tensors[1] + B.tensors[1])
  else
    # TODO: currently it only transfer the tree to ITensor, do the addition, then trasferring the output to an MPS
    out = ITensor(A) + ITensor(B)
    mps = MPS(out, inds(out); kwargs...)
    return TreeTensor(mps...)
  end
end

ITensors.sum(tensors::Vector{TreeTensor}; kwargs...) = ITensors.sum(tensors...; kwargs...)

function ITensors.sum(t1::TreeTensor, t2::TreeTensor...; kwargs...)
  return +(t1, sum(t2...; kwargs...); kwargs...)
end

ITensors.sum(t::TreeTensor; kwargs...) = t

include("mincut_tree.jl")
include("contract.jl")


text:
# TODO: Make this not play in eyes

function play_out(board::Board, num_rounds::Integer)
    forced_pass = false
    for i = 1:num_rounds
        candidates = legal_moves(board)
        if length(candidates) == 1
            # Forced pass for both players
            if forced_pass
                return board
            end
            forced_pass = true
        else
            forced_pass = false
        end
        move = rand(candidates)
        play_move(board, move)
    end
    board
end


text:
# using Optimize
# using NLPModels
#
# using Plots
# # pyplot()
#
# using LineSearch
# using Stopping
# using LSDescentMethods
# using ScalarSolvers
#
# include("MPBProblems-1D.jl")
# include("MPBProblems.jl")
# include("compare_solvers.jl")


text:
function numericsummary(INPUT::Union{Array,DataFrame},VarNames::Symbol)  #数値型の基本統計量の算出
  SummaryVar=StatsBase.var(INPUT)
  SummaryStd=StatsBase.std(INPUT)
  SummaryQuartile=StatsBase.quantile( INPUT , [0.00, 0.25, 0.50, 0.75, 1.00])
  SummaryMedian=StatsBase.median(INPUT)
  SummaryMean=StatsBase.mean(INPUT)

  Output=DataFrame(colname=VarNames,Var=SummaryVar,Std=SummaryStd,Mean=SummaryMean, Min=SummaryQuartile[1] ,Quartile1st=SummaryQuartile[2] ,Median=SummaryMedian,Quartile3rd=SummaryQuartile[4],Max=SummaryQuartile[5])

  return Output
end

function nonnumericsummary(INPUT::Union{Array,DataFrame},VarNames::Symbol)  #非数値型の基本統計量の算出
  Output=combine(groupby(INPUT, VarNames, sort=false, skipmissing=false), VarNames=>df -> size(df, 1))
  rename!(Output,[VarNames,:count])

  return Output
end

function summarymerge(INPUT::DataFrame, Summary::DataFrame ,FirstMergeFlag::Bool)  #データの集約
  if FirstMergeFlag ==true
    Summary=INPUT
    FirstMergeFlag=false
  else
    Summary=vcat(Summary,INPUT)
  end

  return Summary,FirstMergeFlag
end

function univariate(INPUT::DataFrame;graphplot::Bool=false)
  VarNames=propertynames(INPUT)
  Vartype=eltype.(eachcol(INPUT))
  SummaryNonNum=DataFrame(colname="",hist=0)
  SummaryNum=DataFrame(colname="",Var=0.0,Std=0.0,Mean=0.0, Min=0.0 ,Quartile1st=0.0 ,Median=0.0,Quartile3rd=0.0,Max=0.0)
  FirstMergeFlagNum=true
  FirstMergeFlagNonNum=true
  typearray=0
  typearrayflag=true

  for  i = 1 : size(INPUT,2)
    if Vartype[i] <: Real
      #数値型の基本統計量の算出
      work=numericsummary(INPUT[:,i],VarNames[i])

      #基本統計量の集約
      SummaryNum,FirstMergeFlagNum=summarymerge(work,SummaryNum,FirstMergeFlagNum)
      #列がReal型かどうか判定
      if typearrayflag
        typearray=i
        typearrayflag=false
      else
        typearray=hcat(typearray,i)
      end
    else
      #非数値型の基本統計量の算出
      work=nonnumericsummary(INPUT,VarNames[i])

      #基本統計量の集約
      SummaryNonNum,FirstMergeFlagNonNum=summarymerge(work,SummaryNonNum,FirstMergeFlagNonNum)
    end
  end

  if(graphplot)
   # gr()
   # @df INPUT corrplot(cols(typearray),grid=true)
  end

  return SummaryNum,SummaryNonNum
end


text:
function rename_param(param)
    mappings = Dict(
        "atom" => "name",
        "r1" => "r₁",
        "theta0" => "θ₀",
        "x1" => "x₁",
        "d1" => "d₁",
        "zeta" => "ζ",
        "z1" => "z₁",
        "vi" => "vᵢ",
        "uj" => "uⱼ",
        "xi" => "xᵢ"
    )

    get(mappings, param, param)
end

atom_type_number(atom_type) = Symbol(String(atom_type[:name])[3:min(3, end)])
atom_type_name(atom_type) = Symbol(String(atom_type[:name])[1:2])

@generated function atom_type_params(uff::UFF, atom_type::Symbol)
    filename_uff_params = joinpath(Pkg.dir("Alpine"), "src/potentials/uff", "uff.txt")
    header, params = readdlm(filename_uff_params, header = true)
    params = rename_param.(params)
    atom_types = Dict(
        Symbol(header[i, 1]) => Dict(
            Symbol(param) => header[i, j] for (j, param) in enumerate(params)
        ) for i in 1:size(header, 1)
    )

    :($atom_types[atom_type])
end

# van der Waals
function vdw(uff::UFF, i, j)
    x_ij = √(i[:x₁] * j[:x₁])
    d_ij = √(i[:d₁] * j[:d₁])
    ϵ = d_ij
    σ = x_ij * 0.5^(1/6)

    # d = d_ij, x = x_ij
    return ϵ, σ
end

# Bond stretching
function stretching(uff::UFF, i, j, n)
    λ = 0.1332
    r_bo = -λ * (i[:r₁] + j[:r₁]) * log(n)
    r_en = i[:r₁] * j[:r₁] * (√(i[:xᵢ]) - √(j[:xᵢ]))^2 / (i[:xᵢ] * i[:r₁] + j[:xᵢ] * j[:r₁])
    r_ij = i[:r₁] + j[:r₁] + r_bo - r_en

    g = 332.06
    k_ij = (2 * g * i[:z₁] * j[:z₁]) / (r_ij^3)
    k_ij /= 2

    r, k = r_ij, k_ij
    return r, k
end

# Bond bending (θ₀ [in degrees] is optional)
function bending(uff::UFF, i, j, k, n_ij, n_jk, θ₀ = j[:θ₀])
    c₂ = 1 / (4 * sind(θ₀)^2)
    c₁ = -4 * c₂ * cosd(θ₀)
    c₀ = c₂ * (2 * cosd(θ₀)^2 + 1)

    r_ij = stretching(i, j, n_ij)[1]
    r_jk = stretching(j, k, n_jk)[1]
    r_ik = √(r_ij^2 + r_jk^2 - 2*r_ij*r_jk*cosd(θ₀))
    β = 664.12 / (r_ij * r_jk)

    k_ijk = β * ((i[:z₁] * k[:z₁]) / r_ik^5) * r_ij * r_jk * (3 * r_ij * r_jk * (1 - cosd(θ₀)^2) - (r_ik^2)*cosd(θ₀))

    # c₀ = c₀, c₁ = c₁, c₂ = c₂, k = k_ijk
    return (k_ijk / (2 * sind(θ₀)^2)), θ₀
end

# Bond torsion
function torsion(uff::UFF, i, j, k, ℓ, bond_order_jk, num_torsions)
    hybr_i, hybr_j, hybr_k, hybr_ℓ = atom_type_number.((i, j, k, ℓ))
    name_j, name_k = atom_type_name.((j, k))

    hybrid = (hbyr_j, hybr_k)

    local n, ϕ₀, v_ijkℓ

    if hybrid == (:3, :3)
        n = 3
        ϕ₀ = 180
        v_ijkℓ = √(j[:vᵢ] * k[:vᵢ])
    elseif hybrid in ((:2, :3), (:3, :2), (:3, :R), (:R, :3))
        n = 6
        ϕ₀ = 0
        v_ijkℓ = 1
    elseif hybrid in ((:2, :2), (:2, :R), (:R, :2), (:R, :R))
        n = 2
        ϕ₀ = 180
        v_ijkℓ = 5 * √(j[:uⱼ] * k[:uⱼ]) * (1 + 4.18 * log(bond_order_jk)) # Official paper says 4.18; 2nd paper says 4.8
    else
        n = 0
        ϕ₀ = 0
        v_ijkℓ = 0
    end

    group16_elements = (:O_, :S_, :Se, :Te, :Po, :Lv)
    if name_j ∈ group16_elements || name_k ∈ group16_elements
        if hybrid == (:3, :3)
            n = 2
            ϕ₀ = 90
            v_j = name_j == :O_ ? 2 : 6.8
            v_k = name_k == :O_ ? 2 : 6.8
            v_ijkℓ = √(v_j * v_k)
        elseif hybrid in ((:2, :3), (:3, :2), (:R, :3), (:3, :R))
            n = 2
            ϕ₀ = 90
            v_ijkℓ = 5 * √(j[:uⱼ] * k[:uⱼ]) # Eq. 17 w/ bond-order = 1
            bond_order_jk != 1 && println("Bond order ≂̸ 1")
        end

        if (hybrid ∈ ((:2, :3), (:R, :3)) && hybr_i == (:2, :R)) || (hybrid ∈ ((:3, :2), (:3, :R)) && hybr_ℓ == (:2, :R))
            n = 3
            ϕ₀ = 180
            v_ijkℓ = 2
        end
    end

    v_ijkℓ /= num_torsions

    # k = v_ijkℓ / 2, ϕ₀ = ϕ₀, n = n

    # return k, ϕₒ, n
    return v_ijkℓ / 2, -round(cosd(n * ϕ₀), 0), n
end

# Bond inversion — only supports ω₀ = 0 for now
function inversion(uff::UFF, i, j, k, ℓ)
    hybr_i, hybr_j, hybr_k, hybr_ℓ = atom_type_number.((i, j, k, ℓ))
    name_i, name_j, name_k = atom_type_name.((i, j, k))

    # a₂ = 1 / (cosd(γ₀)^2 + 2*sind(γ₀) - 2)
    # a₁ = 4 * a₂ * sind(γ₀)
    # a₀ = a₂ * (2*cosd(γ₀)^2 - 3)

    if name_i == :C_ && hybr_i == (:2, :R)
        c₀ = 1
        c₁ = -1
        c₂ = 0

        if :O_2 in (name_j, name_k, name_ℓ)
            k_ijkℓ = 50
        else
            k_ijkℓ = 6
        end

        # k = k_ijkℓ, c₀ = c₀, c₁ = c₁, c₂ = c₂
        return k_ijkℓ
    else
        return 0
    end
end

max_stars_repo_name: NickMcNutt/Alpine

max_issues_repo_name: NickMcNutt/Alpine

max_forks_repo_name: NickMcNutt/Alpine


text:
##==============================================================================
## Accessors
##==============================================================================
##==============================================================================
## PointParametricEst
##==============================================================================
"$(SIGNATURES)"
getPPEMax(est::AbstractPointParametricEst) = est.max
getPPEMax(fg::AbstractDFG, varlabel::Symbol, solveKey::Symbol=:default) =
                getPPE(fg, varlabel, solveKey) |> getPPEMax

"$(SIGNATURES)"
getPPEMean(est::AbstractPointParametricEst) = est.mean
getPPEMean(fg::AbstractDFG, varlabel::Symbol, solveKey::Symbol=:default) =
                getPPE(fg, varlabel, solveKey) |> getPPEMean

"$(SIGNATURES)"
getPPESuggested(est::AbstractPointParametricEst) = est.suggested
getPPESuggested(fg::AbstractDFG, varlabel::Symbol, solveKey::Symbol=:default) =
                getPPE(fg, varlabel, solveKey) |> getPPESuggested

"$(SIGNATURES)"
getLastUpdatedTimestamp(est::AbstractPointParametricEst) = est.lastUpdatedTimestamp

##==============================================================================
## Variable Node Data
##==============================================================================

## COMMON
# getSolveInProgress
# isSolveInProgress

##------------------------------------------------------------------------------
## variableType
##------------------------------------------------------------------------------
"""
    $(SIGNATURES)

Variable nodes `variableType` information holding a variety of meta data associated with the type of variable stored in that node of the factor graph.

Notes
- API Quirk in that this function returns and instance of `::T` not a `::Type{<:InferenceVariable}`.

DevWork
- TODO, see IncrementalInference.jl 1228

Related

getVariableType
"""
getVariableType(v::DFGVariable{T}) where T <: InferenceVariable = T()

function getVariableType(vnd::VariableNodeData)
    # @warn "getVariableType(::VariableNodeData) is being deprecated, use getVariableType(::DFGVariable) instead."
    return vnd.variableType
end

# TODO: Confirm that we can switch this out, instead of retrieving the complete variable.
# getVariableType(v::DFGVariable) = getVariableType(getSolverData(v))

# Optimized in CGDFG
getVariableType(dfg::AbstractDFG, lbl::Symbol) = getVariableType(getVariable(dfg,lbl))

##------------------------------------------------------------------------------
## InferenceVariable
##------------------------------------------------------------------------------

# """
#     $SIGNATURES
# Interface function to return the `variableType` manifolds of an InferenceVariable, extend this function for all Types<:InferenceVariable.
# """
# function getManifolds end

# getManifolds(::Type{<:T}) where {T <: ManifoldsBase.AbstractManifold} = convert(Tuple, T)
# getManifolds(::T) where {T <: ManifoldsBase.AbstractManifold} = getManifolds(T)

"""
    @defVariable StructName manifolds<:ManifoldsBase.AbstractManifold

A macro to create a new variable with name `StructName` and manifolds.  Note that
the `manifolds` is an object and *must* be a subtype of `ManifoldsBase.AbstractManifold`.
See documentation in [Manifolds.jl on making your own](https://juliamanifolds.github.io/Manifolds.jl/stable/examples/manifold.html).

Example:
```
DFG.@defVariable Pose2 SpecialEuclidean(2) ProductRepr([0;0.0],[1 0; 0 1.0])
```
"""
macro defVariable(structname, manifold, point_identity)
    return esc(quote
        Base.@__doc__ struct $structname <: InferenceVariable end

        # user manifold must be a <:Manifold
        @assert ($manifold isa AbstractManifold) "@defVariable of "*string($structname)*" requires that the "*string($manifold)*" be a subtype of `ManifoldsBase.AbstractManifold`"

        DFG.getManifold(::Type{$structname}) = $manifold

        DFG.getPointType(::Type{$structname}) = typeof($point_identity)

        DFG.getPointIdentity(::Type{$structname}) = $point_identity

        DFG.getVariableType(::typeof($manifold)) = $structname

    end)
end

Base.convert(::Type{<:AbstractManifold}, ::Union{<:T, Type{<:T}}) where {T <: InferenceVariable} = getManifold(T)

"""
    $SIGNATURES
Interface function to return the `<:ManifoldsBase.AbstractManifold` object of `variableType<:InferenceVariable`.
"""
getManifold(vari::DFGVariable) = getVariableType(vari) |> getManifold
getManifold(::T) where {T <: InferenceVariable} = getManifold(T)

"""
    $SIGNATURES
Interface function to return the `variableType` dimension of an InferenceVariable, extend this function for all Types<:InferenceVariable.
"""
function getDimension end

getDimension(::Type{T}) where {T <: InferenceVariable} = manifold_dimension(getManifold(T))
getDimension(::T) where {T <: InferenceVariable} = manifold_dimension(getManifold(T))
getDimension(M::ManifoldsBase.AbstractManifold) = manifold_dimension(M)
getDimension(var::DFGVariable) = getDimension(getVariableType(var))

"""
    $SIGNATURES
Interface function to return the manifold point type of an InferenceVariable, extend this function for all Types<:InferenceVariable.
"""
function getPointType end
getPointType(::T) where {T <: InferenceVariable} = getPointType(T)

"""
    $SIGNATURES
Interface function to return the user provided identity point for this InferenceVariable manifold, extend this function for all Types<:InferenceVariable.

Notes
- Used in transition period for Serialization.  This function will likely be changed or deprecated entirely.
"""
function getPointIdentity end
getPointIdentity(::T) where {T <: InferenceVariable} = getPointIdentity(T)

"""
    $SIGNATURES

Default escalzation from coordinates to a group representation point.  Override if defaults are not correct.
E.g. coords -> se(2) -> SE(2).

DevNotes
- TODO Likely remove as part of serialization updates, see #590
- Used in transition period for Serialization.  This function will likely be changed or deprecated entirely.

Related

[`getCoordinates`](@ref)
"""
function getPoint(::Type{T}, v::AbstractVector, basis=ManifoldsBase.DefaultOrthogonalBasis()) where {T <: InferenceVariable}
    M = getManifold(T)
    p0 = getPointIdentity(T)
    X = ManifoldsBase.get_vector(M, p0, v, basis)
    ManifoldsBase.exp(M, p0, X)
end

"""
    $SIGNATURES

Default reduction of a variable point value (a group element) into coordinates as `Vector`.  Override if defaults are not correct.

DevNotes
- TODO Likely remove as part of serialization updates, see #590
- Used in transition period for Serialization.  This function will likely be changed or deprecated entirely.

Related

[`getPoint`](@ref)
"""
function getCoordinates(::Type{T}, p, basis=ManifoldsBase.DefaultOrthogonalBasis()) where {T <: InferenceVariable}
    M = getManifold(T)
    p0 = getPointIdentity(T)
    X = ManifoldsBase.log(M, p0, p)
    ManifoldsBase.get_coordinates(M, p0, X, basis)
end

##------------------------------------------------------------------------------
## solvedCount
##------------------------------------------------------------------------------

"""
    $SIGNATURES

Get the number of times a variable has been inferred -- i.e. `solvedCount`.

Related

isSolved, setSolvedCount!
"""
getSolvedCount(v::VariableNodeData) = v.solvedCount
getSolvedCount(v::VariableDataLevel2, solveKey::Symbol=:default) = getSolverData(v, solveKey) |> getSolvedCount
getSolvedCount(dfg::AbstractDFG, sym::Symbol, solveKey::Symbol=:default) = getSolvedCount(getVariable(dfg, sym), solveKey)

"""
    $SIGNATURES

Update/set the `solveCount` value.

Related

getSolved, isSolved
"""
setSolvedCount!(v::VariableNodeData, val::Int) = v.solvedCount = val
setSolvedCount!(v::VariableDataLevel2, val::Int, solveKey::Symbol=:default) = setSolvedCount!(getSolverData(v, solveKey), val)
setSolvedCount!(dfg::AbstractDFG, sym::Symbol, val::Int, solveKey::Symbol=:default) = setSolvedCount!(getVariable(dfg, sym), val, solveKey)

"""
    $SIGNATURES

Boolean on whether the variable has been solved.

Related

getSolved, setSolved!
"""
isSolved(v::VariableNodeData) = 0 < v.solvedCount
isSolved(v::VariableDataLevel2, solveKey::Symbol=:default) = getSolverData(v, solveKey) |> isSolved
isSolved(dfg::AbstractDFG, sym::Symbol, solveKey::Symbol=:default) = isSolved(getVariable(dfg, sym), solveKey)

##------------------------------------------------------------------------------
## initialized
##------------------------------------------------------------------------------
"""
    $SIGNATURES

Returns state of variable data `.initialized` flag.

Notes:
- used by both factor graph variable and Bayes tree clique logic.
"""
function isInitialized(var::DFGVariable, key::Symbol=:default)
  data = getSolverData(var, key)
  if data === nothing
    #TODO we still have a mixture of 2 error behaviours
      # DF, not sure I follow the error here?
  return false
  else
    return data.initialized
  end
end

function isInitialized(dfg::AbstractDFG, label::Symbol, key::Symbol=:default)
  return isInitialized(getVariable(dfg, label), key)::Bool
end

"""
    $SIGNATURES

Return `::Bool` on whether this variable has been marginalized.

Notes:
- VariableNodeData default `solveKey=:default`
"""
isMarginalized(vert::DFGVariable, solveKey::Symbol=:default) = getSolverData(vert, solveKey).ismargin
isMarginalized(dfg::AbstractDFG, sym::Symbol, solveKey::Symbol=:default) = isMarginalized(DFG.getVariable(dfg, sym), solveKey)

"""
    $SIGNATURES

Mark a variable as marginalized `true` or `false`.
"""
function setMarginalized!(vnd::VariableNodeData, val::Bool)
  vnd.ismargin = val
end
setMarginalized!(vari::DFGVariable, val::Bool, solveKey::Symbol=:default) = setMarginalized!(getSolverData(vari, solveKey), val)
setMarginalized!(dfg::AbstractDFG, sym::Symbol, val::Bool, solveKey::Symbol=:default) = setMarginalized!(getVariable(dfg, sym), val, solveKey)

##==============================================================================
## Variables
##==============================================================================
#
# |                     | label | tags | timestamp | ppe | variableTypeName | solvable | solverData | smallData | dataEntries |
# |---------------------|:-----:|:----:|:---------:|:---:|:----------------:|:--------:|:----------:|:---------:|:-----------:|
# | SkeletonDFGVariable |   X   |   X  |           |     |                  |          |            |           |             |
# | DFGVariableSummary  |   X   |   X  |     X     |  X  |         X        |          |            |           |       X     |
# | DFGVariable         |   X   |   X  |     x     |  X  |                  |     X    |      X     |     X     |       X     |
#
##------------------------------------------------------------------------------

##------------------------------------------------------------------------------
## label
##------------------------------------------------------------------------------

## COMMON
# getLabel

##------------------------------------------------------------------------------
## tags
##------------------------------------------------------------------------------

## COMMON
# getTags
# setTags!

##------------------------------------------------------------------------------
## timestamp
##------------------------------------------------------------------------------

## COMMON
# getTimestamp

"""
    $SIGNATURES

Set the timestamp of a DFGVariable object returning a new DFGVariable.
Note:
Since the `timestamp` field is not mutable `setTimestamp` returns a new variable with the updated timestamp (note the absence of `!`).
Use [`updateVariable!`](@ref) on the returened variable to update it in the factor graph if needed. Alternatively use [`setTimestamp!`](@ref).
See issue #315.
"""
function setTimestamp(v::DFGVariable, ts::ZonedDateTime; verbose::Bool=true)
    if verbose
        @warn "verbose=true: setTimestamp(::DFGVariable,...) creates a returns a new immutable DFGVariable object (and didn't change a distributed factor graph object), make sure you are using the right pointers: getVariable(...).  See setTimestamp!(...) and note suggested use is at addVariable!(..., [timestamp=...]).  See DFG #315 for explanation."
    end
    return DFGVariable(v.label, ts, v.nstime, v.tags, v.ppeDict, v.solverDataDict, v.smallData, v.dataDict, Ref(v.solvable))
end

setTimestamp(v::AbstractDFGVariable, ts::DateTime, timezone=localzone(); verbose::Bool=true) = setTimestamp(v, ZonedDateTime(ts,  timezone); verbose=verbose)

function setTimestamp(v::DFGVariableSummary, ts::ZonedDateTime; verbose::Bool=true)
    if verbose
        @warn "verbose=true: setTimestamp(::DFGVariableSummary,...) creates and returns a new immutable DFGVariable object (and didn't change a distributed factor graph object), make sure you are using the right pointers: getVariable(...).  See setTimestamp!(...) and note suggested use is at addVariable!(..., [timestamp=...]).  See DFG #315 for explanation."
    end
    return DFGVariableSummary(v.label, ts, v.tags, v.ppeDict, v.variableTypeName, v.dataDict)
end

##------------------------------------------------------------------------------
## solvable
##------------------------------------------------------------------------------

## COMMON: solvable
# getSolvable
# setSolvable!
# isSolvable

## COMMON:

##------------------------------------------------------------------------------
## ppeDict
##------------------------------------------------------------------------------

"""
    $SIGNATURES

Get the PPE dictionary for a variable.  Recommended to use CRUD operations instead, [`getPPE`](@ref), [`addPPE!`](@ref), [`updatePPE!`](@ref), [`deletePPE!`](@ref).
"""
getPPEDict(v::VariableDataLevel1) = v.ppeDict

#TODO FIXME don't know if this should exist, should rather always update with fg object to simplify inmem vs cloud
"""
    $SIGNATURES

Get the parametric point estimate (PPE) for a variable in the factor graph.

Notes
- Defaults on keywords `solveKey` and `method`

Related

getMeanPPE, getMaxPPE, getKDEMean, getKDEFit, getPPEs, getVariablePPEs
"""
function getPPE(vari::VariableDataLevel1, solveKey::Symbol=:default)
    return  getPPEDict(vari)[solveKey]
    # return haskey(ppeDict, solveKey) ? ppeDict[solveKey] : nothing
end

# afew more aliases on PPE, brought back from deprecated DF

"""
    $SIGNATURES

Return full dictionary of PPEs in a variable, recommended to rather use CRUD: [`getPPE`](@ref),
"""
getVariablePPEDict(vari::VariableDataLevel1) = getPPEDict(vari)

getVariablePPE(args...) = getPPE(args...)

##------------------------------------------------------------------------------
## solverDataDict
##------------------------------------------------------------------------------

"""
    $SIGNATURES

Get solver data dictionary for a variable.  Advised to use graph CRUD operations instead.
"""
getSolverDataDict(v::DFGVariable) = v.solverDataDict

# TODO move to crud, don't know if this should exist, should rather always update with fg object to simplify inmem vs cloud
"""
    $SIGNATURES

Retrieve solver data structure stored in a variable.
"""
function getSolverData(v::DFGVariable, key::Symbol=:default)
    #TODO this does not fit in with some of the other error behaviour. but its used so added @error
    vnd =  haskey(v.solverDataDict, key) ? v.solverDataDict[key] : (@error "Variable does not have solver data $(key)"; nothing)
    return vnd
end

#TODO Repeated functionality? same as update
"""
    $SIGNATURES
Set solver data structure stored in a variable.
"""
function setSolverData!(v::DFGVariable, data::VariableNodeData, key::Symbol=:default)
    @assert key == data.solveKey "VariableNodeData.solveKey=:$(data.solveKey) does not match requested :$(key)"
    v.solverDataDict[key] = data
end

##------------------------------------------------------------------------------
## smallData
##------------------------------------------------------------------------------

"""
    $(SIGNATURES)
Get the small data for a variable.
Note: Rather use SmallData CRUD
"""
getSmallData(v::DFGVariable) = v.smallData

"""
    $(SIGNATURES)
Set the small data for a variable.
This will overwrite old smallData.
Note: Rather use SmallData CRUD
"""
function setSmallData!(v::DFGVariable, smallData::Dict{Symbol, SmallDataTypes})
    empty!(v.smallData)
    merge!(v.smallData, smallData)
end

# Generic SmallData CRUD
# TODO optimize for difference in in-memory by extending in other drivers.

"""
    $(SIGNATURES)
Get the small data entry at `key` for variable `label` in `dfg`
"""
function getSmallData(dfg::AbstractDFG, label::Symbol, key::Symbol)
    getVariable(dfg, label).smallData[key]
end

"""
    $(SIGNATURES)
Add a small data pair `key=>value` for variable `label` in `dfg`
"""
function addSmallData!(dfg::AbstractDFG, label::Symbol, pair::Pair{Symbol, <:SmallDataTypes})
    v = getVariable(dfg, label)
    haskey(v.smallData, pair.first) && error("$(pair.first) already exists.")
    push!(v.smallData, pair)
    updateVariable!(dfg, v)
    return v.smallData #or pair TODO
end

"""
    $(SIGNATURES)
Update a small data pair `key=>value` for variable `label` in `dfg`
"""
function updateSmallData!(dfg::AbstractDFG, label::Symbol, pair::Pair{Symbol, <:SmallDataTypes}; warn_if_absent::Bool=true)
    v = getVariable(dfg, label)
    warn_if_absent && !haskey(v.smallData, pair.first) && @warn("$(pair.first) does not exist, adding.")
    push!(v.smallData, pair)
    updateVariable!(dfg, v)
    return v.smallData #or pair TODO
end

"""
    $(SIGNATURES)
Delete a small data entry at `key` for variable `label` in `dfg`
"""
function deleteSmallData!(dfg::AbstractDFG, label::Symbol, key::Symbol)
    v = getVariable(dfg, label)
    rval = pop!(v.smallData, key)
    updateVariable!(dfg, v)
    return rval
end

"""
    $(SIGNATURES)
List all small data keys for a variable `label` in `dfg`
"""
function listSmallData(dfg::AbstractDFG, label::Symbol)
    v = getVariable(dfg, label)
    return collect(keys(v.smallData)) #or pair TODO
end

"""
    $(SIGNATURES)
Empty all small data from variable `label` in `dfg`
"""
function emptySmallData!(dfg::AbstractDFG, label::Symbol)
    v = getVariable(dfg, label)
    empty!(v.smallData)
    updateVariable!(dfg, v)
    return v.smallData #or pair TODO
end

##------------------------------------------------------------------------------
## Data Entries and Blobs
##------------------------------------------------------------------------------

## see DataEntryBlob Folder

##------------------------------------------------------------------------------
## variableTypeName
##------------------------------------------------------------------------------
## getter in DFGVariableSummary only
## can be utility function for others
## TODO this should return the variableType object, or try to. it should be getVariableTypeName for the accessor
## TODO Consider parameter N in variableType for dims, and storing constructor in variableTypeName
## TODO or just not having this function at all
# getVariableType(v::DFGVariableSummary) = v.softypename()
##------------------------------------------------------------------------------

"""
    $SIGNATURES
Retrieve the soft type name symbol for a DFGVariableSummary. ie :Point2, Pose2, etc.
"""
getVariableTypeName(v::DFGVariableSummary) = v.variableTypeName::Symbol

function getVariableType(v::DFGVariableSummary)::InferenceVariable
    @warn "Looking for type in `Main`. Only use if `variableType` has only one implementation, ie. Pose2. Otherwise use the full variable."
    return getfield(Main, v.variableTypeName)()
end

##==============================================================================
## Layer 2 CRUD and SET
##==============================================================================

##==============================================================================
## TAGS - See CommonAccessors
##==============================================================================

##==============================================================================
## Variable Node Data
##==============================================================================
##------------------------------------------------------------------------------
## CRUD: get, add, update, delete
##------------------------------------------------------------------------------

"""
    $(SIGNATURES)
Get variable solverdata for a given solve key.
"""
function getVariableSolverData(dfg::AbstractDFG, variablekey::Symbol, solvekey::Symbol=:default)
    v = getVariable(dfg, variablekey)
    !haskey(v.solverDataDict, solvekey) && error("Solve key '$solvekey' not found in variable '$variablekey'")
    return v.solverDataDict[solvekey]
end

"""
    $(SIGNATURES)
Add variable solver data, errors if it already exists.
"""
function addVariableSolverData!(dfg::AbstractDFG, variablekey::Symbol, vnd::VariableNodeData)
    var = getVariable(dfg, variablekey)
    if haskey(var.solverDataDict, vnd.solveKey)
        error("VariableNodeData '$(vnd.solveKey)' already exists")
    end
    var.solverDataDict[vnd.solveKey] = vnd
    return vnd
end

"""
    $(SIGNATURES)
Add a new solver data  entry from a deepcopy of the source variable solver data.
NOTE: Copies the solver data.
"""
addVariableSolverData!(dfg::AbstractDFG, sourceVariable::DFGVariable, solveKey::Symbol=:default) =
    addVariableSolverData!(dfg, sourceVariable.label, deepcopy(getSolverData(sourceVariable, solveKey)))

"""
    $(SIGNATURES)
Update variable solver data if it exists, otherwise add it.

Notes:
- `useCopy=true` to copy solver data and keep separate memory.
- Use `fields` to updated only a few VND.fields while adhering to `useCopy`.

Related

mergeVariableSolverData!
"""
function updateVariableSolverData!(dfg::AbstractDFG,
                                   variablekey::Symbol,
                                   vnd::VariableNodeData,
                                   useCopy::Bool=true,
                                   fields::Vector{Symbol}=Symbol[];
                                   warn_if_absent::Bool=true)
    #This is basically just setSolverData
    var = getVariable(dfg, variablekey)

    warn_if_absent && !haskey(var.solverDataDict, vnd.solveKey) && @warn "VariableNodeData '$(vnd.solveKey)' does not exist, adding"

    # for InMemoryDFGTypes do memory copy or repointing, for cloud this would be an different kind of update.
    usevnd = useCopy ? deepcopy(vnd) : vnd
    # should just one, or many pointers be updated?
    useExisting = haskey(var.solverDataDict, vnd.solveKey) && isa(var.solverDataDict[vnd.solveKey], VariableNodeData) && length(fields) != 0
    # @error useExisting vnd.solveKey
    if useExisting
      # change multiple pointers inside the VND var.solverDataDict[solvekey]
      for field in fields
        destField = getfield(var.solverDataDict[vnd.solveKey], field)
        srcField = getfield(usevnd, field)
        if isa(destField, Array) && size(destField) == size(srcField)
          # use broadcast (in-place operation)
          destField .= srcField
        else
          # change pointer of destination VND object member
          setfield!(var.solverDataDict[vnd.solveKey], field, srcField)
        end
      end
    else
      # change a single pointer in var.solverDataDict
      var.solverDataDict[vnd.solveKey] = usevnd
    end

    return var.solverDataDict[vnd.solveKey]
end

function updateVariableSolverData!(dfg::AbstractDFG,
                                   variablekey::Symbol,
                                   vnd::VariableNodeData,
                                   solveKey::Symbol,
                                   useCopy::Bool=true,
                                   fields::Vector{Symbol}=Symbol[];
                                   warn_if_absent::Bool=true)

    # TODO not very clean
    if vnd.solveKey != solveKey
        @warn("updateVariableSolverData with solveKey parameter might change in the future, see DFG #565. Future warnings are suppressed", maxlog=1)
        usevnd = useCopy ? deepcopy(vnd) : vnd
        usevnd.solveKey = solveKey
        return updateVariableSolverData!(dfg, variablekey, usevnd, useCopy, fields; warn_if_absent=warn_if_absent)
    else
        return updateVariableSolverData!(dfg, variablekey, vnd, useCopy, fields; warn_if_absent=warn_if_absent)
    end
end

function updateVariableSolverData!( dfg::AbstractDFG,
                                    sourceVariable::DFGVariable,
                                    solveKey::Symbol=:default,
                                    useCopy::Bool=true,
                                    fields::Vector{Symbol}=Symbol[];
                                    warn_if_absent::Bool=true )
    #
    vnd = getSolverData(sourceVariable, solveKey)
    # toshow = listSolveKeys(sourceVariable) |> collect
    # @info "update DFGVar solveKey" solveKey vnd.solveKey
    # @show toshow
    @assert solveKey == vnd.solveKey "VariableNodeData's solveKey=:$(vnd.solveKey) does not match requested :$solveKey"
    updateVariableSolverData!(dfg, sourceVariable.label, vnd, useCopy, fields; warn_if_absent=warn_if_absent)
end

function updateVariableSolverData!(dfg::AbstractDFG,
                                   sourceVariables::Vector{<:DFGVariable},
                                   solveKey::Symbol=:default,
                                   useCopy::Bool=true,
                                   fields::Vector{Symbol}=Symbol[];
                                   warn_if_absent::Bool=true)
    #I think cloud would do this in bulk for speed
    for var in sourceVariables
        updateVariableSolverData!(dfg, var.label, getSolverData(var, solveKey), useCopy, fields; warn_if_absent=warn_if_absent)
    end
end

"""
    $SIGNATURES
Duplicate a supersolve (solveKey).
"""
function deepcopySolvekeys!(dfg::AbstractDFG,
                            dest::Symbol,
                            src::Symbol;
                            solvable::Int=0,
                            labels=ls(dfg, solvable=solvable),
                            verbose::Bool=false  )
  #
  for x in labels
      sd = deepcopy(getSolverData(getVariable(dfg,x), src))
      sd.solveKey = dest
      updateVariableSolverData!(dfg, x, sd, true, Symbol[]; warn_if_absent=verbose )
  end
end
const deepcopySupersolve! = deepcopySolvekeys!

"""
    $(SIGNATURES)
Delete variable solver data, returns the deleted element.
"""
function deleteVariableSolverData!(dfg::AbstractDFG, variablekey::Symbol, solveKey::Symbol=:default)
    var = getVariable(dfg, variablekey)

    if !haskey(var.solverDataDict, solveKey)
        error("VariableNodeData '$(solveKey)' does not exist")
    end
    vnd = pop!(var.solverDataDict, solveKey)
    return vnd
end

"""
    $(SIGNATURES)
Delete variable solver data, returns the deleted element.
"""
deleteVariableSolverData!(dfg::AbstractDFG, sourceVariable::DFGVariable, solveKey::Symbol=:default) =
    deleteVariableSolverData!(dfg, sourceVariable.label, solveKey)

##------------------------------------------------------------------------------
## SET: list, merge
##------------------------------------------------------------------------------

"""
    $(SIGNATURES)
List all the solver data keys in the variable.
"""
function listVariableSolverData(dfg::AbstractDFG, variablekey::Symbol)::Vector{Symbol}
    v = getVariable(dfg, variablekey)
    return collect(keys(v.solverDataDict))
end

"""
    $(SIGNATURES)
Merges and updates solver and estimate data for a variable (variable can be from another graph).
If the same key is present in another collection, the value for that key will be the value it has in the last collection listed (updated).
Note: Makes a copy of the estimates and solver data so that there is no coupling between graphs.
"""
function mergeVariableSolverData!(destVariable::DFGVariable, sourceVariable::DFGVariable)
    # We don't know which graph this came from, must be copied!
    merge!(destVariable.solverDataDict, deepcopy(sourceVariable.solverDataDict))
    return destVariable
end

mergeVariableSolverData!(dfg::AbstractDFG, sourceVariable::DFGVariable) =     mergeVariableSolverData!(getVariable(dfg,getLabel(sourceVariable)), sourceVariable)

##==============================================================================
## Point Parametric Estimates
##==============================================================================

##------------------------------------------------------------------------------
## CRUD: get, add, update, delete
##------------------------------------------------------------------------------

"""
    $(SIGNATURES)
Get the parametric point estimate (PPE) for a variable in the factor graph for a given solve key.

Notes
- Defaults on keywords `solveKey` and `method`

Related
getMeanPPE, getMaxPPE, getKDEMean, getKDEFit, getPPEs, getVariablePPEs
"""
function getPPE(dfg::AbstractDFG, variablekey::Symbol, ppekey::Symbol=:default)
    v = getVariable(dfg, variablekey)
    !haskey(v.ppeDict, ppekey) && error("PPE key '$ppekey' not found in variable '$variablekey'")
    return v.ppeDict[ppekey]
end

# Not the most efficient call but it at least reuses above (in memory it's probably ok)
getPPE(dfg::AbstractDFG, sourceVariable::VariableDataLevel1, ppekey::Symbol=:default) = getPPE(dfg, sourceVariable.label, ppekey)

"""
    $(SIGNATURES)
Add variable PPE, errors if it already exists.
"""
function addPPE!(dfg::AbstractDFG, variablekey::Symbol, ppe::P) where {P <: AbstractPointParametricEst}
    var = getVariable(dfg, variablekey)
    if haskey(var.ppeDict, ppe.solveKey)
        error("PPE '$(ppe.solveKey)' already exists")
    end
    var.ppeDict[ppe.solveKey] = ppe
    return ppe
end

"""
    $(SIGNATURES)
Add a new PPE entry from a deepcopy of the source variable PPE.
NOTE: Copies the PPE.
"""
addPPE!(dfg::AbstractDFG, sourceVariable::DFGVariable, ppekey::Symbol=:default) =
    addPPE!(dfg, sourceVariable.label, deepcopy(getPPE(sourceVariable, ppekey)))

"""
    $(SIGNATURES)
Update PPE data if it exists, otherwise add it -- one call per `key::Symbol=:default`.
"""
function updatePPE!(dfg::AbstractDFG, variablekey::Symbol, ppe::AbstractPointParametricEst; warn_if_absent::Bool=true)
    var = getVariable(dfg, variablekey)
    if warn_if_absent && !haskey(var.ppeDict, ppe.solveKey)
        @warn "PPE '$(ppe.solveKey)' does not exist, adding"
    end
    #for InMemoryDFGTypes, cloud would update here
    var.ppeDict[ppe.solveKey] = ppe
    return ppe
end

"""
    $(SIGNATURES)
Update PPE data if it exists, otherwise add it.
NOTE: Copies the PPE data.
"""
updatePPE!(dfg::AbstractDFG, sourceVariable::VariableDataLevel1, ppekey::Symbol=:default; warn_if_absent::Bool=true) =
    updatePPE!(dfg, sourceVariable.label, deepcopy(getPPE(sourceVariable, ppekey)); warn_if_absent=warn_if_absent)

"""
    $(SIGNATURES)
Update PPE data if it exists, otherwise add it.
"""
function updatePPE!(dfg::AbstractDFG, sourceVariables::Vector{<:VariableDataLevel1}, ppekey::Symbol=:default; warn_if_absent::Bool=true)
    #I think cloud would do this in bulk for speed
    for var in sourceVariables
        updatePPE!(dfg, var.label, getPPE(dfg, var, ppekey); warn_if_absent=warn_if_absent)
    end
end

"""
    $(SIGNATURES)
Delete PPE data, returns the deleted element.
"""
function deletePPE!(dfg::AbstractDFG, variablekey::Symbol, ppekey::Symbol=:default)
    var = getVariable(dfg, variablekey)

    if !haskey(var.ppeDict, ppekey)
        error("VariableNodeData '$(ppekey)' does not exist")
    end
    vnd = pop!(var.ppeDict, ppekey)
    return vnd
end

"""
    $(SIGNATURES)
Delete PPE data, returns the deleted element.
"""
deletePPE!(dfg::AbstractDFG, sourceVariable::DFGVariable, ppekey::Symbol=:default) =
    deletePPE!(dfg, sourceVariable.label, ppekey)

##------------------------------------------------------------------------------
## SET: list, merge
##------------------------------------------------------------------------------

"""
    $(SIGNATURES)
List all the PPE data keys in the variable.
"""
function listPPEs(dfg::AbstractDFG, variablekey::Symbol)
    v = getVariable(dfg, variablekey)
    return collect(keys(v.ppeDict))::Vector{Symbol}
end

#TODO API and only correct level
"""
    $(SIGNATURES)
Merges and updates solver and estimate data for a variable (variable can be from another graph).
Note: Makes a copy of the estimates and solver data so that there is no coupling between graphs.
"""
function mergePPEs!(destVariable::AbstractDFGVariable, sourceVariable::AbstractDFGVariable)
    # We don't know which graph this came from, must be copied!
    merge!(destVariable.ppeDict, deepcopy(sourceVariable.ppeDict))
    return destVariable
end


text:
using FunctionEnsembles
using Base.Test

v = [sin,cos]
e = Ensemble(v)
@test e[1] === v[1] # e behaves very much like a vector
@test length(e) == length(v)

@test e(1) == @ensemble(v(1)) == @ensemble([sin,cos](1)) == [v[1](1), v[2](1)] # These are all equivalent
@test @ensemble(e(1)) == e(1)
@ensemble gg = [sin,cos](1)
@test gg == e(1)

@test e(+,0,1) == sum(e(1)) # Works like reduce

a = randn(4)
sum(abs2, a)
mean(abs2, a)
@test std(abs2.(a)) == @functionfirst std(abs2, a)
@test std(abs2.(a)) == @functionfirst std(a) do x
    abs2(x)
end


text:
# For Julia operator precedences, see
# https://raw.githubusercontent.com/JuliaLang/julia/master/src/julia-parser.scm

test = """
    1 + 2 * 3 + 4 * 5 + 6
    1 + (2 * 3) + (4 * (5 + 6))
    2 * 3 + (4 * 5)
    5 + (8 * 3 + 9 + 3 * 4 * 3)
    5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))
    ((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2
    """

function eval_input(io, pairs...)
    return sum([eval_expr(line, pairs...) for line in readlines(io)])
end

function eval_expr(input::AbstractString, pairs...)
    join(replace(split(input, ""), pairs...), "") |> Meta.parse |> eval
end

# + and * have equal precedence
q1(io) = eval_input(io, "*" => "⊕")
a ⊕ b = a * b

# + and * have swapped precedence
q2(io) = eval_input(io, "*" => "⊞", "+" => "⊠")
a ⊞ b = a * b
a ⊠ b = a + b

@assert q1(IOBuffer(test)) == 71 + 51 + 26 + 437 + 12240 + 13632
@assert q2(IOBuffer(test)) == 231 + 51 + 46 + 1445 + 669060 + 23340

println("Q1: ", q1("day18.in"))
println("Q2: ", q2("day18.in"))

max_stars_repo_name: dhanak/competitive-coding

max_issues_repo_name: dhanak/competitive-coding

max_forks_repo_name: dhanak/competitive-coding


text:
"""
pn.jl
"""

"""
$(TYPEDEF)
Projected Newton Solver
Direct method developed by the REx Lab at Stanford University
Achieves machine-level constraint satisfaction by projecting onto the feasible subspace.
It can also take a full Newton step by solving the KKT system.
This solver is to be used exlusively for solutions that are close to the optimal solution.
It is intended to be used as a "solution polishing" method for augmented Lagrangian methods.
"""
struct ProjectedNewtonSolver{T,Tm,To,Tx,Tix,Tu,Tiu,TH,Tg,TE,TD,Td} <: ConstrainedSolver{T}
    # problem info
    n::Int
    m::Int
    N::Int
    model::Tm
    obj::To
    convals::Vector{Vector{ConVal}}
    # trajectory
    X::Vector{Tx}
    X_tmp::Vector{Tx}
    # state indices in global constraint
    x_ginds::Vector{Tix}
    U::Vector{Tu}
    U_tmp::Vector{Tu}
    # control indices in global constraint
    u_ginds::Vector{Tiu}
    # global derivatives
    H::TH
    g::Tg
    E::TE
    # global constraints
    # constraint jacobian
    D::TD
    # constraint values
    d::Td
    # duals
    λ::Td
    # active set
    a::Vector{Bool}
    # misc
    opts::SolverOptions{T}
    stats::SolverStats{T}
    solver_name::Symbol
end

function ProjectedNewtonSolver(prob::Problem{IR,T}, opts::SolverOptions,
                               stats::SolverStats) where {IR,T}
    n, m, N = size(prob)
    NZ = n * N + m * (N - 1)
    M = prob.M
    V = prob.V
    # derivatives
    H = spzeros(NZ, NZ)
    g = zeros(NZ)
    # count number of constraint values
    NP = 0
    for convals_ in prob.convals
        for conval in convals_
            NP += length(conval.con)
        end
    end
    # constraints
    D = spzeros(NP, NZ)
    d = zeros(NP)
    λ = zeros(NP)
    a = zeros(Bool, NP)
    # build x_ginds and u_ginds
    x_ginds = [V((1:n) .+ k * (n + m)) for k = 0:N - 1]
    u_ginds = [V((1:m) .+ (n + k * (n + m))) for k = 0:N - 2]
    # put it all together
    Tm = typeof(prob.model)
    To = typeof(prob.obj)
    Tx = eltype(prob.X)
    Tix = eltype(x_ginds)
    Tu = eltype(prob.U)
    Tiu = eltype(u_ginds)
    TH = typeof(H)
    Tg = typeof(g)
    TE = typeof(prob.E)
    TD = typeof(D)
    Td = typeof(d)
    return ProjectedNewtonSolver{T,Tm,To,Tx,Tix,Tu,Tiu,TH,Tg,TE,TD,Td}(
        n, m, N, prob.model, prob.obj, prob.convals, prob.X, prob.X_tmp, x_ginds,
        prob.U, prob.U_tmp, u_ginds, H, g, prob.E, D, d, λ, a, opts, stats, :ProjectedNewton
    )
end

# methods
Base.size(solver::ProjectedNewtonSolver) = solver.n, solver.m, solver.N


text:
module DataValues

using Dates

export DataValue, DataValueException, NA

export DataValueArray, DataValueVector, DataValueMatrix

export isna, hasvalue, dropna, dropna!, padna!, padna

include("scalar/core.jl")
# TODO 0.7 migration, enable again
# include("scalar/broadcast.jl")
include("scalar/operations.jl")

include("array/typedefs.jl")
include("array/constructors.jl")
include("array/indexing.jl")
include("array/datavaluevector.jl")
include("array/primitives.jl")
# TODO 0.7 migration, enable again
# include("array/broadcast.jl")
include("array/reduce.jl")
include("array/promotion.jl")

# include("utils.jl")

end


text:
# REPL tests
let exename=joinpath(JULIA_HOME,(ccall(:jl_is_debugbuild,Cint,())==0?"julia":"julia-debug"))

# Test REPL in dumb mode
@unix_only begin

const O_RDWR = Base.FS.JL_O_RDWR
const O_NOCTTY = Base.FS.JL_O_NOCTTY

fdm = ccall(:posix_openpt,Cint,(Cint,),O_RDWR|O_NOCTTY)
fdm == -1 && error("Failed to open PTY master")
rc = ccall(:grantpt,Cint,(Cint,),fdm)
rc != 0 && error("grantpt failed")
rc = ccall(:unlockpt,Cint,(Cint,),fdm)
rc != 0 && error("unlockpt")

fds = ccall(:open,Cint,(Ptr{Uint8},Cint),ccall(:ptsname,Ptr{Uint8},(Cint,),fdm), O_RDWR|O_NOCTTY)

# slave
slave   = RawFD(fds)
master = Base.TTY(RawFD(fdm); readable = true)

nENV = copy(ENV)
nENV["TERM"] = "dumb"
p = spawn(setenv(`$exename -f --quiet`,nENV),slave,slave,slave)
start_reading(master)
Base.wait_readnb(master,1)
write(master,"1\nquit()\n")

wait(p)

output = readavailable(master)
@test output == "julia> 1\r\nquit()\r\n1\r\n\r\njulia> "

close(master)
ccall(:close,Cint,(Cint,),fds)

end

# Test stream mode
outs, ins, p = readandwrite(`$exename -f --quiet`)
write(ins,"1\nquit()\n")
@test readall(outs) == "1\n"
end

max_stars_repo_name: porterjamesj/julia

max_issues_repo_name: porterjamesj/julia

max_forks_repo_name: porterjamesj/julia


text:
srcdir = "src/htslib/"
rootdir = "htslib-1.10.2/"
headerfiles = [
    "htslib/bgzf.h",
    "htslib/knetfile.h",
    "htslib/kstring.h",
    "htslib/kfunc.h",
    "htslib/hfile.h",
    "htslib/hts_os.h",
    "htslib/hts_log.h",
    "htslib/faidx.h",
    "htslib/hts.h",
    "htslib/tbx.h",
    "htslib/regidx.h",
    "htslib/sam.h",
    "htslib/cram.h",
]
for headerfile in headerfiles
    headerfile = relpath(normpath(joinpath(rootdir, headerfile)))
    @assert startswith(headerfile, rootdir)
    translatedfile = joinpath(srcdir, string(splitext(headerfile)[1][lastindex(rootdir)+1:end], ".jl"))
    println(headerfile, " => ", translatedfile)
    run(pipeline(headerfile, `julia scripts/translate_exported_functions.jl`, translatedfile))
end


text:
using BasisFunctions, LinearAlgebra, DomainSets, GridArrays, Test, StaticArrays, FrameFun

@testset begin
    B = (Fourier(11) → -1..1)^2
    Dom = Disk(0.8)
    @test support(dictionary(∂x(random_expansion(extensionframe(B, Dom)))))≈Dom

    # @test SamplingStyle(ExtensionFramePlatform(FrameFun.ProductPlatform(FourierPlatform(),FourierPlatform()),(0.0..0.5)^2)) ==
    #     ProductSamplingStyle(OversamplingStyle(),OversamplingStyle())

    @test dictionary(_ap(Fourier(100),0.0..0.5)) == extensionframe(Fourier(100),0.0..0.5)
    # Test defaults
    @test AZ_A(Fourier(100),0.0..0.5; samplingstyle=OversamplingStyle(),oversamplingfactor=2,normalizedsampling=false)≈
        AZ_A(Fourier(100),0.0..0.5)

    ap0 = _ap(Fourier(100), 0.0..0.5; samplingstyle=OversamplingStyle(), oversamplingfactor=2, normalizedsampling=false)
    A = AZ_A(ap0)
    L = samplingparameter(ap0)
    a1 = evaluation(Fourier(L),interpolation_grid(Fourier(L)))
    a2 = IndexRestriction(GridBasis(interpolation_grid(Fourier(L))),1:200)
    a3 = BasisFunctions.FourierIndexExtension(Fourier(100),Fourier(L))
    @test A≈a2*a1*a3

    ap1 = approximationproblem(Fourier(100), 0.0..0.5; samplingstyle=OversamplingStyle(), oversamplingfactor=2, normalizedsampling=true)
    A = AZ_A(ap1)
    L = samplingparameter(ap1)
    a1 = evaluation(Fourier(L),interpolation_grid(Fourier(L)))
    a2 = IndexRestriction(GridBasis(interpolation_grid(Fourier(L))),1:200)
    a3 = BasisFunctions.FourierIndexExtension(Fourier(100),Fourier(L))
    a4 = ScalingOperator(dest(a2),1/sqrt(L))
    @test A≈a4*a2*a1*a3

    # Test differnence sampling_normalization
    ap2 = approximationproblem(Fourier(100),0.0..0.5;
            samplingstyle=OversamplingStyle(), oversamplingfactor=2, normalizedsampling=false)
    s = svdvals(AZ_A(ap2))
    N = sampling_weights(FrameFun.NormalizedSampling(OversamplingStyle()),approximationproblem(Fourier(100),0.0..0.5))
    L = samplingparameter(ap2)
    @test L == 399
    @test N[1] ≈ 1/sqrt(L)
    @test 47==sum(s.<.1*sqrt(L))
    @test 49==sum(s.>.9*sqrt(L))

    s = svdvals(AZ_A(Fourier(100),0.0..0.5;oversamplingfactor=2,normalizedsampling=true))
    @test 47==sum(s.<.1)
    @test 49==sum(1+1e-10 .> s .>.9)

    # right side should be appropriately normalized
    @test sample_data(exp, Fourier(100), 0.0..0.5; oversamplingfactor=2,normalizedsampling=true)≈
        1/sqrt(399)*GridSampling(subgrid(interpolation_grid(Fourier(399)),0.0..0.5))*exp

    # left side should be appropriately normalized
    @test AZ_A(Fourier(100),0.0..0.5;samplingstyle=OversamplingStyle(),oversamplingfactor=2,normalizedsampling=true)≈
        discretization(exp, Fourier(100), 0.0..0.5; oversamplingfactor=2,normalizedsampling=true)

    @test sample_data(exp, Fourier(100),0.0..0.5; oversamplingfactor=2,normalizedsampling=false)≈
        GridSampling(subgrid(interpolation_grid(Fourier(399)),0.0..0.5))*exp

    @test AZ_A(Fourier(100), 0.0..0.5; samplingstyle=OversamplingStyle(),oversamplingfactor=2,normalizedsampling=false)≈
        discretization(exp, Fourier(100), 0.0..0.5; oversamplingfactor=2, normalizedsampling=false)

    F = approximate(exp, Fourier(100), 0.0..0.5; samplingstyle=OversamplingStyle(),oversamplingfactor=2,normalizedsampling=true)
    @test abs(F[1](.2)-exp(.2) )< 1e-12

    F = approximate(exp, Fourier(100), 0.0..0.5; samplingstyle=OversamplingStyle(),oversamplingfactor=2,normalizedsampling=false)
    @test abs(F[1](.2)-exp(.2) )< 1e-12

    P = WeightedSumPlatform(FourierPlatform(),x->1,x->sqrt(x))
    ap = approximationproblem(P,(10,10))
    azdual(ap)
end


text:
function get_current_state(obj::FieldOrekitStepInterpolator)
    return jcall(obj, "getCurrentState", FieldSpacecraftState, ())
end

function get_interpolated_state(obj::FieldOrekitStepInterpolator, arg0::FieldAbsoluteDate)
    return jcall(obj, "getInterpolatedState", FieldSpacecraftState, (FieldAbsoluteDate,), arg0)
end

function get_previous_state(obj::FieldOrekitStepInterpolator)
    return jcall(obj, "getPreviousState", FieldSpacecraftState, ())
end

function is_forward(obj::FieldOrekitStepInterpolator)
    return jcall(obj, "isForward", jboolean, ())
end


text:
#=

Running a very large-scale example with 1e9 variables (note this requires a lot of RAM).

Problem is quite simple: minimize || x - p ||^2 over the probability simplex

NOTE.
1. running standard FW with agnostic step-size here as overhead from line searches etc is quite substantial
2. observe that the memory consummption is sub-linear in the number of iterations

=#

include("activate.jl")

using LinearAlgebra

n = Int(1e7)
k = 1000

xpi = rand(n);
total = sum(xpi);
const xp = xpi ./ total;

f(x) = norm(x - xp)^2
function grad!(storage, x)
    @. storage = 2 * (x - xp)
end

# better for memory consumption as we do coordinate-wise ops

function cf(x, xp)
    return LinearAlgebra.norm(x .- xp)^2
end

function cgrad!(storage, x, xp)
    return @. storage = 2 * (x - xp)
end

lmo = FrankWolfe.ProbabilitySimplexOracle(1);
x0 = FrankWolfe.compute_extreme_point(lmo, zeros(n));

FrankWolfe.benchmark_oracles(
    x -> cf(x, xp),
    (str, x) -> cgrad!(str, x, xp),
    () -> randn(n),
    lmo;
    k=100,
)

@time x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(
    x -> cf(x, xp),
    (str, x) -> cgrad!(str, x, xp),
    lmo,
    x0,
    max_iteration=k,
    line_search=FrankWolfe.Agnostic(),
    print_iter=k / 10,
    emphasis=FrankWolfe.memory,
    verbose=true,
);


text:
module OrbitalTrajectories

    using Reexport
    using GeneralizedGenerated: NGG

    function __init__()
        # XXX: Ensure that NGG is initialized appropriately, so that
        # GeneralizedGenerated functions work properly. See the NGG_modules constant.
        map(NGG.module_index, NGG_modules)
        nothing
    end

    #----------#
    # INCLUDES #
    #----------#
    include("piracy.jl")

    include("SPICE/spice.jl")
    include("dynamics/dynamics.jl")

    #----------------#
    # IMPORT MODULES #
    #----------------#
    @reexport using OrbitalTrajectories.Dynamics
    @reexport using OrbitalTrajectories.SpiceUtils

    #-----------#
    # CONSTANTS #
    #-----------#
    # Output of this gives the order that we should touch module_index() in __init__
    const NGG_modules = NGG._modules

end # module


text:
import Dates

import ..AstroDates: DateTime, year, month, day,
    hour, minute, second, millisecond,
    time, date, fractionofday, yearmonthday, dayofyear

export timescale

timescale(ep::Epoch{S}) where {S} = S

function DateTime(ep::Epoch)
    if !isfinite(ep.offset)
        if ep.offset < 0
            return DateTime(AstroDates.MIN_EPOCH, AstroDates.H00)
        else
            return DateTime(AstroDates.MAX_EPOCH, Time(23, 59, 59.999))
        end
    end

    sum = ep.offset + ep.ts_offset
    o′ = sum - ep.ts_offset
    d′ = sum - o′
    Δo = ep.offset - o′
    Δd = ep.ts_offset - d′
    residual = Δo + Δd

    carry = floor(Int64, sum)
    offset2000B = (sum - carry) + residual
    offset2000A = ep.epoch + carry + Int64(43200)
    if offset2000B < 0
        offset2000A -= 1
        offset2000B += 1
    end
    time = offset2000A % Int64(86400)
    if time < 0
        time += Int64(86400)
    end
    date = Int((offset2000A - time) ÷ Int64(86400))

    date_comp = Date(AstroDates.J2000_EPOCH, date)
    time_comp = Time(time, offset2000B)

    if insideleap(ep)
        leap = getleap(ep)
        h = hour(time_comp)
        m = minute(time_comp)
        s = second(Float64, time_comp) + leap
        time_comp = Time(h, m, s)
    end

    DateTime(date_comp, time_comp)
end

"""
    year(ep::Epoch)

Get the year of the epoch `ep`.
"""
year(ep::Epoch) = year(DateTime(ep))

"""
    month(ep::Epoch)

Get the month of the epoch `ep`.
"""
month(ep::Epoch) = month(DateTime(ep))

"""
    day(ep::Epoch)

Get the day of the epoch `ep`.
"""
day(ep::Epoch) = day(DateTime(ep))

"""
    yearmonthday(ep::Epoch)

Get the year, month, and day of the epoch `ep` as a tuple.
"""
yearmonthday(ep::Epoch) = yearmonthday(DateTime(ep))

"""
    dayofyear(ep::Epoch)

Get the day of the year of the epoch `ep`.
"""
dayofyear(ep::Epoch) = dayofyear(DateTime(ep))

"""
    hour(ep::Epoch)

Get the hour of the epoch `ep`.
"""
hour(ep::Epoch) = hour(DateTime(ep))

"""
    minute(ep::Epoch)

Get the minute of the epoch `ep`.
"""
minute(ep::Epoch) = minute(DateTime(ep))

"""
    second(type, ep::Epoch)

Get the second of the epoch `ep` as a `type`.
"""
second(typ, ep::Epoch) = second(typ, DateTime(ep))

"""
    second(ep::Epoch) -> Int

Get the second of the epoch `ep` as an `Int`.
"""
second(ep::Epoch) = second(Int, DateTime(ep))

"""
    millisecond(ep::Epoch)

Get the number of milliseconds of the epoch `ep`.
"""
millisecond(ep::Epoch) = millisecond(DateTime(ep))

"""
    time(ep::Epoch)

Get the time of the epoch `ep`.
"""
time(ep::Epoch) = time(DateTime(ep))

"""
    date(ep::Epoch)

Get the date of the epoch `ep`.
"""
date(ep::Epoch) = date(DateTime(ep))

"""
    fractionofday(ep::Epoch)

Get the time of the day of the epoch `ep` as a fraction.
"""
fractionofday(ep::Epoch) = fractionofday(time(ep))

"""
    Dates.DatetTime(ep::Epoch)

Convert the epoch `ep` to a `Dates.DateTime`.
"""
Dates.DateTime(ep::Epoch) = Dates.DateTime(DateTime(ep))


text:
JSON.json(jws::JSONWorksheet) = JSON.json(data(jws))
JSON.json(jws::JSONWorksheet, indent) = JSON.json(data(jws), indent)

function write(file::Union{String, IO}, jws::JSONWorksheet; indent = 2, drop_null = false)
    open(file, "w") do io
        data = JSON.json(jws, indent)
        # drop null array such as [null, null, ....]
        if drop_null
            data = replace(data, r"(\"[\w]*\":null,)|(,?\"[\w]*\":null)" => "")
        end
        Base.write(io, data)
    end
end

function write(path::String, jwb::JSONWorkbook; kwargs...)
    f = splitext(basename(xlsxpath(jwb)))[1]
    for s in sheetnames(jwb)
        write(joinpath(path, "$(f)_$(s).json"), jwb[s]; kwargs...)
    end
end

function write_xlsx(file::String, jwb::JSONWorkbook; delim = ";", anchor_cell = "A1")
    XLSX.openxlsx(file, mode="w") do xf

        for (i, s) in enumerate(sheetnames(jwb))
            jws = jwb[s]
            if i == 1
                sheet = xf[1]
                XLSX.rename!(sheet, s)
            else
                sheet = XLSX.addsheet!(xf, s)
            end

            labels = map(el -> "/" * join(el.tokens, "/"), jws.pointer)
            columns = []
            for p in jws.pointer
                data = get.(jws.data, Ref(p), missing)
                if eltype(data) <: Array
                    data = join.(data, delim)
                end
                push!(columns, data)
            end

            XLSX.writetable!(sheet, columns, labels, anchor_cell=XLSX.CellRef(anchor_cell))
        end
    end
end

max_issues_repo_name: devsisters/XLSXasJSON

max_forks_repo_name: devsisters/XLSXasJSON


text:
using GRAMPC
using Documenter

DocMeta.setdocmeta!(GRAMPC, :DocTestSetup, :(using GRAMPC); recursive=true)

makedocs(;
    modules=[GRAMPC],
    authors="Ian McInerney and contributors",
    repo="https://github.com/imciner2/GRAMPC.jl/blob/{commit}{path}#{line}",
    sitename="GRAMPC.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://imciner2.github.io/GRAMPC.jl",
        assets=String[],
    ),
    pages=
    [
        "Home" => "index.md",
        "Usage" =>
        [
            "Solver Options" => "options.md"
        ],
        "Internals" =>
        [
            "Error Handling" => "error_handling.md",
            "Problem Functions" => "problem_functions.md"
        ]
    ],
)

#deploydocs(;
#    repo="github.com/imciner2/GRAMPC.jl",
#)