licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 4027 | ## Gradient Enhanced Kriging
Gradient-enhanced Kriging is an extension of kriging which supports gradient information. GEK is usually more accurate than kriging. However, it is not computationally efficient when the number of inputs, the number of sampling points, or both, are high. This is mainly due to the size of the corresponding correlation matrix, which increases proportionally with both the number of inputs and the number of sampling points.
Let's have a look at the following function to use Gradient Enhanced Surrogate:
``f(x) = sin(x) + 2*x^2``
First of all, we will import `Surrogates` and `Plots` packages:
```@example GEK1D
using Surrogates
using Plots
default()
```
### Sampling
We choose to sample f in 8 points between 0 and 1 using the `sample` function. The sampling points are chosen using a Sobol sequence, this can be done by passing `SobolSample()` to the `sample` function.
```@example GEK1D
n_samples = 10
lower_bound = 2
upper_bound = 10
xs = lower_bound:0.001:upper_bound
x = sample(n_samples, lower_bound, upper_bound, SobolSample())
f(x) = x^3 - 6x^2 + 4x + 12
y1 = f.(x)
der = x -> 3 * x^2 - 12 * x + 4
y2 = der.(x)
y = vcat(y1, y2)
scatter(x, y1, label = "Sampled points", xlims = (lower_bound, upper_bound), legend = :top)
plot!(f, label = "True function", xlims = (lower_bound, upper_bound), legend = :top)
```
### Building a surrogate
With our sampled points, we can build the Gradient Enhanced Kriging surrogate using the `GEK` function.
```@example GEK1D
my_gek = GEK(x, y, lower_bound, upper_bound, p = 1.4);
scatter(x, y1, label = "Sampled points", xlims = (lower_bound, upper_bound), legend = :top)
plot!(f, label = "True function", xlims = (lower_bound, upper_bound), legend = :top)
plot!(my_gek, label = "Surrogate function", ribbon = p -> std_error_at_point(my_gek, p),
xlims = (lower_bound, upper_bound), legend = :top)
```
## Gradient Enhanced Kriging Surrogate Tutorial (ND)
First of all, let's define the function we are going to build a surrogate for.
```@example GEK_ND
using Plots # hide
default(c = :matter, legend = false, xlabel = "x", ylabel = "y") # hide
using Surrogates # hide
```
Now, let's define the function:
```@example GEK_ND
function leon(x)
x1 = x[1]
x2 = x[2]
term1 = 100 * (x2 - x1^3)^2
term2 = (1 - x1)^2
y = term1 + term2
end
```
### Sampling
Let's define our bounds, this time we are working in two dimensions. In particular, we want our first dimension `x` to have bounds `0, 10`, and `0, 10` for the second dimension. We are taking 80 samples of the space using Sobol Sequences. We then evaluate our function on all the sampling points.
```@example GEK_ND
n_samples = 45
lower_bound = [0, 0]
upper_bound = [10, 10]
xys = sample(n_samples, lower_bound, upper_bound, SobolSample())
y1 = leon.(xys);
```
```@example GEK_ND
x, y = 0:10, 0:10 # hide
p1 = surface(x, y, (x1, x2) -> leon((x1, x2))) # hide
xs = [xy[1] for xy in xys] # hide
ys = [xy[2] for xy in xys] # hide
scatter!(xs, ys, y1) # hide
p2 = contour(x, y, (x1, x2) -> leon((x1, x2))) # hide
scatter!(xs, ys) # hide
plot(p1, p2, title = "True function") # hide
```
### Building a surrogate
Using the sampled points, we build the surrogate, the steps are analogous to the 1-dimensional case.
```@example GEK_ND
grad1 = x1 -> 2 * (300 * (x[1])^5 - 300 * (x[1])^2 * x[2] + x[1] - 1)
grad2 = x2 -> 200 * (x[2] - (x[1])^3)
d = 2
n = 10
function create_grads(n, d, grad1, grad2, y)
c = 0
y2 = zeros(eltype(y[1]), n * d)
for i in 1:n
y2[i + c] = grad1(x[i])
y2[i + c + 1] = grad2(x[i])
c = c + 1
end
return y2
end
y2 = create_grads(n, d, grad2, grad2, y)
y = vcat(y1, y2)
```
```@example GEK_ND
my_GEK = GEK(xys, y, lower_bound, upper_bound, p = [1.9, 1.9])
```
```@example GEK_ND
p1 = surface(x, y, (x, y) -> my_GEK([x y])) # hide
scatter!(xs, ys, y1, marker_z = y1) # hide
p2 = contour(x, y, (x, y) -> my_GEK([x y])) # hide
scatter!(xs, ys, marker_z = y1) # hide
plot(p1, p2, title = "Surrogate") # hide
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 2923 | ## GEKPLS Surrogate Tutorial
Gradient Enhanced Kriging with Partial Least Squares Method (GEKPLS) is a surrogate modeling technique that brings down computation time and returns improved accuracy for high-dimensional problems. The Julia implementation of GEKPLS is adapted from the Python version by [SMT](https://github.com/SMTorg) which is based on this [paper](https://arxiv.org/pdf/1708.02663.pdf).
The following are the inputs when building a GEKPLS surrogate:
1. x - The vector containing the training points
2. y - The vector containing the training outputs associated with each of the training points
3. grads - The gradients at each of the input X training points
4. n_comp - Number of components to retain for the partial least squares regression (PLS)
5. delta_x - The step size to use for the first order Taylor approximation
6. lb - The lower bound for the training points
7. ub - The upper bound for the training points
8. extra_points - The number of additional points to use for the PLS
9. theta - The hyperparameter to use for the correlation model
### Basic GEKPLS Usage
The following example illustrates how to use GEKPLS:
```@example gekpls_water_flow
using Surrogates
using Zygote
function water_flow(x)
r_w = x[1]
r = x[2]
T_u = x[3]
H_u = x[4]
T_l = x[5]
H_l = x[6]
L = x[7]
K_w = x[8]
log_val = log(r / r_w)
return (2 * pi * T_u * (H_u - H_l)) /
(log_val * (1 + (2 * L * T_u / (log_val * r_w^2 * K_w)) + T_u / T_l))
end
n = 1000
lb = [0.05, 100, 63070, 990, 63.1, 700, 1120, 9855]
ub = [0.15, 50000, 115600, 1110, 116, 820, 1680, 12045]
x = sample(n, lb, ub, SobolSample())
grads = gradient.(water_flow, x)
y = water_flow.(x)
n_test = 100
x_test = sample(n_test, lb, ub, GoldenSample())
y_true = water_flow.(x_test)
n_comp = 2
delta_x = 0.0001
extra_points = 2
initial_theta = [0.01 for i in 1:n_comp]
g = GEKPLS(x, y, grads, n_comp, delta_x, lb, ub, extra_points, initial_theta)
y_pred = g.(x_test)
rmse = sqrt(sum(((y_pred - y_true) .^ 2) / n_test)) #root mean squared error
println(rmse) #0.0347
```
### Using GEKPLS With Surrogate Optimization
GEKPLS can also be used to find the minimum of a function with the surrogates.jl optimization function.
This next example demonstrates how this can be accomplished.
```@example gekpls_optimization
using Surrogates
using Zygote
function sphere_function(x)
return sum(x .^ 2)
end
lb = [-5.0, -5.0, -5.0]
ub = [5.0, 5.0, 5.0]
n_comp = 2
delta_x = 0.0001
extra_points = 2
initial_theta = [0.01 for i in 1:n_comp]
n = 100
x = sample(n, lb, ub, SobolSample())
grads = gradient.(sphere_function, x)
y = sphere_function.(x)
g = GEKPLS(x, y, grads, n_comp, delta_x, lb, ub, extra_points, initial_theta)
x_point, minima = surrogate_optimize(sphere_function, SRBF(), lb, ub, g,
RandomSample(); maxiters = 20,
num_new_samples = 20, needs_gradient = true)
println(minima)
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 1885 | ## Gramacy & Lee Function
the Gramacy & Lee function is a continuous function. It is not convex. The function is defined on a 1-dimensional space. It is unimodal. The function can be defined on any input domain, but it is usually evaluated on
``x \in [-0.5, 2.5]``.
The Gramacy & Lee is as follows:
``f(x) = \frac{\sin(10\pi x)}{2x} + (x-1)^4``.
Let's import these two packages `Surrogates` and `Plots`:
```@example gramacylee1D
using Surrogates
using SurrogatesPolyChaos
using Plots
default()
```
Now, let's define our objective function:
```@example gramacylee1D
function gramacylee(x)
term1 = sin(10 * pi * x) / 2 * x
term2 = (x - 1)^4
y = term1 + term2
end
```
Let's sample f in 25 points between -0.5 and 2.5 using the `sample` function. The sampling points are chosen using a Sobol sample, this can be done by passing `SobolSample()` to the `sample` function.
```@example gramacylee1D
n = 25
lower_bound = -0.5
upper_bound = 2.5
x = sample(n, lower_bound, upper_bound, SobolSample())
y = gramacylee.(x)
xs = lower_bound:0.001:upper_bound
scatter(x, y, label = "Sampled points", xlims = (lower_bound, upper_bound),
ylims = (-5, 20), legend = :top)
plot!(xs, gramacylee.(xs), label = "True function", legend = :top)
```
Now, let's fit Gramacy & Lee function with different surrogates:
```@example gramacylee1D
my_pol = PolynomialChaosSurrogate(x, y, lower_bound, upper_bound)
loba_1 = LobachevskySurrogate(x, y, lower_bound, upper_bound)
krig = Kriging(x, y, lower_bound, upper_bound)
scatter(x, y, label = "Sampled points", xlims = (lower_bound, upper_bound),
ylims = (-5, 20), legend = :top)
plot!(xs, gramacylee.(xs), label = "True function", legend = :top)
plot!(xs, my_pol.(xs), label = "Polynomial expansion", legend = :top)
plot!(xs, loba_1.(xs), label = "Lobachevsky", legend = :top)
plot!(xs, krig.(xs), label = "Kriging", legend = :top)
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 5381 | # Surrogates.jl: Surrogate models and optimization for scientific machine learning
A surrogate model is an approximation method that mimics the behavior of a computationally
expensive simulation. In more mathematical terms: suppose we are attempting to optimize a function
``\; f(p)``, but each calculation of ``\; f`` is very expensive. It may be the case that we need to solve a PDE for each point or use advanced numerical linear algebra machinery, which is usually costly. The idea is then to develop a surrogate model ``\; g`` which approximates ``\; f`` by training on previous data collected from evaluations of ``\; f``.
The construction of a surrogate model can be seen as a three-step process:
1. Sample selection
2. Construction of the surrogate model
3. Surrogate optimization
The sampling methods are super important for the behavior of the surrogate. Sampling can be done through [QuasiMonteCarlo.jl](https://github.com/SciML/QuasiMonteCarlo.jl), all the functions available there can be used in Surrogates.jl.
The available surrogates are:
- Linear
- Radial Basis
- Kriging
- Custom Kriging provided with Stheno
- Neural Network
- Support Vector Machine
- Random Forest
- Second Order Polynomial
- Inverse Distance
After the surrogate is built, we need to optimize it with respect to some objective function.
That is, simultaneously looking for a minimum **and** sampling the most unknown region.
The available optimization methods are:
- Stochastic RBF (SRBF)
- Lower confidence-bound strategy (LCBS)
- Expected improvement (EI)
- Dynamic coordinate search (DYCORS)
## Multi-output Surrogates
In certain situations, the function being modeled may have a multi-dimensional output space.
In such a case, the surrogate models can take advantage of correlations between the
observed output variables to obtain more accurate predictions.
When constructing the original surrogate, each element of the passed `y` vector should
itself be a vector. For example, the following `y` are all valid.
```
using Surrogates
using StaticArrays
x = sample(5, [0.0; 0.0], [1.0; 1.0], SobolSample())
f_static = (x) -> StaticVector(x[1], log(x[2]*x[1]))
f = (x) -> [x, log(x)/2]
y = f_static.(x)
y = f.(x)
```
Currently, the following are implemented as multi-output surrogates:
- Radial Basis
- Neural Network (via Flux)
- Second Order Polynomial
- Inverse Distance
- Custom Kriging (via Stheno)
## Gradients
The surrogates implemented here are all automatically differentiable via Zygote. Because
of this property, surrogates are useful models for processes which aren't explicitly
differentiable, and can be used as layers in, for instance, Flux models.
## Installation
Surrogates is registered in the Julia General Registry. In the REPL:
```
using Pkg
Pkg.add("Surrogates")
```
## Contributing
- Please refer to the
[SciML ColPrac: Contributor's Guide on Collaborative Practices for Community Packages](https://github.com/SciML/ColPrac/blob/master/README.md)
for guidance on PRs, issues, and other matters relating to contributing to SciML.
- See the [SciML Style Guide](https://github.com/SciML/SciMLStyle) for common coding practices and other style decisions.
- There are a few community forums:
+ The #diffeq-bridged and #sciml-bridged channels in the
[Julia Slack](https://julialang.org/slack/)
+ The #diffeq-bridged and #sciml-bridged channels in the
[Julia Zulip](https://julialang.zulipchat.com/#narrow/stream/279055-sciml-bridged)
+ On the [Julia Discourse forums](https://discourse.julialang.org)
+ See also [SciML Community page](https://sciml.ai/community/)
## Quick example
```@example
using Surrogates
num_samples = 10
lb = 0.0
ub = 10.0
#Sampling
x = sample(num_samples, lb, ub, SobolSample())
f = x -> log(x) * x^2 + x^3
y = f.(x)
#Creating surrogate
alpha = 2.0
n = 6
my_lobachevsky = LobachevskySurrogate(x, y, lb, ub, alpha = alpha, n = n)
#Approximating value at 5.0
value = my_lobachevsky(5.0)
#Adding more data points
surrogate_optimize(f, SRBF(), lb, ub, my_lobachevsky, RandomSample())
#New approximation
value = my_lobachevsky(5.0)
```
## Reproducibility
```@raw html
<details><summary>The documentation of this SciML package was built using these direct dependencies,</summary>
```
```@example
using Pkg # hide
Pkg.status() # hide
```
```@raw html
</details>
```
```@raw html
<details><summary>and using this machine and Julia version.</summary>
```
```@example
using InteractiveUtils # hide
versioninfo() # hide
```
```@raw html
</details>
```
```@raw html
<details><summary>A more complete overview of all dependencies and their versions is also provided.</summary>
```
```@example
using Pkg # hide
Pkg.status(; mode = PKGMODE_MANIFEST) # hide
```
```@raw html
</details>
```
```@eval
using TOML
using Markdown
version = TOML.parse(read("../../Project.toml", String))["version"]
name = TOML.parse(read("../../Project.toml", String))["name"]
link_manifest = "https://github.com/SciML/" * name * ".jl/tree/gh-pages/v" * version *
"/assets/Manifest.toml"
link_project = "https://github.com/SciML/" * name * ".jl/tree/gh-pages/v" * version *
"/assets/Project.toml"
Markdown.parse("""You can also download the
[manifest]($link_manifest)
file and the
[project]($link_project)
file.
""")
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 5456 | ## Kriging surrogate tutorial (1D)
Kriging or Gaussian process regression, is a method of interpolation in which the interpolated values are modeled by a Gaussian process.
We are going to use a Kriging surrogate to optimize $f(x)=(6x-2)^2sin(12x-4)$. (function from Forrester et al. (2008)).
First of all, import `Surrogates` and `Plots`.
```@example kriging_tutorial1d
using Surrogates
using Plots
default()
```
### Sampling
We choose to sample f in 4 points between 0 and 1 using the `sample` function. The sampling points are chosen using a Sobol sequence; This can be done by passing `SobolSample()` to the `sample` function.
```@example kriging_tutorial1d
# https://www.sfu.ca/~ssurjano/forretal08.html
# Forrester et al. (2008) Function
f(x) = (6 * x - 2)^2 * sin(12 * x - 4)
n_samples = 4
lower_bound = 0.0
upper_bound = 1.0
xs = lower_bound:0.001:upper_bound
x = sample(n_samples, lower_bound, upper_bound, SobolSample())
y = f.(x)
scatter(
x, y, label = "Sampled points", xlims = (lower_bound, upper_bound), ylims = (-7, 17))
plot!(xs, f.(xs), label = "True function", legend = :top)
```
### Building a surrogate
With our sampled points, we can build the Kriging surrogate using the `Kriging` function.
`kriging_surrogate` behaves like an ordinary function, which we can simply plot. A nice statistical property of this surrogate is being able to calculate the error of the function at each point. We plot this as a confidence interval using the `ribbon` argument.
```@example kriging_tutorial1d
kriging_surrogate = Kriging(x, y, lower_bound, upper_bound);
plot(x, y, seriestype = :scatter, label = "Sampled points",
xlims = (lower_bound, upper_bound), ylims = (-7, 17), legend = :top)
plot!(xs, f.(xs), label = "True function", legend = :top)
plot!(xs, kriging_surrogate.(xs), label = "Surrogate function",
ribbon = p -> std_error_at_point(kriging_surrogate, p), legend = :top)
```
### Optimizing
Having built a surrogate, we can now use it to search for minima in our original function `f`.
To optimize using our surrogate, we call `surrogate_optimize` method. We choose to use Stochastic RBF as the optimization technique and again Sobol sampling as the sampling technique.
```@example kriging_tutorial1d
@show surrogate_optimize(
f, SRBF(), lower_bound, upper_bound, kriging_surrogate, SobolSample())
scatter(x, y, label = "Sampled points", ylims = (-7, 7), legend = :top)
plot!(xs, f.(xs), label = "True function", legend = :top)
plot!(xs, kriging_surrogate.(xs), label = "Surrogate function",
ribbon = p -> std_error_at_point(kriging_surrogate, p), legend = :top)
```
## Kriging surrogate tutorial (ND)
First of all, let's define the function we are going to build a surrogate for. Notice how its argument is a vector of numbers, one for each coordinate, and its output is a scalar.
```@example kriging_tutorialnd
using Plots # hide
default(c = :matter, legend = false, xlabel = "x", ylabel = "y") # hide
using Surrogates # hide
function branin(x)
x1 = x[1]
x2 = x[2]
a = 1
b = 5.1 / (4 * Ο^2)
c = 5 / Ο
r = 6
s = 10
t = 1 / (8Ο)
a * (x2 - b * x1 + c * x1 - r)^2 + s * (1 - t) * cos(x1) + s
end
```
### Sampling
Let's define our bounds, this time we are working in two dimensions. In particular, we want our first dimension `x` to have bounds `-5, 10`, and `0, 15` for the second dimension. We are taking 50 samples of the space using Sobol sequences. We then evaluate our function on all the sampling points.
```@example kriging_tutorialnd
n_samples = 10
lower_bound = [-5.0, 0.0]
upper_bound = [10.0, 15.0]
xys = sample(n_samples, lower_bound, upper_bound, GoldenSample())
zs = branin.(xys);
```
```@example kriging_tutorialnd
x, y = -5:10, 0:15 # hide
p1 = surface(x, y, (x1, x2) -> branin((x1, x2))) # hide
xs = [xy[1] for xy in xys] # hide
ys = [xy[2] for xy in xys] # hide
scatter!(xs, ys, zs) # hide
p2 = contour(x, y, (x1, x2) -> branin((x1, x2))) # hide
scatter!(xs, ys) # hide
plot(p1, p2, title = "True function") # hide
```
### Building a surrogate
Using the sampled points, we build the surrogate, the steps are analogous to the 1-dimensional case.
```@example kriging_tutorialnd
kriging_surrogate = Kriging(
xys, zs, lower_bound, upper_bound, p = [2.0, 2.0], theta = [0.03, 0.003])
```
```@example kriging_tutorialnd
p1 = surface(x, y, (x, y) -> kriging_surrogate([x y])) # hide
scatter!(xs, ys, zs, marker_z = zs) # hide
p2 = contour(x, y, (x, y) -> kriging_surrogate([x y])) # hide
scatter!(xs, ys, marker_z = zs) # hide
plot(p1, p2, title = "Surrogate") # hide
```
### Optimizing
With our surrogate, we can now search for the minima of the branin function.
Notice how the new sampled points, which were created during the optimization process, are appended to the `xys` array.
This is why its size changes.
```@example kriging_tutorialnd
size(xys)
```
```@example kriging_tutorialnd
surrogate_optimize(branin, SRBF(), lower_bound, upper_bound, kriging_surrogate,
SobolSample(); maxiters = 100, num_new_samples = 10)
```
```@example kriging_tutorialnd
size(xys)
```
```@example kriging_tutorialnd
p1 = surface(x, y, (x, y) -> kriging_surrogate([x y])) # hide
xs = [xy[1] for xy in xys] # hide
ys = [xy[2] for xy in xys] # hide
zs = branin.(xys) # hide
scatter!(xs, ys, zs, marker_z = zs) # hide
p2 = contour(x, y, (x, y) -> kriging_surrogate([x y])) # hide
scatter!(xs, ys, marker_z = zs) # hide
plot(p1, p2) # hide
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 5354 | # Lobachevsky surrogate tutorial
Lobachevsky splines function is a function that is used for univariate and multivariate scattered interpolation. Introduced by Lobachevsky in 1842 to investigate errors in astronomical measurements.
We are going to use a Lobachevsky surrogate to optimize $f(x)=sin(x)+sin(10/3 * x)$.
First of all import `Surrogates` and `Plots`.
```@example LobachevskySurrogate_tutorial
using Surrogates
using Plots
default()
```
## Sampling
We choose to sample f in 4 points between 0 and 4 using the `sample` function. The sampling points are chosen using a Sobol sequence, this can be done by passing `SobolSample()` to the `sample` function.
```@example LobachevskySurrogate_tutorial
f(x) = sin(x) + sin(10 / 3 * x)
n_samples = 5
lower_bound = 1.0
upper_bound = 4.0
x = sample(n_samples, lower_bound, upper_bound, SobolSample())
y = f.(x)
scatter(x, y, label = "Sampled points", xlims = (lower_bound, upper_bound))
plot!(f, label = "True function", xlims = (lower_bound, upper_bound))
```
## Building a surrogate
With our sampled points, we can build the Lobachevsky surrogate using the `LobachevskySurrogate` function.
`lobachevsky_surrogate` behaves like an ordinary function, which we can simply plot. Alpha is the shape parameter, and n specifies how close you want Lobachevsky function to be to the radial basis function.
```@example LobachevskySurrogate_tutorial
alpha = 2.0
n = 6
lobachevsky_surrogate = LobachevskySurrogate(
x, y, lower_bound, upper_bound, alpha = 2.0, n = 6)
plot(x, y, seriestype = :scatter, label = "Sampled points",
xlims = (lower_bound, upper_bound))
plot!(f, label = "True function", xlims = (lower_bound, upper_bound))
plot!(
lobachevsky_surrogate, label = "Surrogate function", xlims = (lower_bound, upper_bound))
```
## Optimizing
Having built a surrogate, we can now use it to search for minima in our original function `f`.
To optimize using our surrogate we call `surrogate_optimize` method. We choose to use Stochastic RBF as the optimization technique and again Sobol sampling as the sampling technique.
```@example LobachevskySurrogate_tutorial
@show surrogate_optimize(
f, SRBF(), lower_bound, upper_bound, lobachevsky_surrogate, SobolSample())
scatter(x, y, label = "Sampled points")
plot!(f, label = "True function", xlims = (lower_bound, upper_bound))
plot!(
lobachevsky_surrogate, label = "Surrogate function", xlims = (lower_bound, upper_bound))
```
In the example below, it shows how to use `lobachevsky_surrogate` for higher dimension problems.
# Lobachevsky Surrogate Tutorial (ND):
First of all, we will define the `Schaffer` function we are going to build surrogate for. Notice, one how its argument is a vector of numbers, one for each coordinate, and its output is a scalar.
```@example LobachevskySurrogate_ND
using Plots # hide
default(c = :matter, legend = false, xlabel = "x", ylabel = "y") # hide
using Surrogates # hide
function schaffer(x)
x1 = x[1]
x2 = x[2]
fact1 = x1^2
fact2 = x2^2
y = fact1 + fact2
end
```
## Sampling
Let's define our bounds, this time we are working in two dimensions. In particular, we want our first dimension `x` to have bounds `0, 8`, and `0, 8` for the second dimension. We are taking 60 samples of the space using Sobol Sequences. We then evaluate our function on all of the sampling points.
```@example LobachevskySurrogate_ND
n_samples = 60
lower_bound = [0.0, 0.0]
upper_bound = [8.0, 8.0]
xys = sample(n_samples, lower_bound, upper_bound, SobolSample())
zs = schaffer.(xys);
```
```@example LobachevskySurrogate_ND
x, y = 0:8, 0:8 # hide
p1 = surface(x, y, (x1, x2) -> schaffer((x1, x2))) # hide
xs = [xy[1] for xy in xys] # hide
ys = [xy[2] for xy in xys] # hide
scatter!(xs, ys, zs) # hide
p2 = contour(x, y, (x1, x2) -> schaffer((x1, x2))) # hide
scatter!(xs, ys) # hide
plot(p1, p2, title = "True function") # hide
```
## Building a surrogate
Using the sampled points, we build the surrogate, the steps are analogous to the 1-dimensional case.
```@example LobachevskySurrogate_ND
Lobachevsky = LobachevskySurrogate(
xys, zs, lower_bound, upper_bound, alpha = [2.4, 2.4], n = 8)
```
```@example LobachevskySurrogate_ND
p1 = surface(x, y, (x, y) -> Lobachevsky([x y])) # hide
scatter!(xs, ys, zs, marker_z = zs) # hide
p2 = contour(x, y, (x, y) -> Lobachevsky([x y])) # hide
scatter!(xs, ys, marker_z = zs) # hide
plot(p1, p2, title = "Surrogate") # hide
```
## Optimizing
With our surrogate, we can now search for the minima of the function.
Notice how the new sampled points, which were created during the optimization process, are appended to the `xys` array.
This is why its size changes.
```@example LobachevskySurrogate_ND
size(Lobachevsky.x)
```
```@example LobachevskySurrogate_ND
surrogate_optimize(schaffer, SRBF(), lower_bound, upper_bound, Lobachevsky,
SobolSample(), maxiters = 1, num_new_samples = 10)
```
```@example LobachevskySurrogate_ND
size(Lobachevsky.x)
```
```@example LobachevskySurrogate_ND
p1 = surface(x, y, (x, y) -> Lobachevsky([x y])) # hide
xys = Lobachevsky.x # hide
xs = [i[1] for i in xys] # hide
ys = [i[2] for i in xys] # hide
zs = schaffer.(xys) # hide
scatter!(xs, ys, zs, marker_z = zs) # hide
p2 = contour(x, y, (x, y) -> Lobachevsky([x y])) # hide
scatter!(xs, ys, marker_z = zs) # hide
plot(p1, p2) # hide
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 1202 | # Lp norm function
The Lp norm function is defined as:
``f(x) = \sqrt[p]{ \sum_{i=1}^d \vert x_i \vert ^p}``
Let's import Surrogates and Plots:
```@example lp
using Surrogates
using SurrogatesPolyChaos
using Plots
using LinearAlgebra
default()
```
Define the objective function:
```@example lp
function f(x, p)
return norm(x, p)
end
```
Let's see a simple 1D case:
```@example lp
n = 30
lb = -5.0
ub = 5.0
p = 1.3
x = sample(n, lb, ub, SobolSample())
y = f.(x, p)
xs = lb:0.001:ub
plot(x, y, seriestype = :scatter, label = "Sampled points",
xlims = (lb, ub), ylims = (0, 5), legend = :top)
plot!(xs, f.(xs, p), label = "True function", legend = :top)
```
Fitting different surrogates:
```@example lp
my_pol = PolynomialChaosSurrogate(x, y, lb, ub)
loba_1 = LobachevskySurrogate(x, y, lb, ub)
krig = Kriging(x, y, lb, ub)
plot(x, y, seriestype = :scatter, label = "Sampled points",
xlims = (lb, ub), ylims = (0, 5), legend = :top)
plot!(xs, f.(xs, p), label = "True function", legend = :top)
plot!(xs, my_pol.(xs), label = "Polynomial expansion", legend = :top)
plot!(xs, loba_1.(xs), label = "Lobachevsky", legend = :top)
plot!(xs, krig.(xs), label = "Kriging", legend = :top)
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 4026 | ## Mixture of Experts (MOE)
!!! note
This surrogate requires the 'SurrogatesMOE' module, which can be added by inputting "]add SurrogatesMOE" from the Julia command line.
The Mixture of Experts (MOE) Surrogate model represents the interpolating function as a combination of other surrogate models. SurrogatesMOE is a Julia implementation of the [Python version from SMT](https://smt.readthedocs.io/en/latest/_src_docs/applications/moe.html).
MOE is most useful when we have a discontinuous function. For example, let's say we want to build a surrogate for the following function:
### 1D Example
```@example MOE_1D
function discont_1D(x)
if x < 0.0
return -5.0
elseif x >= 0.0
return 5.0
end
end
nothing # hide
```
Let's choose the MOE Surrogate for 1D. Note that we have to import the `SurrogatesMOE` package in addition to `Surrogates` and `Plots`.
```@example MOE_1D
using Surrogates
using SurrogatesMOE
using Plots
default()
lb = -1.0
ub = 1.0
x = sample(50, lb, ub, SobolSample())
y = discont_1D.(x)
scatter(
x, y, label = "Sampled Points", xlims = (lb, ub), ylims = (-6.0, 7.0), legend = :top)
```
How does a regular surrogate perform on such a dataset?
```@example MOE_1D
RAD_1D = RadialBasis(x, y, lb, ub, rad = linearRadial(), scale_factor = 1.0, sparse = false)
RAD_at0 = RAD_1D(0.0) #true value should be 5.0
```
As we can see, the prediction is far from the ground truth. Now, how does the MOE perform?
```@example MOE_1D
expert_types = [
RadialBasisStructure(radial_function = linearRadial(), scale_factor = 1.0,
sparse = false),
RadialBasisStructure(radial_function = linearRadial(), scale_factor = 1.0,
sparse = false)
]
MOE_1D_RAD_RAD = MOE(x, y, expert_types)
MOE_at0 = MOE_1D_RAD_RAD(0.0)
```
As we can see, the accuracy is significantly better.
### Under the Hood - How SurrogatesMOE Works
First, we create Gaussian Mixture Models for the number of expert types provided using the x and y values. For example, in the above example, we create two clusters. Then, using a small test dataset kept aside from the input data, we choose the best surrogate model for each of the clusters. At prediction time, we use the appropriate surrogate model based on the cluster to which the new point belongs.
### N-Dimensional Example
```@example MOE_ND
using Surrogates
using SurrogatesMOE
# helper to test accuracy of predictors
function rmse(a, b)
a = vec(a)
b = vec(b)
if (size(a) != size(b))
println("error in inputs")
return
end
n = size(a, 1)
return sqrt(sum((a - b) .^ 2) / n)
end
# multidimensional input function
function discont_NDIM(x)
if (x[1] >= 0.0 && x[2] >= 0.0)
return sum(x .^ 2) + 5
else
return sum(x .^ 2) - 5
end
end
lb = [-1.0, -1.0]
ub = [1.0, 1.0]
n = 150
x = sample(n, lb, ub, RandomSample())
y = discont_NDIM.(x)
x_test = sample(10, lb, ub, GoldenSample())
expert_types = [
RadialBasisStructure(radial_function = linearRadial(), scale_factor = 1.0,
sparse = false),
RadialBasisStructure(radial_function = linearRadial(), scale_factor = 1.0,
sparse = false)
]
moe_nd_rad_rad = MOE(x, y, expert_types, ndim = 2)
moe_pred_vals = moe_nd_rad_rad.(x_test)
true_vals = discont_NDIM.(x_test)
moe_rmse = rmse(true_vals, moe_pred_vals)
rbf = RadialBasis(x, y, lb, ub)
rbf_pred_vals = rbf.(x_test)
rbf_rmse = rmse(true_vals, rbf_pred_vals)
println(rbf_rmse > moe_rmse)
```
### Usage Notes - Example With Other Surrogates
From the above example, simply change or add to the expert types:
```@example SurrogateExamples
using Surrogates
#To use Inverse Distance and Radial Basis Surrogates
expert_types = [
KrigingStructure(p = [1.0, 1.0], theta = [1.0, 1.0]),
InverseDistanceStructure(p = 1.0)
]
#With 3 Surrogates
expert_types = [
RadialBasisStructure(radial_function = linearRadial(), scale_factor = 1.0,
sparse = false),
LinearStructure(),
InverseDistanceStructure(p = 1.0)
]
nothing # hide
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 1287 | # Multi-objective optimization
## Case 1: Non-colliding objective functions
```@example multi_obj
using Surrogates
m = 10
f = x -> [x^i for i in 1:m]
lb = 1.0
ub = 10.0
x = sample(50, lb, ub, GoldenSample())
y = f.(x)
my_radial_basis_ego = RadialBasis(x, y, lb, ub)
pareto_set, pareto_front = surrogate_optimize(
f, SMB(), lb, ub, my_radial_basis_ego, SobolSample(); maxiters = 10, n_new_look = 100)
m = 5
f = x -> [x^i for i in 1:m]
lb = 1.0
ub = 10.0
x = sample(50, lb, ub, SobolSample())
y = f.(x)
my_radial_basis_rtea = RadialBasis(x, y, lb, ub)
Z = 0.8
K = 2
p_cross = 0.5
n_c = 1.0
sigma = 1.5
surrogate_optimize(
f, RTEA(Z, K, p_cross, n_c, sigma), lb, ub, my_radial_basis_rtea, SobolSample())
```
## Case 2: objective functions with conflicting minima
```@example multi_obj
f = x -> [sqrt((x[1] - 4)^2 + 25 * (x[2])^2),
sqrt((x[1] + 4)^2 + 25 * (x[2])^2),
sqrt((x[1] - 3)^2 + (x[2] - 1)^2)]
lb = [2.5, -0.5]
ub = [3.5, 0.5]
x = sample(50, lb, ub, SobolSample())
y = f.(x)
my_radial_basis_ego = RadialBasis(x, y, lb, ub)
#I can find my pareto set and pareto front by calling again the surrogate_optimize function:
pareto_set, pareto_front = surrogate_optimize(
f, SMB(), lb, ub, my_radial_basis_ego, SobolSample(); maxiters = 10, n_new_look = 100);
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 2122 | # Neural network tutorial
!!! note
This surrogate requires the 'SurrogatesFlux' module, which can be added by inputting "]add SurrogatesFlux" from the Julia command line.
It's possible to define a neural network as a surrogate, using Flux.
This is useful because we can call optimization methods on it.
First of all we will define the `Schaffer` function we are going to build a surrogate for.
```@example Neural_surrogate
using Plots
default(c = :matter, legend = false, xlabel = "x", ylabel = "y") # hide
using Surrogates
using Flux
using SurrogatesFlux
function schaffer(x)
x1 = x[1]
x2 = x[2]
fact1 = x1^2
fact2 = x2^2
y = fact1 + fact2
end
```
## Sampling
Let's define our bounds, this time we are working in two dimensions. In particular we want our first dimension `x` to have bounds `0, 8`, and `0, 8` for the second dimension. We are taking 60 samples of the space using Sobol Sequences. We then evaluate our function on all the sampling points.
```@example Neural_surrogate
n_samples = 60
lower_bound = [0.0, 0.0]
upper_bound = [8.0, 8.0]
xys = sample(n_samples, lower_bound, upper_bound, SobolSample())
zs = schaffer.(xys);
```
```@example Neural_surrogate
x, y = 0:8, 0:8 # hide
p1 = surface(x, y, (x1, x2) -> schaffer((x1, x2))) # hide
xs = [xy[1] for xy in xys] # hide
ys = [xy[2] for xy in xys] # hide
scatter!(xs, ys, zs) # hide
p2 = contour(x, y, (x1, x2) -> schaffer((x1, x2))) # hide
scatter!(xs, ys) # hide
plot(p1, p2, title = "True function") # hide
```
## Building a surrogate
You can specify your own model, optimization function, loss functions, and epochs.
As always, getting the model right is the hardest thing.
```@example Neural_surrogate
model1 = Chain(
Dense(2, 5, Ο),
Dense(5, 2, Ο),
Dense(2, 1)
)
neural = NeuralSurrogate(xys, zs, lower_bound, upper_bound, model = model1, n_echos = 10)
```
## Optimization
We can now call an optimization function on the neural network:
```@example Neural_surrogate
surrogate_optimize(schaffer, SRBF(), lower_bound, upper_bound, neural,
SobolSample(), maxiters = 20, num_new_samples = 10)
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 1179 | # Optimization techniques
- SRBF
```@docs
surrogate_optimize(obj::Function,::SRBF,lb,ub,surr::AbstractSurrogate,sample_type::SamplingAlgorithm;maxiters=100,num_new_samples=100)
```
- LCBS
```@docs
surrogate_optimize(obj::Function,::LCBS,lb,ub,krig,sample_type::SamplingAlgorithm;maxiters=100,num_new_samples=100)
```
- EI
```@docs
surrogate_optimize(obj::Function,::EI,lb,ub,krig,sample_type::SamplingAlgorithm;maxiters=100,num_new_samples=100)
```
- DYCORS
```@docs
surrogate_optimize(obj::Function,::DYCORS,lb,ub,surrn::AbstractSurrogate,sample_type::SamplingAlgorithm;maxiters=100,num_new_samples=100)
```
- SOP
```@docs
surrogate_optimize(obj::Function,sop1::SOP,lb::Number,ub::Number,surrSOP::AbstractSurrogate,sample_type::SamplingAlgorithm;maxiters=100,num_new_samples=min(500*1,5000))
```
## Adding another optimization method
To add another optimization method, you just need to define a new
SurrogateOptimizationAlgorithm and write its corresponding algorithm, overloading the following:
```
surrogate_optimize(obj::Function,::NewOptimizationType,lb,ub,surr::AbstractSurrogate,sample_type::SamplingAlgorithm;maxiters=100,num_new_samples=100)
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 3391 | # Parallel Optimization
There are some situations where it can be beneficial to run multiple optimizations in parallel. For example, if your objective function is very expensive to evaluate, you may want to run multiple evaluations in parallel.
## Ask-Tell Interface
To enable parallel optimization, we make use of an Ask-Tell interface. The user will construct the initial surrogate model the same way as for non-parallel surrogate models, but instead of using `surrogate_optimize`, the user will use `potential_optimal_points`. This will return the coordinates of points that the optimizer has determined are most useful to evaluate next. How the user evaluates these points is up to them. The Ask-Tell interface requires more manual control than `surrogate_optimize`, but it allows for more flexibility. After the point has been evaluated, the user will *tell* the surrogate model the new points with the `add_point!` function.
## Virtual Points
To ensure that points of interest returned by `potential_optimal_points` are sufficiently far from each other, the function makes use of *virtual points*. They are used as follows:
1. `potential_optimal_points` is told to return `n` points.
2. The point with the highest merit function value is selected.
3. This point is now treated as a virtual point and is assigned a temporary value that changes the landscape of the merit function. How the temporary value is chosen depends on the strategy used. (see below)
4. The point with the new highest merit is selected.
5. The process is repeated until `n` points have been selected.
The following strategies are available for virtual point selection for all optimization algorithms:
- "Minimum Constant Liar (MinimumConstantLiar)":
+ The virtual point is assigned using the lowest known value of the merit function across all evaluated points.
- "Mean Constant Liar (MeanConstantLiar)":
+ The virtual point is assigned using the mean of the merit function across all evaluated points.
- "Maximum Constant Liar (MaximumConstantLiar)":
+ The virtual point is assigned using the greatest known value of the merit function across all evaluated points.
For Kriging surrogates, specifically, the above and following strategies are available:
- "Kriging Believer (KrigingBeliever):
+ The virtual point is assigned using the mean of the Kriging surrogate at the virtual point.
- "Kriging Believer Upper Bound (KrigingBelieverUpperBound)":
+ The virtual point is assigned using 3$\sigma$ above the mean of the Kriging surrogate at the virtual point.
- "Kriging Believer Lower Bound (KrigingBelieverLowerBound)":
+ The virtual point is assigned using 3$\sigma$ below the mean of the Kriging surrogate at the virtual point.
In general, MinimumConstantLiar and KrigingBelieverLowerBound tend to favor exploitation, while MaximumConstantLiar and KrigingBelieverUpperBound tend to favor exploration. MeanConstantLiar and KrigingBeliever tend to be compromises between the two.
## Examples
```@example
using Surrogates
lb = 0.0
ub = 10.0
f = x -> log(x) * exp(x)
x = sample(5, lb, ub, SobolSample())
y = f.(x)
my_k = Kriging(x, y, lb, ub)
for _ in 1:10
new_x, eis = potential_optimal_points(
EI(), MeanConstantLiar(), lb, ub, my_k, SobolSample(), 3)
add_point!(my_k, new_x, f.(new_x))
end
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 1720 | # Polynomial chaos surrogate
!!! note
This surrogate requires the 'SurrogatesPolyChaos' module which can be added by inputting "]add SurrogatesPolyChaos" from the Julia command line.
We can create a surrogate using a polynomial expansion,
with a different polynomial basis depending on the distribution of the data
we are trying to fit. Under the hood, PolyChaos.jl has been used.
It is possible to specify a type of polynomial for each dimension of the problem.
### Sampling
We choose to sample f in 25 points between 0 and 10 using the `sample` function. The sampling points are chosen using a Low Discrepancy. This can be done by passing `HaltonSample()` to the `sample` function.
```@example polychaos
using Surrogates
using SurrogatesPolyChaos
using Plots
default()
n = 20
lower_bound = 1.0
upper_bound = 6.0
x = sample(n, lower_bound, upper_bound, HaltonSample())
f = x -> log(x) * x + sin(x)
y = f.(x)
scatter(x, y, label = "Sampled points", xlims = (lower_bound, upper_bound), legend = :top)
plot!(f, label = "True function", xlims = (lower_bound, upper_bound), legend = :top)
```
## Building a Surrogate
```@example polychaos
poly1 = PolynomialChaosSurrogate(x, y, lower_bound, upper_bound)
poly2 = PolynomialChaosSurrogate(
x, y, lower_bound, upper_bound, op = SurrogatesPolyChaos.GaussOrthoPoly(5))
plot(x, y, seriestype = :scatter, label = "Sampled points",
xlims = (lower_bound, upper_bound), legend = :top)
plot!(f, label = "True function", xlims = (lower_bound, upper_bound), legend = :top)
plot!(poly1, label = "First polynomial", xlims = (lower_bound, upper_bound), legend = :top)
plot!(poly2, label = "Second polynomial", xlims = (lower_bound, upper_bound), legend = :top)
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 5538 | ## Radial Surrogates
The Radial Basis Surrogate model represents the interpolating function as a linear combination of basis functions, one for each training point. Let's start with something easy to get our hands dirty. I want to build a surrogate for:
```math
f(x) = \log(x) \cdot x^2+x^3
```
Let's choose the Radial Basis Surrogate for 1D. First of all we have to import these two packages: `Surrogates` and `Plots`,
```@example RadialBasisSurrogate
using Surrogates
using Plots
default()
```
We choose to sample f in 30 points between 5 to 25 using `sample` function. The sampling points are chosen using a Sobol sequence, this can be done by passing `SobolSample()` to the `sample` function.
```@example RadialBasisSurrogate
f(x) = log(x) * x^2 + x^3
n_samples = 30
lower_bound = 5.0
upper_bound = 25.0
x = sort(sample(n_samples, lower_bound, upper_bound, SobolSample()))
y = f.(x)
scatter(x, y, label = "Sampled Points", xlims = (lower_bound, upper_bound), legend = :top)
plot!(x, y, label = "True function", legend = :top)
```
## Building Surrogate
With our sampled points we can build the **Radial Surrogate** using the `RadialBasis` function.
We can simply calculate `radial_surrogate` for any value.
```@example RadialBasisSurrogate
radial_surrogate = RadialBasis(x, y, lower_bound, upper_bound)
val = radial_surrogate(5.4)
```
We can also use cubic radial basis functions.
```@example RadialBasisSurrogate
radial_surrogate = RadialBasis(x, y, lower_bound, upper_bound, rad = cubicRadial())
val = radial_surrogate(5.4)
```
Currently, available radial basis functions are `linearRadial` (the default), `cubicRadial`, `multiquadricRadial`, and `thinplateRadial`.
Now, we will simply plot `radial_surrogate`:
```@example RadialBasisSurrogate
plot(x, y, seriestype = :scatter, label = "Sampled points",
xlims = (lower_bound, upper_bound), legend = :top)
plot!(f, label = "True function", xlims = (lower_bound, upper_bound), legend = :top)
plot!(radial_surrogate, label = "Surrogate function",
xlims = (lower_bound, upper_bound), legend = :top)
```
## Optimizing
Having built a surrogate, we can now use it to search for minima in our original function `f`.
To optimize using our surrogate, we call `surrogate_optimize` method. We choose to use Stochastic RBF as the optimization technique and again Sobol sampling as the sampling technique.
```@example RadialBasisSurrogate
@show surrogate_optimize(
f, SRBF(), lower_bound, upper_bound, radial_surrogate, SobolSample())
scatter(x, y, label = "Sampled points", legend = :top)
plot!(f, label = "True function", xlims = (lower_bound, upper_bound), legend = :top)
plot!(radial_surrogate, label = "Surrogate function",
xlims = (lower_bound, upper_bound), legend = :top)
```
## Radial Basis Surrogate tutorial (ND)
First of all, we will define the `Booth` function we are going to build the surrogate for:
$f(x) = (x_1 + 2*x_2 - 7)^2 + (2*x_1 + x_2 - 5)^2$
Notice, how its argument is a vector of numbers, one for each coordinate, and its output is a scalar.
```@example RadialBasisSurrogateND
using Plots # hide
default(c = :matter, legend = false, xlabel = "x", ylabel = "y") # hide
using Surrogates # hide
function booth(x)
x1 = x[1]
x2 = x[2]
term1 = (x1 + 2 * x2 - 7)^2
term2 = (2 * x1 + x2 - 5)^2
y = term1 + term2
end
```
### Sampling
Let's define our bounds, this time we are working in two dimensions. In particular we want our first dimension `x` to have bounds `-5, 10`, and `0, 15` for the second dimension. We are taking 80 samples of the space using Sobol Sequences. We then evaluate our function on all of the sampling points.
```@example RadialBasisSurrogateND
n_samples = 80
lower_bound = [-5.0, 0.0]
upper_bound = [10.0, 15.0]
xys = sample(n_samples, lower_bound, upper_bound, SobolSample())
zs = booth.(xys);
```
```@example RadialBasisSurrogateND
x, y = -5.0:10.0, 0.0:15.0 # hide
p1 = surface(x, y, (x1, x2) -> booth((x1, x2))) # hide
xs = [xy[1] for xy in xys] # hide
ys = [xy[2] for xy in xys] # hide
scatter!(xs, ys, zs) # hide
p2 = contour(x, y, (x1, x2) -> booth((x1, x2))) # hide
scatter!(xs, ys) # hide
plot(p1, p2, title = "True function") # hide
```
### Building a surrogate
Using the sampled points we build the surrogate, the steps are analogous to the 1-dimensional case.
```@example RadialBasisSurrogateND
radial_basis = RadialBasis(xys, zs, lower_bound, upper_bound)
```
```@example RadialBasisSurrogateND
p1 = surface(x, y, (x, y) -> radial_basis([x y])) # hide
scatter!(xs, ys, zs, marker_z = zs) # hide
p2 = contour(x, y, (x, y) -> radial_basis([x y])) # hide
scatter!(xs, ys, marker_z = zs) # hide
plot(p1, p2, title = "Surrogate") # hide
```
### Optimizing
With our surrogate, we can now search for the minima of the function.
Notice how the new sampled points, which were created during the optimization process, are appended to the `xys` array.
This is why its size changes.
```@example RadialBasisSurrogateND
size(xys)
```
```@example RadialBasisSurrogateND
surrogate_optimize(
booth, SRBF(), lower_bound, upper_bound, radial_basis, RandomSample(), maxiters = 50)
```
```@example RadialBasisSurrogateND
size(xys)
```
```@example RadialBasisSurrogateND
p1 = surface(x, y, (x, y) -> radial_basis([x y])) # hide
xs = [xy[1] for xy in xys] # hide
ys = [xy[2] for xy in xys] # hide
zs = booth.(xys) # hide
scatter!(xs, ys, zs, marker_z = zs) # hide
p2 = contour(x, y, (x, y) -> radial_basis([x y])) # hide
scatter!(xs, ys, marker_z = zs) # hide
plot(p1, p2) # hide
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 5319 | ## Random forests surrogate tutorial
!!! note
This surrogate requires the 'SurrogatesRandomForest' module, which can be added by inputting "]add SurrogatesRandomForest" from the Julia command line.
Random forests is a supervised learning algorithm that randomly creates and merges multiple decision trees into one forest.
We are going to use a random forests surrogate to optimize $f(x)=sin(x)+sin(10/3 * x)$.
First of all import `Surrogates` and `Plots`.
```@example RandomForestSurrogate_tutorial
using Surrogates
using SurrogatesRandomForest
using Plots
default()
```
### Sampling
We choose to sample f in 4 points between 0 and 1 using the `sample` function. The sampling points are chosen using a Sobol sequence, this can be done by passing `SobolSample()` to the `sample` function.
```@example RandomForestSurrogate_tutorial
f(x) = sin(x) + sin(10 / 3 * x)
n_samples = 5
lower_bound = 2.7
upper_bound = 7.5
x = sample(n_samples, lower_bound, upper_bound, SobolSample())
y = f.(x)
scatter(x, y, label = "Sampled points", xlims = (lower_bound, upper_bound))
plot!(f, label = "True function", xlims = (lower_bound, upper_bound), legend = :top)
```
### Building a surrogate
With our sampled points, we can build the Random forests surrogate using the `RandomForestSurrogate` function.
`randomforest_surrogate` behaves like an ordinary function, which we can simply plot. Additionally, you can specify the number of trees created
using the parameter num_round
```@example RandomForestSurrogate_tutorial
num_round = 2
randomforest_surrogate = RandomForestSurrogate(
x, y, lower_bound, upper_bound, num_round = 2)
plot(x, y, seriestype = :scatter, label = "Sampled points",
xlims = (lower_bound, upper_bound), legend = :top)
plot!(f, label = "True function", xlims = (lower_bound, upper_bound), legend = :top)
plot!(randomforest_surrogate, label = "Surrogate function",
xlims = (lower_bound, upper_bound), legend = :top)
```
### Optimizing
Having built a surrogate, we can now use it to search for minima in our original function `f`.
To optimize using our surrogate, we call `surrogate_optimize` method. We choose to use Stochastic RBF as the optimization technique and again Sobol sampling as the sampling technique.
```@example RandomForestSurrogate_tutorial
@show surrogate_optimize(
f, SRBF(), lower_bound, upper_bound, randomforest_surrogate, SobolSample())
scatter(x, y, label = "Sampled points")
plot!(f, label = "True function", xlims = (lower_bound, upper_bound), legend = :top)
plot!(randomforest_surrogate, label = "Surrogate function",
xlims = (lower_bound, upper_bound), legend = :top)
```
## Random Forest ND
First of all we will define the `Bukin Function N. 6` function we are going to build a surrogate for.
```@example RandomForestSurrogateND
using Plots # hide
default(c = :matter, legend = false, xlabel = "x", ylabel = "y") # hide
using Surrogates # hide
function bukin6(x)
x1 = x[1]
x2 = x[2]
term1 = 100 * sqrt(abs(x2 - 0.01 * x1^2))
term2 = 0.01 * abs(x1 + 10)
y = term1 + term2
end
```
### Sampling
Let's define our bounds, this time we are working in two dimensions. In particular we want our first dimension `x` to have bounds `-5, 10`, and `0, 15` for the second dimension. We are taking 50 samples of the space using Sobol Sequences. We then evaluate our function on all the sampling points.
```@example RandomForestSurrogateND
n_samples = 50
lower_bound = [-5.0, 0.0]
upper_bound = [10.0, 15.0]
xys = sample(n_samples, lower_bound, upper_bound, SobolSample())
zs = bukin6.(xys);
```
```@example RandomForestSurrogateND
x, y = -5:10, 0:15 # hide
p1 = surface(x, y, (x1, x2) -> bukin6((x1, x2))) # hide
xs = [xy[1] for xy in xys] # hide
ys = [xy[2] for xy in xys] # hide
scatter!(xs, ys, zs) # hide
p2 = contour(x, y, (x1, x2) -> bukin6((x1, x2))) # hide
scatter!(xs, ys) # hide
plot(p1, p2, title = "True function") # hide
```
### Building a surrogate
Using the sampled points, we build the surrogate, the steps are analogous to the 1-dimensional case.
```@example RandomForestSurrogateND
using SurrogatesRandomForest
RandomForest = RandomForestSurrogate(xys, zs, lower_bound, upper_bound)
```
```@example RandomForestSurrogateND
p1 = surface(x, y, (x, y) -> RandomForest([x y])) # hide
scatter!(xs, ys, zs, marker_z = zs) # hide
p2 = contour(x, y, (x, y) -> RandomForest([x y])) # hide
scatter!(xs, ys, marker_z = zs) # hide
plot(p1, p2, title = "Surrogate") # hide
```
### Optimizing
With our surrogate, we can now search for the minima of the function.
Notice how the new sampled points, which were created during the optimization process, are appended to the `xys` array.
This is why its size changes.
```@example RandomForestSurrogateND
size(xys)
```
```@example RandomForestSurrogateND
surrogate_optimize(
bukin6, SRBF(), lower_bound, upper_bound, RandomForest, SobolSample(), maxiters = 20)
```
```@example RandomForestSurrogateND
size(xys)
```
```@example RandomForestSurrogateND
p1 = surface(x, y, (x, y) -> RandomForest([x y])) # hide
xs = [xy[1] for xy in xys] # hide
ys = [xy[2] for xy in xys] # hide
zs = bukin6.(xys) # hide
scatter!(xs, ys, zs, marker_z = zs) # hide
p2 = contour(x, y, (x, y) -> RandomForest([x y])) # hide
scatter!(xs, ys, marker_z = zs) # hide
plot(p1, p2) # hide
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 1724 | # Rosenbrock function
The Rosenbrock function is defined as:
``f(x) = \sum_{i=1}^{d-1}[ (x_{i+1}-x_i)^2 + (x_i - 1)^2]``
I will treat the 2D version, which is commonly defined as:
``f(x,y) = (1-x)^2 + 100(y-x^2)^2``
Let's import Surrogates and Plots:
```@example rosen
using Surrogates
using SurrogatesPolyChaos
using Plots
default()
```
Define the objective function:
```@example rosen
function f(x)
x1 = x[1]
x2 = x[2]
return (1 - x1)^2 + 100 * (x2 - x1^2)^2
end
```
Let's plot it:
```@example rosen
n = 100
lb = [0.0, 0.0]
ub = [8.0, 8.0]
xys = sample(n, lb, ub, SobolSample());
zs = f.(xys);
x, y = 0:8, 0:8
p1 = surface(x, y, (x1, x2) -> f((x1, x2)))
xs = [xy[1] for xy in xys]
ys = [xy[2] for xy in xys]
scatter!(xs, ys, zs) # hide
p2 = contour(x, y, (x1, x2) -> f((x1, x2)))
scatter!(xs, ys)
plot(p1, p2, title = "True function")
```
Fitting different surrogates:
```@example rosen
mypoly = PolynomialChaosSurrogate(xys, zs, lb, ub)
loba = LobachevskySurrogate(xys, zs, lb, ub)
inver = InverseDistanceSurrogate(xys, zs, lb, ub)
```
Plotting:
```@example rosen
p1 = surface(x, y, (x, y) -> mypoly([x y]))
scatter!(xs, ys, zs, marker_z = zs)
p2 = contour(x, y, (x, y) -> mypoly([x y]))
scatter!(xs, ys, marker_z = zs)
plot(p1, p2, title = "Polynomial expansion")
```
```@example rosen
p1 = surface(x, y, (x, y) -> loba([x y]))
scatter!(xs, ys, zs, marker_z = zs)
p2 = contour(x, y, (x, y) -> loba([x y]))
scatter!(xs, ys, marker_z = zs)
plot(p1, p2, title = "Lobachevsky")
```
```@example rosen
p1 = surface(x, y, (x, y) -> inver([x y]))
scatter!(xs, ys, zs, marker_z = zs)
p2 = contour(x, y, (x, y) -> inver([x y]))
scatter!(xs, ys, marker_z = zs)
plot(p1, p2, title = "Inverse distance")
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 1218 | # Sampling
Sampling methods are provided by the [QuasiMonteCarlo package](https://docs.sciml.ai/QuasiMonteCarlo/stable/).
The syntax for sampling in an interval or region is the following:
```
sample(n,lb,ub,S::SamplingAlgorithm)
```
where lb and ub are, respectively, the lower and upper bounds.
There are many sampling algorithms to choose from:
- Grid sample
```
GridSample{T}
sample(n,lb,ub,S::GridSample)
```
- Uniform sample
```
sample(n,lb,ub,::RandomSample)
```
- Sobol sample
```
sample(n,lb,ub,::SobolSample)
```
- Latin Hypercube sample
```
sample(n,lb,ub,::LatinHypercubeSample)
```
- Low Discrepancy sample
```
sample(n,lb,ub,S::HaltonSample)
```
- Sample on section
```
SectionSample
sample(n,lb,ub,S::SectionSample)
```
## Adding a new sampling method
Adding a new sampling method is a two- step process:
1. Adding a new SamplingAlgorithm type
2. Overloading the sample function with the new type.
**Example**
```
struct NewAmazingSamplingAlgorithm{OPTIONAL} <: QuasiMonteCarlo.SamplingAlgorithm end
function sample(n,lb,ub,::NewAmazingSamplingAlgorithm)
if lb is Number
...
return x
else
...
return Tuple.(x)
end
end
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 1197 | # Second order polynomial tutorial
The square polynomial model can be expressed by:
``y = XΞ² + Ο΅``
Where X is the matrix of the linear model augmented by adding 2d columns,
containing pair by pair products of variables and variables squared.
```@example second_order_tut
using Surrogates
using Plots
default()
```
## Sampling
```@example second_order_tut
f = x -> 3 * sin(x) + 10 / x
lb = 3.0
ub = 6.0
n = 10
x = sample(n, lb, ub, HaltonSample())
y = f.(x)
scatter(x, y, label = "Sampled points", xlims = (lb, ub))
plot!(f, label = "True function", xlims = (lb, ub))
```
## Building the surrogate
```@example second_order_tut
sec = SecondOrderPolynomialSurrogate(x, y, lb, ub)
plot(x, y, seriestype = :scatter, label = "Sampled points", xlims = (lb, ub))
plot!(f, label = "True function", xlims = (lb, ub))
plot!(sec, label = "Surrogate function", xlims = (lb, ub))
```
## Optimizing
```@example second_order_tut
@show surrogate_optimize(f, SRBF(), lb, ub, sec, SobolSample())
scatter(x, y, label = "Sampled points")
plot!(f, label = "True function", xlims = (lb, ub))
plot!(sec, label = "Surrogate function", xlims = (lb, ub))
```
The optimization method successfully found the minimum.
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 2160 | # Sphere function
The sphere function of dimension d is defined as:
``f(x) = \sum_{i=1}^d x_i^2``
with lower bound -10 and upper bound 10.
Let's import Surrogates and Plots:
```@example sphere_function
using Surrogates
using Plots
default()
```
Define the objective function:
```@example sphere_function
function sphere_function(x)
return sum(x .^ 2)
end
```
The 1D case is just a simple parabola, let's plot it:
```@example sphere_function
n = 20
lb = -10
ub = 10
x = sample(n, lb, ub, SobolSample())
y = sphere_function.(x)
xs = lb:0.001:ub
plot(x, y, seriestype = :scatter, label = "Sampled points",
xlims = (lb, ub), ylims = (-2, 120), legend = :top)
plot!(xs, sphere_function.(xs), label = "True function", legend = :top)
```
Fitting RadialSurrogate with different radial basis:
```@example sphere_function
rad_1d_linear = RadialBasis(x, y, lb, ub)
rad_1d_cubic = RadialBasis(x, y, lb, ub, rad = cubicRadial())
rad_1d_multiquadric = RadialBasis(x, y, lb, ub, rad = multiquadricRadial())
plot(x, y, seriestype = :scatter, label = "Sampled points",
xlims = (lb, ub), ylims = (-2, 120), legend = :top)
plot!(xs, sphere_function.(xs), label = "True function", legend = :top)
plot!(xs, rad_1d_linear.(xs), label = "Radial surrogate with linear", legend = :top)
plot!(xs, rad_1d_cubic.(xs), label = "Radial surrogate with cubic", legend = :top)
plot!(xs, rad_1d_multiquadric.(xs),
label = "Radial surrogate with multiquadric", legend = :top)
```
Fitting Lobachevsky Surrogate with different values of hyperparameter alpha:
```@example sphere_function
loba_1 = LobachevskySurrogate(x, y, lb, ub)
loba_2 = LobachevskySurrogate(x, y, lb, ub, alpha = 1.5, n = 6)
loba_3 = LobachevskySurrogate(x, y, lb, ub, alpha = 0.3, n = 6)
plot(x, y, seriestype = :scatter, label = "Sampled points",
xlims = (lb, ub), ylims = (-2, 120), legend = :top)
plot!(xs, sphere_function.(xs), label = "True function", legend = :top)
plot!(xs, loba_1.(xs), label = "Lobachevsky surrogate 1", legend = :top)
plot!(xs, loba_2.(xs), label = "Lobachevsky surrogate 2", legend = :top)
plot!(xs, loba_3.(xs), label = "Lobachevsky surrogate 3", legend = :top)
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 2061 | # Surrogate
Every surrogate has a different definition depending on the parameters needed.
However, they have in common:
1. `add_point!(::AbstractSurrogate,x_new,y_new)`
2. `AbstractSurrogate(value)`
The first function adds a sample point to the surrogate, thus changing the internal
coefficients. The second one calculates the approximation at value.
- Linear surrogate
```@docs
LinearSurrogate(x,y,lb,ub)
```
- Radial basis function surrogate
```@docs
RadialBasis(x, y, lb, ub; rad::RadialFunction = linearRadial, scale_factor::Real=1.0, sparse = false)
```
- Kriging surrogate
```@docs
Kriging(x,y,p,theta)
```
- Lobachevsky surrogate
```@docs
LobachevskySurrogate(x,y,lb,ub; alpha = collect(one.(x[1])),n::Int = 4, sparse = false)
lobachevsky_integral(loba::LobachevskySurrogate,lb,ub)
```
- Support vector machine surrogate, requires `using LIBSVM` and `using SurrogatesSVM`
```
SVMSurrogate(x,y,lb::Number,ub::Number)
```
- Random forest surrogate, requires `using XGBoost` and `using SurrogatesRandomForest`
```
RandomForestSurrogate(x,y,lb,ub;num_round::Int = 1)
```
- Neural network surrogate, requires `using Flux` and `using SurrogatesFlux`
```
NeuralSurrogate(x,y,lb,ub; model = Chain(Dense(length(x[1]),1), first), loss = (x,y) -> Flux.mse(model(x), y),opt = Descent(0.01),n_echos::Int = 1)
```
# Creating another surrogate
It's great that you want to add another surrogate to the library!
You will need to:
1. Define a new mutable struct and a constructor function
2. Define add\_point!(your\_surrogate::AbstractSurrogate,x\_new,y\_new)
3. Define your\_surrogate(value) for the approximation
**Example**
```
mutable struct NewSurrogate{X,Y,L,U,C,A,B} <: AbstractSurrogate
x::X
y::Y
lb::L
ub::U
coeff::C
alpha::A
beta::B
end
function NewSurrogate(x,y,lb,ub,parameters)
...
return NewSurrogate(x,y,lb,ub,calculated\_coeff,alpha,beta)
end
function add_point!(NewSurrogate,x\_new,y\_new)
nothing
end
function (s::NewSurrogate)(value)
return s.coeff*value + s.alpha
end
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 1012 | # Tensor product function
The tensor product function is defined as:
``f(x) = \prod_{i=1}^d \cos(a\pi x_i)``
Let's import Surrogates and Plots:
```@example tensor
using Surrogates
using Plots
default()
```
Define the 1D objective function:
```@example tensor
function f(x)
a = 0.5
return cos(a * pi * x)
end
```
```@example tensor
n = 30
lb = -5.0
ub = 5.0
a = 0.5
x = sample(n, lb, ub, SobolSample())
y = f.(x)
xs = lb:0.001:ub
scatter(x, y, label = "Sampled points", xlims = (lb, ub), ylims = (-1, 1), legend = :top)
plot!(xs, f.(xs), label = "True function", legend = :top)
```
Fitting and plotting different surrogates:
```@example tensor
loba_1 = LobachevskySurrogate(x, y, lb, ub)
krig = Kriging(x, y, lb, ub)
scatter(
x, y, label = "Sampled points", xlims = (lb, ub), ylims = (-2.5, 2.5), legend = :bottom)
plot!(xs, f.(xs), label = "True function", legend = :top)
plot!(xs, loba_1.(xs), label = "Lobachevsky", legend = :top)
plot!(xs, krig.(xs), label = "Kriging", legend = :top)
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 3302 | ## Surrogates 101
Let's start with something easy to get our hands dirty.
I want to build a surrogate for ``f(x) = \log(x) \cdot x^2+x^3``.
Let's choose the radial basis surrogate.
```@example
using Surrogates
f = x -> log(x) * x^2 + x^3
lb = 1.0
ub = 10.0
x = sample(50, lb, ub, SobolSample())
y = f.(x)
my_radial_basis = RadialBasis(x, y, lb, ub)
#I want an approximation at 5.4
approx = my_radial_basis(5.4)
```
Let's now see an example in 2D.
```@example
using Surrogates
using LinearAlgebra
f = x -> x[1] * x[2]
lb = [1.0, 2.0]
ub = [10.0, 8.5]
x = sample(50, lb, ub, SobolSample())
y = f.(x)
my_radial_basis = RadialBasis(x, y, lb, ub)
#I want an approximation at (1.0,1.4)
approx = my_radial_basis((1.0, 1.4))
```
## Kriging standard error
Let's now use the Kriging surrogate, which is a single-output Gaussian process.
This surrogate has a nice feature: not only does it approximate the solution at a
point, it also calculates the standard error at such a point.
Let's see an example:
```@example kriging
using Surrogates
f = x -> exp(x) * x^2 + x^3
lb = 0.0
ub = 10.0
x = sample(50, lb, ub, RandomSample())
y = f.(x)
p = 1.9
my_krig = Kriging(x, y, lb, ub, p = p)
#I want an approximation at 5.4
approx = my_krig(5.4)
#I want to find the standard error at 5.4
std_err = std_error_at_point(my_krig, 5.4)
```
Let's now optimize the Kriging surrogate using the lower confidence bound method. This is just a one-liner:
```@example kriging
surrogate_optimize(
f, LCBS(), lb, ub, my_krig, RandomSample(); maxiters = 10, num_new_samples = 10)
```
Surrogate optimization methods have two purposes: they both sample the space in unknown regions and look for the minima at the same time.
## Lobachevsky integral
The Lobachevsky surrogate has the nice feature of having a closed formula for its
integral, which is something that other surrogates are missing.
Let's compare it with QuadGK:
```@example
using Surrogates
using QuadGK
obj = x -> 3 * x + log(x)
a = 1.0
b = 4.0
x = sample(2000, a, b, SobolSample())
y = obj.(x)
alpha = 2.0
n = 6
my_loba = LobachevskySurrogate(x, y, a, b, alpha = alpha, n = n)
#1D integral
int_1D = lobachevsky_integral(my_loba, a, b)
int = quadgk(obj, a, b)
int_val_true = int[1] - int[2]
println(int_1D)
println(int_val_true)
```
## Example of NeuralSurrogate
Basic example of fitting a neural network on a simple function of two variables.
```@example
using Surrogates
using Flux
using Statistics
using SurrogatesFlux
f = x -> x[1]^2 + x[2]^2
bounds = Float32[-1.0, -1.0], Float32[1.0, 1.0]
# Flux models are in single precision by default.
# Thus, single precision will also be used here for our training samples.
x_train = sample(100, bounds..., SobolSample())
y_train = f.(x_train)
# Perceptron with one hidden layer of 20 neurons.
model = Chain(Dense(2, 20, relu), Dense(20, 1))
loss(x, y) = Flux.mse(model(x), y)
# Training of the neural network
learning_rate = 0.1
optimizer = Descent(learning_rate) # Simple gradient descent. See Flux documentation for other options.
n_epochs = 50
sgt = NeuralSurrogate(x_train, y_train, bounds..., model = model,
loss = loss, opt = optimizer, n_echos = n_epochs)
# Testing the new model
x_test = sample(30, bounds..., SobolSample())
test_error = mean(abs2, sgt(x)[1] - f(x) for x in x_test)
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 1123 | # Variable fidelity Surrogates
With the variable fidelity surrogate, we can specify two different surrogates: one for high-fidelity data and one for low-fidelity data.
By default, the first half of the samples are considered high-fidelity and the second half low-fidelity.
```@example variablefid
using Surrogates
using Plots
default()
```
```@example variablefid
n = 20
lower_bound = 1.0
upper_bound = 6.0
x = sample(n, lower_bound, upper_bound, SobolSample())
f = x -> 1 / 3 * x
y = f.(x)
plot(x, y, seriestype = :scatter, label = "Sampled points",
xlims = (lower_bound, upper_bound), legend = :top)
plot!(f, label = "True function", xlims = (lower_bound, upper_bound), legend = :top)
```
```@example variablefid
varfid = VariableFidelitySurrogate(x, y, lower_bound, upper_bound)
```
```@example variablefid
plot(x, y, seriestype = :scatter, label = "Sampled points",
xlims = (lower_bound, upper_bound), legend = :top)
plot!(f, label = "True function", xlims = (lower_bound, upper_bound), legend = :top)
plot!(
varfid, label = "Surrogate function", xlims = (lower_bound, upper_bound), legend = :top)
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 1271 | # Water flow function
The water flow function is defined as:
``f(r_w,r,T_u,H_u,T_l,H_l,L,K_w) = \frac{2*\pi*T_u(H_u - H_l)}{\log(\frac{r}{r_w})*[1 + \frac{2LT_u}{\log(\frac{r}{r_w})*r_w^2*K_w}+ \frac{T_u}{T_l} ]}``
It has 8 dimensions.
```@example water
using Surrogates
using SurrogatesPolyChaos
using Plots
using LinearAlgebra
default()
```
Define the objective function:
```@example water
function f(x)
r_w = x[1]
r = x[2]
T_u = x[3]
H_u = x[4]
T_l = x[5]
H_l = x[6]
L = x[7]
K_w = x[8]
log_val = log(r / r_w)
return (2 * pi * T_u * (H_u - H_l)) /
(log_val * (1 + (2 * L * T_u / (log_val * r_w^2 * K_w)) + T_u / T_l))
end
```
```@example water
n = 180
d = 8
lb = [0.05, 100, 63070, 990, 63.1, 700, 1120, 9855]
ub = [0.15, 50000, 115600, 1110, 116, 820, 1680, 12045]
x = sample(n, lb, ub, SobolSample())
y = f.(x)
n_test = 1000
x_test = sample(n_test, lb, ub, GoldenSample());
y_true = f.(x_test);
```
```@example water
my_rad = RadialBasis(x, y, lb, ub)
y_rad = my_rad.(x_test)
my_poly = PolynomialChaosSurrogate(x, y, lb, ub)
y_poly = my_poly.(x_test)
mse_rad = norm(y_true - y_rad, 2) / n_test
mse_poly = norm(y_true - y_poly, 2) / n_test
println("MSE Radial: $mse_rad")
println("MSE Radial: $mse_poly")
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 1252 | # Welded beam function
The welded beam function is defined as:
``f(h,l,t) = \sqrt{\frac{a^2 + b^2 + abl}{\sqrt{0.25(l^2+(h+t)^2)}}}``
With:
``a = \frac{6000}{\sqrt{2}hl}``
``b = \frac{6000(14 + 0.5l)*\sqrt{0.25(l^2+(h+t)^2)}}{2*[0.707hl(\frac{l^2}{12}+0.25*(h+t)^2)]}``
It has 3 dimension.
```@example welded
using Surrogates
using Plots
using LinearAlgebra
default()
```
Define the objective function:
```@example welded
function f(x)
h = x[1]
l = x[2]
t = x[3]
a = 6000 / (sqrt(2) * h * l)
b = (6000 * (14 + 0.5 * l) * sqrt(0.25 * (l^2 + (h + t)^2))) /
(2 * (0.707 * h * l * (l^2 / 12 + 0.25 * (h + t)^2)))
return (sqrt(a^2 + b^2 + l * a * b)) / (sqrt(0.25 * (l^2 + (h + t)^2)))
end
```
```@example welded
n = 300
d = 3
lb = [0.125, 5.0, 5.0]
ub = [1.0, 10.0, 10.0]
x = sample(n, lb, ub, SobolSample())
y = f.(x)
n_test = 1000
x_test = sample(n_test, lb, ub, GoldenSample());
y_true = f.(x_test);
```
```@example welded
my_rad = RadialBasis(x, y, lb, ub)
y_rad = my_rad.(x_test)
mse_rad = norm(y_true - y_rad, 2) / n_test
println("MSE Radial: $mse_rad")
my_loba = LobachevskySurrogate(x, y, lb, ub)
y_loba = my_loba.(x_test)
mse_rad = norm(y_true - y_loba, 2) / n_test
println("MSE Lobachevsky: $mse_rad")
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 6.10.0 | ba29564853a3f7b10eb699f1e99a62cdb6a3770f | docs | 1215 | # Wendland Surrogate
The Wendland surrogate is a compact surrogate: it allocates much less memory than other surrogates.
The coefficients are found using an iterative solver.
``f = x -> exp(-x^2)``
```@example wendland
using Surrogates
using Plots
```
```@example wendland
n = 40
lower_bound = 0.0
upper_bound = 1.0
f = x -> exp(-x^2)
x = sample(n, lower_bound, upper_bound, SobolSample())
y = f.(x)
```
We choose to sample f in 30 points between 5 and 25 using `sample` function. The sampling points are chosen using a Sobol sequence, this can be done by passing `SobolSample()` to the `sample` function.
## Building Surrogate
The choice of the right parameter is especially important here:
a slight change in Ο΅ would produce a totally different fit.
Try it yourself with this function!
```@example wendland
my_eps = 0.5
wend = Wendland(x, y, lower_bound, upper_bound, eps = my_eps)
```
```@example wendland
plot(x, y, seriestype = :scatter, label = "Sampled points",
xlims = (lower_bound, upper_bound), legend = :top)
plot!(f, label = "True function", xlims = (lower_bound, upper_bound), legend = :top)
plot!(wend, label = "Surrogate function", xlims = (lower_bound, upper_bound), legend = :top)
```
| Surrogates | https://github.com/SciML/Surrogates.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 853 | using Documenter
using SatelliteToolboxAtmosphericModels
makedocs(
modules = [SatelliteToolboxAtmosphericModels],
format = Documenter.HTML(
prettyurls = !("local" in ARGS),
canonical = "https://juliaspace.github.io/SatelliteToolboxAtmosphericModels.jl/stable/",
),
sitename = "SatelliteToolboxAtmosphericModels.jl",
authors = "Ronan Arraes Jardim Chagas",
pages = [
"Home" => "index.md",
"Atmospheric Models" => [
"Exponential" => "man/exponential.md",
"Jacchia-Roberts 1971" => "man/jr1971.md",
"Jacchia-Bowman 2008" => "man/jb2008.md",
"NRLMSISE-00" => "man/nrlmsise00.md"
],
"Library" => "lib/library.md",
],
)
deploydocs(
repo = "github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git",
target = "build",
)
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 1712 | ## Description #############################################################################
#
# Definition of the module AtmosphericModels to access the models defined here.
#
############################################################################################
module AtmosphericModels
using Accessors
using Crayons
using LinearAlgebra
using PolynomialRoots
using Printf
using SpaceIndices
using SatelliteToolboxBase
using SatelliteToolboxCelestialBodies
using SatelliteToolboxLegendre
import Base: show
############################################################################################
# Constants #
############################################################################################
const _D = string(Crayon(reset = true))
const _B = string(crayon"bold")
############################################################################################
# Includes #
############################################################################################
include("./exponential/constants.jl")
include("./exponential/exponential.jl")
include("./jr1971/types.jl")
include("./jr1971/constants.jl")
include("./jr1971/jr1971.jl")
include("./jr1971/show.jl")
include("./jb2008/types.jl")
include("./jb2008/constants.jl")
include("./jb2008/jb2008.jl")
include("./jb2008/show.jl")
include("./nrlmsise00/types.jl")
include("./nrlmsise00/auxiliary.jl")
include("./nrlmsise00/constants.jl")
include("./nrlmsise00/math.jl")
include("./nrlmsise00/nrlmsise00.jl")
include("./nrlmsise00/show.jl")
end # module AtmosphericModels
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 475 | module SatelliteToolboxAtmosphericModels
using Reexport
@reexport using SpaceIndices
export AtmosphericModels
############################################################################################
# Includes #
############################################################################################
include("./AtmosphericModels.jl")
end # module SatelliteToolboxAtmosphericModels
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 1865 | ## Description #############################################################################
#
# Constants for the exponential atmosphere model.
#
## References ##############################################################################
#
# [1] Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications. 4th ed.
# Microcosm Press, Hawthorn, CA, USA.
#
############################################################################################
"""
const _EXPONENTIAL_ATMOSPHERE_Hβ
Base altitude for the exponential atmospheric model [km].
"""
const _EXPONENTIAL_ATMOSPHERE_Hβ = [
0,
25,
30,
40,
50,
60,
70,
80,
90,
100,
110,
120,
130,
140,
150,
180,
200,
250,
300,
350,
400,
450,
500,
600,
700,
800,
900,
1000
]
"""
const _EXPONENTIAL_ATMOSPHERE_Οβ
Nominal density for the exponential atmospheric model [kg / mΒ³].
"""
const _EXPONENTIAL_ATMOSPHERE_Οβ = [
1.225,
3.899e-2,
1.774e-2,
3.972e-3,
1.057e-3,
3.206e-4,
8.770e-5,
1.905e-5,
3.396e-6,
5.297e-7,
9.661e-8,
2.438e-8,
8.484e-9,
3.845e-9,
2.070e-9,
5.464e-10,
2.789e-10,
7.248e-11,
2.418e-11,
9.518e-12,
3.725e-12,
1.585e-12,
6.967e-13,
1.454e-13,
3.614e-14,
1.170e-14,
5.245e-15,
3.019e-15
]
"""
const _EXPONENTIAL_ATMOSPHERE_H
Scale height for the exponential atmospheric model [km].
"""
const _EXPONENTIAL_ATMOSPHERE_H = [
7.249,
6.349,
6.682,
7.554,
8.382,
7.714,
6.549,
5.799,
5.382,
5.877,
7.263,
9.473,
12.636,
16.149,
22.523,
29.740,
37.105,
45.546,
53.628,
53.298,
58.515,
60.828,
63.822,
71.835,
88.667,
124.64,
181.05,
268.00
]
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 1435 | ## Description #############################################################################
#
# Exponential atmosphere model.
#
## Reference ###############################################################################
#
# [1] Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications. 4th ed.
# Microcosm Press, Hawthorn, CA, USA.
#
############################################################################################
export exponential
"""
exponential(h::Number) -> Float64
Compute the atmospheric density [kg / mΒ³] at the altitude `h` [m] above the ellipsoid using
the exponential atmospheric model:
β β
β h - hβ β
Ο(h) = Οβ . exp β - ββββββββ β ,
β H β
β β
in which `Οβ`, `hβ`, and `H` are parameters obtained from tables that depend only on `h`.
"""
function exponential(h::Number)
# Check the bounds.
h < 0 && throw(ArgumentError("The height must be positive."))
# Transform `h` to km.
h /= 1000
# Get the values for the exponential model.
aux = findfirst(>(0), _EXPONENTIAL_ATMOSPHERE_Hβ .- h)
id = isnothing(aux) ? 28 : aux - 1
hβ = _EXPONENTIAL_ATMOSPHERE_Hβ[id]
Οβ = _EXPONENTIAL_ATMOSPHERE_Οβ[id]
H = _EXPONENTIAL_ATMOSPHERE_H[id]
# Compute the density.
density = Οβ * exp(-(h - hβ) / H)
return density
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 1748 | ## Description #############################################################################
#
# Constants for the Jacchia-Bowman 2008 Atmospheric Model.
#
############################################################################################
# Constants to compute the `ΞTc` correction.
const _JB2008_B = (
-0.457512297e+01,
-0.512114909e+01,
-0.693003609e+02,
0.203716701e+03,
0.703316291e+03,
-0.194349234e+04,
0.110651308e+04,
-0.174378996e+03,
0.188594601e+04,
-0.709371517e+04,
0.922454523e+04,
-0.384508073e+04,
-0.645841789e+01,
0.409703319e+02,
-0.482006560e+03,
0.181870931e+04,
-0.237389204e+04,
0.996703815e+03,
0.361416936e+02,
)
const _JB2008_C = (
-0.155986211e+02,
-0.512114909e+01,
-0.693003609e+02,
0.203716701e+03,
0.703316291e+03,
-0.194349234e+04,
0.110651308e+04,
-0.220835117e+03,
0.143256989e+04,
-0.318481844e+04,
0.328981513e+04,
-0.135332119e+04,
0.199956489e+02,
-0.127093998e+02,
0.212825156e+02,
-0.275555432e+01,
0.110234982e+02,
0.148881951e+03,
-0.751640284e+03,
0.637876542e+03,
0.127093998e+02,
-0.212825156e+02,
0.275555432e+01
)
# F(z) global model values, 1997 - 2006 fit.
const _JB2008_FZM = (0.2689e+00, -0.1176e-01, 0.2782e-01, -0.2782e-01, 0.3470e-03)
# G(t) global model values, 1997 - 2006 fit.
const _JB2008_GTM = (
-0.3633e+00,
0.8506e-01,
0.2401e+00,
-0.1897e+00,
-0.2554e+00,
-0.1790e-01,
0.5650e-03,
-0.6407e-03,
-0.3418e-02,
-0.1252e-02
)
# Coefficients for high altitude density correction.
const _JB2008_CHT = (0.22e0, -0.20e-02, 0.115e-02, -0.211e-05)
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 32337 | ## Description #############################################################################
#
# The Jacchia-Bowman 2008 Atmospheric Model, a product of the Space Environment
# Technologies.
#
# The source code is available at the following git:
#
# http://sol.spacenvironment.net/jb2008/code.html
#
# For more information about the model, see:
#
# http://sol.spacenvironment.net/~JB2008/
#
## References ##############################################################################
#
# [1] Bowman, B. R., Tobiska, W. K., Marcos, F. A., Huang, C. Y., Lin, C. S., Burke, W. J
# (2008). A new empirical thermospheric density model JB2008 using new solar and
# geomagnetic indices. AIAA/AAS Astrodynamics Specialist Conference, Honolulu, Hawaii.
#
# [2] Bowman, B. R., Tobiska, W. K., Marcos, F. A., Valladares, C (2007). The JB2006
# empirical thermospheric density model. Journal of Atmospheric and Solar-Terrestrial
# Physics, v. 70, p. 774-793.
#
# [3] Jacchia, L. G (1970). New static models of the thermosphere and exosphere with
# empirical temperature profiles. SAO Special Report #313.
#
############################################################################################
export jb2008
"""
jb2008(instant::DateTime, Ο_gd::Number, Ξ»::Number, h::Number[, F10::Number, F10β::Number, S10::Number, S10β::Number, M10::Number, M10β::Number, Y10::Number, Y10β::Number, DstΞTc::Number]) -> JB2008Output{Float64}
jb2008(jd::Number, Ο_gd::Number, Ξ»::Number, h::Number[, F10::Number, F10β::Number, S10::Number, S10β::Number, M10::Number, M10β::Number, Y10::Number, Y10β::Number, DstΞTc::Number]) -> JB2008Output{Float64}
Compute the atmospheric density using the Jacchia-Bowman 2008 (JB2008) model.
This model is a product of the **Space Environment Technologies**, please, refer to the
following website for more information:
http://sol.spacenvironment.net/JB2008/
If we omit all space indices, the system tries to obtain them automatically for the selected
day `jd` or `instant`. However, the indices must be already initialized using the function
`SpaceIndices.init()`.
# Arguments
- `jd::Number`: Julian day to compute the model.
- `instant::DateTime`: Instant to compute the model represent using `DateTime`.
- `Ο_gd`: Geodetic latitude [rad].
- `Ξ»`: Longitude [rad].
- `h`: Altitude [m].
- `F10`: 10.7-cm solar flux [sfu] obtained 1 day before `jd`.
- `F10β`: 10.7-cm averaged solar flux using a 81-day window centered on input time obtained
1 day before `jd`.
- `S10`: EUV index (26-34 nm) scaled to F10.7 obtained 1 day before `jd`.
- `S10β`: EUV 81-day averaged centered index obtained 1 day before `jd`.
- `M10`: MG2 index scaled to F10.7 obtained 2 days before `jd`.
- `M10β`: MG2 81-day averaged centered index obtained 2 day before `jd`.
- `Y10`: Solar X-ray & Ly-Ξ± index scaled to F10.7 obtained 5 days before `jd`.
- `Y10β`: Solar X-ray & Ly-Ξ± 81-day averaged centered index obtained 5 days before `jd`.
- `DstΞTc`: Temperature variation related to the Dst.
# Returns
- `JB2008Output{Float64}`: Structure containing the results obtained from the model.
"""
function jb2008(instant::DateTime, Ο_gd::Number, Ξ»::Number, h::Number)
return jb2008(datetime2julian(instant), Ο_gd, Ξ», h)
end
function jb2008(jd::Number, Ο_gd::Number, Ξ»::Number, h::Number)
# Get the data in the desired Julian Day considering the tabular time of the model.
F10 = space_index(Val(:F10obs), jd - 1)
F10β = sum((space_index.(Val(:F10obs), k) for k in (jd - 1 - 40):(jd - 1 + 40))) / 81
S10 = space_index(Val(:S10), jd - 1)
S10β = space_index(Val(:S81a), jd - 1)
M10 = space_index(Val(:M10), jd - 2)
M10β = space_index(Val(:M81a), jd - 2)
Y10 = space_index(Val(:Y10), jd - 5)
Y10β = space_index(Val(:Y81a), jd - 5)
DstΞTc = space_index(Val(:DTC), jd)
@debug """
JB2008 - Fetched Space Indices
Daily F10.7 : $(F10) sfu
81-day averaged F10.7 : $(F10β) sfu
Daily S10 : $(S10)
81-day averaged S10 : $(S10β)
Daily M10 : $(M10)
81-day averaged M10 : $(M10β)
Daily Y10 : $(Y10)
81-day averaged Y10 : $(Y10β)
Exo. temp. variation : $(DstΞTc)
"""
return jb2008(jd, Ο_gd, Ξ», h, F10, F10β, S10, S10β, M10, M10β, Y10, Y10β, DstΞTc)
end
function jb2008(
instant::DateTime,
Ο_gd::Number,
Ξ»::Number,
h::Number,
F10::Number,
F10β::Number,
S10::Number,
S10β::Number,
M10::Number,
M10β::Number,
Y10::Number,
Y10β::Number,
DstΞTc::Number
)
jd = datetime2julian(instant)
return jb2008(jd, Ο_gd, Ξ», h, F10, F10β, S10, S10β, M10, M10β, Y10, Y10β, DstΞTc)
end
function jb2008(
jd::Number,
Ο_gd::Number,
Ξ»::Number,
h::Number,
F10::Number,
F10β::Number,
S10::Number,
S10β::Number,
M10::Number,
M10β::Number,
Y10::Number,
Y10β::Number,
DstΞTc::Number
)
########################################################################################
# Constants #
########################################################################################
Tβ = 183.0 # ............................... Temperature at the lower bound [K]
zβ = 90.0 # ................................. Altitude of the lower bound [km]
zx = 125.0 # ............................ Altitude of the inflection point [km]
Rstar = 8314.32 # .. Rstar is the universal gas-constant (mks) [joules / (K . kmol)]
Οβ = 3.46e-6 # ........................................ Density at `zβ` [kg / mΒ³]
A = 6.02257e26 # ..................... Avogadro's constant (mks) [molecules / kmol]
# Assumed sea-level composition.
Mbβ = 28.960
qβNβ = 0.78110
qβOβ = 0.20955
qβAr = 9.3400e-3
qβHe = 1.2890e-5
# Molecular weights of each specie [kg / kmol].
MNβ = 28.0134
MOβ = 31.9988
MO = 15.9994
MAr = 39.9480
MHe = 4.0026
MH = 1.00797
# Thermal diffusion coefficient for each specie.
Ξ±_Nβ = 0.0
Ξ±_Oβ = 0.0
Ξ±_O = 0.0
Ξ±_Ar = 0.0
Ξ±_He = -0.38
Ξ±_Hβ = 0.0
# Values used to establish height step sizes in the integration process between 90 km to
# 105 km, 105 km to 500 km, and above 500km.
R1 = 0.010
R2 = 0.025
R3 = 0.075
########################################################################################
# Preliminaries #
########################################################################################
# Convert the altitude from [m] to [km].
h /= 1000
# Compute the Sun position represented in the inertial reference frame (MOD).
s_i = sun_position_mod(jd)
# Compute the Sun declination [rad].
Ξ΄s = atan(s_i[3], β(s_i[1] * s_i[1] + s_i[2] * s_i[2]))
# Compute the Sun right ascension [rad].
Ξ©s = atan(s_i[2], s_i[1])
# Compute the right ascension of the selected location w.r.t. the inertial reference
# frame.
Ξ©p = Ξ» + jd_to_gmst(jd)
# Compute the hour angle at the selected location, which is the angle measured at the XY
# plane between the right ascension of the selected position and the right ascension of
# the Sun.
H = Ξ©p - Ξ©s
# Compute the local solar time.
lst = mod((H + Ο) * 12 / Ο, 24)
########################################################################################
# Algorithm #
########################################################################################
# == Eq. 2 [1], Eq. 14 [3] =============================================================
#
# Nighttime minimum of the global exospheric temperature distribution when the planetary
# geomagnetic index Kp is zero.
ΞF10 = F10 - F10β
ΞS10 = S10 - S10β
ΞM10 = M10 - M10β
ΞY10 = Y10 - Y10β
Wt = min((F10β / 240)^(1 / 4), 1.0)
Fsβ = F10β * Wt + S10β * (1-Wt)
Tc = 392.4 + 3.227Fsβ + 0.298ΞF10 + 2.259ΞS10 + 0.312ΞM10 + 0.178ΞY10
# == Eq. 15 [3] ========================================================================
Ξ· = abs(Ο_gd - Ξ΄s) / 2
ΞΈ = abs(Ο_gd + Ξ΄s) / 2
# == Eq. 16 [3] ========================================================================
Ο = H - 0.64577182 + 0.10471976sin(H + 0.75049158)
# == Eq. 17 [3] ========================================================================
m = 2.5
n = 3.0
R = 0.31
C = cos(Ξ·)^m
S = sin(ΞΈ)^m
# NOTE: The original equation in [3] does not have the `abs` as in the source-code of
# JB2008.
Tl = Tc * (1 + R * (S + (C - S) * abs(cos(Ο / 2))^n))
# Compute the correction to `Tc` considering the local solar time and latitude.
ΞTc = _jb2008_ΞTc(F10, lst, Ο_gd, h)
# Compute the local exospheric temperature with the geomagnetic storm effect.
T_exo = Tl + DstΞTc
Tβ = T_exo + ΞTc
# == Eq. 9 [3] =========================================================================
#
# Temperature at the inflection point `z = 125 km`.
a = 444.3807
b = 0.02385
c = -392.8292
k = -0.0021357
Tx = a + b * Tβ + c * exp(k * Tβ)
# == Eq. 5 [3] =========================================================================
#
# From 90 to 105 km, for a given temperature profile `T[k]`, the density Ο is computed
# by integrating the barometric equation:
#
# β β
# β MΒ΄ β MΜΒ΄ g
# d ln(ΟΒ΄) = d ln β βββ β - ββββββ dz ,
# β T β Rβ T
# β β
#
# which can be rewritten as:
#
# β β
# β ΟΒ΄T β MΜΒ΄ g
# d ln β βββββ β - ββββββ dz .
# β MΜΒ΄ β Rβ T
# β β
#
# Here, we will compute the following integral:
#
#
# β zβ
# β MΜΒ΄ g
# β ββββββ dz
# β T
# β― zβ
#
# in which zβ is the minimum value between `h` and 105 km. The integration will be
# computed by Newton-Cotes 4th degree method.
zβ = min(h, 105.0)
int, zβ = _jb2008_β«(zβ, zβ, R1, Tx, Tβ, _jb2008_Ξ΄f1)
Mbβ = _jb2008_mean_molecular_mass(zβ)
Tlβ = _jb2008_temperature(zβ, Tx, Tβ)
Mbβ = _jb2008_mean_molecular_mass(zβ)
Tlβ = _jb2008_temperature(zβ, Tx, Tβ)
# `Mbj` and `Tlj` contains, respectively, the mean molecular mass and local temperature
# at the boundary of the integration interval.
#
# The factor 1000 converts `Rstar` to the appropriate units.
Ο = Οβ * (Mbβ / Mbβ) * (Tlβ / Tlβ) * exp(-1000 * int / Rstar)
# == Eq. 2 [3] =========================================================================
NM = A * Ο
N = NM / Mbβ
# == Eq. 3 [3] =========================================================================
log_nNβ = log(qβNβ * NM / Mbβ)
log_nAr = log(qβAr * NM / Mbβ)
log_nHe = log(qβHe * NM / Mbβ)
# == Eq. 4 [3] =========================================================================
log_nOβ = log(NM / Mbβ * (1 + qβOβ) - N)
log_nO = log(2 * (N - NM / Mbβ))
log_nH = 0.0
Tz = 0.0
if h <= 105
Tz = Tlβ
log_nHβ = log_nHe - 25
else
# == Eq.6 [3] ======================================================================
#
# From 100 km to 500 km, neglecting the thermal diffusion coefficient,
# the eq. 6 in [3] can be written as:
#
# β β
# β 1 + Ξ±α΅’β MΜΒ΄ g
# d ln βn . T β = - ββββββ dz ,
# β β R* T
# β β
#
# where `n` is number density for the i-th specie. This equations must be integrated
# for each specie we are considering.
#
# Here, we will compute the following integral:
#
# β zβ
# β g
# β βββ dz
# β T
# β― zβ
#
# in which zβ is the minimum value between `h` and 500 km. The integration will be
# computed by Newton-Cotes 4th degree method.
zβ = min(h, 500.0)
intβ, zβ = _jb2008_β«(zβ, zβ, R1, Tx, Tβ, _jb2008_Ξ΄f2)
Tlβ = _jb2008_temperature(zβ, Tx, Tβ)
# If `h` is lower than 500 km, then keep integrating until 500 km due to the
# hydrogen. Otherwise, continue the integration until `h`. Hence, we will compute
# the following integral:
#
# β zβ
# β g
# β βββ dz
# β T
# β― zβ
#
# in which zβ is the maximum value between `h` and 500 km. The integration will be
# computed by Newton-Cotes 4th degree method.
zβ = max(h, 500.0)
intβ, zβ = _jb2008_β«(zβ, zβ, (h <= 500) ? R2 : R3, Tx, Tβ, _jb2008_Ξ΄f2)
Tlβ = _jb2008_temperature(zβ, Tx, Tβ)
if h <= 500
Tz = Tlβ
log_TfoTi = log(Tlβ / Tlβ)
H_sign = +1
# g
# goRT = βββββ
# Rβ T
goRT = 1000 * intβ / Rstar
else
Tz = Tlβ
log_TfoTi = log(Tlβ / Tlβ)
H_sign = -1
# g
# goRT = βββββ
# Rβ T
goRT = 1000 * (intβ + intβ) / Rstar
end
log_nNβ += -(1 + Ξ±_Nβ) * log_TfoTi - goRT * MNβ
log_nOβ += -(1 + Ξ±_Oβ) * log_TfoTi - goRT * MOβ
log_nO += -(1 + Ξ±_O ) * log_TfoTi - goRT * MO
log_nAr += -(1 + Ξ±_Ar) * log_TfoTi - goRT * MAr
log_nHe += -(1 + Ξ±_He) * log_TfoTi - goRT * MHe
# == Eq. 7 [3] =====================================================================
#
# The equation of [3] will be converted from `logββ` to `log`. Furthermore, the
# units will be converted to [1 / cmΒ³] to [1 / mΒ³].
logββ_nH_500km = @evalpoly(log10(Tβ), 73.13, -39.40, 5.5)
log_nH_500km = log(10) * (logββ_nH_500km + 6)
# ^
# |
# This factor converts from [1 / cmΒ³] to [1 / mΒ³].
# Compute the hydrogen density based on the value at 500km.
log_nH = log_nH_500km + H_sign * (log(Tlβ / Tlβ) + 1000 / Rstar * intβ * MH)
end
# == Eq. 24 [3] - Seasonal-latitudinal variation =======================================
#
# TODO: The term related to the year in the source-code of JB 2008 is different from
# [3]. This must be verified.
# | Modified jd |
Ξ¦ = mod((jd - 2400000.5 - 36204 ) / 365.2422, 1)
ΞlogββΟ = 0.02 * (h - 90) * sign(Ο_gd) * exp(-0.045(h - 90)) * sin(Ο_gd)^2 * sin(2Ο * Ξ¦ + 1.72 )
# Convert from `log10` to `log`.
ΞlogΟ = log(10) * ΞlogββΟ
# == Eq. 23 [3] - Semiannual variation =================================================
if h < 2000
# Compute the year given the selected Julian Day.
year, month, day, = jd_to_date(jd)
# Compute the day of the year.
doy = jd - date_to_jd(year, 1, 1, 0, 0, 0) + 1
# Use the new semiannual model from [1].
Fz, Gz, ΞsalogββΟ = _jb2008_semiannual(doy, h, F10β, S10β, M10β)
(Fz < 0) && (ΞsalogββΟ = 0.0)
# Convert from `log10` to `log`.
ΞsalogΟ = log(10) * ΞsalogββΟ
else
ΞsalogΟ = 0.0
end
# Compute the total variation.
ΞΟ = ΞlogΟ + ΞsalogΟ
# Apply to the number densities.
log_nNβ += ΞΟ
log_nOβ += ΞΟ
log_nO += ΞΟ
log_nAr += ΞΟ
log_nHe += ΞΟ
log_nH += ΞΟ
# Compute the high altitude exospheric density correction factor.
#
# The source-code computes this correction after computing the mass density and mean
# molecular weight. Hence, the correction is applied only to the total density. However,
# we will apply the correction to each specie.
#
# TODO: Verify if this is reasonable.
log_FΟH = log(_jb2008_high_altitude(h, F10β))
log_nNβ += log_FΟH
log_nOβ += log_FΟH
log_nO += log_FΟH
log_nAr += log_FΟH
log_nHe += log_FΟH
log_nH += log_FΟH
# Compute the mass density and mean molecular weight and convert number density logs
# from natural to common.
sum_n = 0.0
sum_mn = 0.0
for (log_n, M) in (
(log_nNβ, MNβ),
(log_nOβ, MOβ),
(log_nO, MO),
(log_nAr, MAr),
(log_nHe, MHe),
(log_nH, MH)
)
n = exp(log_n)
sum_n += n
sum_mn += n * M
end
nNβ = exp(log_nNβ)
nOβ = exp(log_nOβ)
nO = exp(log_nO)
nAr = exp(log_nAr)
nHe = exp(log_nHe)
nH = exp(log_nH)
Ο = sum_mn / A
# Create and return the output structure.
return JB2008Output{Float64}(
Ο,
Tz,
T_exo,
nNβ,
nOβ,
nO,
nAr,
nHe,
nH,
)
end
############################################################################################
# Private Functions #
############################################################################################
# _jb2008_gravity(z::Number) -> Float64
#
# Compute the gravity [m / s] at altitude `z` [km] according to the model Jacchia 1971 [3].
function _jb2008_gravity(z::Number)
# Mean Earth radius [km].
Re = 6356.776
# Gravity at Earth surface [m/sΒ²].
gβ = 9.80665
# Gravity at desired altitude [m/sΒ²].
return gβ / (1 + z / Re)^2
end
# _jb2008_high_altitude(h::Number, F10β::Number) -> Float64
#
# Compute the high altitude exospheric density correction factor in altitude `h` [km] and
# the averaged 10.7-cm solar flux `F10β` [sfu], which must be obtained using 81-day centered
# on input time.
#
# This function uses the model in Section 6.2 of [2].
function _jb2008_high_altitude(h::Number, F10β::Number)
# Auxiliary variables.
C = _JB2008_CHT
# Compute the high-altitude density correction.
FΟH = 1.0
@inbounds if 1000 <= h <= 1500
z = (h - 1000) / 500
# In this case, the `Fββ
ββ` is the density factor at 1500 km.
Fββ
ββ = C[1] + C[2] * F10β + 1500 * (C[3] + C[4] * F10β)
βFββ
ββ_βz = 500 * (C[3] + C[4] * F10β)
# In [2], there is an error when computing this coefficients (eq. 11). The partial
# derivative has the `500` factor and the coefficients have other `500` factor that
# **is not** present in the source-code.
c0 = +1
c1 = +0
c2 = +3Fββ
ββ - βFββ
ββ_βz - 3
c3 = -2Fββ
ββ + βFββ
ββ_βz + 2
FΟH = @evalpoly(z, c0, c1, c2, c3)
elseif h > 1500
FΟH = C[1] + C[2] * F10β + C[3] * h + C[4] * h * F10β
end
return FΟH
end
# _jb2008_M(z::R) where R -> Float64
#
# Compute the mean molecular mass at altitude `z` [km] using the empirical profile in eq. 1
# [3].
function _jb2008_mean_molecular_mass(z::Number)
!(90 <= z < 105.1) &&
@warn "The empirical model for the mean molecular mass is valid only for 90 <= z <= 105 km."
M = @evalpoly(
z - 100,
+28.15204,
-0.085586,
+1.2840e-4,
-1.0056e-5,
-1.0210e-5,
+1.5044e-6,
+9.9826e-8
)
return M
end
# _jb2008_temperature(z::Number, Tx::Number, Tβ::Number)
#
# Compute the temperature [K] at height `z` [km] given the temperature `Tx` [K] at the
# inflection point, and the exospheric temperature `Tβ` [K] according to the theory of the
# model Jacchia 1971 [3].
#
# The inflection point is considered to by `z = 125 km`.
function _jb2008_temperature(z::Number, Tx::Number, Tβ::Number)
# == Constants =========================================================================
Tβ = 183 # .................................... Temperature at the lower bound [K]
zβ = 90 # ...................................... Altitude of the lower bound [km]
zx = 125 # ................................. Altitude of the inflection point [km]
Ξzβ = zβ - zx
# == Check the Parameters ==============================================================
(z < zβ) && throw(ArgumentError("The altitude must not be lower than $(zβ) km."))
(Tβ < 0) && throw(ArgumentError("The exospheric temperature must be positive."))
# Compute the temperature gradient at the inflection point.
Gx = 1.9 * (Tx - Tβ) / (zx - zβ)
# == Compute the Temperature at the Desire Altitude ====================================
Ξz = z - zx
if z <= zx
cβ = Gx
cβ = 0
cβ =-5.1 / (5.7 * Ξzβ^2) * Gx
cβ = 0.8 / (1.9 * Ξzβ^3) * Gx
T = @evalpoly(Ξz, Tx, cβ, cβ, cβ, cβ)
else
A = 2 * (Tβ - Tx) / Ο
T = Tx + A * atan(Gx / A * Ξz * (1 + 4.5e-6 * Ξz^2.5))
end
return T
end
# _jb2008_Ξ΄f1(z::Number, Tx::Number, Tβ::Number) -> Float64
#
# Auxiliary function to compute the integrand in `_jb2008_β«`.
function _jb2008_Ξ΄f1(z::Number, Tx::Number, Tβ::Number)
Mb = _jb2008_mean_molecular_mass(z)
Tl = _jb2008_temperature(z, Tx, Tβ)
g = _jb2008_gravity(z)
return Mb * g / Tl
end
# _jb2008_Ξ΄f2(z, Tx, Tβ)
#
# Auxiliary function to compute the integrand in `_jb2008_β«`.
function _jb2008_Ξ΄f2(z::Number, Tx::Number, Tβ::Number)
Tl = _jb2008_temperature(z, Tx, Tβ)
g = _jb2008_gravity(z)
return g / Tl
end
# _jb2008_β«(zβ::Number, zβ::Number, R::Number, Tx::Number, Tβ::Number, Ξ΄f::Function) -> Float64, Float64
#
# Compute the integral of the function `Ξ΄f` between `zβ` and `zβ` using the Newton-Cotes 4th
# degree method. `R` is a number that defines the step size, `Tx` is the temperature at the
# inflection point, and `Tβ` is the exospheric temperature.
#
# The integrand function `Ξ΄f` must be `_jb2008_Ξ΄f1` or `_jb2008_Ξ΄f2`.
#
# # Returns
#
# - `Float64`: Value of the integral.
# - `Float64`: Last value of `z` used in the numerical algorithm.
function _jb2008_β«(
zβ::Number,
zβ::Number,
R::Number,
Tx::Number,
Tβ::Number,
Ξ΄f::Function
)
# Compute the number of integration steps.
#
# This is computed so that `zβ = zβ*(zr)^n`. Hence, `zr` is the factor that defines the
# size of each integration interval.
al = log(zβ / zβ)
n = floor(Int64, al / R) + 1
zr = exp(al / n)
# Initialize the integration auxiliary variables.
ziβ = zβ
zj = 0.0
Mbj = 0.0
Tlj = 0.0
# Variable to store the integral from `zβ` to `zβ`.
int = 0.0
# For each integration step, use the Newton-Cotes 4th degree formula to integrate
# (Boole's rule).
@inbounds for i in 1:n
ziβ = ziβ # ............... The beginning of the i-th integration step
ziβ = zr * ziβ # ..................... The end of the i-th integration step
Ξz = (ziβ - ziβ) / 4 # ....................... Step for the i-th integration step
# Compute the Newton-Cotes 4th degree sum.
zj = ziβ
int_i = 14 // 45 * Ξ΄f(zj, Tx, Tβ)
zj += Ξz
int_i += 64 // 45 * Ξ΄f(zj, Tx, Tβ)
zj += Ξz
int_i += 24 // 45 * Ξ΄f(zj, Tx, Tβ)
zj += Ξz
int_i += 64 // 45 * Ξ΄f(zj, Tx, Tβ)
zj += Ξz
int_i += 14 // 45 * Ξ΄f(zj, Tx, Tβ)
# Accumulate the sum.
int += int_i * Ξz
end
return int, zj
end
#
# _jb2008_semiannual(doy::Number, h::Number, F10β::Number, S10β::Number, M10β::Number)
#
# Compute the semiannual density variation considering the JB2008 model [1].
#
# # Arguments
#
# - `doy::Number`: Day of the year + fraction of the day.
# - `h::Number`: Height [km].
# - `F10β::Number`: Averaged 10.7-cm flux, which must use a 81-day window centered on
# the input time [10β»Β²Β² W / (MΒ² Hz)].
# - `S10β`: EUV 81-day averaged centered index.
# - `M10β`: MG2 81-day averaged centered index.
#
# # Returns
#
# - `Float64`: Semiannual F(z) height function.
# - `Float64`: Semiannual G(t) yearly periodic function.
# - `Float64`: Semiannual variation of the density `ΞsalogββΟ`.
function _jb2008_semiannual(
doy::Number,
h::Number,
F10β::Number,
S10β::Number,
M10β::Number
)
# Auxiliary variables.
B = _JB2008_FZM
C = _JB2008_GTM
z = h / 1000
Ο = 2Ο * (doy - 1) / 365 # .............................................. See eq. 4 [2]
# Compute the new 81-day centered solar index for F(z) according to eq. 4 [1].
Fsmjβ = 1F10β - 0.7S10β - 0.04M10β
# Compute the semiannual F(z) height function according to eq. 5 [1].
Fz = B[1] + B[2] * Fsmjβ + B[3] * z * Fsmjβ + B[4] * z^2 * Fsmjβ + B[5] * z * Fsmjβ^2
# Compute the new 81-day centered solar index for G(t) according to eq. 6 [1].
Fsmβ = 1F10β - 0.75S10β - 0.37M10β
# Compute the semiannual G(t) yearly periodic function according to eq. 7
# [1].
sΟ, cΟ = sincos(1Ο)
s2Ο, c2Ο = sincos(2Ο)
Gt = (C[1] + C[2] * sΟ + C[3] * cΟ + C[4] * s2Ο + C[5] * c2Ο) +
(C[6] + C[7] * sΟ + C[8] * cΟ + C[9] * s2Ο + C[10] * c2Ο) * Fsmβ
Fz = max(Fz, 1e-6)
ΞsalogββΟ = Fz * Gt
return Fz, Gt, ΞsalogββΟ
end
# _jb2008_ΞTc(F10::Number, lst::Number, Ο_gd::Number, h::Number)
#
# Compute the correction in the `Tc` for Jacchia-Bowman model.
#
# This correction is mention in [2]. However, the equations do not seem to match those in
# the source-code. The ones implemented here are exactly the same as in the source-code.
#
# # Arguments
#
# - `F10::Number`: F10.7 flux.
# - `lst::Number`: Local solar time (0 - 24) [hr].
# - `Ο_gd::Number`: Geodetic latitude [rad].
# - `h::Number`: Altitude [km].
#
# # Returns
#
# - `Float64`: The correction `ΞTc` [K].
function _jb2008_ΞTc(F10::Number, lst::Number, Ο_gd::Number, h::Number)
# Auxiliary variables according to [2, p. 784].
B = _JB2008_B
C = _JB2008_C
F = (F10 - 100) / 100
ΞΈ = lst / 24
ΞΈΒ² = ΞΈ^2
ΞΈΒ³ = ΞΈ^3
ΞΈβ΄ = ΞΈ^4
ΞΈβ΅ = ΞΈ^5
cΟ = cos(Ο_gd)
ΞTc = 0.0
# Compute the temperature variation given the altitude.
@inbounds if 120 <= h <= 200
ΞTc200 = C[17] +
C[18] * ΞΈ * cΟ +
C[19] * ΞΈΒ² * cΟ +
C[20] * ΞΈΒ³ * cΟ +
C[21] * F * cΟ +
C[22] * ΞΈ * F * cΟ +
C[23] * ΞΈΒ² * F * cΟ
ΞTc200Ξz = C[ 1] +
B[ 2] * F +
C[ 3] * ΞΈ * F +
C[ 4] * ΞΈΒ² * F +
C[ 5] * ΞΈΒ³ * F +
C[ 6] * ΞΈβ΄ * F +
C[ 7] * ΞΈβ΅ * F +
C[ 8] * ΞΈ * cΟ +
C[ 9] * ΞΈΒ² * cΟ +
C[10] * ΞΈΒ³ * cΟ +
C[11] * ΞΈβ΄ * cΟ +
C[12] * ΞΈβ΅ * cΟ +
C[13] * cΟ +
C[14] * F * cΟ +
C[15] * ΞΈ * F * cΟ +
C[16] * ΞΈΒ² * F * cΟ
zp = (h - 120) / 80
ΞTc = (3ΞTc200 - ΞTc200Ξz) * zp^2 + (ΞTc200Ξz - 2ΞTc200) * zp^3
elseif 200 < h <= 240
H = (h - 200) / 50
ΞTc = C[ 1] * H +
B[ 2] * F * H +
C[ 3] * ΞΈ * F * H +
C[ 4] * ΞΈΒ² * F * H +
C[ 5] * ΞΈΒ³ * F * H +
C[ 6] * ΞΈβ΄ * F * H +
C[ 7] * ΞΈβ΅ * F * H +
C[ 8] * ΞΈ * cΟ * H +
C[ 9] * ΞΈΒ² * cΟ * H +
C[10] * ΞΈΒ³ * cΟ * H +
C[11] * ΞΈβ΄ * cΟ * H +
C[12] * ΞΈβ΅ * cΟ * H +
C[13] * cΟ * H +
C[14] * F * cΟ * H +
C[15] * ΞΈ * F * cΟ * H +
C[16] * ΞΈΒ² * F * cΟ * H +
C[17] +
C[18] * ΞΈ * cΟ +
C[19] * ΞΈΒ² * cΟ +
C[20] * ΞΈΒ³ * cΟ +
C[21] * F * cΟ +
C[22] * ΞΈ * F * cΟ +
C[23] * ΞΈΒ² * F * cΟ
elseif 240 < h <= 300
H = 40 / 50
aux1 = C[ 1] * H +
B[ 2] * F * H +
C[ 3] * ΞΈ * F * H +
C[ 4] * ΞΈΒ² * F * H +
C[ 5] * ΞΈΒ³ * F * H +
C[ 6] * ΞΈβ΄ * F * H +
C[ 7] * ΞΈβ΅ * F * H +
C[ 8] * ΞΈ * cΟ * H +
C[ 9] * ΞΈΒ² * cΟ * H +
C[10] * ΞΈΒ³ * cΟ * H +
C[11] * ΞΈβ΄ * cΟ * H +
C[12] * ΞΈβ΅ * cΟ * H +
C[13] * cΟ * H +
C[14] * F * cΟ * H +
C[15] * ΞΈ * F * cΟ * H +
C[16] * ΞΈΒ² * F * cΟ * H +
C[17] +
C[18] * ΞΈ * cΟ +
C[19] * ΞΈΒ² * cΟ +
C[20] * ΞΈΒ³ * cΟ +
C[21] * F * cΟ +
C[22] * ΞΈ * F * cΟ +
C[23] * ΞΈΒ² * F * cΟ
aux2 = C[ 1] +
B[ 2] * F +
C[ 3] * ΞΈ * F +
C[ 4] * ΞΈΒ² * F +
C[ 5] * ΞΈΒ³ * F +
C[ 6] * ΞΈβ΄ * F +
C[ 7] * ΞΈβ΅ * F +
C[ 8] * ΞΈ * cΟ +
C[ 9] * ΞΈΒ² * cΟ +
C[10] * ΞΈΒ³ * cΟ +
C[11] * ΞΈβ΄ * cΟ +
C[12] * ΞΈβ΅ * cΟ +
C[13] * cΟ +
C[14] * F * cΟ +
C[15] * ΞΈ * F * cΟ +
C[16] * ΞΈΒ² * F * cΟ
H = 300 / 100
ΞTc300 = B[ 1] +
B[ 2] * F +
B[ 3] * ΞΈ * F +
B[ 4] * ΞΈΒ² * F +
B[ 5] * ΞΈΒ³ * F +
B[ 6] * ΞΈβ΄ * F +
B[ 7] * ΞΈβ΅ * F +
B[ 8] * ΞΈ * cΟ +
B[ 9] * ΞΈΒ² * cΟ +
B[10] * ΞΈΒ³ * cΟ +
B[11] * ΞΈβ΄ * cΟ +
B[12] * ΞΈβ΅ * cΟ +
B[13] * H * cΟ +
B[14] * ΞΈ * H * cΟ +
B[15] * ΞΈΒ² * H * cΟ +
B[16] * ΞΈΒ³ * H * cΟ +
B[17] * ΞΈβ΄ * H * cΟ +
B[18] * ΞΈβ΅ * H * cΟ +
B[19] * cΟ
ΞTc300Ξz = B[13] * cΟ +
B[14] * ΞΈ * cΟ +
B[15] * ΞΈΒ² * cΟ +
B[16] * ΞΈΒ³ * cΟ +
B[17] * ΞΈβ΄ * cΟ +
B[18] * ΞΈβ΅ * cΟ
aux3 = 3ΞTc300 - ΞTc300Ξz - 3aux1 - 2aux2
aux4 = ΞTc300 - aux1 - aux2 - aux3
zp = (h - 240) / 60
ΞTc = @evalpoly(zp, aux1, aux2, aux3, aux4)
elseif 300 < h <= 600
H = h / 100
ΞTc = B[ 1] +
B[ 2] * F +
B[ 3] * ΞΈ * F +
B[ 4] * ΞΈΒ² * F +
B[ 5] * ΞΈΒ³ * F +
B[ 6] * ΞΈβ΄ * F +
B[ 7] * ΞΈβ΅ * F +
B[ 8] * ΞΈ * cΟ +
B[ 9] * ΞΈΒ² * cΟ +
B[10] * ΞΈΒ³ * cΟ +
B[11] * ΞΈβ΄ * cΟ +
B[12] * ΞΈβ΅ * cΟ +
B[13] * H * cΟ +
B[14] * ΞΈ * H * cΟ +
B[15] * ΞΈΒ² * H * cΟ +
B[16] * ΞΈΒ³ * H * cΟ +
B[17] * ΞΈβ΄ * H * cΟ +
B[18] * ΞΈβ΅ * H * cΟ +
B[19] * cΟ
elseif 600 < h <= 800
zp = (h - 600) / 100
hp = 600 / 100
aux1 = B[ 1] +
B[ 2] * F +
B[ 3] * ΞΈ * F +
B[ 4] * ΞΈΒ² * F +
B[ 5] * ΞΈΒ³ * F +
B[ 6] * ΞΈβ΄ * F +
B[ 7] * ΞΈβ΅ * F +
B[ 8] * ΞΈ * cΟ +
B[ 9] * ΞΈΒ² * cΟ +
B[10] * ΞΈΒ³ * cΟ +
B[11] * ΞΈβ΄ * cΟ +
B[12] * ΞΈβ΅ * cΟ +
B[13] * hp * cΟ +
B[14] * ΞΈ * hp * cΟ +
B[15] * ΞΈΒ² * hp * cΟ +
B[16] * ΞΈΒ³ * hp * cΟ +
B[17] * ΞΈβ΄ * hp * cΟ +
B[18] * ΞΈβ΅ * hp * cΟ +
B[19] * cΟ
aux2 = B[13] * cΟ +
B[14] * ΞΈ * cΟ +
B[15] * ΞΈΒ² * cΟ +
B[16] * ΞΈΒ³ * cΟ +
B[17] * ΞΈβ΄ * cΟ +
B[18] * ΞΈβ΅ * cΟ
aux3 = -(3aux1 + 4aux2) / 4
aux4 = ( aux1 + aux2) / 4
ΞTc = @evalpoly(zp, aux1, aux2, aux3, aux4)
end
return ΞTc
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 2155 | ## Description #############################################################################
#
# Function to show the results of the Jacchia-Bowman 2008 atmospheric model.
#
############################################################################################
function show(io::IO, out::JB2008Output)
# Check for color support in the `io`.
color = get(io, :color, false)
b = color ? _B : ""
d = color ? _D : ""
print(io, "$(b)JB2008 output$(d) (Ο = ", @sprintf("%g", out.total_density), " kg / mΒ³)")
return nothing
end
function show(io::IO, mime::MIME"text/plain", out::JB2008Output)
# Check for color support in the `io`.
color = get(io, :color, false)
b = color ? _B : ""
d = color ? _D : ""
str_total_density = @sprintf("%15g", out.total_density)
str_temperature = @sprintf("%15.2f", out.temperature)
str_exospheric_temp = @sprintf("%15.2f", out.exospheric_temperature)
str_Nβ_number_den = @sprintf("%15g", out.N2_number_density)
str_Oβ_number_den = @sprintf("%15g", out.O2_number_density)
str_O_number_den = @sprintf("%15g", out.O_number_density)
str_Ar_number_den = @sprintf("%15g", out.Ar_number_density)
str_He_number_den = @sprintf("%15g", out.He_number_density)
str_H_number_den = @sprintf("%15g", out.H_number_density)
println(io, "Jacchia-Bowman 2008 Atmospheric Model Result:")
println(io, "$(b) Total density :$(d)", str_total_density, " kg / mΒ³")
println(io, "$(b) Temperature :$(d)", str_temperature, " K")
println(io, "$(b) Exospheric Temp. :$(d)", str_exospheric_temp, " K")
println(io, "$(b) Nβ number density :$(d)", str_Nβ_number_den, " 1 / mΒ³")
println(io, "$(b) Oβ number density :$(d)", str_Oβ_number_den, " 1 / mΒ³")
println(io, "$(b) O number density :$(d)", str_O_number_den, " 1 / mΒ³")
println(io, "$(b) Ar number density :$(d)", str_Ar_number_den, " 1 / mΒ³")
println(io, "$(b) He number density :$(d)", str_He_number_den, " 1 / mΒ³")
print(io, "$(b) H number density :$(d)", str_H_number_den, " 1 / mΒ³")
return nothing
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 1152 | ## Description #############################################################################
#
# Types related to the Jacchia-Bowman 2008 atmospheric model.
#
############################################################################################
export JB2008Output
"""
struct JB2008Output{T<:Number}
Output of the atmospheric model Jacchia-Bowman 2008.
# Fields
- `total_density::T`: Total atmospheric density [1 / mΒ³].
- `temperature::T`: Temperature at the selected position [K].
- `exospheric_temperature::T`: Exospheric temperature [K].
- `N2_number_density::T`: Number density of Nβ [1 / mΒ³].
- `O2_number_density::T`: Number density of Oβ [1 / mΒ³].
- `O_number_density::T`: Number density of O [1 / mΒ³].
- `Ar_number_density::T`: Number density of Ar [1 / mΒ³].
- `He_number_density::T`: Number density of He [1 / mΒ³].
- `H_number_density::T`: Number density of H [1 / mΒ³].
"""
struct JB2008Output{T<:Number}
total_density::T
temperature::T
exospheric_temperature::T
N2_number_density::T
O2_number_density::T
O_number_density::T
Ar_number_density::T
He_number_density::T
H_number_density::T
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 6959 | ## Description #############################################################################
#
# Constants for the Jacchia-Roberts 1971 Atmospheric Model.
#
############################################################################################
"""
const _JR1971_CONSTANTS
Constants for the Jacchia-Roberts 1971 atmospheric model.
"""
const _JR1971_CONSTANTS = (;
########################################################################################
# General Constants #
########################################################################################
Rstar = 8.31432, # ........ Rstar is the universal gas-constant [joules / (K . mol)]
Av = 6.022045e23, # ..................... Avogadro's constant (mks) [molecules / mol]
Ra = 6356.766, # .......................................... Mean Earth radius [km]
gβ = 9.80665, # ................................... Gravity at sea level [m / sΒ²]
########################################################################################
# Values at The Sea Level #
########################################################################################
Mβ = 28.960, # .............................. Mean molecular mass at sea level [g / mol]
########################################################################################
# Values at Lower Boundary #
########################################################################################
Tβ = 183.0, # .................................... Temperature at the lower bound [K]
zβ = 90.0, # ...................................... Altitude of the lower bound [km]
Mβ = 28.82678, # ................................. Mean molecular mass at `zβ` [g / mol]
Οβ = 3.46e-9, # ............................................. Density at `zβ` [g / cmΒ³]
########################################################################################
# Values at the Second Division #
########################################################################################
zβ = 100.0,
########################################################################################
# Values at the Inflection Point #
########################################################################################
zx = 125.0, # .................................... Altitude of the inflection point [km]
########################################################################################
# Molecular Mass [g / mol] #
########################################################################################
Mi = (
Nβ = 28.0134,
Oβ = 31.9988,
O = 15.9994,
Ar = 39.9480,
He = 4.0026,
H = 1.00797
),
########################################################################################
# Thermal Diffusion Coefficient #
########################################################################################
Ξ±i = (
Nβ = 0,
Oβ = 0,
O = 0,
Ar = 0,
He = -0.38,
H = 0
),
########################################################################################
# Constituent density * Mβ / Ο_βββ / Av #
########################################################################################
ΞΌi = (
Nβ = 0.78110,
Oβ = 0.161778,
O = 0.095544,
Ar = 0.0093432,
He = 0.61471e-5,
H = 0
),
########################################################################################
# Coefficients for Series Expansion #
########################################################################################
Aa = (
-435093.363387,
28275.5646391,
-765.33466108,
11.043387545,
-0.08958790995,
0.00038737586,
-0.000000697444
),
Ca = (
-89284375.0,
3542400.0,
-52687.5,
340.5,
-0.8
),
la = (
0.1031445e+5,
0.2341230e+1,
0.1579202e-2,
-0.1252487e-5,
0.2462708e-9
),
Ξ± = (
3144902516.672729,
-123774885.4832917,
1816141.096520398,
-11403.31079489267,
24.36498612105595,
0.008957502869707995
),
Ξ² = (
-52864482.17910969,
-16632.50847336828,
-1.308252378125,
0,
0,
0
),
ΞΆ = (
0.1985549e-10,
-0.1833490e-14,
0.1711735e-17,
-0.1021474e-20,
0.3727894e-24,
-0.7734110e-28,
0.7026942e-32
),
Ξ΄ij = (
Nβ = (
0.1093155e2,
0.1186783e-2, # (1 / K)
-0.1677341e-5, # (1 / K)Β²
0.1420228e-8, # (1 / K)Β³
-0.7139785e-12, # (1 / K)β΄
0.1969715e-15, # (1 / K)β΅
-0.2296182e-19 # (1 / K)βΆ
),
Oβ = (
0.9924237e1,
0.1600311e-2, # (1 / K)
-0.2274761e-5, # (1 / K)Β²
0.1938454e-8, # (1 / K)Β³
-0.9782183e-12, # (1 / K)β΄
0.2698450e-15, # (1 / K)β΅
-0.3131808e-19 # (1 / K)βΆ
),
O = (
0.1097083e2,
0.6118742e-4, # (1 / K)
-0.1165003e-6, # (1 / K)Β²
0.9239354e-10, # (1 / K)Β³
-0.3490739e-13, # (1 / K)β΄
0.5116298e-17, # (1 / K)β΅
0 # (1 / K)βΆ
),
Ar = (
0.8049405e1,
0.2382822e-2, # (1 / K)
-0.3391366e-5, # (1 / K)Β²
0.2909714e-8, # (1 / K)Β³
-0.1481702e-11, # (1 / K)β΄
0.4127600e-15, # (1 / K)β΅
-0.4837461e-19 # (1 / K)βΆ
),
He = (
0.7646886e1,
-0.4383486e-3, # (1 / K)
0.4694319e-6, # (1 / K)Β²
-0.2894886e-9, # (1 / K)Β³
0.9451989e-13, # (1 / K)β΄
-0.1270838e-16, # (1 / K)β΅
0 # (1 / K)βΆ
),
)
)
"""
const _JR1971_ROOT_GUESS
First guess to compute the roots of a polynomial to find the density below 125 km.
"""
const _JR1971_ROOT_GUESS = Complex{Float64}[166.10; 61.32; 9.91 + 1.31im; 9.91 - 1.31im]
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 21749 | ## Description #############################################################################
#
# The Jacchia-Roberts 1971 Atmospheric Model.
#
## References ##############################################################################
#
# [1] Roberts, C. R (1971). An analytic model for upper atmosphere densities based upon
# Jacchia's 1970 models.
#
# [2] Jacchia, L. G (1970). New static models of the thermosphere and exosphere with
# empirical temperature profiles. SAO Special Report #313.
#
# [3] Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications. 4th ed.
# Microcosm Press, Hawthorn, CA, USA.
#
# [4] Long, A. C., Cappellari Jr., J. O., Velez, C. E., Fuchs, A. J (editors) (1989).
# Goddard Trajectory Determination System (GTDS) Mathematical Theory (Revision 1).
# FDD/552-89/0001 and CSC/TR-89/6001.
#
############################################################################################
export jr1971
"""
jr1971(instant::DateTime, Ο_gd::Number, Ξ»::Number, h::Number[, F10::Number, F10β::Number, Kp::Number]) -> JR1971Output{Float64}
jr1971(jd::Number, Ο_gd::Number, Ξ»::Number, h::Number[, F10::Number, F10β::Number, Kp::Number]) -> JR1971Output{Float64}
Compute the atmospheric density using the Jacchia-Roberts 1971 model.
If we omit all space indices, the system tries to obtain them automatically for the selected
day `jd` or `instant`. However, the indices must be already initialized using the function
`SpaceIndices.init()`.
# Arguments
- `jd::Number`: Julian day to compute the model.
- `instant::DateTime`: Instant to compute the model represent using `DateTime`.
- `Ο_gd::Number`: Geodetic latitude [rad].
- `Ξ»::Number`: Longitude [rad].
- `h::Number`: Altitude [m].
- `F10::Number`: 10.7-cm solar flux [sfu].
- `F10β::Number`: 10.7-cm averaged solar flux, 81-day centered on input time [sfu].
- `Kp::Number`: Kp geomagnetic index with a delay of 3 hours.
# Returns
- `JR1971Output{Float64}`: Structure containing the results obtained from the model.
"""
function jr1971(instant::DateTime, Ο_gd::Number, Ξ»::Number, h::Number)
return jr1971(datetime2julian(instant), Ο_gd, Ξ», h)
end
function jr1971(jd::Number, Ο_gd::Number, Ξ»::Number, h::Number)
# Get the data in the desired Julian Day.
F10 = space_index(Val(:F10obs), jd)
F10β = sum((space_index.(Val(:F10obs), k) for k in (jd - 40):(jd + 40))) / 81
# For the Kp, we must obtain the index using a 3-hour delay. Thus, we need to obtain the
# Kp vector first, containing the Kp values for every 3 hours.
instant = julian2datetime(jd)
instant_3h_delay = instant - Hour(3)
Kp_vect = space_index(Val(:Kp), instant_3h_delay)
# Now, we need to obtain the value for the required instant. In this case, we will
# consider the Kp constant inside the 3h-interval provided by the space index vector.
# Get the number of seconds elapsed since the beginning of the day.
day = Date(instant) |> DateTime
Ξt = Dates.value(instant - day) / 1000
# Get the index and the Kp value.
id = round(Int, clamp(div(Ξt, 10_800) + 1, 1, 8))
Kp = Kp_vect[id]
@debug """
JR1971 - Fetched Space Indices
Daily F10.7 : $(F10) sfu
81-day averaged F10.7 : $(F10β) sfu
3-hour delayed Kp : $(Kp)
"""
return jr1971(jd, Ο_gd, Ξ», h, F10, F10β, Kp)
end
function jr1971(
instant::DateTime,
Ο_gd::Number,
Ξ»::Number,
h::Number,
F10::Number,
F10β::Number,
Kp::Number
)
return jr1971(datetime2julian(instant), Ο_gd, Ξ», h, F10, F10β, Kp)
end
function jr1971(
jd::Number,
Ο_gd::Number,
Ξ»::Number,
h::Number,
F10::Number,
F10β::Number,
Kp::Number
)
# == Constants =========================================================================
Rstar = _JR1971_CONSTANTS.Rstar
Av = _JR1971_CONSTANTS.Av
Ra = _JR1971_CONSTANTS.Ra
gβ = _JR1971_CONSTANTS.gβ
Mβ = _JR1971_CONSTANTS.Mβ
zβ = _JR1971_CONSTANTS.zβ
zβ = _JR1971_CONSTANTS.zβ
Tβ = _JR1971_CONSTANTS.Tβ
Mβ = _JR1971_CONSTANTS.Mβ
Οβ = _JR1971_CONSTANTS.Οβ
zx = _JR1971_CONSTANTS.zx
Mi = _JR1971_CONSTANTS.Mi
Ξ±i = _JR1971_CONSTANTS.Ξ±i
ΞΌi = _JR1971_CONSTANTS.ΞΌi
Aa = _JR1971_CONSTANTS.Aa
Ca = _JR1971_CONSTANTS.Ca
la = _JR1971_CONSTANTS.la
Ξ± = _JR1971_CONSTANTS.Ξ±
Ξ² = _JR1971_CONSTANTS.Ξ²
ΞΆ = _JR1971_CONSTANTS.ΞΆ
Ξ΄ij = _JR1971_CONSTANTS.Ξ΄ij
# == Auxiliary variables ===============================================================
RaΒ² = Ra * Ra # ........................................ Mean Earth radius squared [kmΒ²]
# == Preliminaries =====================================================================
# Convert the altitude from [m] to [km].
h /= 1000
# Compute the Sun position represented in the inertial reference frame (MOD).
s_i = sun_position_mod(jd)
# Compute the Sun declination [rad].
Ξ΄s = atan(s_i[3], β(s_i[1] * s_i[1] + s_i[2] * s_i[2]))
# Compute the Sun right ascension [rad].
Ξ©s = atan(s_i[2], s_i[1])
# Compute the right ascension of the selected location w.r.t. the inertial reference
# frame.
Ξ©p = Ξ» + jd_to_gmst(jd)
# Compute the hour angle at the selected location, which is the angle measured at the XY
# plane between the right ascension of the selected position and the right ascension of
# the Sun.
H = Ξ©p - Ξ©s
########################################################################################
# Algorithm #
########################################################################################
# == Exospheric Temperature ============================================================
# -- Diurnal Variation -----------------------------------------------------------------
# Eq. 14 [2], Section B.1.1 [3]
#
# Nighttime minimum of the global exospheric temperature distribution when the planetary
# geomagnetic index Kp is zero.
ΞF10 = F10 - F10β
Tc = 379 + 3.24F10 + 1.3ΞF10
# Eq. 15 [2], Section B.1.1 [3]
Ξ· = abs(Ο_gd - Ξ΄s) / 2
ΞΈ = abs(Ο_gd + Ξ΄s) / 2
# Eq. 16 [2], Section B.1.1 [3]
Ο = H + deg2rad(-37 + 6sin(H + deg2rad(43)))
# Eq. 17 [2], Section B.1.1 [3]
C = cos(Ξ·)^2.2
S = sin(ΞΈ)^2.2
Tl = Tc * (1 + 0.3 * (S + (C - S) * cos(Ο / 2)^3))
# == Variations with Geomagnetic Activity ==============================================
# Eq. 18 or Eq. 20 [2], Section B.1.1 [3]
ΞTβ = (h < 200) ? 14Kp + 0.02exp(Kp) : 28Kp + 0.03exp(Kp)
# -- Section B.1.1 [3] -----------------------------------------------------------------
#
# Compute the local exospheric temperature with the geomagnetic storm effect.
Tβ = Tl + ΞTβ
# == Temperature at the Desired Altitude ===============================================
# -- Section B.1.1 [3] -----------------------------------------------------------------
#
# Compute the temperature at inflection point `zx`.
#
# The values at [1, p. 369] are from an old version of Jacchia 1971 model. We will use
# the new values available at [2].
a = 371.6678
b = 0.0518806
c = -294.3505
d = -0.00216222
Tx = a + b * Tβ + c * exp(d * Tβ)
# Compute the temperature at desired point.
Tz = _jr1971_temperature(h, Tx, Tβ)
# == Corrections to the Density (Eqs. 4-96 to 4-101 [3]) ===============================
# -- Geomagnetic Effect, Eq. B-7 [3] ---------------------------------------------------
ΞlogββΟ_g = h < 200 ? 0.012Kp + 1.2e-5exp(Kp) : 0.0
# -- Semi-annual Variation, Section B.1.3 [3] ------------------------------------------
# Number of days since January 1, 1958.
Ξ¦ = (jd - 2436204.5) / 365.2422
Ο_sa = Ξ¦ + 0.09544 * ((1 / 2 * (1 + sin(2Ο * Ξ¦ + 6.035)))^(1.65) - 1 / 2)
f_z = (5.876e-7h^2.331 + 0.06328) * exp(-0.002868h)
g_t = 0.02835 + (0.3817 + 0.17829sin(2Ο * Ο_sa + 4.137)) * sin(4Ο * Ο_sa + 4.259)
ΞlogββΟ_sa = f_z * g_t
# -- Seasonal Latitudinal Variation, Section B.1.3 [3] ---------------------------------
sin_Ο_gd = sin(Ο_gd)
abs_sin_Ο_gd = abs(sin_Ο_gd)
ΞlogββΟ_lt = 0.014 * (h - 90) * exp(-0.0013 * (h - 90)^2) * sin(2Ο * Ξ¦ + 1.72) * sin_Ο_gd * abs_sin_Ο_gd
# -- Total Correction, Eq. B-10 [4] ----------------------------------------------------
ΞlogββΟ_c = ΞlogββΟ_g + ΞlogββΟ_lt + ΞlogββΟ_sa
ΞΟ_c = 10^(ΞlogββΟ_c)
# == Density ===========================================================================
if h == zβ
# Compute the total density.
Ο = Οβ * ΞΟ_c
# Convert to SI and return.
return JR1971Output(
1000Ο,
Tz,
Tβ,
(Ο * ΞΌi.Nβ) * Av / Mi.Nβ * 1e6,
(Ο * ΞΌi.Oβ) * Av / Mi.Oβ * 1e6,
(Ο * ΞΌi.O) * Av / Mi.O * 1e6,
(Ο * ΞΌi.Ar) * Av / Mi.Ar * 1e6,
(Ο * ΞΌi.He) * Av / Mi.He * 1e6,
(Ο * ΞΌi.H) * Av / Mi.H * 1e6
)
elseif zβ < h <= zx
# First, we need to find the roots of the polynomial:
#
# P(Z) = cβ + cβ β
z + cβ β
zΒ² + cβ β
zΒ³ + cβ β
zβ΄
cβ = (35^4 * Tx / (Tx - Tβ) + Ca[1]) / Ca[5]
cβ = Ca[2] / Ca[5]
cβ = Ca[3] / Ca[5]
cβ = Ca[4] / Ca[5]
cβ = Ca[5] / Ca[5]
rβ, rβ, x, y = _jr1971_roots([cβ, cβ, cβ, cβ, cβ])
# -- f and k, [1. p. 371] ----------------------------------------------------------
f = 35^4 * RaΒ² / Ca[5]
k = -gβ / (Rstar * (Tx - Tβ))
# -- U(Ξ½), V(Ξ½), and W(Ξ½) Functions, [1, p. 372] -----------------------------------
U(Ξ½) = (Ξ½ + Ra)^2 * (Ξ½^2 - 2x * Ξ½ + x^2 + y^2) * (rβ - rβ)
V(Ξ½) = (Ξ½^2 - 2x * Ξ½ + x^2 + y^2) * (Ξ½ - rβ) * (Ξ½ - rβ)
# The equation for `W(Ξ½)` in [1] was:
#
# W(Ξ½) = rβ * rβ * RaΒ² * (Ξ½ + Ra) + (x^2 + y^2) * Ra * (Ra * Ξ½ + rβ * rβ)
#
# However, [3,4] mention that this is not correct, and must be replaced by:
W(Ξ½) = rβ * rβ * Ra * (Ra + Ξ½) * (Ra + (x^2 + y^2) / Ξ½)
# -- X, [1, p. 372] ----------------------------------------------------------------
X = -2rβ * rβ * Ra * (RaΒ² + 2x * Ra + x^2 + y^2)
# The original paper [1] divided into two sections: 90 km to 105 km, and 105 km to
# 125 km. However, [3] divided into 90 to 100 km, and 100 km to 125 km.
if h <= zβ
# == Altitudes Between 90 km and 100 km ========================================
# -- S(z) Polynomial, [1, p. 371] ----------------------------------------------
Bβ = Ξ±[1] + Ξ²[1] * Tx / (Tx - Tβ)
Bβ = Ξ±[2] + Ξ²[2] * Tx / (Tx - Tβ)
Bβ = Ξ±[3] + Ξ²[3] * Tx / (Tx - Tβ)
Bβ = Ξ±[4] + Ξ²[4] * Tx / (Tx - Tβ)
Bβ = Ξ±[5] + Ξ²[5] * Tx / (Tx - Tβ)
Bβ
= Ξ±[6] + Ξ²[6] * Tx / (Tx - Tβ)
S(z) = @evalpoly(z, Bβ, Bβ, Bβ, Bβ, Bβ, Bβ
)
# -- Auxiliary Variables, [1. p. 372] ------------------------------------------
pβ = S(rβ) / U(rβ)
pβ = -S(rβ) / U(rβ)
pβ
= S(-Ra) / V(-Ra)
# There is a typo in the fourth term in [1] that was corrected in [3].
pβ = (
Bβ - rβ * rβ * RaΒ² * (Bβ + (2x + rβ + rβ - Ra) * Bβ
) -
rβ * rβ * Ra * (x^2 + y^2) * Bβ
+ rβ * rβ * (RaΒ² - (x^2 + y^2)) * pβ
+
W(rβ) * pβ + W(rβ) * pβ
) / X
pβ = Bβ + (2x + rβ + rβ - Ra ) * Bβ
- pβ
- 2(x + Ra) * pβ - (rβ + Ra) * pβ - (rβ + Ra) * pβ
pβ = Bβ
- 2pβ - pβ - pβ
# -- Fβ and Fβ, [1, p. 372-373] ------------------------------------------------
log_Fβ = pβ * log((h + Ra) / (zβ + Ra)) +
pβ * log((h - rβ) / (zβ - rβ)) +
pβ * log((h - rβ) / (zβ - rβ)) +
pβ * log((h^2 - 2x * h + x^2 + y^2 ) / (zβ^2 - 2x * zβ + x^2 + y^2))
# This equation in [4] is wrong, since `f` is multiplying `Aβ`. We will use the
# one in [3].
Fβ = (h - zβ) * (Aa[7] + pβ
/ ((h + Ra) * (zβ + Ra))) +
pβ / y * atan(y * (h - zβ) / (y^2 + (h - x) * (zβ - x)))
# -- Compute the Density, eq. 13 [1] -------------------------------------------
Mz = _jr1971_mean_molecular_mass(h)
Ο = Οβ * ΞΟ_c * Mz * Tβ / (Mβ * Tz) * exp(k * (log_Fβ + Fβ))
# Convert to SI and return.
return JR1971Output(
1000Ο,
Tz,
Tβ,
(Ο * ΞΌi.Nβ) * Av / Mi.Nβ * 1e6,
(Ο * ΞΌi.Oβ) * Av / Mi.Oβ * 1e6,
(Ο * ΞΌi.O) * Av / Mi.O * 1e6,
(Ο * ΞΌi.Ar) * Av / Mi.Ar * 1e6,
(Ο * ΞΌi.He) * Av / Mi.He * 1e6,
(Ο * ΞΌi.H) * Av / Mi.H * 1e6,
)
else
# == Altitudes Between 100 km and 125 km =======================================
# First, we need to compute the temperature and density at 100 km.
Tβββ = _jr1971_temperature(zβ, Tx, Tβ)
# References [3,4] suggest to compute the density using a polynomial fit, so
# that the computational burden can be reduced:
#
Οβββ = @evalpoly(Tβ, ΞΆ[1], ΞΆ[2], ΞΆ[3], ΞΆ[4], ΞΆ[5], ΞΆ[6], ΞΆ[7]) * Mβ
# However, it turns out that this approach leads to discontinuity at 100 km.
# This was also seen by GMAT [5].
#
# TODO: Check if we need to fix this.
# Apply the density correction to the density at 100 km.
Οβββ *= ΞΟ_c
# -- Auxiliary Variables, [1, p. 374] ------------------------------------------
qβ = 1 / U(rβ)
qβ = -1 / U(rβ)
qβ
= 1 / V(-Ra)
qβ = (1 + rβ * rβ * (RaΒ² - (x^2 + y^2)) * qβ
+ W(rβ) * qβ + W(rβ) * qβ) / X
qβ = -qβ
- 2 * (x + Ra) * qβ - (rβ + Ra) * qβ - (rβ + Ra) * qβ
qβ = -2qβ - qβ - qβ
# -- Fβ and Fβ, [1, p. 374] ----------------------------------------------------
log_Fβ = qβ * log((h + Ra) / (zβ + Ra)) +
qβ * log((h - rβ) / (zβ - rβ)) +
qβ * log((h - rβ) / (zβ - rβ)) +
qβ * log((h^2 - 2x*h + x^2 + y^2) / (zβ^2 - 2x*zβ + x^2 + y^2))
Fβ = qβ
* (h - zβ) / ((h + Ra) * (Ra + zβ)) +
qβ / y * atan(y * (h - zβ) / (y^2 + (h - x) * (zβ - x)))
# -- Compute the Density of Each Specie [3] ------------------------------------
expk = k * f * (log_Fβ + Fβ)
ΟNβ = Οβββ * Mi[1] / Mβ * ΞΌi[1] * (Tβββ / Tz)^(1 + Ξ±i.Nβ) * exp(Mi[1] * expk)
ΟOβ = Οβββ * Mi[2] / Mβ * ΞΌi[2] * (Tβββ / Tz)^(1 + Ξ±i.Oβ) * exp(Mi[2] * expk)
ΟO = Οβββ * Mi[3] / Mβ * ΞΌi[3] * (Tβββ / Tz)^(1 + Ξ±i.O ) * exp(Mi[3] * expk)
ΟAr = Οβββ * Mi[4] / Mβ * ΞΌi[4] * (Tβββ / Tz)^(1 + Ξ±i.Ar) * exp(Mi[4] * expk)
ΟHe = Οβββ * Mi[5] / Mβ * ΞΌi[5] * (Tβββ / Tz)^(1 + Ξ±i.He) * exp(Mi[5] * expk)
# Compute the total density.
Ο = ΟNβ + ΟOβ + ΟO + ΟAr + ΟHe
# Convert to SI and return.
return JR1971Output(
1000Ο,
Tz,
Tβ,
ΟNβ * Av / Mi.Nβ * 1e6,
ΟOβ * Av / Mi.Oβ * 1e6,
ΟO * Av / Mi.O * 1e6,
ΟAr * Av / Mi.Ar * 1e6,
ΟHe * Av / Mi.He * 1e6,
0.0,
)
end
else
# == Altitudes Higher than 125 km ==================================================
# First, we need to compute the density at 125 km with the corrections.
# References [3,4] suggest to compute the density using a polynomial fit, so that
# the computational burden can be reduced:
Οβββ
_Nβ = ΞΟ_c * Mi[1] * 10^(@evalpoly(Tβ, Ξ΄ij.Nβ...)) / Av
Οβββ
_Oβ = ΞΟ_c * Mi[2] * 10^(@evalpoly(Tβ, Ξ΄ij.Oβ...)) / Av
Οβββ
_O = ΞΟ_c * Mi[3] * 10^(@evalpoly(Tβ, Ξ΄ij.O...)) / Av
Οβββ
_Ar = ΞΟ_c * Mi[4] * 10^(@evalpoly(Tβ, Ξ΄ij.Ar...)) / Av
Οβββ
_He = ΞΟ_c * Mi[5] * 10^(@evalpoly(Tβ, Ξ΄ij.He...)) / Av
# However, it turns out that this approach leads to discontinuity at 100 km. This
# was also seen by GMAT [5].
#
# TODO: Check if we need to fix this.
# -- Compute `l` According to eq. 4-136 [3] ----------------------------------------
l = @evalpoly(Tβ, la[1], la[2], la[3], la[4], la[5])
# -- Eq. 25' [1] -------------------------------------------------------------------
Ξ³ = (gβ * RaΒ² / (Rstar * l * Tβ) * (Tβ - Tx) / (Tx - Tβ) * (zx - zβ) / (Ra + zx))
Ξ³Nβ = Ξ³ * Mi[1]
Ξ³Oβ = Ξ³ * Mi[2]
Ξ³O = Ξ³ * Mi[3]
Ξ³Ar = Ξ³ * Mi[4]
Ξ³He = Ξ³ * Mi[5]
# -- Eq. 25 [1] --------------------------------------------------------------------
ΟNβ = Οβββ
_Nβ * (Tx / Tz)^(1 + Ξ±i.Nβ + Ξ³Nβ) * ((Tβ - Tz) / (Tβ - Tx)) ^ Ξ³Nβ
ΟOβ = Οβββ
_Oβ * (Tx / Tz)^(1 + Ξ±i.Oβ + Ξ³Oβ) * ((Tβ - Tz) / (Tβ - Tx)) ^ Ξ³Oβ
ΟO = Οβββ
_O * (Tx / Tz)^(1 + Ξ±i.O + Ξ³O ) * ((Tβ - Tz) / (Tβ - Tx)) ^ Ξ³O
ΟAr = Οβββ
_Ar * (Tx / Tz)^(1 + Ξ±i.Ar + Ξ³Ar) * ((Tβ - Tz) / (Tβ - Tx)) ^ Ξ³Ar
ΟHe = Οβββ
_He * (Tx / Tz)^(1 + Ξ±i.He + Ξ³He) * ((Tβ - Tz) / (Tβ - Tx)) ^ Ξ³He
# -- Correction of Seasonal Variations of Helium by Latitude, Eq. 4-101 [3] --------
ΞlogββΟ_He = 0.65 / deg2rad(23.439291) * abs(Ξ΄s) * (
sin(Ο / 4 - Ο_gd * Ξ΄s / (2abs(Ξ΄s)))^3 - 0.35355
)
ΟHe *= 10^(ΞlogββΟ_He)
# -- For Altitude Higher than 500 km, We Must Account for H ------------------------
ΟH = 0.0
if h > 500
# Compute the temperature and the H density at 500 km.
Tβ
ββ = _jr1971_temperature(500.0, Tx, Tβ)
logββ_Tβ
ββ = log10(Tβ
ββ)
Οβ
ββ_H = Mi.H / Av * 10^(73.13 - (39.4 - 5.5logββ_Tβ
ββ) * logββ_Tβ
ββ)
# Compute the H density at desired altitude.
Ξ³H = Mi.H * Ξ³
ΟH = ΞΟ_c * Οβ
ββ_H * (Tβ
ββ / Tz)^(1 + Ξ³H) * ((Tβ - Tz) / (Tβ - Tβ
ββ))^Ξ³H
end
# Apply the corrections.
Ο = ΟNβ + ΟOβ + ΟO + ΟAr + ΟHe + ΟH
# Convert to SI and return.
return JR1971Output(
1000Ο,
Tz,
Tβ,
ΟNβ * Av / Mi.Nβ * 1e6,
ΟOβ * Av / Mi.Oβ * 1e6,
ΟO * Av / Mi.O * 1e6,
ΟAr * Av / Mi.Ar * 1e6,
ΟHe * Av / Mi.He * 1e6,
ΟH * Av / Mi.H * 1e6,
)
end
end
############################################################################################
# Private Functions #
############################################################################################
# _jr1971_mean_molecular_mass(z::Number) -> Float64
#
# Compute the mean molecular mass at altitude `z` [km] using the empirical profile in eq. 1
# **[3, 4]**.
function _jr1971_mean_molecular_mass(z::Number)
!(90 <= z <= 100) &&
@warn("The empirical model for the mean molecular mass is valid only for 90 <= z <= 100 km.")
Aa = _JR1971_CONSTANTS.Aa
molecular_mass = @evalpoly(z, Aa[1], Aa[2], Aa[3], Aa[4], Aa[5], Aa[6], Aa[7])
return molecular_mass
end
# _jr1971_roots(p::AbstractVector) where T<:Number -> NTuple{4, Float64}
#
# Compute the roots of the polynomial `p` necessary to compute the density below 125 km. It
# returns `rβ`, `rβ`, `x`, and `y`.
function _jr1971_roots(p::AbstractVector)
# Compute the roots with a first guess.
r = roots(p, _JR1971_ROOT_GUESS; polish = true)
# We expect two real roots and two complex roots. Here, we will perform the following
# processing:
#
# rβ -> Highest real root.
# rβ -> Lowest real root.
# x -> Real part of the complex root.
# y -> Positive imaginary part of the complex root.
rβ = maximum(v -> abs(imag(v)) < 1e-10 ? real(v) : -Inf, r)
rβ = minimum(v -> abs(imag(v)) < 1e-10 ? real(v) : +Inf, r)
c = findfirst(v -> imag(v) >= 1e-10, r)
x = real(r[c])
y = abs(imag(r[c]))
return rβ, rβ, x, y
end
# _jr1971_temperature(z::Number, Tx::Number, Tβ::Number) -> Float64
#
# Compute the temperature [K] at height `z` [km] according to the theory of the model
# Jacchia-Roberts 1971 [1, 3, 4] given the temperature `Tx` [K] at the inflection point and
# the exospheric temperature `Tβ` [K].
#
# The inflection point is considered to by `z = 125 km`.
function _jr1971_temperature(z::Number, Tx::Number, Tβ::Number)
Tβ = _JR1971_CONSTANTS.Tβ
zβ = _JR1971_CONSTANTS.zβ
zx = _JR1971_CONSTANTS.zx
# == Check the Parameters ==============================================================
(z < zβ) && throw(ArgumentError("The altitude must not be lower than $(zβ) km."))
(Tβ < 0 ) && throw(ArgumentError("The exospheric temperature must be positive."))
# == Compute the Temperature at Desire Altitude ========================================
if z <= zx
Ca = _JR1971_CONSTANTS.Ca
aux = @evalpoly(z, Ca[1], Ca[2], Ca[3], Ca[4], Ca[5])
T = Tx + (Tx - Tβ) / 35^4 * aux
else
Ra = _JR1971_CONSTANTS.Ra
la = _JR1971_CONSTANTS.la
l = @evalpoly(Tβ, la[1], la[2], la[3], la[4], la[5])
T = Tβ - (Tβ - Tx) * exp(
-l * ((Tx - Tβ) / (Tβ - Tx)) * ((z - zx) / (zx - zβ)) / (Ra + z)
)
end
return T
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 2157 | ## Description #############################################################################
#
# Function to show the results of the Jacchia-Roberts 1971 atmospheric model.
#
############################################################################################
function show(io::IO, out::JR1971Output)
# Check for color support in the `io`.
color = get(io, :color, false)
b = color ? _B : ""
d = color ? _D : ""
print(io, "$(b)JR1971 output$(d) (Ο = ", @sprintf("%g", out.total_density), " kg / mΒ³)")
return nothing
end
function show(io::IO, mime::MIME"text/plain", out::JR1971Output)
# Check for color support in the `io`.
color = get(io, :color, false)
b = color ? _B : ""
d = color ? _D : ""
str_total_density = @sprintf("%15g", out.total_density)
str_temperature = @sprintf("%15.2f", out.temperature)
str_exospheric_temp = @sprintf("%15.2f", out.exospheric_temperature)
str_Nβ_number_den = @sprintf("%15g", out.N2_number_density)
str_Oβ_number_den = @sprintf("%15g", out.O2_number_density)
str_O_number_den = @sprintf("%15g", out.O_number_density)
str_Ar_number_den = @sprintf("%15g", out.Ar_number_density)
str_He_number_den = @sprintf("%15g", out.He_number_density)
str_H_number_den = @sprintf("%15g", out.H_number_density)
println(io, "Jacchia-Roberts 1971 Atmospheric Model Result:")
println(io, "$(b) Total density :$(d)", str_total_density, " kg / mΒ³")
println(io, "$(b) Temperature :$(d)", str_temperature, " K")
println(io, "$(b) Exospheric Temp. :$(d)", str_exospheric_temp, " K")
println(io, "$(b) Nβ number density :$(d)", str_Nβ_number_den, " 1 / mΒ³")
println(io, "$(b) Oβ number density :$(d)", str_Oβ_number_den, " 1 / mΒ³")
println(io, "$(b) O number density :$(d)", str_O_number_den, " 1 / mΒ³")
println(io, "$(b) Ar number density :$(d)", str_Ar_number_den, " 1 / mΒ³")
println(io, "$(b) He number density :$(d)", str_He_number_den, " 1 / mΒ³")
print(io, "$(b) H number density :$(d)", str_H_number_den, " 1 / mΒ³")
return nothing
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 1154 | ## Description #############################################################################
#
# Types related to the Jacchia-Roberts 1971 atmospheric model.
#
############################################################################################
export JR1971Output
"""
struct JR1971Output{T<:Number}
Output of the atmospheric model Jacchia-Roberts 1971.
# Fields
- `total_density::T`: Total atmospheric density [1 / mΒ³].
- `temperature::T`: Temperature at the selected position [K].
- `exospheric_temperature::T`: Exospheric temperature [K].
- `N2_number_density::T`: Number density of Nβ [1 / mΒ³].
- `O2_number_density::T`: Number density of Oβ [1 / mΒ³].
- `O_number_density::T`: Number density of O [1 / mΒ³].
- `Ar_number_density::T`: Number density of Ar [1 / mΒ³].
- `He_number_density::T`: Number density of He [1 / mΒ³].
- `H_number_density::T`: Number density of H [1 / mΒ³].
"""
struct JR1971Output{T<:Number}
total_density::T
temperature::T
exospheric_temperature::T
N2_number_density::T
O2_number_density::T
O_number_density::T
Ar_number_density::T
He_number_density::T
H_number_density::T
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 4643 | ## Description #############################################################################
#
# Auxiliary private functions for the NRLMSISE-00 model.
#
############################################################################################
"""
_ccor(h::T, r::T, hβ::T, zh::T) where T<:Number -> T
Compute the chemistry / dissociation correction for MSIS models.
# Arguments
- `h::Number`: Altitude.
- `r::Number`: Target ratio.
- `hβ::Number`: Transition scale length.
- `zh::Number`: Altitude of `1/2 r`.
"""
function _ccor(h::T, r::T, hβ::T, zh::T) where T<:Number
e = (h - zh) / hβ
(e > +70) && return exp(T(0))
(e < -70) && return exp(r)
return exp(r / (1 + exp(e)))
end
"""
_ccor2(alt::T, r::T, hβ::T, zh::T, hβ::T) where T<:Number -> T
Compute the O and Oβ chemistry / dissociation correction for MSIS models.
# Arguments
- `h::Number`: Altitude.
- `r::Number`: Target ration.
- `hβ::Number`: Transition scale length.
- `zh::Number`: Altitude of `1/2 r`.
- `hβ::Number`: Transition scale length 2.
"""
function _ccor2(h::T, r::T, hβ::T, zh::T, hβ::T) where T<:Number
e1 = (h - zh) / hβ
e2 = (h - zh) / hβ
((e1 > +70) || (e2 > +70)) && return exp(T(0))
((e1 < -70) && (e2 < -70)) && return exp(r)
return exp(r / (1 + (exp(e1) + exp(e2)) / 2))
end
"""
_dnet(dd::T, dm::T, zhm::T, xmm::T, xm::T) where T<:Number -> T
Compute the turbopause correction for MSIS models, returning the combined density.
# Arguments
- `dd::T`: Diffusive density.
- `dm::T`: Full mixed density.
- `zhm::T`: Transition scale length.
- `xmm::T`: Full mixed molecular weight.
- `xm::T`: Species molecular weight.
"""
function _dnet(dd::T, dm::T, zhm::T, xmm::T, xm::T) where T<:Number
a = zhm / (xmm - xm)
if !((dm > 0) && (dd > 0))
if (dd == 0) && (dm == 0)
dd = T(1)
end
(dm == 0) && return dd
(dd == 0) && return dm
end
ylog = a * log(dm / dd)
(ylog < -10) && return dd
(ylog > +10) && return dm
return dd * (1 + exp(ylog))^(1 / a)
end
"""
_gravity_and_effective_radius(Ο_gd::T) where T<:Number -> T, T
Compute the gravity [cm / sΒ²] and effective radius [km] at the geodetic latitude `Ο_gd` [Β°].
"""
function _gravity_and_effective_radius(Ο_gd::T) where T<:Number
# Auxiliary variable to reduce computational burden.
c_2Ο = cos(2 * T(_DEG_TO_RAD) * Ο_gd)
# Compute the gravity at the selected latitude.
g_lat = T(_REFERENCE_GRAVITY) * (1 - T(0.0026373) * c_2Ο)
# Compute the effective radius at the selected latitude.
r_lat = 2 * g_lat / (T(3.085462e-6) + T(2.27e-9) * c_2Ο) * T(1e-5)
return g_lat, r_lat
end
"""
_scale_height(h::T, xm::T, temp::T, g_lat::T, r_lat::T) where T<:Number -> T
Compute the scale height.
# Arguments
- `h::T`: Altitude [km].
- `xm::T`: Species molecular weight [ ].
- `temp::T`: Temperature [K].
- `g_lat::T`: Reference gravity at desired latitude [cm / sΒ²].
- `r_lat::T`: Reference radius at desired latitude [km].
"""
function _scale_height(h::T, xm::T, temp::T, g_lat::T, r_lat::T) where T<:Number
# Compute the gravity at the selected altitude.
gh = g_lat / (1 + h / r_lat)^2
# Compute the scale height
sh = T(_RGAS) * temp / (gh * xm)
return sh
end
############################################################################################
# 3hr Magnetic Activity Functions #
############################################################################################
"""
_g0(a::Number, p::AbstractVector)
Compute `gβ` function (see Eq. A24d) using the coefficients `abs_p25 = abs(p[25])` and
`p26 = p[26]`.
"""
function _gβ(a::Number, abs_p25::Number, p26::Number)
return (a - 4 + (p26 - 1) * (a - 4 + (exp(-abs_p25 * (a - 4)) - 1) / abs_p25))
end
"""
_sgβ(ex::Number, ap::AbstractVector, abs_p25::Number, p26::Number)
Compute the `sgβ` function (see Eq. A24a) using the `ap` vector and the coefficients
`abs_p25` and `p26`.
"""
function _sgβ(ex::Number, ap::AbstractVector, abs_p25::Number, p26::Number)
# Auxiliary variables.
gβ = _gβ(ap[2], abs_p25, p26)
gβ = _gβ(ap[3], abs_p25, p26)
gβ = _gβ(ap[4], abs_p25, p26)
gβ
= _gβ(ap[5], abs_p25, p26)
gβ = _gβ(ap[6], abs_p25, p26)
gβ = _gβ(ap[7], abs_p25, p26)
exΒ² = ex * ex
exΒ³ = exΒ² * ex
exβ΄ = exΒ² * exΒ²
exβΈ = exβ΄ * exβ΄
exΒΉΒ² = exβΈ * exβ΄
exΒΉβΉ = exΒΉΒ² * exβ΄ * exΒ³
sumex = 1 + (1 - exΒΉβΉ) / (1 - ex) * βex
r = gβ + gβ * ex + gβ * exΒ² + gβ
* exΒ³ + (gβ * exβ΄ + gβ * exΒΉΒ²) * (1 - exβΈ) / (1 - ex)
return r / sumex
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 51101 | ## Description #############################################################################
#
# Constants for the NRLMSISE-00 model.
#
############################################################################################
############################################################################################
# Conversion Constants #
############################################################################################
# Conversion factor from degrees to radians.
const _DEG_TO_RAD = 1.74533e-2
# Conversion factor from day to radian.
const _DAY_TO_RAD = 1.72142e-2
# Conversion factor from hour to radian.
const _HOUR_TO_RAD = 0.2618
# Conversion factor from second to radian.
const _SEC_TO_RAD = 7.2722e-5
############################################################################################
# Chemical Constants #
############################################################################################
# Inverse of gas constant.
const _RGAS = 831.4
############################################################################################
# Earth's Constants #
############################################################################################
# Reference latitude [Β°]
const _REFERENCE_LATITUDE = 45
# Gravity on Earth's surface at the reference latitude [cm / sΒ²].
const _REFERENCE_GRAVITY = 980.616
############################################################################################
# NRLMSISE-00 Constants #
############################################################################################
# Array of altitudes #1.
const _ZN1 = (123.435, 110.0, 100.0, 90.0, 72.5)
# Array of altitudes #2.
const _ZN2 = (72.5, 55.0, 45.0, 32.5)
# Array of altitude #3.
const _ZN3 = (32.5, 20.0, 15.0, 10.0, 0.0)
# Mix altitude [km].
const _ZMIX = 62.5
############################################################################################
# Temperature #
############################################################################################
const _NRLMSISE00_PT = [
9.86573e-01, 1.62228e-02, 1.55270e-02,-1.04323e-01,-3.75801e-03,
-1.18538e-03,-1.24043e-01, 4.56820e-03, 8.76018e-03,-1.36235e-01,
-3.52427e-02, 8.84181e-03,-5.92127e-03,-8.61650e+00, 0.00000e+00,
1.28492e-02, 0.00000e+00, 1.30096e+02, 1.04567e-02, 1.65686e-03,
-5.53887e-06, 2.97810e-03, 0.00000e+00, 5.13122e-03, 8.66784e-02,
1.58727e-01, 0.00000e+00, 0.00000e+00, 0.00000e+00,-7.27026e-06,
0.00000e+00, 6.74494e+00, 4.93933e-03, 2.21656e-03, 2.50802e-03,
0.00000e+00, 0.00000e+00,-2.08841e-02,-1.79873e+00, 1.45103e-03,
2.81769e-04,-1.44703e-03,-5.16394e-05, 8.47001e-02, 1.70147e-01,
5.72562e-03, 5.07493e-05, 4.36148e-03, 1.17863e-04, 4.74364e-03,
6.61278e-03, 4.34292e-05, 1.44373e-03, 2.41470e-05, 2.84426e-03,
8.56560e-04, 2.04028e-03, 0.00000e+00,-3.15994e+03,-2.46423e-03,
1.13843e-03, 4.20512e-04, 0.00000e+00,-9.77214e+01, 6.77794e-03,
5.27499e-03, 1.14936e-03, 0.00000e+00,-6.61311e-03,-1.84255e-02,
-1.96259e-02, 2.98618e+04, 0.00000e+00, 0.00000e+00, 0.00000e+00,
6.44574e+02, 8.84668e-04, 5.05066e-04, 0.00000e+00, 4.02881e+03,
-1.89503e-03, 0.00000e+00, 0.00000e+00, 8.21407e-04, 2.06780e-03,
0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00,
-1.20410e-02,-3.63963e-03, 9.92070e-05,-1.15284e-04,-6.33059e-05,
-6.05545e-01, 8.34218e-03,-9.13036e+01, 3.71042e-04, 0.00000e+00,
4.19000e-04, 2.70928e-03, 3.31507e-03,-4.44508e-03,-4.96334e-03,
-1.60449e-03, 3.95119e-03, 2.48924e-03, 5.09815e-04, 4.05302e-03,
2.24076e-03, 0.00000e+00, 6.84256e-03, 4.66354e-04, 0.00000e+00,
-3.68328e-04, 0.00000e+00, 0.00000e+00,-1.46870e+02, 0.00000e+00,
0.00000e+00, 1.09501e-03, 4.65156e-04, 5.62583e-04, 3.21596e+00,
6.43168e-04, 3.14860e-03, 3.40738e-03, 1.78481e-03, 9.62532e-04,
5.58171e-04, 3.43731e+00,-2.33195e-01, 5.10289e-04, 0.00000e+00,
0.00000e+00,-9.25347e+04, 0.00000e+00,-1.99639e-03, 0.00000e+00,
0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00,
0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00
]
############################################################################################
# Density #
############################################################################################
# == He ====================================================================================
const _NRLMSISE00_PD_HE = [
1.09979E+00,-4.88060E-02,-1.97501E-01,-9.10280E-02,-6.96558E-03,
2.42136E-02, 3.91333E-01,-7.20068E-03,-3.22718E-02, 1.41508E+00,
1.68194E-01, 1.85282E-02, 1.09384E-01,-7.24282E+00, 0.00000E+00,
2.96377E-01,-4.97210E-02, 1.04114E+02,-8.61108E-02,-7.29177E-04,
1.48998E-06, 1.08629E-03, 0.00000E+00, 0.00000E+00, 8.31090E-02,
1.12818E-01,-5.75005E-02,-1.29919E-02,-1.78849E-02,-2.86343E-06,
0.00000E+00,-1.51187E+02,-6.65902E-03, 0.00000E+00,-2.02069E-03,
0.00000E+00, 0.00000E+00, 4.32264E-02,-2.80444E+01,-3.26789E-03,
2.47461E-03, 0.00000E+00, 0.00000E+00, 9.82100E-02, 1.22714E-01,
-3.96450E-02, 0.00000E+00,-2.76489E-03, 0.00000E+00, 1.87723E-03,
-8.09813E-03, 4.34428E-05,-7.70932E-03, 0.00000E+00,-2.28894E-03,
-5.69070E-03,-5.22193E-03, 6.00692E-03,-7.80434E+03,-3.48336E-03,
-6.38362E-03,-1.82190E-03, 0.00000E+00,-7.58976E+01,-2.17875E-02,
-1.72524E-02,-9.06287E-03, 0.00000E+00, 2.44725E-02, 8.66040E-02,
1.05712E-01, 3.02543E+04, 0.00000E+00, 0.00000E+00, 0.00000E+00,
-6.01364E+03,-5.64668E-03,-2.54157E-03, 0.00000E+00, 3.15611E+02,
-5.69158E-03, 0.00000E+00, 0.00000E+00,-4.47216E-03,-4.49523E-03,
4.64428E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
4.51236E-02, 2.46520E-02, 6.17794E-03, 0.00000E+00, 0.00000E+00,
-3.62944E-01,-4.80022E-02,-7.57230E+01,-1.99656E-03, 0.00000E+00,
-5.18780E-03,-1.73990E-02,-9.03485E-03, 7.48465E-03, 1.53267E-02,
1.06296E-02, 1.18655E-02, 2.55569E-03, 1.69020E-03, 3.51936E-02,
-1.81242E-02, 0.00000E+00,-1.00529E-01,-5.10574E-03, 0.00000E+00,
2.10228E-03, 0.00000E+00, 0.00000E+00,-1.73255E+02, 5.07833E-01,
-2.41408E-01, 8.75414E-03, 2.77527E-03,-8.90353E-05,-5.25148E+00,
-5.83899E-03,-2.09122E-02,-9.63530E-03, 9.77164E-03, 4.07051E-03,
2.53555E-04,-5.52875E+00,-3.55993E-01,-2.49231E-03, 0.00000E+00,
0.00000E+00, 2.86026E+01, 0.00000E+00, 3.42722E-04, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00
]
# == O =====================================================================================
const _NRLMSISE00_PD_O = [
1.02315E+00,-1.59710E-01,-1.06630E-01,-1.77074E-02,-4.42726E-03,
3.44803E-02, 4.45613E-02,-3.33751E-02,-5.73598E-02, 3.50360E-01,
6.33053E-02, 2.16221E-02, 5.42577E-02,-5.74193E+00, 0.00000E+00,
1.90891E-01,-1.39194E-02, 1.01102E+02, 8.16363E-02, 1.33717E-04,
6.54403E-06, 3.10295E-03, 0.00000E+00, 0.00000E+00, 5.38205E-02,
1.23910E-01,-1.39831E-02, 0.00000E+00, 0.00000E+00,-3.95915E-06,
0.00000E+00,-7.14651E-01,-5.01027E-03, 0.00000E+00,-3.24756E-03,
0.00000E+00, 0.00000E+00, 4.42173E-02,-1.31598E+01,-3.15626E-03,
1.24574E-03,-1.47626E-03,-1.55461E-03, 6.40682E-02, 1.34898E-01,
-2.42415E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00, 6.13666E-04,
-5.40373E-03, 2.61635E-05,-3.33012E-03, 0.00000E+00,-3.08101E-03,
-2.42679E-03,-3.36086E-03, 0.00000E+00,-1.18979E+03,-5.04738E-02,
-2.61547E-03,-1.03132E-03, 1.91583E-04,-8.38132E+01,-1.40517E-02,
-1.14167E-02,-4.08012E-03, 1.73522E-04,-1.39644E-02,-6.64128E-02,
-6.85152E-02,-1.34414E+04, 0.00000E+00, 0.00000E+00, 0.00000E+00,
6.07916E+02,-4.12220E-03,-2.20996E-03, 0.00000E+00, 1.70277E+03,
-4.63015E-03, 0.00000E+00, 0.00000E+00,-2.25360E-03,-2.96204E-03,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
3.92786E-02, 1.31186E-02,-1.78086E-03, 0.00000E+00, 0.00000E+00,
-3.90083E-01,-2.84741E-02,-7.78400E+01,-1.02601E-03, 0.00000E+00,
-7.26485E-04,-5.42181E-03,-5.59305E-03, 1.22825E-02, 1.23868E-02,
6.68835E-03,-1.03303E-02,-9.51903E-03, 2.70021E-04,-2.57084E-02,
-1.32430E-02, 0.00000E+00,-3.81000E-02,-3.16810E-03, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00,-9.05762E-04,-2.14590E-03,-1.17824E-03, 3.66732E+00,
-3.79729E-04,-6.13966E-03,-5.09082E-03,-1.96332E-03,-3.08280E-03,
-9.75222E-04, 4.03315E+00,-2.52710E-01, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00
]
# == Nβ ====================================================================================
const _NRLMSISE00_PD_N2 = [
1.16112E+00, 0.00000E+00, 0.00000E+00, 3.33725E-02, 0.00000E+00,
3.48637E-02,-5.44368E-03, 0.00000E+00,-6.73940E-02, 1.74754E-01,
0.00000E+00, 0.00000E+00, 0.00000E+00, 1.74712E+02, 0.00000E+00,
1.26733E-01, 0.00000E+00, 1.03154E+02, 5.52075E-02, 0.00000E+00,
0.00000E+00, 8.13525E-04, 0.00000E+00, 0.00000E+00, 8.66784E-02,
1.58727E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00,-2.50482E+01, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-2.48894E-03,
6.16053E-04,-5.79716E-04, 2.95482E-03, 8.47001E-02, 1.70147E-01,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 2.47425E-05, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00
]
# == TLB ===================================================================================
const _NRLMSISE00_PD_TLB = [
9.44846E-01, 0.00000E+00, 0.00000E+00,-3.08617E-02, 0.00000E+00,
-2.44019E-02, 6.48607E-03, 0.00000E+00, 3.08181E-02, 4.59392E-02,
0.00000E+00, 0.00000E+00, 0.00000E+00, 1.74712E+02, 0.00000E+00,
2.13260E-02, 0.00000E+00,-3.56958E+02, 0.00000E+00, 1.82278E-04,
0.00000E+00, 3.07472E-04, 0.00000E+00, 0.00000E+00, 8.66784E-02,
1.58727E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 3.83054E-03, 0.00000E+00, 0.00000E+00,
-1.93065E-03,-1.45090E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00,-1.23493E-03, 1.36736E-03, 8.47001E-02, 1.70147E-01,
3.71469E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
5.10250E-03, 2.47425E-05, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 3.68756E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00
]
# == Oβ ====================================================================================
const _NRLMSISE00_PD_O2 = [
1.35580E+00, 1.44816E-01, 0.00000E+00, 6.07767E-02, 0.00000E+00,
2.94777E-02, 7.46900E-02, 0.00000E+00,-9.23822E-02, 8.57342E-02,
0.00000E+00, 0.00000E+00, 0.00000E+00, 2.38636E+01, 0.00000E+00,
7.71653E-02, 0.00000E+00, 8.18751E+01, 1.87736E-02, 0.00000E+00,
0.00000E+00, 1.49667E-02, 0.00000E+00, 0.00000E+00, 8.66784E-02,
1.58727E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00,-3.67874E+02, 5.48158E-03, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 8.47001E-02, 1.70147E-01,
1.22631E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
8.17187E-03, 3.71617E-05, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-2.10826E-03,
-3.13640E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
-7.35742E-02,-5.00266E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 1.94965E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00
]
# == Ar ====================================================================================
const _NRLMSISE00_PD_AR = [
1.04761E+00, 2.00165E-01, 2.37697E-01, 3.68552E-02, 0.00000E+00,
3.57202E-02,-2.14075E-01, 0.00000E+00,-1.08018E-01,-3.73981E-01,
0.00000E+00, 3.10022E-02,-1.16305E-03,-2.07596E+01, 0.00000E+00,
8.64502E-02, 0.00000E+00, 9.74908E+01, 5.16707E-02, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 8.66784E-02,
1.58727E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 3.46193E+02, 1.34297E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-3.48509E-03,
-1.54689E-04, 0.00000E+00, 0.00000E+00, 8.47001E-02, 1.70147E-01,
1.47753E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
1.89320E-02, 3.68181E-05, 1.32570E-02, 0.00000E+00, 0.00000E+00,
3.59719E-03, 7.44328E-03,-1.00023E-03,-6.50528E+03, 0.00000E+00,
1.03485E-02,-1.00983E-03,-4.06916E-03,-6.60864E+01,-1.71533E-02,
1.10605E-02, 1.20300E-02,-5.20034E-03, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
-2.62769E+03, 7.13755E-03, 4.17999E-03, 0.00000E+00, 1.25910E+04,
0.00000E+00, 0.00000E+00, 0.00000E+00,-2.23595E-03, 4.60217E-03,
5.71794E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
-3.18353E-02,-2.35526E-02,-1.36189E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 2.03522E-02,-6.67837E+01,-1.09724E-03, 0.00000E+00,
-1.38821E-02, 1.60468E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 1.51574E-02,
-5.44470E-04, 0.00000E+00, 7.28224E-02, 6.59413E-02, 0.00000E+00,
-5.15692E-03, 0.00000E+00, 0.00000E+00,-3.70367E+03, 0.00000E+00,
0.00000E+00, 1.36131E-02, 5.38153E-03, 0.00000E+00, 4.76285E+00,
-1.75677E-02, 2.26301E-02, 0.00000E+00, 1.76631E-02, 4.77162E-03,
0.00000E+00, 5.39354E+00, 0.00000E+00,-7.51710E-03, 0.00000E+00,
0.00000E+00,-8.82736E+01, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00
]
# == H =====================================================================================
const _NRLMSISE00_PD_H = [
1.26376E+00,-2.14304E-01,-1.49984E-01, 2.30404E-01, 2.98237E-02,
2.68673E-02, 2.96228E-01, 2.21900E-02,-2.07655E-02, 4.52506E-01,
1.20105E-01, 3.24420E-02, 4.24816E-02,-9.14313E+00, 0.00000E+00,
2.47178E-02,-2.88229E-02, 8.12805E+01, 5.10380E-02,-5.80611E-03,
2.51236E-05,-1.24083E-02, 0.00000E+00, 0.00000E+00, 8.66784E-02,
1.58727E-01,-3.48190E-02, 0.00000E+00, 0.00000E+00, 2.89885E-05,
0.00000E+00, 1.53595E+02,-1.68604E-02, 0.00000E+00, 1.01015E-02,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.84552E-04,
-1.22181E-03, 0.00000E+00, 0.00000E+00, 8.47001E-02, 1.70147E-01,
-1.04927E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00,-5.91313E-03,
-2.30501E-02, 3.14758E-05, 0.00000E+00, 0.00000E+00, 1.26956E-02,
8.35489E-03, 3.10513E-04, 0.00000E+00, 3.42119E+03,-2.45017E-03,
-4.27154E-04, 5.45152E-04, 1.89896E-03, 2.89121E+01,-6.49973E-03,
-1.93855E-02,-1.48492E-02, 0.00000E+00,-5.10576E-02, 7.87306E-02,
9.51981E-02,-1.49422E+04, 0.00000E+00, 0.00000E+00, 0.00000E+00,
2.65503E+02, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 6.37110E-03, 3.24789E-04,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
6.14274E-02, 1.00376E-02,-8.41083E-04, 0.00000E+00, 0.00000E+00,
0.00000E+00,-1.27099E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00,
-3.94077E-03,-1.28601E-02,-7.97616E-03, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00,-6.71465E-03,-1.69799E-03, 1.93772E-03, 3.81140E+00,
-7.79290E-03,-1.82589E-02,-1.25860E-02,-1.04311E-02,-3.02465E-03,
2.43063E-03, 3.63237E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00
]
# == N =====================================================================================
const _NRLMSISE00_PD_N = [
7.09557E+01,-3.26740E-01, 0.00000E+00,-5.16829E-01,-1.71664E-03,
9.09310E-02,-6.71500E-01,-1.47771E-01,-9.27471E-02,-2.30862E-01,
-1.56410E-01, 1.34455E-02,-1.19717E-01, 2.52151E+00, 0.00000E+00,
-2.41582E-01, 5.92939E-02, 4.39756E+00, 9.15280E-02, 4.41292E-03,
0.00000E+00, 8.66807E-03, 0.00000E+00, 0.00000E+00, 8.66784E-02,
1.58727E-01, 9.74701E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 6.70217E+01,-1.31660E-03, 0.00000E+00,-1.65317E-02,
0.00000E+00, 0.00000E+00, 8.50247E-02, 2.77428E+01, 4.98658E-03,
6.15115E-03, 9.50156E-03,-2.12723E-02, 8.47001E-02, 1.70147E-01,
-2.38645E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00, 1.37380E-03,
-8.41918E-03, 2.80145E-05, 7.12383E-03, 0.00000E+00,-1.66209E-02,
1.03533E-04,-1.68898E-02, 0.00000E+00, 3.64526E+03, 0.00000E+00,
6.54077E-03, 3.69130E-04, 9.94419E-04, 8.42803E+01,-1.16124E-02,
-7.74414E-03,-1.68844E-03, 1.42809E-03,-1.92955E-03, 1.17225E-01,
-2.41512E-02, 1.50521E+04, 0.00000E+00, 0.00000E+00, 0.00000E+00,
1.60261E+03, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00,-3.54403E-04,-1.87270E-02,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
2.76439E-02, 6.43207E-03,-3.54300E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00,-2.80221E-02, 8.11228E+01,-6.75255E-04, 0.00000E+00,
-1.05162E-02,-3.48292E-03,-6.97321E-03, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00,-1.45546E-03,-1.31970E-02,-3.57751E-03,-1.09021E+00,
-1.50181E-02,-7.12841E-03,-6.64590E-03,-3.52610E-03,-1.87773E-02,
-2.22432E-03,-3.93895E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00
]
# == Hot O =================================================================================
const _NRLMSISE00_PD_HOT_O = [
6.04050E-02, 1.57034E+00, 2.99387E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-1.51018E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00,-8.61650E+00, 1.26454E-02,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 5.50878E-03, 0.00000E+00, 0.00000E+00, 8.66784E-02,
1.58727E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 6.23881E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 8.47001E-02, 1.70147E-01,
-9.45934E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00
]
# == S Parameters ==========================================================================
const _NRLMSISE00_PS = [
9.56827E-01, 6.20637E-02, 3.18433E-02, 0.00000E+00, 0.00000E+00,
3.94900E-02, 0.00000E+00, 0.00000E+00,-9.24882E-03,-7.94023E-03,
0.00000E+00, 0.00000E+00, 0.00000E+00, 1.74712E+02, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 2.74677E-03, 0.00000E+00, 1.54951E-02, 8.66784E-02,
1.58727E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00,-6.99007E-04, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 1.24362E-02,-5.28756E-03, 8.47001E-02, 1.70147E-01,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 2.47425E-05, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00
]
# == Turbo =================================================================================
const _NRLMSISE00_PDL_1 = [
1.09930E+00, 3.90631E+00, 3.07165E+00, 9.86161E-01, 1.63536E+01,
4.63830E+00, 1.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 1.28840E+00, 3.10302E-02, 1.18339E-01
]
const _NRLMSISE00_PDL_2 = [
1.00000E+00, 7.00000E-01, 1.15020E+00, 3.44689E+00, 1.28840E+00,
1.00000E+00, 1.08738E+00, 1.22947E+00, 1.10016E+00, 7.34129E-01,
1.15241E+00, 2.22784E+00, 7.95046E-01, 4.01612E+00, 4.47749E+00,
1.23435E+02,-7.60535E-02, 1.68986E-06, 7.44294E-01, 1.03604E+00,
1.72783E+02, 1.15020E+00, 3.44689E+00,-7.46230E-01, 9.49154E-01
]
# == Lower Boundary ========================================================================
const _NRLMSISE00_PTM = [
1.04130E+03, 3.86000E+02, 1.95000E+02, 1.66728E+01, 2.13000E+02,
1.20000E+02, 2.40000E+02, 1.87000E+02,-2.00000E+00, 0.00000E+00
]
const _NRLMSISE00_PDM_1 = [
2.45600E+07, 6.71072E-06, 1.00000E+02, 0.00000E+00, 1.10000E+02,
1.00000E+01, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00
]
const _NRLMSISE00_PDM_2 = [
8.59400E+10, 1.00000E+00, 1.05000E+02,-8.00000E+00, 1.10000E+02,
1.00000E+01, 9.00000E+01, 2.00000E+00, 0.00000E+00, 0.00000E+00
]
const _NRLMSISE00_PDM_3 = [
2.81000E+11, 0.00000E+00, 1.05000E+02, 2.80000E+01, 2.89500E+01,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00
]
const _NRLMSISE00_PDM_4 = [
3.30000E+10, 2.68270E-01, 1.05000E+02, 1.00000E+00, 1.10000E+02,
1.00000E+01, 1.10000E+02,-1.00000E+01, 0.00000E+00, 0.00000E+00
]
const _NRLMSISE00_PDM_5 = [
1.33000E+09, 1.19615E-02, 1.05000E+02, 0.00000E+00, 1.10000E+02,
1.00000E+01, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00
]
const _NRLMSISE00_PDM_6 = [
1.76100E+05, 1.00000E+00, 9.50000E+01,-8.00000E+00, 1.10000E+02,
1.00000E+01, 9.00000E+01, 2.00000E+00, 0.00000E+00, 0.00000E+00,
]
const _NRLMSISE00_PDM_7 = [
1.00000E+07, 1.00000E+00, 1.05000E+02,-8.00000E+00, 1.10000E+02,
1.00000E+01, 9.00000E+01, 2.00000E+00, 0.00000E+00, 0.00000E+00
]
const _NRLMSISE00_PDM_8 = [
1.00000E+06, 1.00000E+00, 1.05000E+02,-8.00000E+00, 5.50000E+02,
7.60000E+01, 9.00000E+01, 2.00000E+00, 0.00000E+00, 4.00000E+03
]
# == TN1(2) ================================================================================
const _NRLMSISE00_PTL_1 = [
1.00858E+00, 4.56011E-02,-2.22972E-02,-5.44388E-02, 5.23136E-04,
-1.88849E-02, 5.23707E-02,-9.43646E-03, 6.31707E-03,-7.80460E-02,
-4.88430E-02, 0.00000E+00, 0.00000E+00,-7.60250E+00, 0.00000E+00,
-1.44635E-02,-1.76843E-02,-1.21517E+02, 2.85647E-02, 0.00000E+00,
0.00000E+00, 6.31792E-04, 0.00000E+00, 5.77197E-03, 8.66784E-02,
1.58727E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00,-8.90272E+03, 3.30611E-03, 3.02172E-03, 0.00000E+00,
-2.13673E-03,-3.20910E-04, 0.00000E+00, 0.00000E+00, 2.76034E-03,
2.82487E-03,-2.97592E-04,-4.21534E-03, 8.47001E-02, 1.70147E-01,
8.96456E-03, 0.00000E+00,-1.08596E-02, 0.00000E+00, 0.00000E+00,
5.57917E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 9.65405E-03, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == TN1(3) ================================================================================
const _NRLMSISE00_PTL_2 = [
9.39664E-01, 8.56514E-02,-6.79989E-03, 2.65929E-02,-4.74283E-03,
1.21855E-02,-2.14905E-02, 6.49651E-03,-2.05477E-02,-4.24952E-02,
0.00000E+00, 0.00000E+00, 0.00000E+00, 1.19148E+01, 0.00000E+00,
1.18777E-02,-7.28230E-02,-8.15965E+01, 1.73887E-02, 0.00000E+00,
0.00000E+00, 0.00000E+00,-1.44691E-02, 2.80259E-04, 8.66784E-02,
1.58727E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 2.16584E+02, 3.18713E-03, 7.37479E-03, 0.00000E+00,
-2.55018E-03,-3.92806E-03, 0.00000E+00, 0.00000E+00,-2.89757E-03,
-1.33549E-03, 1.02661E-03, 3.53775E-04, 8.47001E-02, 1.70147E-01,
-9.17497E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
3.56082E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00,-1.00902E-02, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == TN1(4) ================================================================================
const _NRLMSISE00_PTL_3 = [
9.85982E-01,-4.55435E-02, 1.21106E-02, 2.04127E-02,-2.40836E-03,
1.11383E-02,-4.51926E-02, 1.35074E-02,-6.54139E-03, 1.15275E-01,
1.28247E-01, 0.00000E+00, 0.00000E+00,-5.30705E+00, 0.00000E+00,
-3.79332E-02,-6.24741E-02, 7.71062E-01, 2.96315E-02, 0.00000E+00,
0.00000E+00, 0.00000E+00, 6.81051E-03,-4.34767E-03, 8.66784E-02,
1.58727E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 1.07003E+01,-2.76907E-03, 4.32474E-04, 0.00000E+00,
1.31497E-03,-6.47517E-04, 0.00000E+00,-2.20621E+01,-1.10804E-03,
-8.09338E-04, 4.18184E-04, 4.29650E-03, 8.47001E-02, 1.70147E-01,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
-4.04337E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-9.52550E-04,
8.56253E-04, 4.33114E-04, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 1.21223E-03,
2.38694E-04, 9.15245E-04, 1.28385E-03, 8.67668E-04,-5.61425E-06,
1.04445E+00, 3.41112E+01, 0.00000E+00,-8.40704E-01,-2.39639E+02,
7.06668E-01,-2.05873E+01,-3.63696E-01, 2.39245E+01, 0.00000E+00,
-1.06657E-03,-7.67292E-04, 1.54534E-04, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == TN1(5), TN2(1) ========================================================================
const _NRLMSISE00_PTL_4 = [
1.00320E+00, 3.83501E-02,-2.38983E-03, 2.83950E-03, 4.20956E-03,
5.86619E-04, 2.19054E-02,-1.00946E-02,-3.50259E-03, 4.17392E-02,
-8.44404E-03, 0.00000E+00, 0.00000E+00, 4.96949E+00, 0.00000E+00,
-7.06478E-03,-1.46494E-02, 3.13258E+01,-1.86493E-03, 0.00000E+00,
-1.67499E-02, 0.00000E+00, 0.00000E+00, 5.12686E-04, 8.66784E-02,
1.58727E-01,-4.64167E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00,
4.37353E-03,-1.99069E+02, 0.00000E+00,-5.34884E-03, 0.00000E+00,
1.62458E-03, 2.93016E-03, 2.67926E-03, 5.90449E+02, 0.00000E+00,
0.00000E+00,-1.17266E-03,-3.58890E-04, 8.47001E-02, 1.70147E-01,
0.00000E+00, 0.00000E+00, 1.38673E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 1.60571E-03,
6.28078E-04, 5.05469E-05, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-1.57829E-03,
-4.00855E-04, 5.04077E-05,-1.39001E-03,-2.33406E-03,-4.81197E-04,
1.46758E+00, 6.20332E+00, 0.00000E+00, 3.66476E-01,-6.19760E+01,
3.09198E-01,-1.98999E+01, 0.00000E+00,-3.29933E+02, 0.00000E+00,
-1.10080E-03,-9.39310E-05, 1.39638E-04, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == TN2(2) ================================================================================
const _NRLMSISE00_PMA_1 = [
9.81637E-01,-1.41317E-03, 3.87323E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-3.58707E-02,
-8.63658E-03, 0.00000E+00, 0.00000E+00,-2.02226E+00, 0.00000E+00,
-8.69424E-03,-1.91397E-02, 8.76779E+01, 4.52188E-03, 0.00000E+00,
2.23760E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00,-7.07572E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00,
-4.11210E-03, 3.50060E+01, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00,-8.36657E-03, 1.61347E+01, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00,-1.45130E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 1.24152E-03,
6.43365E-04, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 1.33255E-03,
2.42657E-03, 1.60666E-03,-1.85728E-03,-1.46874E-03,-4.79163E-06,
1.22464E+00, 3.53510E+01, 0.00000E+00, 4.49223E-01,-4.77466E+01,
4.70681E-01, 8.41861E+00,-2.88198E-01, 1.67854E+02, 0.00000E+00,
7.11493E-04, 6.05601E-04, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == TN2(3) ================================================================================
const _NRLMSISE00_PMA_2 = [
1.00422E+00,-7.11212E-03, 5.24480E-03, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-5.28914E-02,
-2.41301E-02, 0.00000E+00, 0.00000E+00,-2.12219E+01,-1.03830E-02,
-3.28077E-03, 1.65727E-02, 1.68564E+00,-6.68154E-03, 0.00000E+00,
1.45155E-02, 0.00000E+00, 8.42365E-03, 0.00000E+00, 0.00000E+00,
0.00000E+00,-4.34645E-03, 0.00000E+00, 0.00000E+00, 2.16780E-02,
0.00000E+00,-1.38459E+02, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 7.04573E-03,-4.73204E+01, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 1.08767E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-8.08279E-03,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 5.21769E-04,
-2.27387E-04, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 3.26769E-03,
3.16901E-03, 4.60316E-04,-1.01431E-04, 1.02131E-03, 9.96601E-04,
1.25707E+00, 2.50114E+01, 0.00000E+00, 4.24472E-01,-2.77655E+01,
3.44625E-01, 2.75412E+01, 0.00000E+00, 7.94251E+02, 0.00000E+00,
2.45835E-03, 1.38871E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == TN2(4), TN3(1) ========================================================================
const _NRLMSISE00_PMA_3 = [
1.01890E+00,-2.46603E-02, 1.00078E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-6.70977E-02,
-4.02286E-02, 0.00000E+00, 0.00000E+00,-2.29466E+01,-7.47019E-03,
2.26580E-03, 2.63931E-02, 3.72625E+01,-6.39041E-03, 0.00000E+00,
9.58383E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00,-1.85291E-03, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 1.39717E+02, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 9.19771E-03,-3.69121E+02, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00,-1.57067E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-7.07265E-03,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-2.92953E-03,
-2.77739E-03,-4.40092E-04, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.47280E-03,
2.95035E-04,-1.81246E-03, 2.81945E-03, 4.27296E-03, 9.78863E-04,
1.40545E+00,-6.19173E+00, 0.00000E+00, 0.00000E+00,-7.93632E+01,
4.44643E-01,-4.03085E+02, 0.00000E+00, 1.15603E+01, 0.00000E+00,
2.25068E-03, 8.48557E-04,-2.98493E-04, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == TN3(2) ================================================================================
const _NRLMSISE00_PMA_4 = [
9.75801E-01, 3.80680E-02,-3.05198E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 3.85575E-02,
5.04057E-02, 0.00000E+00, 0.00000E+00,-1.76046E+02, 1.44594E-02,
-1.48297E-03,-3.68560E-03, 3.02185E+01,-3.23338E-03, 0.00000E+00,
1.53569E-02, 0.00000E+00,-1.15558E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 4.89620E-03, 0.00000E+00, 0.00000E+00,-1.00616E-02,
-8.21324E-03,-1.57757E+02, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 6.63564E-03, 4.58410E+01, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00,-2.51280E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 9.91215E-03,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-8.73148E-04,
-1.29648E-03,-7.32026E-05, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-4.68110E-03,
-4.66003E-03,-1.31567E-03,-7.39390E-04, 6.32499E-04,-4.65588E-04,
-1.29785E+00,-1.57139E+02, 0.00000E+00, 2.58350E-01,-3.69453E+01,
4.10672E-01, 9.78196E+00,-1.52064E-01,-3.85084E+03, 0.00000E+00,
-8.52706E-04,-1.40945E-03,-7.26786E-04, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == TN3(3) ================================================================================
const _NRLMSISE00_PMA_5 = [
9.60722E-01, 7.03757E-02,-3.00266E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.22671E-02,
4.10423E-02, 0.00000E+00, 0.00000E+00,-1.63070E+02, 1.06073E-02,
5.40747E-04, 7.79481E-03, 1.44908E+02, 1.51484E-04, 0.00000E+00,
1.97547E-02, 0.00000E+00,-1.41844E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 5.77884E-03, 0.00000E+00, 0.00000E+00, 9.74319E-03,
0.00000E+00,-2.88015E+03, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00,-4.44902E-03,-2.92760E+01, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 2.34419E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 5.36685E-03,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-4.65325E-04,
-5.50628E-04, 3.31465E-04, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-2.06179E-03,
-3.08575E-03,-7.93589E-04,-1.08629E-04, 5.95511E-04,-9.05050E-04,
1.18997E+00, 4.15924E+01, 0.00000E+00,-4.72064E-01,-9.47150E+02,
3.98723E-01, 1.98304E+01, 0.00000E+00, 3.73219E+03, 0.00000E+00,
-1.50040E-03,-1.14933E-03,-1.56769E-04, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == TN3(4) ================================================================================
const _NRLMSISE00_PMA_6 = [
1.03123E+00,-7.05124E-02, 8.71615E-03, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-3.82621E-02,
-9.80975E-03, 0.00000E+00, 0.00000E+00, 2.89286E+01, 9.57341E-03,
0.00000E+00, 0.00000E+00, 8.66153E+01, 7.91938E-04, 0.00000E+00,
0.00000E+00, 0.00000E+00, 4.68917E-03, 0.00000E+00, 0.00000E+00,
0.00000E+00, 7.86638E-03, 0.00000E+00, 0.00000E+00, 9.90827E-03,
0.00000E+00, 6.55573E+01, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00,-4.00200E+01, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 7.07457E-03, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 5.72268E-03,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-2.04970E-04,
1.21560E-03,-8.05579E-06, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-2.49941E-03,
-4.57256E-04,-1.59311E-04, 2.96481E-04,-1.77318E-03,-6.37918E-04,
1.02395E+00, 1.28172E+01, 0.00000E+00, 1.49903E-01,-2.63818E+01,
0.00000E+00, 4.70628E+01,-2.22139E-01, 4.82292E-02, 0.00000E+00,
-8.67075E-04,-5.86479E-04, 5.32462E-04, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == TN3(4), Surface Temperature TSL =======================================================
const _NRLMSISE00_PMA_7 = [
1.00828E+00,-9.10404E-02,-2.26549E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-2.32420E-02,
-9.08925E-03, 0.00000E+00, 0.00000E+00, 3.36105E+01, 0.00000E+00,
0.00000E+00, 0.00000E+00,-1.24957E+01,-5.87939E-03, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 2.79765E+01, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 2.01237E+03, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00,-1.75553E-02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 3.29699E-03,
1.26659E-03, 2.68402E-04, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 1.17894E-03,
1.48746E-03, 1.06478E-04, 1.34743E-04,-2.20939E-03,-6.23523E-04,
6.36539E-01, 1.13621E+01, 0.00000E+00,-3.93777E-01, 2.38687E+03,
0.00000E+00, 6.61865E+02,-1.21434E-01, 9.27608E+00, 0.00000E+00,
1.68478E-04, 1.24892E-03, 1.71345E-03, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == TGN3(2), Surface Gradient TSLG ========================================================
const _NRLMSISE00_PMA_8 = [
1.57293E+00,-6.78400E-01, 6.47500E-01, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-7.62974E-02,
-3.60423E-01, 0.00000E+00, 0.00000E+00, 1.28358E+02, 0.00000E+00,
0.00000E+00, 0.00000E+00, 4.68038E+01, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00,-1.67898E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 2.90994E+04, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 3.15706E+01, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == TGN2(1), TGN1(2) ======================================================================
const _NRLMSISE00_PMA_9 = [
8.60028E-01, 3.77052E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-1.17570E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 7.77757E-03, 0.00000E+00,
0.00000E+00, 0.00000E+00, 1.01024E+02, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 6.54251E+02, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,-1.56959E-02,
1.91001E-02, 3.15971E-02, 1.00982E-02,-6.71565E-03, 2.57693E-03,
1.38692E+00, 2.82132E-01, 0.00000E+00, 0.00000E+00, 3.81511E+02,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == TGN3(1), TGN2(2) ======================================================================
const _NRLMSISE00_PMA_10 = [
1.06029E+00,-5.25231E-02, 3.73034E-01, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 3.31072E-02,
-3.88409E-01, 0.00000E+00, 0.00000E+00,-1.65295E+02,-2.13801E-01,
-4.38916E-02,-3.22716E-01,-8.82393E+01, 1.18458E-01, 0.00000E+00,
-4.35863E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00,-1.19782E-01, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 2.62229E+01, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00,-5.37443E+01, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00,-4.55788E-01, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 3.84009E-02,
3.96733E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 5.05494E-02,
7.39617E-02, 1.92200E-02,-8.46151E-03,-1.34244E-02, 1.96338E-02,
1.50421E+00, 1.88368E+01, 0.00000E+00, 0.00000E+00,-5.13114E+01,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00,
5.11923E-02, 3.61225E-02, 0.00000E+00, 0.00000E+00, 0.00000E+00,
0.00000E+00, 0.00000E+00, 0.00000E+00, 0.00000E+00, 2.00000E+00
]
# == Middle Atmosphere Averages ============================================================
const _NRLMSISE00_PAVGM = [
2.61000E+02, 2.64000E+02, 2.29000E+02, 2.17000E+02, 2.17000E+02,
2.23000E+02, 2.86760E+02,-2.93940E+00, 2.50000E+00, 0.00000E+00
]
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 5222 | ## Description #############################################################################
#
# Mathematical functions used in the NRLMSISE-00 model.
#
## References ##############################################################################
#
# [1] https://www.brodo.de/space/nrlmsise/index.html
#
############################################################################################
"""
_spline_β«(x::NTuple{N, T}, y::NTuple{N, T}, βΒ²y::NTuple{N, T}, xf::Number) where {N, T<:Number} -> float(T)
Compute the integral of the cubic spline function `y(x)` from `x[1]` to `xf`, where the
function second derivatives evaluated at `x` are `βΒ²y`.
# Arguments
- `x::NTuple{N, T}`: X components of the tabulated function in ascending order.
- `y::NTuple{N, T}`: Y components of the tabulated function evaluated at `x`.
- `βΒ²y::NTuple{N, T}`: Second derivatives of `y(x)` `βΒ²y/βxΒ²` evaluated at `x`.
- `xf::Number`: Abscissa endpoint for integration.
"""
function _spline_β«(
x::NTuple{N, T},
y::NTuple{N, T},
βΒ²y::NTuple{N, T},
xf::T
) where {N, T<:Number}
int = T(0)
kβ = 1
kβ = 2
@inbounds while (xf > x[kβ]) && (kβ <= N)
xα΅’ = ((kβ <= (N - 1)) && (xf >= x[kβ])) ? x[kβ] : xf
h = (x[kβ] - x[kβ])
a = (x[kβ] - xα΅’ ) / h
b = (xα΅’ - x[kβ]) / h
aΒ² = a^2
bΒ² = b^2
aβ΄ = a^4
bβ΄ = b^4
hΒ² = h^2
k_a = -(1 + aβ΄) / 4 + aΒ² / 2
k_b = bβ΄ / 4 - bΒ² / 2
int += h * ((1 - aΒ²) * y[kβ] / 2 + bΒ² * y[kβ] / 2 + (k_a * βΒ²y[kβ] + k_b * βΒ²y[kβ]) * hΒ² / 6)
kβ += 1
kβ += 1
end
return int
end
"""
_spline_βΒ²(x::NTuple{N, T}, y::NTuple{N, T}, βΒ²yβ::T, βΒ²yβ::T) where {N, T<:Number} -> NTuple{N, T}
Compute the 2nd derivatives of the cubic spline interpolation `y(x)` given the 2nd
derivatives at `x[1]` (`βΒ²yβ`) and at `x[N]` (`βΒ²yβ`). This functions return a tuple with
the evaluated 2nd derivatives at each point in `x`.
!!! note
This function was adapted from Numerical Recipes.
!!! note
Values higher than `0.99e30` in the 2nd derivatives at the borders (`βΒ²yβ` and `βΒ²yβ`)
are interpreted as `0`.
# Arguments
- `x::NTuple{N, T}`: X components of the tabulated function in ascending order.
- `y::NTuple{N, T}`: Y components of the tabulated function evaluated at `x`.
- `βΒ²yβ::T`: Second derivative of `y(x)` `βΒ²y/βxΒ²` evaluated at `x[1]`.
- `βΒ²yβ::T`: Second derivative of `y(x)` `βΒ²y/βxΒ²` evaluated at `x[N]`.
"""
function _spline_βΒ²(
x::NTuple{N, T},
y::NTuple{N, T},
βΒ²yβ::T,
βΒ²yβ::T
) where {N, T<:Number}
# Initialize the tuples that holds the derivatives. Notice that we do not use vectors to
# avoid allocations. This code can be much slower for very large `N`. However, N <= 5
# for the NRLMSISE-00 model.
u = ntuple(_ -> T(0), Val(N))
βΒ²y = ntuple(_ -> T(0), Val(N))
if (βΒ²yβ > 0.99e30)
@reset βΒ²y[1] = T(0)
@reset u[1] = T(0)
else
@reset βΒ²y[1] = -T(1 / 2)
@reset u[1] = (3 / (x[2] - x[1])) * ((y[2] - y[1]) / (x[2] - x[1]) - βΒ²yβ)
end
@inbounds for i in 2:N-1
Ο = (x[i] - x[i-1]) / (x[i+1] - x[i-1])
p = Ο * βΒ²y[i-1] + 2
@reset βΒ²y[i] = (Ο - 1) / p
m_a = (y[i+1] - y[i] ) / (x[i+1] - x[i] )
m_b = (y[i] - y[i-1]) / (x[i] - x[i-1])
@reset u[i] = (6 * (m_a - m_b) / (x[i+1] - x[i-1]) - Ο * u[i-1]) / p
end
if βΒ²yβ > 0.99e30
qβ = T(0)
uβ = T(0)
else
qβ = T(1 / 2)
uβ = (3 / (x[N] - x[N-1])) * (βΒ²yβ - (y[N] - y[N-1]) / (x[N] - x[N-1]))
end
@reset βΒ²y[N] = (uβ - qβ * u[N-1]) / (qβ * βΒ²y[N-1] + 1)
@inbounds for k in N-1:-1:1
@reset βΒ²y[k] = βΒ²y[k] * βΒ²y[k+1] + u[k]
end
return βΒ²y
end
"""
_spline(x::NTuple{N, T}, y::NTuple{N, T}, βΒ²y::NTuple{N, T}, xα΅’::T) where {N, T<:Number} -> float(T)
Compute the interpolation of the cubic spline `y(x)` with second derivatives `βΒ²y` at `xα΅’`.
!!! note
This function was adapted from Numerical Recipes.
# Arguments
- `x::NTuple{N, T}`: X components of the tabulated function in ascending order.
- `y::NTuple{N, T}`: Y components of the tabulated function evaluated at `x`.
- `βΒ²y::NTuple{N, T}`: Second derivatives of `y(x)` `βΒ²y/βxΒ²` evaluated at `x`.
- `xα΅’::T`: Point to compute the interpolation.
"""
function _spline(
x::NTuple{N, T},
y::NTuple{N, T},
βΒ²y::NTuple{N, T},
xα΅’::T
) where {N, T<:Number}
kβ = 1
kβ = N
@inbounds while (kβ - kβ) > 1
k = div(kβ + kβ, 2, RoundNearest)
if x[k] > xα΅’
kβ = k
else
kβ = k
end
end
h = x[kβ] - x[kβ]
(h == 0) &&
throw(ArgumentError("It is not allowed to have two points with the same abscissa."))
a = (x[kβ] - xα΅’ ) / h
b = (xα΅’ - x[kβ]) / h
yα΅’ = a * y[kβ] + b * y[kβ] + ((a^3 - a) * βΒ²y[kβ] + (b^3 - b) * βΒ²y[kβ]) * h^2 / 6
return yα΅’
end
"""
_ΞΆ(r_lat::T, zz::T, zl::T) where T<:Number -> float(T)
Compute the zeta function.
"""
function _ΞΆ(r_lat::T, zz::T, zl::T) where T<:Number
return (zz - zl) * (r_lat + zl) / (r_lat + zz)
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 63136 | ## Description #############################################################################
#
# The NRLMSISE-00 empirical atmosphere model was developed by Mike Picone, Alan Hedin, and
# Doug Drob based on the MSISE90 model.
#
# The MSISE90 model describes the neutral temperature and densities in Earth's atmosphere
# from ground to thermospheric heights. Below 72.5 km the model is primarily based on the
# MAP Handbook (Labitzke et al., 1985) tabulation of zonal average temperature and pressure
# by Barnett and Corney, which was also used for the CIRA-86. Below 20 km these data were
# supplemented with averages from the National Meteorological Center (NMC). In addition,
# pitot tube, falling sphere, and grenade sounder rocket measurements from 1947 to 1972 were
# taken into consideration. Above 72.5 km MSISE-90 is essentially a revised MSIS-86 model
# taking into account data derived from space shuttle flights and newer incoherent scatter
# results. For someone interested only in the thermosphere (above 120 km), the author
# recommends the MSIS-86 model. MSISE is also not the model of preference for specialized
# tropospheric work. It is rather for studies that reach across several atmospheric
# boundaries.
#
# (quoted from http://nssdc.gsfc.nasa.gov/space/model/atmos/nrlmsise00.html)
#
# This Julia version of NRLMSISE-00 was converted from the C version implemented and
# maintained by Dominik Brodowski <[email protected]> and available at
# http://www.brodo.de/english/pub/nrlmsise/index.html .
#
# The source code is available at the following git:
#
# https://git.linta.de/?p=~brodo/nrlmsise-00.git;a=tree
#
# The conversion also used information available at the FORTRAN source code available at
#
# https://ccmc.gsfc.nasa.gov/pub/modelweb/atmospheric/msis/nrlmsise00/
#
## References ##############################################################################
#
# [1] https://www.brodo.de/space/nrlmsise/index.html
# [2] https://www.orekit.org/site-orekit-11.0/xref/org/orekit/models/earth/atmosphere/NRLMSISE00.html
#
############################################################################################
export nrlmsise00
"""
nrlmsise00(instant::DateTime, h::Number, Ο_gd::Number, Ξ»::Number[, F10β::Number, F10::Number, ap::Union{Number, AbstractVector}]; kwargs...) -> Nrlmsise00Output{Float64}
nrlmsise00(jd::Number, h::Number, Ο_gd::Number, Ξ»::Number[, F10β::Number, F10::Number, ap::Union{Number, AbstractVector}]; kwargs...) -> Nrlmsise00Output{Float64}
Compute the atmospheric density using the NRLMSISE-00 model.
If we omit all space indices, the system tries to obtain them automatically for the selected
day `jd` or `instant`. However, the indices must be already initialized using the function
`SpaceIndices.init()`.
# Arguments
- `instant::DateTime`: Instant to compute the model represent using `DateTime`.
- `jd::Number`: Julian day to compute the model.
- `h::Number`: Altitude [m].
- `Ο_gd::Number`: Geodetic latitude [rad].
- `Ξ»::Number`: Longitude [rad].
- `F10β::Number`: 10.7-cm averaged solar flux, 90-day centered on input time [sfu].
- `F10::Number`: 10.7-cm solar flux [sfu].
- `ap::Union{Number, AbstractVector}`: Magnetic index, see the section **AP** for more
information.
# Keywords
- `flags::Nrlmsise00Flags`: A list of flags to configure the model. For more information,
see [`Nrlmsise00Flags`]@(ref). (**Default** = `Nrlmsise00Flags()`)
- `include_anomalous_oxygen::Bool`: If `true`, the anomalous oxygen density will be included
in the total density computation. (**Default** = `true`)
- `P::Union{Nothing, Matrix}`: If the user passes a matrix with dimensions equal to or
greater than 8 Γ 4, it will be used when computing the Legendre associated functions,
reducing allocations and improving the performance. If it is `nothing`, the matrix is
allocated inside the function. (**Default** `nothing`)
# Returns
- `Nrlmsise00Output{Float64}`: Structure containing the results obtained from the model.
# AP
The input variable `ap` contains the magnetic index. It can be a `Number` or an
`AbstractVector`.
If `ap` is a number, it must contain the daily magnetic index.
If `ap` is an `AbstractVector`, it must be a vector with 7 dimensions as described below:
| Index | Description |
|-------|:------------------------------------------------------------------------------|
| 1 | Daily AP. |
| 2 | 3 hour AP index for current time. |
| 3 | 3 hour AP index for 3 hours before current time. |
| 4 | 3 hour AP index for 6 hours before current time. |
| 5 | 3 hour AP index for 9 hours before current time. |
| 6 | Average of eight 3 hour AP indices from 12 to 33 hours prior to current time. |
| 7 | Average of eight 3 hour AP indices from 36 to 57 hours prior to current time. |
# Extended Help
1. The densities of `O`, `H`, and `N` are set to `0` below `72.5 km`.
2. The exospheric temperature is set to global average for altitudes below `120 km`. The
`120 km` gradient is left at global average value for altitudes below `72.5 km`.
3. Anomalous oxygen is defined as hot atomic oxygen or ionized oxygen that can become
appreciable at high altitudes (`> 500 km`) for some ranges of inputs, thereby affection
drag on satellites and debris. We group these species under the term **Anomalous
Oxygen**, since their individual variations are not presently separable with the drag
data used to define this model component.
## Notes on Input Variables
`F10` and `F10β` values used to generate the model correspond to the 10.7 cm radio flux at
the actual distance of the Earth from the Sun rather than the radio flux at 1 AU. The
following site provides both classes of values:
ftp://ftp.ngdc.noaa.gov/STP/SOLAR_DATA/SOLAR_RADIO/FLUX/
`F10`, `F10β`, and `ap` effects are neither large nor well established below 80 km and
these parameters should be set to 150, 150, and 4 respectively.
If `include_anomalous_oxygen` is `false`, the `total_density` field in the output is the sum
of the mass densities of the species `He`, `O`, `Nβ`, `Oβ`, `Ar`, `H`, and `N`, but **does
not** include anomalous oxygen.
If `include_anomalous_oxygen` is `false`, the `total_density` field in the output is the
effective total mass density for drag and is the sum of the mass densities of all species in
this model **including** the anomalous oxygen.
"""
function nrlmsise00(
instant::DateTime,
h::Number,
Ο_gd::Number,
Ξ»::Number;
flags::Nrlmsise00Flags = Nrlmsise00Flags(),
include_anomalous_oxygen::Bool = true,
P::Union{Nothing, Matrix} = nothing
)
return nrlmsise00(
datetime2julian(instant),
h,
Ο_gd,
Ξ»;
flags = flags,
include_anomalous_oxygen = include_anomalous_oxygen,
P = P
)
end
function nrlmsise00(
jd::Number,
h::Number,
Ο_gd::Number,
Ξ»::Number;
flags::Nrlmsise00Flags = Nrlmsise00Flags(),
include_anomalous_oxygen::Bool = true,
P::Union{Nothing, Matrix} = nothing
)
# Fetch the space indices.
#
# NOTE: If the altitude is lower than 80km, set to default according to the instructions
# in NRLMSISE-00 source code.
if h < 80e3
F10β = 150.0
F10 = 150.0
ap = 4.0
@debug """
NRLMSISE00 - Using default indices since h < 80 km
Daily F10.7 : $(F10) sfu
90-day avareged F10.7 : $(F10β) sfu
Ap : $(ap)
"""
else
# TODO: The online version of NRLMSISE-00 seems to use 89 days, whereas the
# NRLMSISE-00 source code mentions 81 days.
F10β = sum((space_index.(Val(:F10adj), k) for k in (jd - 45):(jd + 44))) / 90
F10 = space_index(Val(:F10adj), jd - 1)
ap = sum(space_index(Val(:Ap), jd)) / 8
@debug """
NRLMSISE00 - Fetched Space Indices
Daily F10.7 : $(F10) sfu
90-day avareged F10.7 : $(F10β) sfu
Ap : $(ap)
"""
end
# Call the NRLMSISE-00 model.
return nrlmsise00(
jd,
h,
Ο_gd,
Ξ»,
F10β,
F10,
ap;
flags = flags,
include_anomalous_oxygen = include_anomalous_oxygen,
P = P
)
end
function nrlmsise00(
instant::DateTime,
h::Number,
Ο_gd::Number,
Ξ»::Number,
F10β::Number,
F10::Number,
ap::Union{Number, AbstractVector};
flags::Nrlmsise00Flags = Nrlmsise00Flags(),
include_anomalous_oxygen::Bool = true,
P::Union{Nothing, Matrix} = nothing
)
return nrlmsise00(
datetime2julian(instant),
h,
Ο_gd,
Ξ»,
F10β,
F10,
ap;
flags = flags,
include_anomalous_oxygen = include_anomalous_oxygen,
P = P
)
end
function nrlmsise00(
jd::Number,
h::Number,
Ο_gd::Number,
Ξ»::Number,
F10β::Number,
F10::Number,
ap::T_AP;
flags::Nrlmsise00Flags = Nrlmsise00Flags(),
include_anomalous_oxygen::Bool = true,
P::Union{Nothing, Matrix} = nothing
) where T_AP<:Union{Number, AbstractVector}
# == Compute Auxiliary Variables =======================================================
# Convert the Julian Day to Date.
Y, M, D, hour, min, sec = jd_to_date(jd)
# Get the number of days since the beginning of the year.
doy = round(Int, date_to_jd(Y, M, D, 0, 0, 0) - date_to_jd(Y, 1, 1, 0, 0, 0)) + 1
# Get the number of seconds since the beginning of the day.
Ξds = 3600hour + 60min + sec
# Get the local apparent solar time [hours].
#
# TODO: To be very precise, I think this should also take into consideration the
# Equation of Time. However, the online version of NRLMSISE-00 does not use this.
lst = Ξds / 3600 + Ξ» * 12 / Ο
df = F10 - F10β
dfa = F10β - 150
stloc, ctloc = sincos(1 * _HOUR_TO_RAD * lst)
s2tloc, c2tloc = sincos(2 * _HOUR_TO_RAD * lst)
s3tloc, c3tloc = sincos(3 * _HOUR_TO_RAD * lst)
# Compute Legendre polynomials.
#
# Notice that the original NRLMSISE-00 algorithms considers that the Legendre matrix is
# upper triangular, whereas we use the lower triangular representation. Hence, we need
# to transpose it.
#
# Furthermore, the NRLMSISE-00 algorithm only uses terms with maximum degree 7 and
# maximum order 3.
if isnothing(P)
plg = legendre(Val(:unnormalized), Ο / 2 - Ο_gd, 7, 3; ph_term = false)'
else
rows, cols = size(P)
if (rows < 8) || (cols < 4)
throw(ArgumentError("The matrix P must have at least 8 Γ 4 elements."))
end
legendre!(Val(:unnormalized), P, Ο / 2 - Ο_gd, 7, 3; ph_term = false)
plg = P'
end
# == Latitude Variation of Gravity =====================================================
#
# None for flags.time_independent = false.
g_lat, r_lat = _gravity_and_effective_radius(
(!flags.time_independent) ? Float64(_REFERENCE_LATITUDE) : Float64(Ο_gd / _DEG_TO_RAD)
)
# == Create the NRLMSISE00 Structure ===================================================
nrlmsise00d = Nrlmsise00Structure{Float64, T_AP}(
Y,
doy,
Ξds,
h / 1000,
Ο_gd / _DEG_TO_RAD,
Ξ» / _DEG_TO_RAD,
lst,
F10β,
F10,
ap,
flags,
r_lat,
g_lat,
df,
dfa,
plg,
ctloc,
stloc,
c2tloc,
s2tloc,
c3tloc,
s3tloc,
0,
0,
0,
0,
0
)
# Call the NRLMSISE-00 model.
~, nrlmsise00_out = include_anomalous_oxygen ?
_gtd7d(nrlmsise00d) :
_gtd7(nrlmsise00d)
return nrlmsise00_out
end
############################################################################################
# Private Functions #
############################################################################################
"""
_densm(h::T, d0::T, xm::T, tz::T, r_lat::T, g_lat::T, tn2::NTuple{N2, T}, tgn2::NTuple{2, T}, tn3::NTuple{N3, T}, tgn3::NTuple{2, T}) where {N2<:Interger, N3<:Integer, T<:Number} -> float(T), float(T)
Compute the temperature and density profiles for the lower atmosphere.
!!! note
This function returns the density if `xm` is not 0, or the temperature otherwise.
# Arguments
- `h::T`: Altitude [km].
- `dβ::T`: Reference density, returned if `h > _ZN2[1]`.
- `xm::T`: Species molecular weight [ ].
- `g_lat::T`: Reference gravity at desired latitude [cm / sΒ²].
- `r_lat::T`: Reference radius at desired latitude [km].
- `tn2::NTuple{N2, T}`: Temperature at the nodes for ZN2 scale [K].
- `tgn2::NTuple{N2, T}`: Temperature gradients at the end nodes for ZN2 scale.
- `tn3::NTuple{N3, T}`: Temperature at the nodes for ZN3 scale [K].
- `tgn3::NTuple{N3, T}`: Temperature gradients at the end nodes for ZN3 scale.
# Returns
- `T`: Density [1 / cmΒ³] is `xm` is not 0, or the temperature [K] otherwise.
"""
function _densm(
h::T,
dβ::T,
xm::T,
g_lat::T,
r_lat::T,
tn2::NTuple{4, T},
tgn2::NTuple{2, T},
tn3::NTuple{5, T},
tgn3::NTuple{2, T},
) where T<:Number
# == Initialization of Variables =======================================================
density = dβ
(h > _ZN2[begin]) && return density
# == Stratosphere / Mesosphere Temperature =============================================
z = (h > _ZN2[end]) ? h : _ZN2[end]
z1 = _ZN2[begin]
z2 = _ZN2[end]
t1 = tn2[begin]
t2 = tn2[end]
zg = _ΞΆ(r_lat, z, z1)
zgdif = _ΞΆ(r_lat, z2, z1)
# Set up spline nodes.
xs2 = ntuple(_ -> T(0), Val(4))
ys2 = ntuple(_ -> T(0), Val(4))
@inbounds for k in 1:4
@reset xs2[k] = _ΞΆ(r_lat, _ZN2[k], z1) / zgdif
@reset ys2[k] = 1 / tn2[k]
end
βΒ²yβ = -tgn2[begin] / (t1 * t1) * zgdif
βΒ²yβ = -tgn2[end] / (t2 * t2) * zgdif * ((r_lat + z2) / (r_lat + z1))^2
# Calculate spline coefficients.
βΒ²y = _spline_βΒ²(xs2, ys2, βΒ²yβ, βΒ²yβ)
# Interpolate at desired point.
x = zg / zgdif
y = _spline(xs2, ys2, βΒ²y, x)
# Temperature at altitude.
tz = 1 / y
if xm != 0
# Compute the gravity at `z1`.
g_h = g_lat / (1 + z1 / r_lat)^2
# Calculate stratosphere / mesosphere density.
Ξ³ = xm * g_h * zgdif / T(_RGAS)
# Integrate temperature profile.
expl = min(Ξ³ * _spline_β«(xs2, ys2, βΒ²y, x), T(50));
# Density at altitude.
density *= (t1 / tz) * exp(-expl)
end
if h > _ZN3[1]
if xm == 0
return tz
else
return density
end
end
# == Troposhepre / Stratosphere Temperature ============================================
z = h
z1 = T(_ZN3[begin])
z2 = T(_ZN3[end])
t1 = tn3[begin]
t2 = tn3[end]
zg = _ΞΆ(r_lat, z, z1)
zgdif = _ΞΆ(r_lat, z2, z1)
# Set up spline nodes.
xs3 = ntuple(_ -> T(0), Val(5))
ys3 = ntuple(_ -> T(0), Val(5))
@inbounds for k in 1:5
@reset xs3[k] = _ΞΆ(r_lat, _ZN3[k], z1) / zgdif
@reset ys3[k] = 1 / tn3[k]
end
βΒ²yβ = -tgn3[begin] / (t1 * t1) * zgdif
βΒ²yβ = -tgn3[end] / (t2 * t2) * zgdif * ((r_lat + z2) / (r_lat + z1))^2
# Calculate spline coefficients.
βΒ²y = _spline_βΒ²(xs3, ys3, βΒ²yβ, βΒ²yβ)
x = zg / zgdif
y = _spline(xs3, ys3, βΒ²y, x)
# Temperature at altitude.
tz = 1 / y
if xm != 0
# Compute the gravity at `z1`.
g_h = g_lat / (1 + z1 / r_lat)^2
# Calculate tropospheric / stratosphere density.
Ξ³ = xm * g_h * zgdif / T(_RGAS);
# Integrate temperature profile.
expl = min(Ξ³ * _spline_β«(xs3, ys3, βΒ²y, x) , T(50))
# Density at altitude.
density *= (t1 / tz) * exp(-expl)
return density
else
return tz
end
end
"""
_densu(h::T, dlb::T, tinf::T, tlb::T, xm::T, Ξ±::T, zlb::T, s2::T, g_lat::T, r_lat::T, tn1::NTuple{5, T}, tgn1::NTuple{2, T}) where T<:Number -> T, NTuple{5, T}, NTuple{2, T}
Compute the density [1 / cmΒ³] or temperature [K] profiles according to the new lower thermo
polynomial.
!!! note
This function returns the density if `xm` is not 0, or the temperature otherwise.
# Arguments
- `h::T`: Altitude [km].
- `dlb::T`: Density at lower boundary [1 / cmΒ³].
- `tinf::T`: Exospheric temperature [K].
- `tlb::T`: Temperature at lower boundary [K].
- `xm::T`: Species molecular weight [ ].
- `Ξ±::T`: Thermal diffusion coefficient.
- `zlb::T`: Altitude at lower boundary [km].
- `s2::T`: Slope.
- `g_lat::T`: Reference gravity at the latitude [cm / sΒ²].
- `r_lat::T`: Reference radius at the latitude [km].
- `tn1::NTuple{5, T}`: Temperature at nodes for ZN1 scale [K].
- `tgn1::NTuple{2, T}`: Temperature gradients at end nodes for ZN1 scale.
# Returns
- `T`: Density [1 / cmΒ³] is `xm` is not 0, or the temperature [K] otherwise.
- `NTuple{5, T}`: Updated `tn1`.
- `NTuple{2, T}`: Updated `tgn1`.
"""
function _densu(
h::T,
dlb::T,
tinf::T,
tlb::T,
xm::T,
Ξ±::T,
zlb::T,
s2::T,
g_lat::T,
r_lat::T,
tn1::NTuple{5, T},
tgn1::NTuple{2, T}
) where T<:Number
x = T(0)
z1 = T(0)
t1 = T(0)
zgdif = T(0)
xs = ntuple(_ -> T(0), Val(5))
ys = ntuple(_ -> T(0), Val(5))
βΒ²y = ntuple(_ -> T(0), Val(5))
# Joining altitudes of Bates and spline.
z = max(h, _ZN1[begin])
# Geopotential altitude difference from ZLB.
zg2 = _ΞΆ(r_lat, z, zlb)
# Bates temperature.
tt = tinf - (tinf - tlb) * exp(-s2 * zg2)
ta = tt
tz = tt
@inbounds if h < _ZN1[begin]
# Compute the temperature below ZA temperature gradient at ZA from Bates profile.
dta = (tinf - ta) * s2 * ((r_lat + zlb) / (r_lat + _ZN1[begin]))^2
@reset tgn1[begin] = dta
@reset tn1[begin] = ta
z = (h > _ZN1[end]) ? h : _ZN1[end]
z1 = _ZN1[begin]
z2 = _ZN1[end]
t1 = tn1[begin]
t2 = tn1[end]
# Geopotential difference from z1.
zg = _ΞΆ(r_lat, z, z1)
zgdif = _ΞΆ(r_lat, z2, z1)
# Set up spline nodes.
for k in 1:5
@reset xs[k] = _ΞΆ(r_lat, _ZN1[k], z1) / zgdif
@reset ys[k] = 1 / tn1[k]
end
# End node derivatives.
βΒ²yβ = -tgn1[begin] / (t1 * t1) * zgdif
βΒ²yβ = -tgn1[end] / (t2 * t2) * zgdif * ((r_lat + z2) / (r_lat + z1))^2
# Compute spline coefficients.
@reset βΒ²y = _spline_βΒ²(xs, ys, βΒ²yβ, βΒ²yβ)
# Interpolate at the desired point.
x = zg / zgdif
y = _spline(xs, ys, βΒ²y, x)
# Temperature at altitude.
tz = 1 / y
end
(xm == 0) && return tz, tn1, tgn1
# Compute the gravity at `zlb`.
g_h = g_lat / (1 + zlb / r_lat)^2
# Calculate density above _ZN1[1].
Ξ³ = xm * g_h / (s2 * T(_RGAS) * tinf)
expl = exp(-s2 * Ξ³ * zg2)
if (expl > 50) || (tt <= 0)
expl = T(50)
end
# Density at altitude.
density = dlb * (tlb / tt)^(1 + Ξ± + Ξ³) * expl
(h >= _ZN1[1]) && return density, tn1, tgn1
# Compute the gravity at `z1`.
g_h = g_lat / (1 + z1 / r_lat)^2
# Compute density below _ZN1[1].
Ξ³ = xm * g_h * zgdif / T(_RGAS)
# Integrate spline temperatures.
expl = Ξ³ * _spline_β«(xs, ys, βΒ²y, x)
if (expl > 50) || (tz <= 0)
expl = T(50)
end
# Density at altitude.
density *= (t1 / tz)^(1 + Ξ±) * exp(-expl)
return density, tn1, tgn1
end
"""
_globe7(nrlmsise00d::Nrlmsise00Structure{T}, p::AbstractVector{T}) where T<:Number -> Nrlmsise00Structure{T}, T
Compute the function `G(L)` with upper thermosphere parameters `p` and the NRLMSISE-00
structure `nrlmsise00`.
!!! note
The variables `apt` and `apdf` inside `nrlmsise00d` can be modified inside this
function.
# Returns
- `Nrlmsise00Structure{T}`: Modified structure `nrlmsise00d`.
- `T`: Result of `G(L)`.
"""
function _globe7(nrlmsise00d::Nrlmsise00Structure{T}, p::AbstractVector{T}) where T<:Number
# == Unpack NRLMSISE00 Structure =======================================================
ap = nrlmsise00d.ap
apdf = nrlmsise00d.apdf
apt = nrlmsise00d.apt
c2tloc = nrlmsise00d.c2tloc
c3tloc = nrlmsise00d.c3tloc
ctloc = nrlmsise00d.ctloc
df = nrlmsise00d.df
dfa = nrlmsise00d.dfa
doy = nrlmsise00d.doy
flags = nrlmsise00d.flags
lst = nrlmsise00d.lst
plg = nrlmsise00d.plg
s2tloc = nrlmsise00d.s2tloc
s3tloc = nrlmsise00d.s3tloc
sec = nrlmsise00d.sec
stloc = nrlmsise00d.stloc
Ξ» = nrlmsise00d.Ξ»
Ο_gd = nrlmsise00d.Ο_gd
# == Initialization of Variables =======================================================
tβ = T(0)
tβ = T(0)
tβ = T(0)
tβ = T(0)
tβ
= T(0)
tβ = T(0)
tβ = T(0)
tβ = T(0)
tβ = T(0)
tββ = T(0)
tββ = T(0)
tββ = T(0)
tββ = T(0)
tββ = T(0)
tloc = lst
cd32 = cos(1 * _DAY_TO_RAD * (doy - p[32]))
cd18 = cos(2 * _DAY_TO_RAD * (doy - p[18]))
cd14 = cos(1 * _DAY_TO_RAD * (doy - p[14]))
cd39 = cos(2 * _DAY_TO_RAD * (doy - p[39]))
# == F10.7 Effect ======================================================================
tβ = p[20] * df *(1 + p[60] * dfa) + p[21] * df^2 + p[22] * dfa + p[30] * dfa^2
f1 = 1 + (p[48] * dfa + p[20] * df + p[21] * df^2) * flags.F10_Mean
f2 = 1 + (p[50] * dfa + p[20] * df + p[21] * df^2) * flags.F10_Mean
# == Time Independent ==================================================================
tβ = p[2] * plg[1, 3] + p[3] * plg[1, 5] + p[23] * plg[1, 7] + p[27] * plg[1, 2] +
p[15] * plg[1, 3] * dfa * flags.F10_Mean
# == Symmetrical Annual ================================================================
tβ = p[19] * cd32
# == Symmetrical Semiannual ============================================================
tβ = (p[16] + p[17] * plg[1, 3]) * cd18
# == Asymmetrical Annual ===============================================================
tβ
= f1 * (p[10] * plg[1, 2] + p[11] * plg[1, 4]) * cd14
# == Asymmetrical Semiannual ===========================================================
tβ = p[38] * plg[1, 2] * cd39
# == Diurnal ===========================================================================
if flags.diurnal
t71 = (p[12] * plg[2, 3]) * cd14 * flags.asym_annual
t72 = (p[13] * plg[2, 3]) * cd14 * flags.asym_annual
tβ = f2 * (
(p[4] * plg[2, 2] + p[5] * plg[2, 4] + p[28] * plg[2, 6] + t71) * ctloc +
(p[7] * plg[2, 2] + p[8] * plg[2, 4] + p[29] * plg[2, 6] + t72) * stloc
)
end
# == Semidiurnal =======================================================================
if flags.semidiurnal
t81 = (p[24] * plg[3, 4] + p[36] * plg[3, 6]) * cd14 * flags.asym_annual
t82 = (p[34] * plg[3, 4] + p[37] * plg[3, 6]) * cd14 * flags.asym_annual
tβ = f2 * (
(p[6] * plg[3, 3] + p[42] * plg[3, 5] + t81) * c2tloc +
(p[9] * plg[3, 3] + p[43] * plg[3, 5] + t82) * s2tloc
)
end
# == Terdiurnal ========================================================================
if flags.terdiurnal
t91 = (p[94] * plg[4, 5] + p[47] * plg[4, 7]) * cd14 * flags.asym_annual
t92 = (p[95] * plg[4, 5] + p[49] * plg[4, 7]) * cd14 * flags.asym_annual
tββ = f2 * ((p[40] * plg[4, 4] + t91) * s3tloc + (p[41] * plg[4, 4] + t92) * c3tloc)
end
# == Magnetic Activity Based on Daily AP ===============================================
if ap isa AbstractVector
if p[52] != 0
exp1 = min(exp(-10800 * abs(p[52]) / (1 + p[139] * (45 - abs(Ο_gd)))), 0.99999)
if p[25] < 1.0e-4
p[25] = 1.0e-4
end
apt = _sgβ(exp1, ap, abs(p[25]), p[26])
aux = cos(_HOUR_TO_RAD * (tloc - p[132]))
tβ = apt * (
(p[51] + p[97] * plg[1, 3] + p[55] * plg[1, 5]) +
(p[126] * plg[1, 2] + p[127] * plg[1, 4] + p[128] * plg[1, 6]) * cd14 * flags.asym_annual +
(p[129] * plg[2, 2] + p[130] * plg[2, 4] + p[131] * plg[2, 6]) * aux * flags.diurnal
)
end
else
apd = ap - 4
p44 = p[44]
p45 = p[45]
if p44 < 0
p44 = 1e-5
end
apdf = apd + (p45 - 1) * (apd + (exp(-p44 * apd) - 1) / p44)
if flags.daily_ap
aux = cos(_HOUR_TO_RAD * (tloc - p[125]))
tβ = apdf * (
(p[33] + p[46] * plg[1, 3] + p[35] * plg[1, 5]) +
(p[101] * plg[1, 2] + p[102] * plg[1, 4] + p[103] * plg[1, 6]) * cd14 * flags.asym_annual +
(p[122] * plg[2, 2] + p[123] * plg[2, 4] + p[124] * plg[2, 6]) * aux * flags.diurnal
)
end
end
if flags.all_ut_long_effects && (Ξ» > - 1000)
# == Longitudinal ==================================================================
if flags.longitudinal
sin_g_long, cos_g_long = sincos(_DEG_TO_RAD * Ξ»)
kβ = p[65] * plg[2, 3] + p[66] * plg[2, 5] + p[67] * plg[2, 7] +
p[104] * plg[2, 2] + p[105] * plg[2, 4] + p[106] * plg[2, 6]
kβ = p[110] * plg[2, 2] + p[111] * plg[2, 4] + p[112] * plg[2, 6]
kβ = p[91] * plg[2, 3] + p[92] * plg[2, 5] + p[93] * plg[2, 7] +
p[107] * plg[2, 2] + p[108] * plg[2, 4] + p[109] * plg[2, 6]
kβ = p[113] * plg[2, 2] + p[114] * plg[2, 4] + p[115] * plg[2, 6]
tββ = (1 + p[81] * dfa * flags.F10_Mean) * (
(kβ + flags.asym_annual * kβ * cd14) * cos_g_long +
(kβ + flags.asym_annual * kβ * cd14) * sin_g_long
)
end
# == UT and Mixed UT, Longitude ====================================================
if flags.ut_mixed_ut_long
kβ = (1 + p[96] * plg[1, 2]) * (1 + p[82] * dfa * flags.F10_Mean)
kβ = 1 + p[120] * plg[1, 2] * flags.asym_annual * cd14
kβ = p[69] * plg[1, 2] + p[70] * plg[1, 4] + p[71] * plg[1, 6]
kβ = 1 + p[138] * dfa * flags.F10_Mean
kβ
= p[77] * plg[3, 4] + p[78] * plg[3, 6] + p[79] * plg[3, 8]
auxβ = cos(_SEC_TO_RAD * (sec - p[72]))
auxβ = cos(_SEC_TO_RAD * (sec - p[80]) + 2 * _DEG_TO_RAD * Ξ»)
tββ = kβ * kβ * kβ * auxβ + flags.longitudinal * kβ * kβ
* auxβ
end
# == UT, Longitude Magnetic Activity ===============================================
if flags.mixed_ap_ut_long
if ap isa AbstractVector
if p[52] != 0
kβ = p[53] * plg[2, 3] + p[99] * plg[2, 5] + p[68] * plg[2, 7]
kβ = p[134] * plg[2, 2] + p[135] * plg[2, 4] + p[136] * plg[2, 6]
kβ = p[56] * plg[1, 2] + p[57] * plg[1, 4] + p[58] * plg[1, 6]
auxβ = cos(_DEG_TO_RAD * (Ξ» - p[98]))
auxβ = cos(_DEG_TO_RAD * (Ξ» - p[137]))
auxβ = cos(_SEC_TO_RAD * (sec - p[59]))
tββ = apt * flags.longitudinal * (1 + p[133] * plg[1, 2]) * kβ * auxβ +
apt * flags.longitudinal * flags.asym_annual * kβ * cd14 * auxβ +
apt * flags.ut_mixed_ut_long * kβ * auxβ
end
else
kβ = p[61] * plg[2, 3] + p[62] * plg[2, 5] + p[63] * plg[2, 7]
kβ = p[116] * plg[2, 2] + p[117] * plg[2, 4] + p[118] * plg[2, 6]
kβ = p[84] * plg[1, 2] + p[85] * plg[1, 4] + p[86] * plg[1, 6]
auxβ = cos(_DEG_TO_RAD * (Ξ» - p[64]))
auxβ = cos(_DEG_TO_RAD * (Ξ» - p[119]))
auxβ = cos(_SEC_TO_RAD * (sec - p[76]))
tββ = apdf * flags.longitudinal * (1 + p[121] * plg[1,2]) * kβ * auxβ +
apdf * flags.longitudinal * flags.asym_annual * kβ * cd14 * auxβ +
apdf * flags.ut_mixed_ut_long * kβ * auxβ
end
end
end
# Update the NRLMSISE-00 structure.
@reset nrlmsise00d.apt = apt
@reset nrlmsise00d.apdf = apdf
# Parameters not used: 82, 89, 99, 139-149.
tinf = p[31] +
flags.F10_Mean * tβ +
flags.time_independent * tβ +
flags.sym_annual * tβ +
flags.sym_semiannual * tβ +
flags.asym_annual * tβ
+
flags.asym_semiannual * tβ +
flags.diurnal * tβ +
flags.semidiurnal * tβ +
flags.daily_ap * tβ +
flags.all_ut_long_effects * tββ +
flags.longitudinal * tββ +
flags.ut_mixed_ut_long * tββ +
flags.mixed_ap_ut_long * tββ +
flags.terdiurnal * tββ
return nrlmsise00d, tinf
end
"""
_glob7s(nrlmsise00d::Nrlmsise00Structure{T}, p::AbstractVector{T}) where T<:Number -> T
Compute the function `G(L)` with lower atmosphere parameters `p` and the NRLMSISE-00
structure `nrlmsise00d`.
"""
function _glob7s(nrlmsise00d::Nrlmsise00Structure{T}, p::AbstractVector{T}) where T<:Number
# == Unpack NRLMSISE00 Structure =======================================================
ap = nrlmsise00d.ap
apdf = nrlmsise00d.apdf
apt = nrlmsise00d.apt
c2tloc = nrlmsise00d.c2tloc
c3tloc = nrlmsise00d.c3tloc
ctloc = nrlmsise00d.ctloc
dfa = nrlmsise00d.dfa
doy = nrlmsise00d.doy
flags = nrlmsise00d.flags
plg = nrlmsise00d.plg
s2tloc = nrlmsise00d.s2tloc
s3tloc = nrlmsise00d.s3tloc
stloc = nrlmsise00d.stloc
Ξ» = nrlmsise00d.Ξ»
# == Initialization of Variables =======================================================
tβ = T(0)
tβ = T(0)
tβ = T(0)
tβ = T(0)
tβ
= T(0)
tβ = T(0)
tβ = T(0)
tβ = T(0)
tβ = T(0)
tββ = T(0)
tββ = T(0)
tββ = T(0)
tββ = T(0)
tββ = T(0)
# Confirm parameter set.
if p[100] == 0
p[100] = T(2)
end
(p[100] != 2) && error("Wrong parameter set for `_glob7s!`.")
cd32 = cos(1 * _DAY_TO_RAD * (doy - p[32]))
cd18 = cos(2 * _DAY_TO_RAD * (doy - p[18]))
cd14 = cos(1 * _DAY_TO_RAD * (doy - p[14]))
cd39 = cos(2 * _DAY_TO_RAD * (doy - p[39]))
# == F10.7 =============================================================================
tβ = p[22] * dfa
# == Time Independent ==================================================================
tβ = p[2] * plg[1, 3] + p[3] * plg[1, 5] + p[23] * plg[1, 7] + p[27] * plg[1, 2] +
p[15] * plg[1, 4] + p[60] * plg[1, 6]
# == Symmetrical Annual ================================================================
tβ = (p[19] + p[48] * plg[1, 3] + p[30] * plg[1, 5]) * cd32
# == Symmetrical Semiannual ============================================================
tβ = (p[16] + p[17] * plg[1, 3] + p[31] * plg[1, 5]) * cd18
# == Asymmetrical Annual ===============================================================
tβ
= (p[10] * plg[1, 2] + p[11] * plg[1, 4] + p[21] * plg[1, 6]) * cd14
# == Asymmetrical Semiannual ===========================================================
tβ = p[38] * plg[1, 2] * cd39
# == Diurnal ===========================================================================
if flags.diurnal
t71 = p[12] * plg[2, 3] * cd14 * flags.asym_annual
t72 = p[13] * plg[2, 3] * cd14 * flags.asym_annual
tβ = (p[4] * plg[2, 2] + p[5] * plg[2, 4] + t71) * ctloc +
(p[7] * plg[2, 2] + p[8] * plg[2, 4] + t72) * stloc
end
# == Semidiurnal =======================================================================
if flags.semidiurnal
t81 = (p[24] * plg[3, 4] + p[36] * plg[3, 6]) * cd14 * flags.asym_annual
t82 = (p[34] * plg[3, 4] + p[37] * plg[3, 6]) * cd14 * flags.asym_annual
tβ = (p[6] * plg[3, 3] + p[42] * plg[3, 5] + t81) * c2tloc +
(p[9] * plg[3, 3] + p[43] * plg[3, 5] + t82) * s2tloc
end
# == Terdiurnal ========================================================================
if flags.terdiurnal
tββ = p[40] * plg[4, 4] * s3tloc + p[41] * plg[4, 4] * c3tloc
end
# == Magnetic Activity =================================================================
if flags.daily_ap
tβ = p[51] * apt + p[97] * plg[1, 3] * apt * flags.time_independent
if ap isa AbstractVector
else
tβ = apdf * (p[33] + p[46] * plg[1, 3] * flags.time_independent)
end
end
# == Longitudinal ======================================================================
if !(!flags.all_ut_long_effects || !flags.longitudinal || (Ξ» <= -1000.0))
sin_g_long, cos_g_long = sincos(_DEG_TO_RAD * Ξ»)
kβ = p[65] * plg[2, 3] + p[66] * plg[2, 5] + p[67] * plg[2, 7] + p[75] * plg[2, 2] +
p[76] * plg[2, 4] + p[77] * plg[2, 6]
kβ = p[91] * plg[2, 3] + p[92] * plg[2, 5] + p[93] * plg[2, 7] + p[78] * plg[2, 2] +
p[79] * plg[2, 4] + p[80] * plg[2, 6]
tββ = (kβ * cos_g_long + kβ * sin_g_long) * (
1 + plg[1,2] * (
p[81] * cos(1 * _DAY_TO_RAD * (doy - p[82])) * flags.asym_annual +
p[86] * cos(2 * _DAY_TO_RAD * (doy - p[87])) * flags.asym_semiannual
) + p[84] * cos(1 * _DAY_TO_RAD * (doy - p[85])) * flags.sym_annual +
p[88] * cos(2 * _DAY_TO_RAD * (doy - p[89])) * flags.sym_semiannual
)
end
tinf = flags.F10_Mean * tβ +
flags.time_independent * tβ +
flags.sym_annual * tβ +
flags.sym_semiannual * tβ +
flags.asym_annual * tβ
+
flags.asym_semiannual * tβ +
flags.diurnal * tβ +
flags.semidiurnal * tβ +
flags.daily_ap * tβ +
flags.all_ut_long_effects * tββ +
flags.longitudinal * tββ +
flags.ut_mixed_ut_long * tββ +
flags.mixed_ap_ut_long * tββ +
flags.terdiurnal * tββ
return tinf
end
"""
_gtd7(nrlmsise00d::Nrlmsise00Structure{T}) where T<:Number -> Nrlmsise00Structure{T}, Nrlmsise00Output{T}
Compute the temperatures and densities using the information inside the structure
`nrlmsise00d` without including the anomalous oxygen in the total density.
# Returns
- `Nrlmsise00Structure{T}`: Modified structure `nrlmsise00d`.
- `Nrlmsise00Output{T}`: Structure with the output information.
"""
function _gtd7(nrlmsise00d::Nrlmsise00Structure{T}) where T<:Number
# == Constants =========================================================================
pdm_1 = _NRLMSISE00_PDM_1
pdm_3 = _NRLMSISE00_PDM_3
pdm_4 = _NRLMSISE00_PDM_4
pdm_5 = _NRLMSISE00_PDM_5
pma_1 = _NRLMSISE00_PMA_1
pma_2 = _NRLMSISE00_PMA_2
pma_3 = _NRLMSISE00_PMA_3
pma_4 = _NRLMSISE00_PMA_4
pma_5 = _NRLMSISE00_PMA_5
pma_6 = _NRLMSISE00_PMA_6
pma_7 = _NRLMSISE00_PMA_7
pma_8 = _NRLMSISE00_PMA_8
pma_10 = _NRLMSISE00_PMA_10
pavgm = _NRLMSISE00_PAVGM
# == Unpack NRLMSISE00 Structure =======================================================
flags = nrlmsise00d.flags
g_lat = nrlmsise00d.g_lat
h = nrlmsise00d.h
r_lat = nrlmsise00d.r_lat
# == Initialization of Variables =======================================================
meso_tn2 = ntuple(_ -> T(0), 4)
meso_tn3 = ntuple(_ -> T(0), 5)
meso_tgn2 = ntuple(_ -> T(0), 2)
meso_tgn3 = ntuple(_ -> T(0), 2)
# == Latitude Variation of Gravity =====================================================
xmm = pdm_3[5]
# == Thermosphere / Mesosphere (above _ZN2[1]) =========================================
if h < _ZN2[begin]
@reset nrlmsise00d.h = T(_ZN2[begin])
end
nrlmsise00d, out_thermo = _gts7(nrlmsise00d)
@reset nrlmsise00d.h = h
# Unpack the values again because `gts7` may have modified `nrlmsise00d`.
meso_tn1_5 = nrlmsise00d.meso_tn1_5
meso_tgn1_2 = nrlmsise00d.meso_tgn1_2
dm28 = nrlmsise00d.dm28
# If we are above `_ZN2[1]`, then we do not need to compute anything else.
h >= _ZN2[begin] && return nrlmsise00d, out_thermo
# Unpack the output values from the thermospheric portion.
total_density = out_thermo.total_density
temperature = out_thermo.temperature
exospheric_temperature = out_thermo.exospheric_temperature
N_number_density = out_thermo.N_number_density
N2_number_density = out_thermo.N2_number_density
O_number_density = out_thermo.O_number_density
aO_number_density = out_thermo.aO_number_density
O2_number_density = out_thermo.O2_number_density
H_number_density = out_thermo.H_number_density
He_number_density = out_thermo.He_number_density
Ar_number_density = out_thermo.Ar_number_density
# Convert the unit to SI.
dm28m = dm28 * T(1e6)
# == Lower Mesosphere / Upper Stratosphere (between `_ZN3[1]` and `_ZN2[1]`) ===========
@reset meso_tgn2[1] = meso_tgn1_2
@reset meso_tn2[1] = meso_tn1_5
@reset meso_tn2[2] = pma_1[1] * pavgm[1] / (1 - flags.all_tn2_var * _glob7s(nrlmsise00d, pma_1))
@reset meso_tn2[3] = pma_2[1] * pavgm[2] / (1 - flags.all_tn2_var * _glob7s(nrlmsise00d, pma_2))
@reset meso_tn2[4] = pma_3[1] * pavgm[3] / (1 - flags.all_tn2_var * flags.all_tn3_var * _glob7s(nrlmsise00d, pma_3))
@reset meso_tn3[1] = meso_tn2[4]
@reset meso_tgn2[2] = pavgm[9] * pma_10[1] * (
1 + flags.all_tn2_var * flags.all_tn3_var * _glob7s(nrlmsise00d, pma_10)
) * meso_tn2[4]^2 / (pma_3[1] * pavgm[3])^2
# == Lower Stratosphere and Troposphere (below `zn3[1]`) ===============================
if h < _ZN3[begin]
@reset meso_tgn3[1] = meso_tgn2[2]
@reset meso_tn3[2] = pma_4[1] * pavgm[4] / (1 - flags.all_tn3_var * _glob7s(nrlmsise00d, pma_4))
@reset meso_tn3[3] = pma_5[1] * pavgm[5] / (1 - flags.all_tn3_var * _glob7s(nrlmsise00d, pma_5))
@reset meso_tn3[4] = pma_6[1] * pavgm[6] / (1 - flags.all_tn3_var * _glob7s(nrlmsise00d, pma_6))
@reset meso_tn3[5] = pma_7[1] * pavgm[7] / (1 - flags.all_tn3_var * _glob7s(nrlmsise00d, pma_7))
@reset meso_tgn3[2] = pma_8[1] * pavgm[8] * (
1 + flags.all_tn3_var * _glob7s(nrlmsise00d, pma_8)
) * meso_tn3[5] * meso_tn3[5] / (pma_7[1] * pavgm[7])^2
end
# == Linear Transition to Full Mixing Below `_ZN2[1]` ==================================
dmc = (h > _ZMIX) ? 1 - (T(_ZN2[begin]) - h) / (T(_ZN2[begin]) - T(_ZMIX)) : T(0)
dz28 = N2_number_density
# == Nβ Density ========================================================================
dmr = N2_number_density / dm28m - 1
N2_number_density = _densm(
h,
dm28m,
xmm,
g_lat,
r_lat,
meso_tn2,
meso_tgn2,
meso_tn3,
meso_tgn3
)
N2_number_density *= 1 + dmr * dmc
# == He Density ========================================================================
dmr = He_number_density / (dz28 * pdm_1[2]) - 1
He_number_density = N2_number_density * pdm_1[2] * (1 + dmr * dmc)
# == O Density =========================================================================
O_number_density = T(0)
aO_number_density = T(0)
# == Oβ Density ========================================================================
dmr = O2_number_density / (dz28 * pdm_4[2]) - 1
O2_number_density = N2_number_density * pdm_4[2] * (1 + dmr * dmc)
# == Ar Density ========================================================================
dmr = Ar_number_density / (dz28 * pdm_5[2]) - 1
Ar_number_density = N2_number_density * pdm_5[2] * (1 + dmr * dmc)
# == H Density =========================================================================
H_number_density = T(0)
# == N Density =========================================================================
N_number_density = T(0)
# == Total Mass Density ================================================================
total_density = 1.66e-24 * (
4 * He_number_density +
16 * O_number_density +
28 * N2_number_density +
32 * O2_number_density +
40 * Ar_number_density +
1 * H_number_density +
14 * N_number_density
)
# Convert the units to SI.
total_density /= 1000
# == Temperature at Selected Altitude ==================================================
temperature = _densm(
h,
T(1),
T(0),
g_lat,
r_lat,
meso_tn2,
meso_tgn2,
meso_tn3,
meso_tgn3
)
# Create output structure and return.
nrlmsise00_out = Nrlmsise00Output{T}(
total_density,
temperature,
exospheric_temperature,
N_number_density,
N2_number_density,
O_number_density,
aO_number_density,
O2_number_density,
H_number_density,
He_number_density,
Ar_number_density
)
return nrlmsise00d, nrlmsise00_out
end
"""
_gtd7d(nrlmsise00d::Nrlmsise00Structure{T}) where T<:Number -> Nrlmsise00Structure{T}, Nrlmsise00Output{T}
Compute the temperatures and densities using the information inside the structure
`nrlmsise00d` including the anomalous oxygen in the total density.
# Returns
- `Nrlmsise00Structure{T}`: Modified structure `nrlmsise00d`.
- `Nrlmsise00Output{T}`: Structure with the output information.
"""
function _gtd7d(nrlmsise00d::Nrlmsise00Structure{T}) where T<:Number
# Call `_gt7d!` to compute the NRLMSISE-00 outputs.
nrlmsise00d, out = _gtd7(nrlmsise00d)
# Update the computation of the total mass density.
total_density = 1.66e-24 * (
4 * out.He_number_density +
16 * out.O_number_density +
28 * out.N2_number_density +
32 * out.O2_number_density +
40 * out.Ar_number_density +
1 * out.H_number_density +
14 * out.N_number_density +
16 * out.aO_number_density
)
# Convert the unit to SI.
total_density /= 1000
# Create the new output and return.
nrlmsise00_out = Nrlmsise00Output{T}(
total_density,
out.temperature,
out.exospheric_temperature,
out.N_number_density,
out.N2_number_density,
out.O_number_density,
out.aO_number_density,
out.O2_number_density,
out.H_number_density,
out.He_number_density,
out.Ar_number_density
)
return nrlmsise00d, nrlmsise00_out
end
"""
_gts7(nrlmsise00d::Nrlmsise00Structure{T}) where T<:Number -> Nrlmsise00Structure{T}, Nrlmsise00Output{T}
Compute the temperatures and densities using the information inside the structure
`nrlmsise00d` and including the anomalous oxygen in the total density for altitudes higher
than 72.5 km (thermospheric portion of NRLMSISE-00).
# Returns
- `Nrlmsise00Structure{T}`: Modified structure `nrlmsise00d`.
- `Nrlmsise00Output{T}`: Structure with the output information.
"""
function _gts7(nrlmsise00d::Nrlmsise00Structure{T}) where T<:Number
# == Constants =========================================================================
pdl_1 = _NRLMSISE00_PDL_1
pdl_2 = _NRLMSISE00_PDL_2
ptm = _NRLMSISE00_PTM
pdm_1 = _NRLMSISE00_PDM_1
pdm_2 = _NRLMSISE00_PDM_2
pdm_3 = _NRLMSISE00_PDM_3
pdm_4 = _NRLMSISE00_PDM_4
pdm_5 = _NRLMSISE00_PDM_5
pdm_6 = _NRLMSISE00_PDM_6
pdm_7 = _NRLMSISE00_PDM_7
pdm_8 = _NRLMSISE00_PDM_8
pt = _NRLMSISE00_PT
ps = _NRLMSISE00_PS
pd_TLB = _NRLMSISE00_PD_TLB
pd_N2 = _NRLMSISE00_PD_N2
ptl_1 = _NRLMSISE00_PTL_1
ptl_2 = _NRLMSISE00_PTL_2
ptl_3 = _NRLMSISE00_PTL_3
ptl_4 = _NRLMSISE00_PTL_4
pma_9 = _NRLMSISE00_PMA_9
pd_He = _NRLMSISE00_PD_HE
pd_O = _NRLMSISE00_PD_O
pd_O2 = _NRLMSISE00_PD_O2
pd_Ar = _NRLMSISE00_PD_AR
pd_H = _NRLMSISE00_PD_H
pd_N = _NRLMSISE00_PD_N
pd_hotO = _NRLMSISE00_PD_HOT_O
# Thermal diffusion coefficients for the species.
Ξ± = (-0.38, 0.0, 0.0, 0.0, 0.17, 0.0, -0.38, 0.0, 0.0)
# Net density computation altitude limits for the species.
altl = (200.0, 300.0, 160.0, 250.0, 240.0, 450.0, 320.0, 450.0)
# == Unpack NRLMSISE00 structure =======================================================
dfa = nrlmsise00d.dfa
dm28 = nrlmsise00d.dm28
doy = nrlmsise00d.doy
flags = nrlmsise00d.flags
g_lat = nrlmsise00d.g_lat
h = nrlmsise00d.h
r_lat = nrlmsise00d.r_lat
Ο_gd = nrlmsise00d.Ο_gd
# == Initialization of Variables =======================================================
temperature = T(0)
meso_tn1 = ntuple(_ -> T(0), 5)
meso_tgn1 = ntuple(_ -> T(0), 2)
# == Tinf variations not important below `za` or `zn1[1]` ==============================
if h > _ZN1[1]
nrlmsise00d, G_L = _globe7(nrlmsise00d, pt)
tinf = ptm[1] * pt[1] * (1 + flags.all_tinf_var * G_L)
else
tinf = ptm[1] * pt[1]
end
exospheric_temperature = tinf
# == Gradient variations not important below `zn1[5]` ==================================
if h > _ZN1[5]
nrlmsise00d, G_L = _globe7(nrlmsise00d, ps)
g0 = ptm[4] * ps[1] * (1 + flags.all_s_var * G_L)
else
g0 = ptm[4] * ps[1]
end
nrlmsise00d, G_L = _globe7(nrlmsise00d, pd_TLB)
tlb = ptm[2] * (1 + flags.all_tlb_var * G_L) * pd_TLB[1]
s = g0 / (tinf - tlb)
# Lower thermosphere temperature variations not significant for density above 300 km.
if h < 300
@reset meso_tn1[2] = ptm[7] * ptl_1[1] / (1 - flags.all_tn1_var * _glob7s(nrlmsise00d, ptl_1))
@reset meso_tn1[3] = ptm[3] * ptl_2[1] / (1 - flags.all_tn1_var * _glob7s(nrlmsise00d, ptl_2))
@reset meso_tn1[4] = ptm[8] * ptl_3[1] / (1 - flags.all_tn1_var * _glob7s(nrlmsise00d, ptl_3))
@reset meso_tn1[5] = ptm[5] * ptl_4[1] / (1 - flags.all_tn1_var * flags.all_tn2_var * _glob7s(nrlmsise00d, ptl_4))
@reset meso_tgn1[2] = ptm[9] * pma_9[1] * (
1 + flags.all_tn1_var * flags.all_tn2_var * _glob7s(nrlmsise00d, pma_9)
) * meso_tn1[5]^2 / (ptm[5] * ptl_4[1])^2
else
@reset meso_tn1[2] = ptm[7] * ptl_1[1]
@reset meso_tn1[3] = ptm[3] * ptl_2[1]
@reset meso_tn1[4] = ptm[8] * ptl_3[1]
@reset meso_tn1[5] = ptm[5] * ptl_4[1]
@reset meso_tgn1[2] = ptm[9] * pma_9[1] * meso_tn1[5]^2 / (ptm[5] * ptl_4[1])^2
end
# N2 variation factor at Zlb.
nrlmsise00d, G_L = _globe7(nrlmsise00d, pd_N2)
g28 = flags.all_nlb_var * G_L
# == Variation of Turbopause Height ====================================================
zhf = pdl_2[25] * (
1 + flags.asym_annual * pdl_1[25] * sin(_DEG_TO_RAD * Ο_gd) * cos(_DAY_TO_RAD * (doy - pt[14]))
)
xmm = pdm_3[5]
# == Nβ Density ========================================================================
# Diffusive density at Zlb.
db28 = pdm_3[1] * exp(g28) * pd_N2[1]
# Diffusive density at desired altitude.
N2_number_density, meso_tn1, meso_tgn1 = _densu(
h,
db28,
tinf,
tlb,
T(28),
Ξ±[3],
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
# Turbopause.
zh28 = pdm_3[3] * zhf
zhm28 = pdm_3[4] * pdl_2[6]
xmd = 28 - xmm
# Mixed density at Zlb.
b28, meso_tn1, meso_tgn1 = _densu(
zh28,
db28,
tinf,
tlb,
xmd,
Ξ±[3] - 1,
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
if flags.departures_from_eq && (h < altl[3])
# Mixed density at desired altitude.
dm28, meso_tn1, meso_tgn1 = _densu(
h,
b28,
tinf,
tlb,
xmm,
Ξ±[3],
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
# Net density at desired altitude.
N2_number_density = _dnet(N2_number_density, dm28, zhm28, xmm, T(28))
end
# == He Density ========================================================================
# Density variation factor at Zlb.
nrlmsise00d, G_L = _globe7(nrlmsise00d, pd_He)
g4 = flags.all_nlb_var * G_L
# Diffusive density at Zlb.
db04 = pdm_1[1] * exp(g4) * pd_He[1]
# Diffusive density at desired altitude.
He_number_density, meso_tn1, meso_tgn1 = _densu(
h,
db04,
tinf,
tlb,
T(4),
Ξ±[1],
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
if flags.departures_from_eq && (h < altl[3])
# Turbopause.
zh04 = pdm_1[3]
# Mixed density at Zlb.
b04, meso_tn1, meso_tgn1 = _densu(
zh04,
db04,
tinf,
tlb,
4 - xmm,
Ξ±[1] - 1,
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
# Mixed density at desired altitude.
dm04, meso_tn1, meso_tgn1 = _densu(
h,
b04,
tinf,
tlb,
xmm,
T(0),
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
zhm04 = zhm28
# Net density at desired altitude.
He_number_density = _dnet(He_number_density, dm04, zhm04, xmm, T(4))
# Correction to specified mixing ration at ground.
rl = log(b28 * pdm_1[2] / b04)
zc04 = pdm_1[5] * pdl_2[1]
hc04 = pdm_1[6] * pdl_2[2]
# Net density corrected at desired altitude.
He_number_density *= _ccor(h, rl, hc04, zc04)
end
# == O Density =========================================================================
# Density variation factor at Zlb.
nrlmsise00d, G_L = _globe7(nrlmsise00d, pd_O)
g16 = flags.all_nlb_var * G_L
# Diffusive density at Zlb.
db16 = pdm_2[1] * exp(g16) * pd_O[1]
# Diffusive density at desired altitude.
O_number_density, meso_tn1, meso_tgn1 = _densu(
h,
db16,
tinf,
tlb,
T(16),
Ξ±[2],
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
if flags.departures_from_eq && (h <= altl[2])
# Turbopause.
zh16 = pdm_2[3]
# Mixed density at Zlb.
b16, meso_tn1, meso_tgn1 = _densu(
zh16,
db16,
tinf,
tlb,
16 - xmm,
Ξ±[2] - 1,
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
# Mixed density at desired altitude.
dm16, meso_tn1, meso_tgn1 = _densu(
h,
b16,
tinf,
tlb,
xmm,
T(0),
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
zhm16 = zhm28
# Net density at desired altitude.
O_number_density = _dnet(O_number_density, dm16, zhm16, xmm, T(16))
rl = pdm_2[2] * pdl_2[17] * (1 + flags.F10_Mean * pdl_1[24] * dfa)
hc16 = pdm_2[6] * pdl_2[4]
zc16 = pdm_2[5] * pdl_2[3]
hc216 = pdm_2[6] * pdl_2[5]
O_number_density *= _ccor2(h, rl, hc16, zc16, hc216)
# Chemistry correction.
hcc16 = pdm_2[8] * pdl_2[14]
zcc16 = pdm_2[7] * pdl_2[13]
rc16 = pdm_2[4] * pdl_2[15]
# Net density corrected at desired altitude.
O_number_density *= _ccor(h, rc16, hcc16, zcc16)
end
# == Oβ Density ========================================================================
# Density variation factor at Zlb.
nrlmsise00d, G_L = _globe7(nrlmsise00d, pd_O2)
g32 = flags.all_nlb_var * G_L
# Diffusive density at Zlb.
db32 = pdm_4[1] * exp(g32) * pd_O2[1]
# Diffusive density at desired altitude.
O2_number_density, meso_tn1, meso_tgn1 = _densu(
h,
db32,
tinf,
tlb,
T(32),
Ξ±[4],
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
if flags.departures_from_eq
if h <= altl[4]
# Turbopause.
zh32 = pdm_4[3]
# Mixed density at Zlb.
b32, meso_tn1, meso_tgn1 = _densu(
zh32,
db32,
tinf,
tlb,
32 - xmm,
Ξ±[4] - 1,
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
# Mixed density at desired altitude.
dm32, meso_tn1, meso_tgn1 = _densu(
h,
b32,
tinf,
tlb,
xmm,
T(0),
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
zhm32 = zhm28
# Net density at desired altitude.
O2_number_density = _dnet(O2_number_density, dm32, zhm32, xmm, T(32))
# Correction to specified mixing ratio at ground.
rl = log(b28 * pdm_4[2] / b32)
hc32 = pdm_4[6] * pdl_2[8]
zc32 = pdm_4[5] * pdl_2[7]
O2_number_density *= _ccor(h, rl, hc32, zc32)
end
# Correction for general departure from diffusive equilibrium above Zlb.
hcc32 = pdm_4[8] * pdl_2[23]
hcc232 = pdm_4[8] * pdl_1[23]
zcc32 = pdm_4[7] * pdl_2[22]
rc32 = pdm_4[4] * pdl_2[24] * (1 + flags.F10_Mean * pdl_1[24] * dfa)
# Net density corrected at desired altitude.
O2_number_density *= _ccor2(h, rc32, hcc32, zcc32, hcc232)
end
# == Ar Density ========================================================================
# Density variation factor at Zlb.
nrlmsise00d, G_L = _globe7(nrlmsise00d, pd_Ar)
g40 = flags.all_nlb_var * G_L
# Diffusive density at Zlb.
db40 = pdm_5[1] * exp(g40) * pd_Ar[1]
# Diffusive density at desired altitude.
Ar_number_density, meso_tn1, meso_tgn1= _densu(
h,
db40,
tinf,
tlb,
T(40),
Ξ±[5],
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
if flags.departures_from_eq && (h <= altl[5])
# Turbopause.
zh40 = pdm_5[3]
# Mixed density at Zlb.
b40, meso_tn1, meso_tgn1 = _densu(
zh40,
db40,
tinf,
tlb,
40 - xmm,
Ξ±[5] - 1,
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
# Mixed density at desired altitude.
dm40, meso_tn1, meso_tgn1 = _densu(
h,
b40,
tinf,
tlb,
xmm,
T(0),
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
zhm40 = zhm28
# Net density at desired altitude.
Ar_number_density = _dnet(Ar_number_density, dm40, zhm40, xmm, T(40))
# Correction to specified mixing ratio at ground.
rl = log(b28 * pdm_5[2] / b40)
hc40 = pdm_5[6] * pdl_2[10]
zc40 = pdm_5[5] * pdl_2[9]
# Net density corrected at desired altitude.
Ar_number_density *= _ccor(h, rl, hc40, zc40)
end
# == H Density =========================================================================
# Density variation factor at Zlb.
nrlmsise00d, G_L = _globe7(nrlmsise00d, pd_H)
g1 = flags.all_nlb_var * G_L
# Diffusive density at Zlb.
db01 = pdm_6[1] * exp(g1) * pd_H[1]
# Diffusive density at desired altitude.
H_number_density, meso_tn1, meso_tgn1 = _densu(
h,
db01,
tinf,
tlb,
T(1),
Ξ±[7],
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
if flags.departures_from_eq && (h <= altl[7])
# Turbopause.
zh01 = pdm_6[3]
# Mixed density at Zlb.
b01, meso_tn1, meso_tgn1 = _densu(
zh01,
db01,
tinf,
tlb,
1 - xmm,
Ξ±[7] - 1,
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
# Mixed density at desired altitude.
dm01, meso_tn1, meso_tgn1 = _densu(
h,
b01,
tinf,
tlb,
xmm,
T(0),
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
zhm01 = zhm28
# Net density at desired altitude.
H_number_density = _dnet(H_number_density, dm01, zhm01, xmm, T(1))
# Correction to specified mixing ratio at ground.
rl = log(b28 * pdm_6[2] * abs(pdl_2[18]) / b01)
hc01 = pdm_6[6] * pdl_2[12]
zc01 = pdm_6[5] * pdl_2[11]
H_number_density *= _ccor(h, rl, hc01, zc01)
# Chemistry correction.
hcc01 = pdm_6[8] * pdl_2[20]
zcc01 = pdm_6[7] * pdl_2[19]
rc01 = pdm_6[4] * pdl_2[21]
# Net density corrected at desired altitude.
H_number_density *= _ccor(h, rc01, hcc01, zcc01)
end
# == N Density =========================================================================
# Density variation factor at Zlb.
nrlmsise00d, G_L = _globe7(nrlmsise00d, pd_N)
g14 = flags.all_nlb_var * G_L
# Diffusive density at Zlb.
db14 = pdm_7[1] * exp(g14) * pd_N[1]
# Diffusive density at desired altitude.
N_number_density, meso_tn1, meso_tgn1 = _densu(
h,
db14,
tinf,
tlb,
T(14),
Ξ±[8],
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
if flags.departures_from_eq && (h <= altl[8])
# Turbopause.
zh14 = pdm_7[3]
# Mixed density at Zlb.
b14, meso_tn1, meso_tgn1 = _densu(
zh14,
db14,
tinf,
tlb,
14 - xmm,
Ξ±[8] - 1,
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
# Mixed density at desired altitude.
dm14, meso_tn1, meso_tgn1 = _densu(
h,
b14,
tinf,
tlb,
xmm,
T(0),
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
zhm14 = zhm28
# Net density at desired altitude.
N_number_density = _dnet(N_number_density, dm14, zhm14, xmm, T(14))
# Correction to specified mixing ratio at ground.
rl = log(b28 * pdm_7[2] * abs(pdl_1[3]) / b14)
hc14 = pdm_7[6] * pdl_1[2]
zc14 = pdm_7[5] * pdl_1[1]
N_number_density *= _ccor(h, rl, hc14, zc14)
# Chemistry correction.
hcc14 = pdm_7[8] * pdl_1[5]
zcc14 = pdm_7[7] * pdl_1[4]
rc14 = pdm_7[4] * pdl_1[6]
# Net density corrected at desired altitude.
N_number_density *= _ccor(h, rc14, hcc14, zcc14)
end
# == Anomalous O Density ===============================================================
nrlmsise00d, G_L = _globe7(nrlmsise00d, pd_hotO)
g16h = flags.all_nlb_var * G_L
db16h = pdm_8[1] * exp(g16h) * pd_hotO[1]
tho = pdm_8[10] * pdl_1[7]
aO_number_density, meso_tn1, meso_tgn1 = _densu(
h,
db16h,
tho,
tho,
T(16),
Ξ±[9],
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
zsht = pdm_8[6]
zmho = pdm_8[5]
zsho = _scale_height(zmho, T(16), tho, g_lat, r_lat)
aO_number_density *= exp(-zsht / zsho * (exp(-(h - zmho) / zsht) - 1))
# == Total Mass Density ================================================================
total_density = 1.66e-24 * (
4 * He_number_density +
16 * O_number_density +
28 * N2_number_density +
32 * O2_number_density +
40 * Ar_number_density +
1 * H_number_density +
14 * N_number_density
)
# == Temperature at Selected Altitude ==================================================
temperature, meso_tn1, meso_tgn1 = _densu(
abs(h),
T(1),
tinf,
tlb,
T(0),
T(0),
ptm[6],
s,
g_lat,
r_lat,
meso_tn1,
meso_tgn1
)
# == Output ============================================================================
# Convert the result to SI.
total_density *= T(1e3)
N_number_density *= T(1e6)
N2_number_density *= T(1e6)
O_number_density *= T(1e6)
aO_number_density *= T(1e6)
O2_number_density *= T(1e6)
H_number_density *= T(1e6)
He_number_density *= T(1e6)
Ar_number_density *= T(1e6)
# Repack variables that were modified.
@reset nrlmsise00d.meso_tn1_5 = meso_tn1[5]
@reset nrlmsise00d.meso_tgn1_2 = meso_tgn1[2]
@reset nrlmsise00d.dm28 = dm28
# Create output structure and return.
nrlmsise00_out = Nrlmsise00Output{T}(
total_density,
temperature,
exospheric_temperature,
N_number_density,
N2_number_density,
O_number_density,
aO_number_density,
O2_number_density,
H_number_density,
He_number_density,
Ar_number_density
)
return nrlmsise00d, nrlmsise00_out
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 2492 | ## Description #############################################################################
#
# Function to show the results of the NRLMSISE-00 atmospheric model.
#
############################################################################################
function show(io::IO, out::Nrlmsise00Output)
# Check for color support in the `io`.
color = get(io, :color, false)
b = color ? _B : ""
d = color ? _D : ""
print(io, "$(b)NRLMSISE-00 output$(d) (Ο = ", @sprintf("%g", out.total_density), " kg / mΒ³)")
return nothing
end
function show(io::IO, mime::MIME"text/plain", out::Nrlmsise00Output)
# Check for color support in the `io`.
color = get(io, :color, false)
b = color ? _B : ""
d = color ? _D : ""
str_total_density = @sprintf("%15g", out.total_density)
str_temperature = @sprintf("%15.2f", out.temperature)
str_exospheric_temp = @sprintf("%15.2f", out.exospheric_temperature)
str_N_number_den = @sprintf("%15g", out.N_number_density)
str_Nβ_number_den = @sprintf("%15g", out.N2_number_density)
str_O_number_den = @sprintf("%15g", out.O_number_density)
str_aO_number_den = @sprintf("%15g", out.aO_number_density)
str_Oβ_number_den = @sprintf("%15g", out.O2_number_density)
str_H_number_den = @sprintf("%15g", out.H_number_density)
str_He_number_den = @sprintf("%15g", out.He_number_density)
str_Ar_number_den = @sprintf("%15g", out.Ar_number_density)
println(io, "NRLMSISE-00 Atmospheric Model Result:")
println(io, "$(b) Total density :$(d)", str_total_density, " kg / mΒ³")
println(io, "$(b) Temperature :$(d)", str_temperature, " K")
println(io, "$(b) Exospheric Temp. :$(d)", str_exospheric_temp, " K")
println(io, "$(b) N number density :$(d)", str_N_number_den, " 1 / mΒ³")
println(io, "$(b) Nβ number density :$(d)", str_Nβ_number_den, " 1 / mΒ³")
println(io, "$(b) O number density :$(d)", str_O_number_den, " 1 / mΒ³")
println(io, "$(b) Anomalous O num. den. :$(d)", str_aO_number_den, " 1 / mΒ³")
println(io, "$(b) Oβ number density :$(d)", str_Oβ_number_den, " 1 / mΒ³")
println(io, "$(b) Ar number density :$(d)", str_Ar_number_den, " 1 / mΒ³")
println(io, "$(b) He number density :$(d)", str_He_number_den, " 1 / mΒ³")
print(io, "$(b) H number density :$(d)", str_H_number_den, " 1 / mΒ³")
return nothing
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 4860 | ## Description #############################################################################
#
# Types related to the NRLMSISE-00 atmospheric model.
#
############################################################################################
export Nrlmsise00Flags, Nrlmsise00Output
"""
struct Nrlmsise00Flags
Flags to configure NRLMSISE-00.
# Fields
- `F10_Mean::Bool`: F10.7 effect on mean.
- `time_independent::Bool`: Independent of time.
- `sym_annual::Bool`: Symmetrical annual.
- `sym_semiannual::Bool`: Symmetrical semiannual.
- `asym_annual::Bool`: Asymmetrical annual.
- `asyn_semiannual::Bool`: Asymmetrical semiannual.
- `diurnal::Bool`: Diurnal.
- `semidiurnal::Bool`: Semidiurnal.
- `daily_ap::Bool`: Daily AP.
- `all_ut_long_effects::Bool`: All UT/long effects.
- `longitudinal::Bool`: Longitudinal.
- `ut_mixed_ut_long::Bool`: UT and mixed UT/long.
- `mixed_ap_ut_long::Bool`: Mixed AP/UT/long.
- `terdiurnal::Bool`: Terdiurnal.
- `departures_from_eq::Bool`: Departures from diffusive equilibrium.
- `all_tinf_var::Bool`: All TINF variations.
- `all_tlb_var::Bool`: All TLB variations.
- `all_tn1_var::Bool`: All TN1 variations.
- `all_s_var::Bool`: All S variations.
- `all_tn2_var::Bool`: All TN2 variations.
- `all_nlb_var::Bool`: All NLB variations.
- `all_tn3_var::Bool`: All TN3 variations.
- `turbo_scale_height::Bool`: Turbo scale height variations.
"""
Base.@kwdef struct Nrlmsise00Flags
F10_Mean::Bool = true
time_independent::Bool = true
sym_annual::Bool = true
sym_semiannual::Bool = true
asym_annual::Bool = true
asym_semiannual::Bool = true
diurnal::Bool = true
semidiurnal::Bool = true
daily_ap::Bool = true
all_ut_long_effects::Bool = true
longitudinal::Bool = true
ut_mixed_ut_long::Bool = true
mixed_ap_ut_long::Bool = true
terdiurnal::Bool = true
departures_from_eq::Bool = true
all_tinf_var::Bool = true
all_tlb_var::Bool = true
all_tn1_var::Bool = true
all_s_var::Bool = true
all_tn2_var::Bool = true
all_nlb_var::Bool = true
all_tn3_var::Bool = true
turbo_scale_height::Bool = true
end
"""
struct Nrlmsise00Structure{T<:Number, T_AP<:Union{Number, AbstractVector}}
Structure with the configuration parameters for NRLMSISE-00 model. `T` is the
floating-number type and `T_AP` is the type of the AP information, which can be a `Number`
or `AbstractVector`.
"""
struct Nrlmsise00Structure{T<:Number, T_AP<:Union{Number, AbstractVector}}
# == Inputs ============================================================================
year::Int
doy::Int
sec::T
h::T
Ο_gd::T
Ξ»::T
lst::T
F10β::T
F10::T
ap::T_AP
flags::Nrlmsise00Flags
# == Auxiliary Variables to Improve Code Performance ===================================
r_lat::T
g_lat::T
df::T
dfa::T
plg::Adjoint{T, Matrix{T}}
ctloc::T
stloc::T
c2tloc::T
s2tloc::T
c3tloc::T
s3tloc::T
# In the original source code, it has 4 components, but only 1 is used.
apt::T
apdf::T
dm28::T
# The original code declared all the `meso_*` vectors as global variables. However,
# only two values really need to be shared between the functions `gts7` and `gtd7`.
meso_tn1_5::T
meso_tgn1_2::T
end
"""
struct Nrlmsise00Output{T<:Number}
Output structure for NRLMSISE00 model.
# Fields
- `total_density::T`: Total mass density [kg / mΒ³].
- `temperature`: Temperature at the selected altitude [K].
- `exospheric_temperature`: Exospheric temperature [K].
- `N_number_density`: Nitrogen number density [1 / mΒ³].
- `N2_number_density`: Nβ number density [1 / mΒ³].
- `O_number_density`: Oxygen number density [1 / mΒ³].
- `aO_number_density`: Anomalous Oxygen number density [1 / mΒ³].
- `O2_number_density`: Oβ number density [1 / mΒ³].
- `H_number_density`: Hydrogen number density [1 / mΒ³].
- `He_number_density`: Helium number density [1 / mΒ³].
- `Ar_number_density`: Argon number density [1 / mΒ³].
# Remarks
Anomalous oxygen is defined as hot atomic oxygen or ionized oxygen that can become
appreciable at high altitudes (`> 500 km`) for some ranges of inputs, thereby affection drag
on satellites and debris. We group these species under the term **Anomalous Oxygen**, since
their individual variations are not presently separable with the drag data used to define
this model component.
"""
struct Nrlmsise00Output{T<:Number}
total_density::T
temperature::T
exospheric_temperature::T
N_number_density::T
N2_number_density::T
O_number_density::T
aO_number_density::T
O2_number_density::T
H_number_density::T
He_number_density::T
Ar_number_density::T
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 2653 | ## Description #############################################################################
#
# Tests related to the exponential atmospheric model.
#
## References ##############################################################################
#
# [1] Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications. 4th ed.
# Microcosm Press, Hawthorn, CA, USA.
#
############################################################################################
# == Functions: exponential ================================================================
############################################################################################
# Test Results #
############################################################################################
#
# == Scenario 01 ===========================================================================
#
# Example 8-4 [1, p. 567]
#
# Using the exponential atmospheric model, one gets:
#
# Ο(747.2119 km) = 2.1219854 β
10β»β΄ kg / mΒ³
#
# == Scenario 02 ===========================================================================
#
# By definition, one gets `Ο(hβ) = Οβ(hβ)` for all tabulated values.
#
# == Scenario 03 ===========================================================================
#
# Inside every interval, the atmospheric density must be monotonically
# decreasing.
#
############################################################################################
@testset "Default Tests" begin
# == Scenario 01 =======================================================================
@test AtmosphericModels.exponential(747211.9) β 2.1219854e-14 rtol = 1e-8
# == Scenario 02 =======================================================================
for i in 1:length(AtmosphericModels._EXPONENTIAL_ATMOSPHERE_Hβ)
h = 1000 * AtmosphericModels._EXPONENTIAL_ATMOSPHERE_Hβ[i]
@test AtmosphericModels.exponential(h) == AtmosphericModels._EXPONENTIAL_ATMOSPHERE_Οβ[i]
end
# == Scenario 03 =======================================================================
for i in 2:length(AtmosphericModels._EXPONENTIAL_ATMOSPHERE_Hβ)
hβi = 1000 * AtmosphericModels._EXPONENTIAL_ATMOSPHERE_Hβ[i - 1]
hβf = 1000 * AtmosphericModels._EXPONENTIAL_ATMOSPHERE_Hβ[i]
Ξ = 100
Ξhβ = (hβf - hβi)/Ξ
Οk = AtmosphericModels.exponential(hβi)
for k in 2:Ξ
Οkββ = Οk
h = hβi + Ξhβ * (k - 1)
Οk = AtmosphericModels.exponential(h)
@test Οk < Οkββ
end
end
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 8217 | ## Description #############################################################################
#
# Tests related to the Jacchia-Robert 1971 model.
#
############################################################################################
# == Functions: jr1971 =====================================================================
############################################################################################
# Test Results #
############################################################################################
#
# == Scenario 01 ===========================================================================
#
# Values obtained from GMAT R2018a using the following inputs:
#
# Date: 2017-01-01 00:00:00 UTC
# Latitude: 45 deg
# Longitude: 0 deg
# F10.7: 100
# F10.7β: 100
# Kp: 4
#
# Result:
#
# | Altitude [km] | Density [g/cmΒ³] |
# |----------------|------------------|
# | 92 | 3.87506e-09 |
# | 100 | 3.96585e-09 |
# | 100.1 | 6.8354e-10 |
# | 110.5 | 1.2124e-10 |
# | 125 | 1.60849e-11 |
# | 125.1 | 1.58997e-11 |
# | 300 | 1.30609e-14 |
# | 700 | 1.34785e-17 |
# | 1500 | 4.00464e-19 |
#
# == Scenario 02 ===========================================================================
#
# Values obtained from GMAT R2018a using the following inputs:
#
# Date: 2017-01-01 00:00:00 UTC
# Latitude: 45 deg
# Longitude: 0 deg
# F10.7: 100
# F10.7β: 100
# Kp: 1
#
# Result:
#
# | Altitude [km] | Density [g/cmΒ³] |
# |----------------|------------------|
# | 92 | 3.56187e-09 |
# | 100 | 3.65299e-09 |
# | 100.1 | 6.28941e-10 |
# | 110.5 | 1.11456e-10 |
# | 125 | 1.46126e-11 |
# | 125.1 | 1.44428e-11 |
# | 300 | 9.08858e-15 |
# | 700 | 8.51674e-18 |
# | 1500 | 2.86915e-19 |
#
# == Scenario 03 ===========================================================================
#
# Values obtained from GMAT R2018a using the following inputs:
#
# Date: 2017-01-01 00:00:00 UTC
# Latitude: 45 deg
# Longitude: 0 deg
# F10.7: 100
# F10.7β: 100
# Kp: 9
#
# Result:
#
# | Altitude [km] | Density [g/cmΒ³] |
# |----------------|------------------|
# | 92 | 5.55597e-09 |
# | 100 | 5.63386e-09 |
# | 100.1 | 9.75634e-10 |
# | 110.5 | 1.73699e-10 |
# | 125 | 2.41828e-11 |
# | 125.1 | 2.39097e-11 |
# | 300 | 3.52129e-14 |
# | 700 | 1.28622e-16 |
# | 1500 | 1.97775e-18 |
#
############################################################################################
@testset "Providing All Space Indices" begin
# Common inputs to all scenarios.
jd = date_to_jd(2017,1,1,0,0,0)
instant = julian2datetime(jd)
Ο_gd = 45 |> deg2rad
Ξ» = 0.0
F10 = 100.0
F10β = 100.0
h = [92, 100, 100.1, 110.5, 125, 125.1, 300, 700, 1500] * 1000
# == Scenario 01 =======================================================================
Kp = 4
# Results in [kg/mΒ³].
results = [
3.87506e-09
3.96585e-09
6.83540e-10
1.21240e-10
1.60849e-11
1.58997e-11
1.30609e-14
1.34785e-17
4.00464e-19
] * 1000
for i in 1:length(h)
ret = AtmosphericModels.jr1971(instant, Ο_gd, Ξ», h[i - 1 + begin], F10, F10β, Kp)
@test ret.total_density β results[i - 1 + begin] rtol = 5e-4
end
# == Scenario 02 =======================================================================
Kp = 1
# Results in [kg/mΒ³].
results = [
3.56187e-09
3.65299e-09
6.28941e-10
1.11456e-10
1.46126e-11
1.44428e-11
9.08858e-15
8.51674e-18
2.86915e-19
] * 1000
for i in 1:length(h)
ret = AtmosphericModels.jr1971(instant, Ο_gd, Ξ», h[i - 1 + begin], F10, F10β, Kp)
@test ret.total_density β results[i - 1 + begin] rtol = 5e-4
end
# == Scenario 03 =======================================================================
Kp = 9
# Results in [kg/mΒ³].
results = [
5.55597e-09
5.63386e-09
9.75634e-10
1.73699e-10
2.41828e-11
2.39097e-11
3.52129e-14
1.28622e-16
1.97775e-18
] * 1000
for i in 1:length(h)
ret = AtmosphericModels.jr1971(instant, Ο_gd, Ξ», h[i - 1 + begin], F10, F10β, Kp)
@test ret.total_density β results[i - 1 + begin] rtol = 5e-4
end
end
############################################################################################
# Test Results #
############################################################################################
#
# In this case, we already tested the function `AtmosphericModel.jr1971`. Hence, we will
# select a day and run this function with and without passing the space indices. The result
# must be the same.
#
# We have the following space indices for the instant 2023-01-01T10:00:00.000:
#
# F10 = 152.6 sfu
# F10β = 159.12345679012347 sfu
# Kp = 2.667
#
############################################################################################
@testset "Fetching All Space Indices" begin
SpaceIndices.init()
# Expected result.
instant = DateTime("2023-01-01T10:00:00")
h = collect(90:50:1000) .* 1000
Ο_gd = -23 |> deg2rad
Ξ» = -45 |> deg2rad
F10 = 152.6
F10β = 159.12345679012347
Kp = 2.667
expected = AtmosphericModels.jr1971.(instant, Ο_gd, Ξ», h, F10, F10β, Kp)
for k in 1:length(h)
result = AtmosphericModels.jr1971(instant, Ο_gd, Ξ», h[k - 1 + begin])
@test result.total_density β expected[k - 1 + begin].total_density
@test result.temperature β expected[k - 1 + begin].temperature
@test result.exospheric_temperature β expected[k - 1 + begin].exospheric_temperature
@test result.N2_number_density β expected[k - 1 + begin].N2_number_density
@test result.O2_number_density β expected[k - 1 + begin].O2_number_density
@test result.O_number_density β expected[k - 1 + begin].O_number_density
@test result.Ar_number_density β expected[k - 1 + begin].Ar_number_density
@test result.He_number_density β expected[k - 1 + begin].He_number_density
@test result.H_number_density β expected[k - 1 + begin].H_number_density
end
end
@testset "Show" begin
result = AtmosphericModels.jr1971(
DateTime("2023-01-01T10:00:00"),
0,
0,
500e3,
100,
100,
3
)
expected = "JR1971 output (Ο = 5.51927e-14 kg / mΒ³)"
str = sprint(show, result)
expected = """
Jacchia-Roberts 1971 Atmospheric Model Result:
Total density : 5.15927e-14 kg / mΒ³
Temperature : 679.39 K
Exospheric Temp. : 679.44 K
Nβ number density : 1.47999e+09 1 / mΒ³
Oβ number density : 1.50981e+07 1 / mΒ³
O number density : 1.58322e+12 1 / mΒ³
Ar number density : 2149.38 1 / mΒ³
He number density : 1.42329e+12 1 / mΒ³
H number density : 0 1 / mΒ³"""
str = sprint(show, MIME("text/plain"), result)
@test str == expected
end
@testset "Errors" begin
@test_throws ArgumentError AtmosphericModels.jr1971(now(), 0, 0, 89.9e3, 100, 100, 3)
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 36029 | ## Description #############################################################################
#
# Tests related to the NRLMSISE-00 Atmospheric Model.
#
## References ##############################################################################
#
# [1] https://ccmc.gsfc.nasa.gov/pub/modelweb/atmospheric/msis/nrlmsise00/nrlmsise00_output.txt
# [2] https://ccmc.gsfc.nasa.gov/modelweb/models/nrlmsise00.php
#
############################################################################################
# == Function: nrlmsise00 ==================================================================
############################################################################################
# Test Results #
############################################################################################
#
# == Scenario 01 ===========================================================================
#
# Simulation using only the daily AP.
#
# Data obtained from the online version of NRLMSISE-00 [2]:
#
# Input parameters
#
# year= 1986, month= 6, day= 19, hour=21.50,
# Time_type = Universal
# Coordinate_type = Geographic
# latitude= -16.00, longitude= 312.00, height= 100.00
# Prof. parameters: start= 0.00 stop= 1000.00 step= 100.00
#
# Optional parametes: F10.7(daily) =121.; F10.7(3-month avg) =80.; ap(daily) = 7.
#
# Selected parameters are:
# 1 Height, km
# 2 O, cm-3
# 3 N2, cm-3
# 4 O2, cm-3
# 5 Mass_density, g/cm-3
# 6 Temperature_neutral, K
# 7 Temperature_exospheric, K
# 8 He, cm-3
# 9 Ar, cm-3
# 10 H, cm-3
# 11 N, cm-3
# 12 Anomalous_Oxygen, cm-3
#
# 1 2 3 4 5 6 7 8 9 10 11 12
# 0.0 0.000E+00 1.918E+19 5.145E+18 1.180E-03 297.7 1027 1.287E+14 2.294E+17 0.000E+00 0.000E+00 0.000E+00
# 100.0 4.244E+11 9.498E+12 2.240E+12 5.783E-10 165.9 1027 1.061E+08 9.883E+10 2.209E+07 3.670E+05 0.000E+00
# 200.0 2.636E+09 2.248E+09 1.590E+08 1.838E-13 829.3 909 5.491E+06 1.829E+06 2.365E+05 3.125E+07 1.802E-09
# 300.0 3.321E+08 6.393E+07 2.881E+06 1.212E-14 900.6 909 3.173E+06 1.156E+04 1.717E+05 6.708E+06 4.938E+00
# 400.0 5.088E+07 2.414E+06 6.838E+04 1.510E-15 907.7 909 1.979E+06 1.074E+02 1.518E+05 1.274E+06 1.237E+03
# 500.0 8.340E+06 1.020E+05 1.839E+03 2.410E-16 908.5 909 1.259E+06 1.170E+00 1.355E+05 2.608E+05 4.047E+03
# 600.0 1.442E+06 4.729E+03 5.500E+01 4.543E-17 908.6 909 8.119E+05 1.455E-02 1.214E+05 5.617E+04 4.167E+03
# 700.0 2.622E+05 2.394E+02 1.817E+00 1.097E-17 908.6 909 5.301E+05 2.050E-04 1.092E+05 1.264E+04 3.173E+03
# 800.0 4.999E+04 1.317E+01 6.608E-02 3.887E-18 908.6 909 3.503E+05 3.254E-06 9.843E+04 2.964E+03 2.246E+03
# 900.0 9.980E+03 7.852E-01 2.633E-03 1.984E-18 908.6 909 2.342E+05 5.794E-08 8.900E+04 7.237E+02 1.571E+03
# 1000.0 2.082E+03 5.055E-02 1.146E-04 1.244E-18 908.6 909 1.582E+05 1.151E-09 8.069E+04 1.836E+02 1.103E+03
#
# == Scenario 02 ===========================================================================
#
# Simulation using the AP vector.
#
# Data obtained from the online version of NRLMSISE-00 [2]:
#
# Input parameters
# year= 2016, month= 6, day= 1, hour=11.00,
# Time_type = Universal
# Coordinate_type = Geographic
# latitude= -23.00, longitude= 315.00, height= 100.00
# Prof. parameters: start= 0.00 stop= 1000.00 step= 100.00
#
# Optional parametes: F10.7(daily) =not specified; F10.7(3-month avg) =not specified; ap(daily) = not specified
#
# Selected parameters are:
# 1 Height, km
# 2 O, cm-3
# 3 N2, cm-3
# 4 O2, cm-3
# 5 Mass_density, g/cm-3
# 6 Temperature_neutral, K
# 7 Temperature_exospheric, K
# 8 He, cm-3
# 9 Ar, cm-3
# 10 H, cm-3
# 11 N, cm-3
# 12 Anomalous_Oxygen, cm-3
# 13 F10_7_daily
# 14 F10_7_3_month_avg
# 15 ap_daily
# 16 ap_00_03_hr_prior
# 17 ap_03_06_hr_prior
# 18 ap_06_09_hr_prior
# 19 ap_09_12_hr_prior
# 20 ap_12_33_hr_prior
# 21 ap_33_59_hr_prior
#
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# 0.0 0.000E+00 1.919E+19 5.149E+18 1.181E-03 296.0 1027 1.288E+14 2.296E+17 0.000E+00 0.000E+00 0.000E+00 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
# 100.0 6.009E+11 9.392E+12 2.213E+12 5.764E-10 165.2 1027 1.339E+08 9.580E+10 2.654E+07 2.737E+05 0.000E+00 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
# 200.0 3.882E+09 1.978E+09 1.341E+08 2.028E-13 687.5 706 2.048E+07 9.719E+05 5.172E+05 1.632E+07 1.399E-09 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
# 300.0 3.140E+08 2.481E+07 9.340E+05 9.666E-15 705.5 706 1.082E+07 1.879E+03 3.860E+05 2.205E+06 3.876E+00 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
# 400.0 2.855E+07 3.737E+05 7.743E+03 8.221E-16 706.0 706 5.938E+06 4.688E+00 3.317E+05 2.633E+05 9.738E+02 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
# 500.0 2.787E+06 6.372E+03 7.382E+01 9.764E-17 706.0 706 3.319E+06 1.397E-02 2.868E+05 3.424E+04 3.186E+03 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
# 600.0 2.910E+05 1.222E+02 8.047E-01 2.079E-17 706.0 706 1.887E+06 4.919E-05 2.490E+05 4.742E+03 3.281E+03 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
# 700.0 3.240E+04 2.622E+00 9.973E-03 8.474E-18 706.0 706 1.090E+06 2.034E-07 2.171E+05 6.946E+02 2.498E+03 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
# 800.0 3.835E+03 6.264E-02 1.398E-04 4.665E-18 706.0 706 6.393E+05 9.809E-10 1.900E+05 1.074E+02 1.768E+03 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
# 900.0 4.816E+02 1.659E-03 2.204E-06 2.817E-18 706.0 706 3.806E+05 5.481E-12 1.669E+05 1.747E+01 1.236E+03 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
# 1000.0 6.400E+01 4.853E-05 3.891E-08 1.772E-18 706.0 706 2.298E+05 3.528E-14 1.471E+05 2.988E+00 8.675E+02 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
#
############################################################################################
@testset "Providing All Space Indices" begin
# == Scenario 01 =======================================================================
# Test outputs.
expected = [
0.0 0.000E+00 1.918E+19 5.145E+18 1.180E-03 297.7 1027 1.287E+14 2.294E+17 0.000E+00 0.000E+00 0.000E+00
100.0 4.244E+11 9.498E+12 2.240E+12 5.783E-10 165.9 1027 1.061E+08 9.883E+10 2.209E+07 3.670E+05 0.000E+00
200.0 2.636E+09 2.248E+09 1.590E+08 1.838E-13 829.3 909 5.491E+06 1.829E+06 2.365E+05 3.125E+07 1.802E-09
300.0 3.321E+08 6.393E+07 2.881E+06 1.212E-14 900.6 909 3.173E+06 1.156E+04 1.717E+05 6.708E+06 4.938E+00
400.0 5.088E+07 2.414E+06 6.838E+04 1.510E-15 907.7 909 1.979E+06 1.074E+02 1.518E+05 1.274E+06 1.237E+03
500.0 8.340E+06 1.020E+05 1.839E+03 2.410E-16 908.5 909 1.259E+06 1.170E+00 1.355E+05 2.608E+05 4.047E+03
600.0 1.442E+06 4.729E+03 5.500E+01 4.543E-17 908.6 909 8.119E+05 1.455E-02 1.214E+05 5.617E+04 4.167E+03
700.0 2.622E+05 2.394E+02 1.817E+00 1.097E-17 908.6 909 5.301E+05 2.050E-04 1.092E+05 1.264E+04 3.173E+03
800.0 4.999E+04 1.317E+01 6.608E-02 3.887E-18 908.6 909 3.503E+05 3.254E-06 9.843E+04 2.964E+03 2.246E+03
900.0 9.980E+03 7.852E-01 2.633E-03 1.984E-18 908.6 909 2.342E+05 5.794E-08 8.900E+04 7.237E+02 1.571E+03
1000.0 2.082E+03 5.055E-02 1.146E-04 1.244E-18 908.6 909 1.582E+05 1.151E-09 8.069E+04 1.836E+02 1.103E+03
]
# Constant input parameters.
year = 1986
month = 6
day = 19
hour = 21
minute = 30
second = 00
Ο_gd = -16 * Ο / 180
Ξ» = 312 * Ο / 180
F10 = 121
F10β = 80
ap = 7
instant = date_to_jd(year, month, day, hour, minute, second) |> julian2datetime
for i in axes(expected, 1)
# Run the NRLMSISE-00 model wih the input parameters.
out = AtmosphericModels.nrlmsise00(
instant,
expected[i, 1] * 1000,
Ο_gd,
Ξ»,
F10β,
F10,
ap;
include_anomalous_oxygen = false
)
@test out.total_density β (expected[i, 5] * 1e3) rtol = 1e-3
@test out.temperature β (expected[i, 6] ) rtol = 1e-1 atol = 1e-9
@test out.exospheric_temperature β (expected[i, 7] ) rtol = 1e-1 atol = 1e-9
@test out.O_number_density β (expected[i, 2] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.N2_number_density β (expected[i, 3] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.O2_number_density β (expected[i, 4] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.He_number_density β (expected[i, 8] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.Ar_number_density β (expected[i, 9] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.H_number_density β (expected[i, 10] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.N_number_density β (expected[i, 11] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.aO_number_density β (expected[i, 12] * 1e6) rtol = 1e-3 atol = 1e-9
# Test the version that calls `gtd7d` instead of `gtd7`.
out = AtmosphericModels.nrlmsise00(
instant,
expected[i, 1] * 1000,
Ο_gd,
Ξ»,
F10β,
F10,
ap;
include_anomalous_oxygen = true
)
@test out.temperature β (expected[i, 6] ) rtol = 1e-1 atol = 1e-9
@test out.exospheric_temperature β (expected[i, 7] ) rtol = 1e-1 atol = 1e-9
@test out.O_number_density β (expected[i, 2] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.N2_number_density β (expected[i, 3] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.O2_number_density β (expected[i, 4] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.He_number_density β (expected[i, 8] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.Ar_number_density β (expected[i, 9] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.H_number_density β (expected[i, 10] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.N_number_density β (expected[i, 11] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.aO_number_density β (expected[i, 12] * 1e6) rtol = 1e-3 atol = 1e-9
expected_total_density = expected[i, 5] + 1.66e-24 * 16 * expected[i, 12]
@test out.total_density β (expected_total_density * 1e3) rtol = 1e-3
end
# == Scenario 02 =======================================================================
# Test outputs.
expected = [
0.0 0.000E+00 1.919E+19 5.149E+18 1.181E-03 296.0 1027 1.288E+14 2.296E+17 0.000E+00 0.000E+00 0.000E+00 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
100.0 6.009E+11 9.392E+12 2.213E+12 5.764E-10 165.2 1027 1.339E+08 9.580E+10 2.654E+07 2.737E+05 0.000E+00 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
200.0 3.882E+09 1.978E+09 1.341E+08 2.028E-13 687.5 706 2.048E+07 9.719E+05 5.172E+05 1.632E+07 1.399E-09 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
300.0 3.140E+08 2.481E+07 9.340E+05 9.666E-15 705.5 706 1.082E+07 1.879E+03 3.860E+05 2.205E+06 3.876E+00 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
400.0 2.855E+07 3.737E+05 7.743E+03 8.221E-16 706.0 706 5.938E+06 4.688E+00 3.317E+05 2.633E+05 9.738E+02 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
500.0 2.787E+06 6.372E+03 7.382E+01 9.764E-17 706.0 706 3.319E+06 1.397E-02 2.868E+05 3.424E+04 3.186E+03 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
600.0 2.910E+05 1.222E+02 8.047E-01 2.079E-17 706.0 706 1.887E+06 4.919E-05 2.490E+05 4.742E+03 3.281E+03 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
700.0 3.240E+04 2.622E+00 9.973E-03 8.474E-18 706.0 706 1.090E+06 2.034E-07 2.171E+05 6.946E+02 2.498E+03 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
800.0 3.835E+03 6.264E-02 1.398E-04 4.665E-18 706.0 706 6.393E+05 9.809E-10 1.900E+05 1.074E+02 1.768E+03 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
900.0 4.816E+02 1.659E-03 2.204E-06 2.817E-18 706.0 706 3.806E+05 5.481E-12 1.669E+05 1.747E+01 1.236E+03 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
1000.0 6.400E+01 4.853E-05 3.891E-08 1.772E-18 706.0 706 2.298E+05 3.528E-14 1.471E+05 2.988E+00 8.675E+02 89.0 89.4 4.9 3.0 4.0 4.0 6.0 9.9 10.6
]
# Constant input parameters.
year = 2016
month = 6
day = 1
hour = 11
minute = 00
second = 00
Ο_gd = -23 * Ο / 180
Ξ» = -45 * Ο / 180
instant = date_to_jd(year, month, day, hour, minute, second) |> julian2datetime
# TODO: The tolerances here are much higher than in the previous test with the daily AP
# only. This must be analyzed. However, it was observed that in the NRLMSISE-00 version,
# the last component of the AP array is the "Average of eight 3 hour AP indices from 36
# to 57 hours prior to current time." Whereas the label from the online version is
# "ap_33_59_hr_prior", which seems to be different. On the other hand, the MSISE90
# describe the last vector of AP array as "Average of eight 3 hr AP indicies [sic] from
# 36 to 59 hrs prior to current time." Hence, it seems that the online version is using
# the old algorithm related to the AP array. We must change the algorithm in our
# implementation to the old one and see if the result is more similar to the online
# version.
#
# The information can be obtained at:
#
# https://ccmc.gsfc.nasa.gov/modelweb/
# https://ccmc.gsfc.nasa.gov/pub/modelweb/atmospheric/msis/msise90/
#
for i in axes(expected, 1)
F10 = expected[i, 13]
F10β = expected[i, 14]
ap_a = expected[i, 15:21]
# Run the NRLMSISE-00 model wih the input parameters.
out = AtmosphericModels.nrlmsise00(
instant,
expected[i, 1] * 1000,
Ο_gd,
Ξ»,
F10β,
F10,
ap_a;
include_anomalous_oxygen = false
)
@test out.total_density β (expected[i, 5] * 1e3) rtol = 5e-2
@test out.temperature β (expected[i, 6] ) rtol = 1e-1 atol = 1e-9
@test out.exospheric_temperature β (expected[i, 7] ) rtol = 1e-1 atol = 1e-9
@test out.O_number_density β (expected[i, 2] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.N2_number_density β (expected[i, 3] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.O2_number_density β (expected[i, 4] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.He_number_density β (expected[i, 8] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.Ar_number_density β (expected[i, 9] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.H_number_density β (expected[i, 10] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.N_number_density β (expected[i, 11] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.aO_number_density β (expected[i, 12] * 1e6) rtol = 9e-2 atol = 1e-9
# Test the version that calls `gtd7d` instead of `gtd7`.
out = AtmosphericModels.nrlmsise00(
instant,
expected[i, 1] * 1000,
Ο_gd,
Ξ»,
F10β,
F10,
ap_a;
include_anomalous_oxygen = true
)
@test out.temperature β (expected[i, 6] ) rtol = 1e-1 atol = 1e-9
@test out.exospheric_temperature β (expected[i, 7] ) rtol = 1e-1 atol = 1e-9
@test out.O_number_density β (expected[i, 2] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.N2_number_density β (expected[i, 3] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.O2_number_density β (expected[i, 4] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.He_number_density β (expected[i, 8] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.Ar_number_density β (expected[i, 9] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.H_number_density β (expected[i, 10] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.N_number_density β (expected[i, 11] * 1e6) rtol = 5e-2 atol = 1e-9
@test out.aO_number_density β (expected[i, 12] * 1e6) rtol = 9e-2 atol = 1e-9
expected_total_density = expected[i, 5] + 1.66e-24 * 16 * expected[i, 12]
@test out.total_density β (expected_total_density * 1e3) rtol = 5e-2
end
end
############################################################################################
# Test Results #
############################################################################################
#
# == Scenario 01 ===========================================================================
#
# Data obtained for the instant 2023-01-01T10:00:00.000 using the online version of
# NRLMSISE-00 [2].
#
# Input parameters
# year= 2023, month= 1, day= 1, hour=10.00,
# Time_type = Universal
# Coordinate_type = Geographic
# latitude= -23.00, longitude= 315.00, height= 100.00
# Prof. parameters: start= 0.00 stop= 1000.00 step= 50.00
# Optional parametes: F10.7(daily) =not specified; F10.7(3-month avg) =not specified; ap(daily) = not specified
#
# Selected parameters are:
# 1 Height, km
# 2 O, cm-3
# 3 N2, cm-3
# 4 O2, cm-3
# 5 Mass_density, g/cm-3
# 6 Temperature_neutral, K
# 7 Temperature_exospheric, K
# 8 He, cm-3
# 9 Ar, cm-3
# 10 H, cm-3
# 11 N, cm-3
# 12 Anomalous_Oxygen, cm-3
# 13 F10_7_daily
# 14 F10_7_3_month_avg
# 15 ap_daily
# 16 ap_00_03_hr_prior
# 17 ap_03_06_hr_prior
# 18 ap_06_09_hr_prior
# 19 ap_09_12_hr_prior
# 20 ap_12_33_hr_prior
# 21 ap_33_59_hr_prior
#
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# 0.0 0.000E+00 1.909E+19 5.122E+18 1.175E-03 297.5 1027 1.281E+14 2.284E+17 0.000E+00 0.000E+00 0.000E+00 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 50.0 0.000E+00 1.777E+16 4.766E+15 1.093E-06 269.0 1027 1.192E+11 2.125E+14 0.000E+00 0.000E+00 0.000E+00 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 100.0 3.854E+11 7.463E+12 1.511E+12 4.423E-10 188.3 1027 8.858E+07 7.379E+10 1.467E+07 2.513E+05 0.000E+00 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 150.0 1.703E+10 3.261E+10 1.970E+09 2.077E-12 688.5 1037 1.166E+07 6.061E+07 3.954E+05 1.246E+07 6.083E-21 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 200.0 4.318E+09 3.615E+09 1.381E+08 2.909E-13 911.5 1037 7.397E+06 2.827E+06 1.103E+05 2.694E+07 8.673E-09 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 250.0 1.584E+09 6.673E+08 1.955E+07 7.452E-14 991.0 1037 5.578E+06 2.589E+05 8.532E+04 1.422E+07 1.542E-02 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 300.0 6.521E+08 1.443E+08 3.382E+06 2.439E-14 1019.9 1037 4.421E+06 2.926E+04 7.816E+04 6.497E+06 2.402E+01 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 350.0 2.812E+08 3.338E+07 6.343E+05 9.150E-15 1030.5 1037 3.569E+06 3.624E+03 7.359E+04 3.058E+06 9.777E+02 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 400.0 1.243E+08 8.016E+06 1.243E+05 3.733E-15 1034.4 1037 2.906E+06 4.726E+02 6.977E+04 1.485E+06 6.035E+03 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 450.0 5.580E+07 1.977E+06 2.509E+04 1.608E-15 1035.9 1037 2.377E+06 6.401E+01 6.631E+04 7.348E+05 1.404E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 500.0 2.540E+07 4.988E+05 5.200E+03 7.196E-16 1036.5 1037 1.952E+06 8.950E+00 6.311E+04 3.685E+05 1.975E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 550.0 1.170E+07 1.285E+05 1.104E+03 3.319E-16 1036.7 1037 1.608E+06 1.289E+00 6.012E+04 1.870E+05 2.142E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 600.0 5.450E+06 3.376E+04 2.396E+02 1.575E-16 1036.8 1037 1.329E+06 1.911E-01 5.731E+04 9.586E+04 2.034E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 650.0 2.567E+06 9.044E+03 5.317E+01 7.717E-17 1036.9 1037 1.101E+06 2.910E-02 5.468E+04 4.961E+04 1.805E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 700.0 1.222E+06 2.468E+03 1.205E+01 3.934E-17 1036.9 1037 9.143E+05 4.553E-03 5.220E+04 2.592E+04 1.548E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 750.0 5.882E+05 6.862E+02 2.791E+00 2.111E-17 1036.9 1037 7.615E+05 7.311E-04 4.987E+04 1.367E+04 1.307E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 800.0 2.859E+05 1.942E+02 6.595E-01 1.207E-17 1036.9 1037 6.358E+05 1.205E-04 4.767E+04 7.270E+03 1.096E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 850.0 1.404E+05 5.593E+01 1.590E-01 7.432E-18 1036.9 1037 5.323E+05 2.035E-05 4.560E+04 3.902E+03 9.162E+03 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 900.0 6.962E+04 1.639E+01 3.910E-02 4.937E-18 1036.9 1037 4.467E+05 3.524E-06 4.364E+04 2.112E+03 7.661E+03 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 950.0 3.486E+04 4.884E+00 9.801E-03 3.517E-18 1036.9 1037 3.757E+05 6.250E-07 4.179E+04 1.153E+03 6.412E+03 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
# 1000.0 1.762E+04 1.480E+00 2.504E-03 2.653E-18 1036.9 1037 3.168E+05 1.135E-07 4.005E+04 6.346E+02 5.377E+03 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
#
############################################################################################
@testset "Fetching Space Indices Automatically" begin
SpaceIndices.init()
expected = [
0.0 0.000E+00 1.909E+19 5.122E+18 1.175E-03 297.5 1027 1.281E+14 2.284E+17 0.000E+00 0.000E+00 0.000E+00 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
50.0 0.000E+00 1.777E+16 4.766E+15 1.093E-06 269.0 1027 1.192E+11 2.125E+14 0.000E+00 0.000E+00 0.000E+00 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
100.0 3.854E+11 7.463E+12 1.511E+12 4.423E-10 188.3 1027 8.858E+07 7.379E+10 1.467E+07 2.513E+05 0.000E+00 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
150.0 1.703E+10 3.261E+10 1.970E+09 2.077E-12 688.5 1037 1.166E+07 6.061E+07 3.954E+05 1.246E+07 6.083E-21 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
200.0 4.318E+09 3.615E+09 1.381E+08 2.909E-13 911.5 1037 7.397E+06 2.827E+06 1.103E+05 2.694E+07 8.673E-09 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
250.0 1.584E+09 6.673E+08 1.955E+07 7.452E-14 991.0 1037 5.578E+06 2.589E+05 8.532E+04 1.422E+07 1.542E-02 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
300.0 6.521E+08 1.443E+08 3.382E+06 2.439E-14 1019.9 1037 4.421E+06 2.926E+04 7.816E+04 6.497E+06 2.402E+01 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
350.0 2.812E+08 3.338E+07 6.343E+05 9.150E-15 1030.5 1037 3.569E+06 3.624E+03 7.359E+04 3.058E+06 9.777E+02 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
400.0 1.243E+08 8.016E+06 1.243E+05 3.733E-15 1034.4 1037 2.906E+06 4.726E+02 6.977E+04 1.485E+06 6.035E+03 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
450.0 5.580E+07 1.977E+06 2.509E+04 1.608E-15 1035.9 1037 2.377E+06 6.401E+01 6.631E+04 7.348E+05 1.404E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
500.0 2.540E+07 4.988E+05 5.200E+03 7.196E-16 1036.5 1037 1.952E+06 8.950E+00 6.311E+04 3.685E+05 1.975E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
550.0 1.170E+07 1.285E+05 1.104E+03 3.319E-16 1036.7 1037 1.608E+06 1.289E+00 6.012E+04 1.870E+05 2.142E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
600.0 5.450E+06 3.376E+04 2.396E+02 1.575E-16 1036.8 1037 1.329E+06 1.911E-01 5.731E+04 9.586E+04 2.034E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
650.0 2.567E+06 9.044E+03 5.317E+01 7.717E-17 1036.9 1037 1.101E+06 2.910E-02 5.468E+04 4.961E+04 1.805E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
700.0 1.222E+06 2.468E+03 1.205E+01 3.934E-17 1036.9 1037 9.143E+05 4.553E-03 5.220E+04 2.592E+04 1.548E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
750.0 5.882E+05 6.862E+02 2.791E+00 2.111E-17 1036.9 1037 7.615E+05 7.311E-04 4.987E+04 1.367E+04 1.307E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
800.0 2.859E+05 1.942E+02 6.595E-01 1.207E-17 1036.9 1037 6.358E+05 1.205E-04 4.767E+04 7.270E+03 1.096E+04 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
850.0 1.404E+05 5.593E+01 1.590E-01 7.432E-18 1036.9 1037 5.323E+05 2.035E-05 4.560E+04 3.902E+03 9.162E+03 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
900.0 6.962E+04 1.639E+01 3.910E-02 4.937E-18 1036.9 1037 4.467E+05 3.524E-06 4.364E+04 2.112E+03 7.661E+03 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
950.0 3.486E+04 4.884E+00 9.801E-03 3.517E-18 1036.9 1037 3.757E+05 6.250E-07 4.179E+04 1.153E+03 6.412E+03 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
1000.0 1.762E+04 1.480E+00 2.504E-03 2.653E-18 1036.9 1037 3.168E+05 1.135E-07 4.005E+04 6.346E+02 5.377E+03 159.5 153.6 13.8 12.0 7.0 15.0 9.0 15.9 28.6
]
for i in axes(expected, 1)
# Run the NRLMSISE-00 model wih the input parameters.
out = AtmosphericModels.nrlmsise00(
DateTime("2023-01-01T10:00:00"),
expected[i, 1] * 1000,
-23 |> deg2rad,
-45 |> deg2rad;
include_anomalous_oxygen = false
)
@test out.total_density β (expected[i, 5] * 1e3) rtol = 3e-3
@test out.temperature β (expected[i, 6] ) rtol = 1e-1 atol = 1e-9
@test out.exospheric_temperature β (expected[i, 7] ) rtol = 1e-1 atol = 1e-9
@test out.O_number_density β (expected[i, 2] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.N2_number_density β (expected[i, 3] * 1e6) rtol = 3e-3 atol = 1e-9
@test out.O2_number_density β (expected[i, 4] * 1e6) rtol = 3e-3 atol = 1e-9
@test out.He_number_density β (expected[i, 8] * 1e6) rtol = 2e-3 atol = 1e-9
@test out.Ar_number_density β (expected[i, 9] * 1e6) rtol = 3e-3 atol = 1e-9
@test out.H_number_density β (expected[i, 10] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.N_number_density β (expected[i, 11] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.aO_number_density β (expected[i, 12] * 1e6) rtol = 1e-3 atol = 1e-9
end
# For altitudes lower than 80 km, we use default space indices.
expected = AtmosphericModels.nrlmsise00(
DateTime("2023-01-01T10:00:00"),
79e3,
-23 |> deg2rad,
-45 |> deg2rad,
150,
150,
4
)
result = AtmosphericModels.nrlmsise00(
DateTime("2023-01-01T10:00:00"),
79e3,
-23 |> deg2rad,
-45 |> deg2rad
)
@test result.total_density β expected.total_density
@test result.temperature β expected.temperature
@test result.exospheric_temperature β expected.exospheric_temperature
@test result.O_number_density β expected.O_number_density
@test result.N2_number_density β expected.N2_number_density
@test result.O2_number_density β expected.O2_number_density
@test result.He_number_density β expected.He_number_density
@test result.Ar_number_density β expected.Ar_number_density
@test result.H_number_density β expected.H_number_density
@test result.N_number_density β expected.N_number_density
@test result.aO_number_density β expected.aO_number_density
end
@testset "Pre-allocating the Legendre Matrix" begin
# We will use the scenario 1 of the first test.
# Test outputs.
expected = [
0.0 0.000E+00 1.918E+19 5.145E+18 1.180E-03 297.7 1027 1.287E+14 2.294E+17 0.000E+00 0.000E+00 0.000E+00
100.0 4.244E+11 9.498E+12 2.240E+12 5.783E-10 165.9 1027 1.061E+08 9.883E+10 2.209E+07 3.670E+05 0.000E+00
200.0 2.636E+09 2.248E+09 1.590E+08 1.838E-13 829.3 909 5.491E+06 1.829E+06 2.365E+05 3.125E+07 1.802E-09
300.0 3.321E+08 6.393E+07 2.881E+06 1.212E-14 900.6 909 3.173E+06 1.156E+04 1.717E+05 6.708E+06 4.938E+00
400.0 5.088E+07 2.414E+06 6.838E+04 1.510E-15 907.7 909 1.979E+06 1.074E+02 1.518E+05 1.274E+06 1.237E+03
500.0 8.340E+06 1.020E+05 1.839E+03 2.410E-16 908.5 909 1.259E+06 1.170E+00 1.355E+05 2.608E+05 4.047E+03
600.0 1.442E+06 4.729E+03 5.500E+01 4.543E-17 908.6 909 8.119E+05 1.455E-02 1.214E+05 5.617E+04 4.167E+03
700.0 2.622E+05 2.394E+02 1.817E+00 1.097E-17 908.6 909 5.301E+05 2.050E-04 1.092E+05 1.264E+04 3.173E+03
800.0 4.999E+04 1.317E+01 6.608E-02 3.887E-18 908.6 909 3.503E+05 3.254E-06 9.843E+04 2.964E+03 2.246E+03
900.0 9.980E+03 7.852E-01 2.633E-03 1.984E-18 908.6 909 2.342E+05 5.794E-08 8.900E+04 7.237E+02 1.571E+03
1000.0 2.082E+03 5.055E-02 1.146E-04 1.244E-18 908.6 909 1.582E+05 1.151E-09 8.069E+04 1.836E+02 1.103E+03
]
# Constant input parameters.
year = 1986
month = 6
day = 19
hour = 21
minute = 30
second = 00
Ο_gd = -16 * Ο / 180
Ξ» = 312 * Ο / 180
F10 = 121
F10β = 80
ap = 7
instant = date_to_jd(year, month, day, hour, minute, second) |> julian2datetime
P = zeros(8, 4)
for i in axes(expected, 1)
# Initialize `P` to check if it is used inside `nrlmsise00`.
P .= 0.0
# Run the NRLMSISE-00 model wih the input parameters.
out = AtmosphericModels.nrlmsise00(
instant,
expected[i, 1] * 1000,
Ο_gd,
Ξ»,
F10β,
F10,
ap;
include_anomalous_oxygen = false,
P = P
)
@test out.total_density β (expected[i, 5] * 1e3) rtol = 1e-3
@test out.temperature β (expected[i, 6] ) rtol = 1e-1 atol = 1e-9
@test out.exospheric_temperature β (expected[i, 7] ) rtol = 1e-1 atol = 1e-9
@test out.O_number_density β (expected[i, 2] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.N2_number_density β (expected[i, 3] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.O2_number_density β (expected[i, 4] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.He_number_density β (expected[i, 8] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.Ar_number_density β (expected[i, 9] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.H_number_density β (expected[i, 10] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.N_number_density β (expected[i, 11] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.aO_number_density β (expected[i, 12] * 1e6) rtol = 1e-3 atol = 1e-9
# Check that P was used.
@test abs(sum(P)) > 0
# Initialize `P` to check if it is used inside `nrlmsise00`.
P .= 0.0
# Test the version that calls `gtd7d` instead of `gtd7`.
out = AtmosphericModels.nrlmsise00(
instant,
expected[i, 1] * 1000,
Ο_gd,
Ξ»,
F10β,
F10,
ap;
include_anomalous_oxygen = true,
P = P
)
@test out.temperature β (expected[i, 6] ) rtol = 1e-1 atol = 1e-9
@test out.exospheric_temperature β (expected[i, 7] ) rtol = 1e-1 atol = 1e-9
@test out.O_number_density β (expected[i, 2] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.N2_number_density β (expected[i, 3] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.O2_number_density β (expected[i, 4] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.He_number_density β (expected[i, 8] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.Ar_number_density β (expected[i, 9] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.H_number_density β (expected[i, 10] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.N_number_density β (expected[i, 11] * 1e6) rtol = 1e-3 atol = 1e-9
@test out.aO_number_density β (expected[i, 12] * 1e6) rtol = 1e-3 atol = 1e-9
expected_total_density = expected[i, 5] + 1.66e-24 * 16 * expected[i, 12]
@test out.total_density β (expected_total_density * 1e3) rtol = 1e-3
# Check that P was used.
@test abs(sum(P)) > 0
end
end
@testset "Errors" begin
# == Wrong Size in Matrix `P` ==========================================================
P = zeros(8, 3)
@test_throws ArgumentError AtmosphericModels.nrlmsise00(
now() |> datetime2julian,
100e3,
0,
0,
100,
100,
20;
P = P
)
P = zeros(7, 4)
@test_throws ArgumentError AtmosphericModels.nrlmsise00(
now() |> datetime2julian,
100e3,
0,
0,
100,
100,
20;
P = P
)
P = zeros(7, 3)
@test_throws ArgumentError AtmosphericModels.nrlmsise00(
now() |> datetime2julian,
100e3,
0,
0,
100,
100,
20;
P = P
)
end
@testset "Show" begin
result = AtmosphericModels.nrlmsise00(
DateTime("2023-01-01T10:00:00"),
500e3,
0,
0,
100,
100,
3
)
expected = "NRLMSISE-00 output (Ο = 2.5893e-13 kg / mΒ³)"
str = sprint(show, result)
expected = """
NRLMSISE-00 Atmospheric Model Result:
Total density : 2.5893e-13 kg / mΒ³
Temperature : 875.50 K
Exospheric Temp. : 875.56 K
N number density : 2.02467e+11 1 / mΒ³
Nβ number density : 7.80367e+10 1 / mΒ³
O number density : 8.908e+12 1 / mΒ³
Anomalous O num. den. : 3.84174e+09 1 / mΒ³
Oβ number density : 1.05499e+09 1 / mΒ³
Ar number density : 619170 1 / mΒ³
He number density : 2.04514e+12 1 / mΒ³
H number density : 1.58356e+11 1 / mΒ³"""
str = sprint(show, MIME("text/plain"), result)
@test str == expected
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 541 | using Test
using DelimitedFiles
using SatelliteToolboxAtmosphericModels
using SatelliteToolboxBase
@testset "Atmospheric Model Jacchia-Roberts 1971" verbose = true begin
include("./jr1971.jl")
end
@testset "Atmospheric Model Jacchia-Bowman 2008" verbose = true begin
cd("./jb2008")
include("./jb2008/jb2008.jl")
cd("..")
end
@testset "Atmospheric Model NRLMSISE-00" verbose = true begin
include("./nrlmsise00.jl")
end
@testset "Exponential Atmospheric Model" verbose = true begin
include("./exponential.jl")
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | code | 4915 | ## Description #############################################################################
#
# Tests related to the Jacchia-Bowman 2008 model.
#
## References ##############################################################################
#
# [1] http://sol.spacenvironment.net/~JB2008/
# [2] https://github.com/JuliaSpace/JB2008_Test
#
############################################################################################
# == Functions: jb2008 =====================================================================
############################################################################################
# Test Results #
############################################################################################
#
# == Scenario 01 ===========================================================================
#
# Compare the results with the tests in files:
#
# JB_AUTO_OUTPUT_01.DAT
# JB_AUTO_OUTPUT_02.DAT
#
# which were created using JuliaSpace/JB2008_Test@ac41221. The other two files are ignored
# due to the lack of data in the space indices.
#
############################################################################################
@testset "Fetching All Space Indices" begin
SpaceIndices.init()
# == Scenario 01 =======================================================================
# Files with the test results.
test_list = [
"JB2008_AUTO_OUTPUT_01.DAT",
"JB2008_AUTO_OUTPUT_02.DAT",
]
# Execute the tests.
for filename in test_list
open(filename) do file
line_num = 0
year = 0
doy = 0
hour = 0
min = 0
sec = 0.0
for line in eachline(file)
line_num += 1
# Ignore 5 lines to skip the header.
(line_num <= 5) && continue
# Ignore others non important lines.
(line_num in [7, 8, 9]) && continue
if line_num == 6
# Read the next line to obtain the input data related to the
# time.
tokens = split(line)
year = parse(Int, tokens[1])
doy = parse(Int, tokens[2])
hour = parse(Int, tokens[3])
min = parse(Int, tokens[4])
sec = parse(Float64, tokens[5])
else
tokens = split(line)
# Read the information about the location.
h = parse(Float64, tokens[1]) * 1000
Ξ» = parse(Float64, tokens[2]) |> deg2rad
Ο_gd = parse(Float64, tokens[3]) |> deg2rad
# Read the model output.
exospheric_temperature = parse(Float64, tokens[4])
temperature = parse(Float64, tokens[5])
total_density = parse(Float64, tokens[6])
# Run the model.
jd = date_to_jd(year, 1, 1, hour, min, sec) - 1 + doy
instant = julian2datetime(jd)
result = AtmosphericModels.jb2008(instant, Ο_gd, Ξ», h)
# Compare the results.
@test result.exospheric_temperature β exospheric_temperature atol = 0.6 rtol = 0.0
@test result.temperature β temperature atol = 0.6 rtol = 0.0
@test result.total_density β total_density atol = 0.0 rtol = 5e-3
end
end
end
end
end
@testset "Show" begin
result = AtmosphericModels.jb2008(
DateTime("2023-01-01T10:00:00"),
0,
0,
500e3,
100,
100,
100,
100,
100,
100,
100,
100,
85
)
expected = "JB2008 output (Ο = 3.52089e-13 kg / mΒ³)"
str = sprint(show, result)
expected = """
Jacchia-Bowman 2008 Atmospheric Model Result:
Total density : 3.52089e-13 kg / mΒ³
Temperature : 923.19 K
Exospheric Temp. : 924.79 K
Nβ number density : 1.38441e+11 1 / mΒ³
Oβ number density : 3.20415e+09 1 / mΒ³
O number density : 1.23957e+13 1 / mΒ³
Ar number density : 2.20193e+06 1 / mΒ³
He number density : 2.4238e+12 1 / mΒ³
H number density : 4.13032e+10 1 / mΒ³"""
str = sprint(show, MIME("text/plain"), result)
@test str == expected
end
@testset "Errors" begin
@test_throws ArgumentError AtmosphericModels.jb2008(
now(),
0,
0,
89.9e3,
100,
100,
100,
100,
100,
100,
100,
100,
85
)
end
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | docs | 1620 | SatelliteToolboxAtmosphericModels.jl Changelog
==============================================
Version 0.1.3
-------------
- ![Enhancement][badge-enhancement] Minor source-code updates.
- ![Enhancement][badge-enhancement] Documentation updates.
Version 0.1.2
-------------
- ![Bugfix][badge-bugfix] In certain conditions, the JR1971 model would generate an array
index that was not an integer. This bug is now fixed.
- ![Feature][badge-feature] NRLMSISE-00 can receive a matrix to call the in-place function
that computes the Legendre associated functions, reducing the allocations.
- ![Enhancement][badge-enhancement] The internal structure of NRLMSISE-00 model was changed
to have a type parameter to indicate whether the AP is a vector or number. This approach
slightly increased the compile time, but reduced one allocation.
- ![Enhancement][badge-enhancement] The user can now call NRLMSISE-00 model without any
allocations, which increases the performance by roughly 20%.
Version 0.1.1
-------------
- ![Enhancement][badge-enhancement] We updated the dependency compatibility bounds.
Version 0.1.0
-------------
- Initial version.
- This version was based on the functions in **SatelliteToolbox.jl**.
[badge-breaking]: https://img.shields.io/badge/BREAKING-red.svg
[badge-deprecation]: https://img.shields.io/badge/Deprecation-orange.svg
[badge-feature]: https://img.shields.io/badge/Feature-green.svg
[badge-enhancement]: https://img.shields.io/badge/Enhancement-blue.svg
[badge-bugfix]: https://img.shields.io/badge/Bugfix-purple.svg
[badge-info]: https://img.shields.io/badge/Info-gray.svg
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | docs | 1792 | <p align="center">
<img src="./docs/src/assets/logo.png" width="150" title="SatelliteToolboxTransformations.jl"><br>
<small><i>This package is part of the <a href="https://github.com/JuliaSpace/SatelliteToolbox.jl">SatelliteToolbox.jl</a> ecosystem.</i></small>
</p>
# SatelliteToolboxAtmosphericModels.jl
[](https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl/actions/workflows/ci.yml)
[](https://codecov.io/gh/JuliaSpace/SatelliteToolboxAtmosphericModels.jl)
[][docs-stable-url]
[][docs-dev-url]
[](https://github.com/invenia/BlueStyle)
[](https://zenodo.org/doi/10.5281/zenodo.10644917)
This package implements atmospheric models for the **SatelliteToolbox.jl** ecosystem.
Currently, the following models are available:
- Exponential atmospheric model;
- Jacchia-Roberts 1971;
- [Jacchia-Bowman 2008](http://sol.spacenvironment.net/jb2008/); and
- [NRLMSISE-00](https://ccmc.gsfc.nasa.gov/modelweb/models/nrlmsise00.php).
## Installation
```julia
julia> using Pkg
julia> Pkg.add("SatelliteToolboxAtmosphericModels")
```
## Documentation
For more information, see the [documentation][docs-stable-url].
[docs-dev-url]: https://juliaspace.github.io/SatelliteToolboxAtmosphericModels.jl/dev
[docs-stable-url]: https://juliaspace.github.io/SatelliteToolboxAtmosphericModels.jl/stable
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | docs | 649 | # SatelliteToolboxAtmosphericModels.jl
This package implements atmospheric models for the **SatelliteToolbox.jl** ecosystem.
Currently, the following models are available:
- Exponential atmospheric model according to [1];
- Jacchia-Roberts 1971;
- [Jacchia-Bowman 2008](http://sol.spacenvironment.net/jb2008/); and
- [NRLMSISE-00](https://ccmc.gsfc.nasa.gov/modelweb/models/nrlmsise00.php).
## Installation
```julia
julia> using Pkg
julia> Pkg.install("SatelliteToolboxAtmosphericModels")
```
## References
- **[1]** **Vallado, D. A** (2013). *Fundamentals of Astrodynamics and Applications*. 4th
ed. **Microcosm Press**, Hawthorn, CA, USA.
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | docs | 173 | Library
=======
Documentation for `SatelliteToolboxAtmosphericModels.jl`.
```@autodocs
Modules = [SatelliteToolboxAtmosphericModels, AtmosphericModels]
Private = true
```
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | docs | 1284 | # Exponential Atmospheric Model
```@meta
CurrentModule = SatelliteToolboxAtmosphericModels
DocTestSetup = quote
using SatelliteToolboxAtmosphericModels
end
```
```@setup exp
using SatelliteToolboxAtmosphericModels
```
This model assumes we can compute the atmospheric density by:
```math
\rho(h) = \rho_0 \cdot exp \left\lbrace - \frac{h - h_0}{H} \right\rbrace~,
```
where ``\rho_0``, ``h_0``, and ``H`` are parameters obtained from tables. Reference [1]
provides a discretization of those parameters based on the selected height ``h`` that was
obtained after evaluation of some accurate models.
In this package, we can compute the model using the following function:
```julia
AtmosphericModels.exponential(h::T) where T<:Number -> Float64
```
where `h` is the desired height [m].
!!! warning
Notice that this model does not consider important effects such as the Sun activity, the
geomagnetic activity, the local time at the desired location, and others. Hence,
although this can be used for fast evaluations, the accuracy is not good.
## Examples
```@repl exp
AtmosphericModels.exponential(700e3)
```
## References
- **[1]** **Vallado, D. A** (2013). *Fundamentals of Astrodynamics and Applications*. 4th
ed. **Microcosm Press**, Hawthorn, CA, USA.
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | docs | 3703 | # Jacchia-Bowman 2008
```@meta
CurrentModule = SatelliteToolboxAtmosphericModels
```
```@setup jb2008
using SatelliteToolboxAtmosphericModels
```
This is an empirical thermospheric density model based on the Jacchia theory. It was
published in:
> **Bowman, B. R., Tobiska, W. K., Marcos, F. A., Huang, C. Y., Lin, C. S., Burke, W. J
> (2008)**. *A new empirical thermospheric density model JB2008 using new solar and
> geomagnetic indices.* **In the proeceeding of the AIAA/AAS Astrodynamics Specialist
> Conference**, Honolulu, Hawaii.
For more information, visit
[http://sol.spacenvironment.net/jb2008](http://sol.spacenvironment.net/jb2008).
In this package, we can evaluate the model using the following functions:
```julia
AtmosphericModels.jb2008(instant::DateTime, Ο_gd::Number, Ξ»::Number, h::Number[, F10::Number, F10β::Number, S10::Number, S10β::Number, M10::Number, M10β::Number, Y10::Number, Y10β::Number, DstΞTc::Number]) -> JB2008Output{Float64}
AtmosphericModels.jb2008(jd::Number, Ο_gd::Number, Ξ»::Number, h::Number[, F10::Number, F10β::Number, S10::Number, S10β::Number, M10::Number, M10β::Number, Y10::Number, Y10β::Number, DstΞTc::Number]) -> JB2008Output{Float64}
```
where:
- `jd::Number`: Julian day to compute the model.
- `instant::DateTime`: Instant to compute the model represent using `DateTime`.
- `Ο_gd`: Geodetic latitude [rad].
- `Ξ»`: Longitude [rad].
- `h`: Altitude [m].
- `F10`: 10.7-cm solar flux [sfu] obtained 1 day before `jd`.
- `F10β`: 10.7-cm averaged solar flux using a 81-day window centered on input time obtained
1 day before `jd`.
- `S10`: EUV index (26-34 nm) scaled to F10.7 obtained 1 day before `jd`.
- `S10β`: EUV 81-day averaged centered index obtained 1 day before `jd`.
- `M10`: MG2 index scaled to F10.7 obtained 2 days before `jd`.
- `M10β`: MG2 81-day averaged centered index obtained 2 day before `jd`.
- `Y10`: Solar X-ray & Ly-Ξ± index scaled to F10.7 obtained 5 days before `jd`.
- `Y10β`: Solar X-ray & Ly-Ξ± 81-day averaged centered index obtained 5 days before `jd`.
- `DstΞTc`: Temperature variation related to the Dst.
If we omit all space indices, the system tries to obtain them automatically for the selected
day `jd` or `instant`. However, the indices must be already initialized using the function
`SpaceIndices.init()`.
These functions return an object of type `JB2008Output{Float64}` that contains the
following fields:
- `total_density::T`: Total atmospheric density [1 / mΒ³].
- `temperature::T`: Temperature at the selected position [K].
- `exospheric_temperature::T`: Exospheric temperature [K].
- `N2_number_density::T`: Number density of Nβ [1 / mΒ³].
- `O2_number_density::T`: Number density of Oβ [1 / mΒ³].
- `O_number_density::T`: Number density of O [1 / mΒ³].
- `Ar_number_density::T`: Number density of Ar [1 / mΒ³].
- `He_number_density::T`: Number density of He [1 / mΒ³].
- `H_number_density::T`: Number density of H [1 / mΒ³].
## Examples
```@repl jb2008
AtmosphericModels.jb2008(
DateTime("2022-06-19T18:35:00"),
deg2rad(-22),
deg2rad(-45),
700e3,
79,
73.5,
55.1,
53.8,
78.9,
73.3,
80.2,
71.7,
50
)
```
```@repl jb2008
SpaceIndices.init()
AtmosphericModels.jb2008(DateTime("2022-06-19T18:35:00"), deg2rad(-22), deg2rad(-45), 700e3)
```
If we use the automatic space index fetching mechanism, it is possible to obtain the fetched
values by turning on the debugging logs according to the [Julia
documentation](https://docs.julialang.org/en/v1/stdlib/Logging/):
```@repl jb2008
using Logging
with_logger(ConsoleLogger(stderr, Logging.Debug)) do
AtmosphericModels.jb2008(DateTime("2022-06-19T18:35:00"), deg2rad(-22), deg2rad(-45), 700e3)
end
```
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | docs | 2937 | # Jacchia-Roberts 1971
```@meta
CurrentModule = SatelliteToolboxAtmosphericModels
```
```@setup jr1971
using SatelliteToolboxAtmosphericModels
```
This is an analytic atmospheric model based on the Jacchia's 1970 model. It was published
in:
> **Roberts, C. E (1971)**. *An analytic model for upper atmosphere densities based upon
> Jacchia's 1970 models*. **Celestial mechanics**, Vol. 4 (3-4), p. 368-377, DOI:
> 10.1007/BF01231398.
Although it is old, this model is still used for some applications, like computing the
estimated reentry time for an object on low Earth orbits.
In this package, we can evaluate the model using the following functions:
```julia
AtmosphericModels.jr1971(instant::DateTime, Ο_gd::Number, Ξ»::Number, h::Number[, F10::Number, F10β::Number, Kp::Number]) -> JR1971Output{Float64}
AtmosphericModels.jr1971(jd::Number, Ο_gd::Number, Ξ»::Number, h::Number[, F10::Number, F10β::Number, Kp::Number]) -> JR1971Output{Float64}
```
where:
- `jd::Number`: Julian day to compute the model.
- `instant::DateTime`: Instant to compute the model represent using `DateTime`.
- `Ο_gd::Number`: Geodetic latitude [rad].
- `Ξ»::Number`: Longitude [rad].
- `h::Number`: Altitude [m].
- `F10::Number`: 10.7-cm solar flux [sfu].
- `F10β::Number`: 10.7-cm averaged solar flux, 81-day centered on input time [sfu].
- `Kp::Number`: Kp geomagnetic index with a delay of 3 hours.
If we omit all space indices, the system tries to obtain them automatically for the selected
day `jd` or `instant`. However, the indices must be already initialized using the function
`SpaceIndices.init()`.
This function return an object of type `JR1971Output{Float64}` that contains the following
fields:
- `total_density::T`: Total atmospheric density [1 / mΒ³].
- `temperature::T`: Temperature at the selected position [K].
- `exospheric_temperature::T`: Exospheric temperature [K].
- `N2_number_density::T`: Number density of Nβ [1 / mΒ³].
- `O2_number_density::T`: Number density of Oβ [1 / mΒ³].
- `O_number_density::T`: Number density of O [1 / mΒ³].
- `Ar_number_density::T`: Number density of Ar [1 / mΒ³].
- `He_number_density::T`: Number density of He [1 / mΒ³].
- `H_number_density::T`: Number density of H [1 / mΒ³].
## Examples
```@repl jr1971
AtmosphericModels.jr1971(
DateTime("2018-06-19T18:35:00"),
deg2rad(-22),
deg2rad(-45),
700e3,
79,
73.5,
1.34
)
```
```@repl jr1971
SpaceIndices.init()
AtmosphericModels.jr1971(DateTime("2022-06-19T18:35:00"), deg2rad(-22), deg2rad(-45), 700e3)
```
If we use the automatic space index fetching mechanism, it is possible to obtain the fetched
values by turning on the debugging logs according to the [Julia
documentation](https://docs.julialang.org/en/v1/stdlib/Logging/):
```@repl jr1971
using Logging
with_logger(ConsoleLogger(stderr, Logging.Debug)) do
AtmosphericModels.jr1971(DateTime("2022-06-19T18:35:00"), deg2rad(-22), deg2rad(-45), 700e3)
end
```
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 8e14a70da3f421ab55cbed464393c94806d1d866 | docs | 4952 | # NRLMSISE-00
```@meta
CurrentModule = SatelliteToolboxAtmosphericModels
```
```@setup nrlmsise00
using SatelliteToolboxAtmosphericModels
```
The NRLMSISE-00 empirical atmosphere model was developed by Mike Picone, Alan Hedin, and
Doug Drob based on the MSISE90 model:
> **Picone, J. M., Hedin, A. E., Drob, D. P., Aikin, A. C (2002)**. *NRLMSISE-00 empirical
> model of the atmosphere: Statistical comparisons and scientific issues*. **Journal of
> Geophysical Research: Space Physics**, Vol. 107 (A12), p. SIA 15-1 -- SIA 15-16, DOI:
> 10.1029/2002JA009430.
In this package, we can compute this model using the following functions:
```julia
AtmosphericModels.nrlmsise00(instant::DateTime, h::Number, Ο_gd::Number, Ξ»::Number[, F10β::Number, F10::Number, ap::Union{Number, AbstractVector}]; kwargs...) -> Nrlmsise00Output{Float64}
AtmosphericModels.nrlmsise00(jd::Number, h::Number, Ο_gd::Number, Ξ»::Number[, F10β::Number, F10::Number, ap::Union{Number, AbstractVector}]; kwargs...) -> Nrlmsise00Output{Float64}
```
where
- `instant::DateTime`: Instant to compute the model represent using `DateTime`.
- `jd::Number`: Julian day to compute the model.
- `h::Number`: Altitude [m].
- `Ο_gd::Number`: Geodetic latitude [rad].
- `Ξ»::Number`: Longitude [rad].
- `F10β::Number`: 10.7-cm averaged solar flux, 90-day centered on input time [sfu].
- `F10::Number`: 10.7-cm solar flux [sfu].
- `ap::Union{Number, AbstractVector}`: Magnetic index, see the section [AP](@ref) for more
information.
The following keywords are available:
- `flags::Nrlmsise00Flags`: A list of flags to configure the model. For more information,
see [`AtmosphericModels.Nrlmsise00Flags`](@ref).
(**Default** = `Nrlmsise00Flags()`)
- `include_anomalous_oxygen::Bool`: If `true`, the anomalous oxygen density will be included
in the total density computation.
(**Default** = `true`)
- `P::Union{Nothing, Matrix}`: If the user passes a matrix with dimensions equal to or
greater than 8 Γ 4, it will be used when computing the Legendre associated functions,
reducing allocations and improving the performance. If it is `nothing`, the matrix is
allocated inside the function.
(**Default** `nothing`)
If we omit all space indices, the system tries to obtain them automatically for the selected
day `jd` or `instant`. However, the indices must be already initialized using the function
`SpaceIndices.init()`.
These functions return an object of type `Nrlmsise00Output{Float64}` that contains the
following fields:
- `total_density::T`: Total mass density [kg / mΒ³].
- `temperature`: Temperature at the selected altitude [K].
- `exospheric_temperature`: Exospheric temperature [K].
- `N_number_density`: Nitrogen number density [1 / mΒ³].
- `N2_number_density`: Nβ number density [1 / mΒ³].
- `O_number_density`: Oxygen number density [1 / mΒ³].
- `aO_number_density`: Anomalous Oxygen number density [1 / mΒ³].
- `O2_number_density`: Oβ number density [1 / mΒ³].
- `H_number_density`: Hydrogen number density [1 / mΒ³].
- `He_number_density`: Helium number density [1 / mΒ³].
- `Ar_number_density`: Argon number density [1 / mΒ³].
## AP
The input variable `ap` contains the magnetic index. It can be a `Number` or an
`AbstractVector`.
If `ap` is a number, it must contain the daily magnetic index.
If `ap` is an `AbstractVector`, it must be a vector with 7 dimensions as described below:
| Index | Description |
|-------|:------------------------------------------------------------------------------|
| 1 | Daily AP. |
| 2 | 3 hour AP index for current time. |
| 3 | 3 hour AP index for 3 hours before current time. |
| 4 | 3 hour AP index for 6 hours before current time. |
| 5 | 3 hour AP index for 9 hours before current time. |
| 6 | Average of eight 3 hour AP indices from 12 to 33 hours prior to current time. |
| 7 | Average of eight 3 hour AP indices from 36 to 57 hours prior to current time. |
## Examples
```@repl nrlmsise00
AtmosphericModels.nrlmsise00(
DateTime("2018-06-19T18:35:00"),
700e3,
deg2rad(-22),
deg2rad(-45),
73.5,
79,
5.13
)
```
```@repl nrlmsise00
SpaceIndices.init()
AtmosphericModels.nrlmsise00(DateTime("2018-06-19T18:35:00"), 700e3, deg2rad(-22), deg2rad(-45))
```
If we use the automatic space index fetching mechanism, it is possible to obtain the fetched
values by turning on the debugging logs according to the [Julia
documentation](https://docs.julialang.org/en/v1/stdlib/Logging/):
```@repl nrlmsise00
using Logging
with_logger(ConsoleLogger(stderr, Logging.Debug)) do
AtmosphericModels.nrlmsise00(DateTime("2018-06-19T18:35:00"), 700e3, deg2rad(-22), deg2rad(-45))
end
```
| SatelliteToolboxAtmosphericModels | https://github.com/JuliaSpace/SatelliteToolboxAtmosphericModels.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 6355 | #=
setindex.jl
Provide setindex!() capabilities like A[i,j] = s for LinearMapAM objects.
The setindex! function here is (necessarily) quite inefficient.
It is provided solely so that a LinearMapAM conforms to the AbstractMatrix
requirement that a setindex! method exists.
Use of this function is strongly discouraged, other than for testing.
2018-01-19, Jeff Fessler, University of Michigan
=#
using LinearMaps #: LinearMaps.FunctionMap
#Indexer = AbstractVector{Int}
"""
`A[i,j] = X`
Mathematically, if B = copy(A) and then we say `B[i,j] = s`, for scalar `s`,
then `B = A + (s - A[i,j]) e_i e_j'`
where `e_i` and `e_j` are the appropriate unit vectors.
Using this basic math, we can perform `B*x` using `A*x` and `A[i,j]`.
This idea generalizes to `B[ii,jj] = X` where `ii` and `jj` are vectors.
This method works because LinearMapAM is a *mutable* struct.
"""
function Base.setindex!(A::LinearMapAM, X::AbstractMatrix,
ii::Indexer, jj::Indexer,
)
# todo: handle WrappedMap differently
L = A._lmap
Aij = A[ii,jj] # must extract this outside of forw() to avoid recursion!
Aij = reshape(Aij, size(X)) # needed for [i,:] case
if true
forw = (x) ->
begin
tmp = L * x
tmp[ii] += (X - Aij) * x[jj]
return tmp
end
end
has_adj = !(typeof(L) <: LinearMaps.FunctionMap) || (L.fc !== nothing)
if has_adj
back = (y) ->
begin
tmp = L' * y
tmp[jj] += (X - Aij)' * y[ii]
return tmp
end
end
#=
# for future reference, some of this could be implemented
A.issymmetric = false # could check if i==j
A.ishermitian = false # could check if i==j and v=v'
A.posdef = false # could check if i==j and v > A[i,j]
=#
if has_adj
A._lmap = LinearMap(forw, back, size(L)...)
else
A._lmap = LinearMap(forw, size(L)...)
end
nothing
end
# [i,j] = s
Base.setindex!(A::LinearMapAM, s::Number, i::Int, j::Int) =
setindex!(A, fill(s,1,1), [i], [j])
# [ii,jj] = X
Base.setindex!(A::LinearMapAM, X::AbstractMatrix,
ii::AbstractVector{Bool}, jj::AbstractVector{Bool}) =
setindex!(A, X, findall(ii), findall(jj))
# [:,jj] = X
Base.setindex!(A::LinearMapAM, X::AbstractMatrix, ::Colon, jj::AbstractVector{Bool}) =
setindex!(A, X, :, findall(jj))
Base.setindex!(A::LinearMapAM, X::AbstractMatrix, ::Colon, jj::Indexer) =
setindex!(A, X, 1:size(A,1), jj)
# [ii,:] = X
Base.setindex!(A::LinearMapAM, X::AbstractMatrix, ii::AbstractVector{Bool}, ::Colon) =
setindex!(A, X, findall(ii), :)
Base.setindex!(A::LinearMapAM, X::AbstractMatrix, ii::Indexer, ::Colon) =
setindex!(A, X, ii, 1:size(A,2))
# [:,j] = v
Base.setindex!(A::LinearMapAM, v::AbstractVector, ::Colon, j::Int) =
setindex!(A, reshape(v,:,1), :, [j])
# [ii,j] = v
Base.setindex!(A::LinearMapAM, v::AbstractVector, ii::Indexer, j::Int) =
setindex!(A, reshape(v,:,1), ii, [j])
# [i,:] = v
Base.setindex!(A::LinearMapAM, v::AbstractVector, i::Int, ::Colon) =
setindex!(A, reshape(v,1,:), [i], :)
# [i,jj] = v
Base.setindex!(A::LinearMapAM, v::AbstractVector, i::Int, jj::Indexer) =
setindex!(A, reshape(v,1,:), [i], jj)
# [ii,jj] = s
Base.setindex!(A::LinearMapAM, s::Number, ii::AbstractVector{Bool}, jj::Indexer) =
setindex!(A, s, findall(ii), jj)
Base.setindex!(A::LinearMapAM, s::Number, ii::Indexer, jj::AbstractVector{Bool}) =
setindex!(A, s, ii, findall(jj))
Base.setindex!(A::LinearMapAM, s::Number,
ii::AbstractVector{Bool}, jj::AbstractVector{Bool}) =
setindex!(A, s, findall(ii), findall(jj))
Base.setindex!(A::LinearMapAM, s::Number, ii::Indexer, jj::Indexer) =
setindex!(A, fill(s,length(ii),length(jj)), ii, jj)
# [:,j] = s
Base.setindex!(A::LinearMapAM, s::Number, ::Colon, j::Int) =
setindex!(A, s, 1:size(A,1), [j])
# [ii,:] = s
Base.setindex!(A::LinearMapAM, s::Number, ii::AbstractVector{Bool}, ::Colon) =
setindex!(A, s, findall(ii), :)
Base.setindex!(A::LinearMapAM, s::Number, ii::Indexer, ::Colon) =
setindex!(A, s, ii, 1:size(A,2))
# [ii,j] = s
Base.setindex!(A::LinearMapAM, s::Number, ii::AbstractVector{Bool}, j::Int) =
setindex!(A, s, findall(ii), [j])
Base.setindex!(A::LinearMapAM, s::Number, ii::Indexer, j::Int) =
setindex!(A, fill(s, length(ii), 1), ii, [j])
# [i,:] = s
Base.setindex!(A::LinearMapAM, s::Number, i::Int, ::Colon) =
setindex!(A, fill(s, 1, size(A,2)), [i], :)
# [i,jj] = s
Base.setindex!(A::LinearMapAM, s::Number, i::Int, jj::AbstractVector{Bool}) =
setindex!(A, s, i, findall(jj))
Base.setindex!(A::LinearMapAM, s::Number, i::Int, jj::Indexer) =
setindex!(A, fill(s, 1, length(jj)), [i], jj)
# [:,jj] = s
Base.setindex!(A::LinearMapAM, s::Number, ::Colon, jj::AbstractVector{Bool}) =
setindex!(A, s, :, findall(jj))
Base.setindex!(A::LinearMapAM, s::Number, ::Colon, jj::Indexer) =
setindex!(A, s, 1:size(A,1), jj)
# [kk]
#= too much work, so unsupported
Base.setindex!(A::LinearMapAM, v::AbstractVector,
kk::Indexer) =
=#
# [:] = v
Base.setindex!(A::LinearMapAM, v::AbstractVector, ::Colon) =
setindex!(A, reshape(v,size(A)), :, :)
# [:] = s
function Base.setindex!(A::LinearMapAM, s::Number, ::Colon)
(M,N) = size(A)
forw = x -> fill(s, M) * (ones(1,N) * x)[1]
back = y -> fill(conj(s), N) * (ones(1, M) * y)[1]
A._lmap = LinearMap(forw, back, M, N)
end
# [:,:] = s
Base.setindex!(A::LinearMapAM, s::Number, ::Colon, ::Colon) =
setindex!(A, s, :)
# [:,:] = X
function Base.setindex!(A::LinearMapAM, X::AbstractMatrix, ::Colon, ::Colon)
A._lmap = LinearMap(X)
end
# [k] = s
"""
`setindex!(A::LinearMapAM, s::Number, k::Int)`
Provide the single index version to meet the `AbstractArray` spec:
https://docs.julialang.org/en/latest/manual/interfaces/#Indexing-1
"""
Base.setindex!(A::LinearMapAM, s::Number, k::Int) =
setindex!(A, s, Tuple(CartesianIndices(size(A))[k])...) # any better way?
#=
"""
`setindex!(A::LinearMapAM, v::Number, k::Int)`
Provide the single index version to meet the `AbstractArray` spec:
https://docs.julialang.org/en/latest/manual/interfaces/#Indexing-1
"""
function Base.setindex!(A::LinearMapAM, v::Number, k::Int)
c = CartesianIndices(size(A))[k] # is there a more elegant way?
setindex!(A, v::Number, c[1], c[2])
end
=#
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 2952 | execute = isempty(ARGS) || ARGS[1] == "run"
org, reps = :JeffFessler, :LinearMapsAA
eval(:(using $reps))
import Documenter
import Literate
# https://juliadocs.github.io/Documenter.jl/stable/man/syntax/#@example-block
ENV["GKSwstype"] = "100"
ENV["GKS_ENCODING"] = "utf-8"
# generate examples using Literate
lit = joinpath(@__DIR__, "lit")
src = joinpath(@__DIR__, "src")
gen = joinpath(@__DIR__, "src/generated")
base = "$org/$reps.jl"
repo_root_url = "https://github.com/$base/blob/main"
nbviewer_root_url =
"https://nbviewer.org/github/$base/tree/gh-pages/dev/generated"
binder_root_url =
"https://mybinder.org/v2/gh/$base/gh-pages?filepath=dev/generated"
repo = eval(:($reps))
Documenter.DocMeta.setdocmeta!(repo, :DocTestSetup, :(using $reps); recursive=true)
# preprocessing
inc1 = "include(\"../../../inc/reproduce.jl\")"
function prep_markdown(str, root, file)
inc_read(file) = read(joinpath("docs/inc", file), String)
repro = inc_read("reproduce.jl")
str = replace(str, inc1 => repro)
urls = inc_read("urls.jl")
file = joinpath(splitpath(root)[end], splitext(file)[1])
tmp = splitpath(root)[end-2:end] # docs lit examples
urls = replace(urls,
"xxxrepo" => joinpath(repo_root_url, tmp...),
"xxxnb" => joinpath(nbviewer_root_url, tmp[end]),
"xxxbinder" => joinpath(binder_root_url, tmp[end]),
)
str = replace(str, "#srcURL" => urls)
end
function prep_notebook(str)
str = replace(str, inc1 => "", "#srcURL" => "")
end
for (root, _, files) in walkdir(lit), file in files
splitext(file)[2] == ".jl" || continue # process .jl files only
ipath = joinpath(root, file)
opath = splitdir(replace(ipath, lit => gen))[1]
Literate.markdown(ipath, opath;
repo_root_url,
preprocess = str -> prep_markdown(str, root, file),
documenter = execute, # run examples
)
Literate.notebook(ipath, opath;
preprocess = prep_notebook,
execute = false, # no-run notebooks
)
end
# Documentation structure
ismd(f) = splitext(f)[2] == ".md"
pages(folder) =
[joinpath("generated/", folder, f) for f in readdir(joinpath(gen, folder)) if ismd(f)]
isci = get(ENV, "CI", nothing) == "true"
format = Documenter.HTML(;
prettyurls = isci,
edit_link = "main",
canonical = "https://$org.github.io/$repo.jl/stable/",
assets = ["assets/custom.css"],
)
Documenter.makedocs(;
modules = [repo],
authors = "Jeff Fessler and contributors",
sitename = "$repo.jl",
format,
pages = [
"Home" => "index.md",
"Methods" => "methods.md",
"Examples" => pages("examples")
],
)
if isci
Documenter.deploydocs(;
repo = "github.com/$base",
devbranch = "main",
devurl = "dev",
versions = ["stable" => "v^", "dev" => "dev"],
forcepush = true,
push_preview = true,
# see https://$org.github.io/$repo.jl/previews/PR##
)
end
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 256 |
# ### Reproducibility
# This page was generated with the following version of Julia:
using InteractiveUtils: versioninfo
io = IOBuffer(); versioninfo(io); split(String(take!(io)), '\n')
# And with the following package versions
import Pkg; Pkg.status()
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 427 |
#=
This page comes from a single Julia file:
[`@__NAME__.jl`](xxxrepo/@__NAME__.jl).
You can access the source code
for such Julia documentation
using the 'Edit on GitHub' link in the top right.
You can view the corresponding notebook in
[nbviewer](https://nbviewer.org/) here:
[`@__NAME__.ipynb`](xxxnb/@__NAME__.ipynb),
or open it in [binder](https://mybinder.org/) here:
[`@__NAME__.ipynb`](xxxbinder/@__NAME__.ipynb).
=#
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 5812 | #=
# [LinearMapsAA overview](@id 01-overview)
This page illustrates the Julia package
[`LinearMapsAA`](https://github.com/JeffFessler/LinearMapsAA.jl).
=#
#srcURL
# ### Setup
# Packages needed here.
using LinearMapsAA
using ImagePhantoms: shepp_logan, SheppLoganToft
using MIRTjim: jim, prompt
using InteractiveUtils: versioninfo
# The following line is helpful when running this file as a script;
# this way it will prompt user to hit a key after each figure is displayed.
isinteractive() ? jim(:prompt, true) : prompt(:draw);
#=
## Overview
Many computational imaging methods use system models
that are too large to store explicitly
as dense matrices,
but nevertheless
are represented mathematically
by a linear mapping `A`.
Often that linear map is thought of as a matrix,
but in imaging problems
it often is more convenient
to think of it as a more general linear operator.
The `LinearMapsAA` package
can represent both "matrix" versions
and "operator" versions
of linear mappings.
This page illustrates both versions
in the context of single-image
[super-resolution](https://en.wikipedia.org/wiki/Super-resolution_imaging)
imaging,
where the operator `A` maps a `M Γ N` image
into a coarser sampled image of size `MΓ·2 Γ NΓ·2`.
Here the operator `A` is akin to down-sampling,
except, rather than simple decimation,
each coarse-resolution pixel
is the average of a 2 Γ 2 block of pixels in the fine-resolution image.
=#
# ## System operator (linear mapping) for down-sampling
# Here is the "forward" function needed to model 2Γ down-sampling:
down1 = (x) -> (x[1:2:end,:] + x[2:2:end,:])/2 # 1D down-sampling by 2Γ
down2 = (x) -> down1(down1(x)')'; # 2D down-sampling by factor of 2Γ
# The `down2` function is a (bounded) linear operator
# and here is its adjoint:
down2_adj(y::AbstractMatrix{<:Number}) = kron(y, fill(0.25, (2,2)));
#=
Mathematically, and adjoint is a generalization
of the (Hermitian) transpose of a matrix.
For a (bounded) linear mapping `A` between
inner product space X
with inner product <.,.>_X
and inner product space Y
with inner product <.,.>_Y,
the adjoint of `A`, denoted `A'`,
is the unique bound linear mapping
that satisfies
<A x, y>_Y = <x, A' y>_X
for all x β X and y β Y.
One can verify that the `down2_adj` function
satisfies that equality
for the usual inner product
on the space of `M Γ N` images.
=#
#=
## LinearMap as an operator for super-resolution
We now pick a specific image size
and define the linear mapping
using the two functions above:
=#
nx, ny = 200, 256
A = LinearMapAA(down2, down2_adj, ((nxΓ·2)*(nyΓ·2), nx*ny);
idim = (nx,ny), odim = (nx,ny) .Γ· 2)
#=
The `idim` argument specifies
that the input image is of size `nx Γ ny`
and
the `odim` argument specifies
that the output image is of size `nxΓ·2 Γ nyΓ·2`.
This means that when we invoke
`y = A * x`
the input `x` must be a 2D array of size `nx Γ ny`
(not a 1D vector!)
and the output `y` will have size `nxΓ·2 Γ nyΓ·2`.
This behavior is a generalization
of what one might expect
from a conventional matrix-vector expression,
but is quite appropriate and convenient
for imaging problems.
Here is an illustration.
We start with a 2D test image.
=#
image = shepp_logan(ny, SheppLoganToft())[(ny-nx)Γ·2 .+ (1:nx),:]
jim(image, "SheppLogan")
# Apply the operator `A` to this image to down-sample it:
down = A * image
jim(down, title="Down-sampled image")
# Apply the adjoint of `A` to that result to "up-sample" it:
up = A' * down
jim(up, title="Adjoint: A' * y")
# That up-sampled image does not have the same range of values
# as the original image because `A'` is an adjoint, not an inverse!
#=
## AbstractMatrix version
Some users may prefer that the operator `A` behave more like a matrix.
We can implement approach from the same ingredients
by using `vec` and `reshape` judiciously.
The code is less elegant,
but similarly efficient
because `vec` and `reshape` are non-allocating operations.
=#
B = LinearMapAA(
x -> vec(down2(reshape(x,nx,ny))),
y -> vec(down2_adj(reshape(y,Int(nx/2),Int(ny/2)))),
((nxΓ·2)*(nyΓ·2), nx*ny),
)
#=
To apply this version to our `image`
we must first vectorize it
because the expected input is a vector in this case.
And then we have to reshape the vector output
as a 2D array to look at it.
(This is why the operator version with `idim` and `odim` is preferable.)
=#
y = B * vec(image) # This would fail here without the `vec`!
jim(reshape(y, nxΓ·2, nyΓ·2)) # Annoying reshape needed here!
#=
Even though we write `y = A * x` above,
one must remember that internally `A` is not stored as a dense matrix.
It is simply a special variable type
that stores the forward function `down2` and the adjoint function `down2_adj`,
along with a few other values like `nx,ny`,
and applies those functions when needed.
Nevertheless,
we can examine elements of `A` and `B`
just like one would with any matrix,
at least for small enough examples to fit in memory.
=#
# Examine `A` and `A'`
nx, ny = 8,6
idim = (nx,ny)
odim = (nx,ny) .Γ· 2
A = LinearMapAA(down2, down2_adj, ((nxΓ·2)*(nyΓ·2), nx*ny); idim, odim)
# Here is `A` shown as a Matrix:
jim(Matrix(A)', "A")
# Here is `A'` shown as a Matrix:
jim(Matrix(A')', "A'")
#=
When defining the adjoint function of a linear mapping,
it is very important to verify
that it is correct (truly the adjoint).
For a small problem we simply use the following test:
=#
@assert Matrix(A)' == Matrix(A')
# For some applications we must check approximate equality like this:
@assert Matrix(A)' β Matrix(A')
# Here is a statistical test that is suitable for large operators.
# Often one would repeat this test several times:
T = eltype(A)
x = randn(T, idim)
y = randn(T, odim)
@assert sum((A*x) .* y) β sum(x .* (A'*y)) # <Ax,y> = <x,A'y>
include("../../../inc/reproduce.jl")
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 4286 | #=
# [Operator example: trace](@id 02-trace)
This page illustrates
the "linear operator" feature
of the Julia package
[`LinearMapsAA`](https://github.com/JeffFessler/LinearMapsAA.jl).
=#
#srcURL
# ### Setup
# Packages needed here.
using LinearMapsAA
using LinearAlgebra: tr, I
using InteractiveUtils: versioninfo
#=
## Overview
The "operator" aspect of this package
may seem unfamiliar
to some readers
who are used to thinking in terms of matrices and vectors,
so this page
describes a simple example:
the matrix
[trace](https://en.wikipedia.org/wiki/Trace_(linear_algebra))
operation.
The trace of a ``N Γ N`` matrix
is the sum of its ``N`` diagonal elements.
We tend to think of this a function,
and indeed it is the `tr` function
in the `LinearAlgebra` package.
But it is a *linear* function
so we can represent it as a linear operator
``π`` that maps a ``N Γ N`` matrix into its trace.
In other words,
``π : \mathbb{C}^{N Γ N} \mapsto \mathbb{C}``
is defined by
``π X = \mathrm{tr}(X)``.
Note that the product
``π X``
is *not* a "matrix vector" product;
it is a linear operator acting on the matrix ``X``.
(Note that we use a
fancy
[unicode character](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols#Chart_for_the_Mathematical_Alphanumeric_Symbols_block)
``π`` here
just as a reminder that it is an operator;
in practical code we usually just use `A`.)
The `LinearMapsAA` package
can represent such an operator easily.
Here is the definition for ``N = 5``:
=#
N = 5
forw(X) = [tr(X)] # forward mapping function
π = LinearMapAA(forw, (1, N*N); idim = (N,N), odim = (1,))
#src B = LinearMapAA(X -> tr(X), (1, N*N); idim = (N,N), odim = ()) # fails
#=
The `idim` argument specifies
that the input is a matrix of size `N Γ N`
and
the `odim` argument specifies
that the output is vector of size `(1,)`.
=#
#=
One subtlety with this particular didactic example
is that the ordinary trace yields a scalar,
but
[`LinearMaps.jl`](https://github.com/JuliaLinearAlgebra/LinearMaps.jl)
is (understandably) designed exclusively
for mapping vectors to vectors,
so we use `[tr(X)]`
above so that the output is a 1-element `Vector`.
This behavior
is consistent with what happens
when one multiplies
a `1 Γ N` matrix with a vector in ``\mathbb{C}^N``.
=#
#=
Here is a verification
that applying this operator
to a matrix
produces the correct result:
=#
X = ones(5)*(1:5)'
π * X, tr(X), (N*(N+1))Γ·2
#=
Although
``π`` here
is *not* a matrix,
we can convert it to a matrix
(at least when ``N`` is sufficiently small)
to perhaps understand it better:
=#
A = Matrix(π)
A = Int8.(A) # just for nicer display
#=
The pattern of 0 and 1 elements
is more obvious
when reshaped:
=#
reshape(A, N, N)
#=
## Adjoint
Although this is largely a didactic example,
there are optimization problems
with
[trace constraints](https://www.optimization-online.org/DB_HTML/2018/08/6765.html)
of the form
``π X = b``.
To solve such problems,
often one would also need the
[adjoint](https://en.wikipedia.org/wiki/Adjoint)
of the operator
``π``.
Mathematically, and adjoint is a generalization
of the (Hermitian) transpose of a matrix.
For a (bounded) linear mapping ``π`` between
inner product space ``π³``
with inner product ``β¨ \cdot, \cdot \rangle_π³``
and inner product space ``π΄``
with inner product ``β¨ \cdot, \cdot \rangle_π΄,``
the adjoint of ``π``, denoted ``π'``,
is the unique bound linear mapping
that satisfies
``β¨ π x, y \rangle_π΄ = β¨ x, π' y \rangle_π³``
for all ``x β π³`` and ``y β π΄``.
Here, let
``π³`` denote the vector space of ``N Γ N`` matrices
with the
Frobenius inner product for matrices:
``β¨ A, B \rangle_π³ = \mathrm{tr}(A'B)``.
Let
``π΄``
simply be ``\mathbb{C}^1``
with the usual inner product
``β¨ x, y \rangle_π΄ = x_1^* y_1``.
With those definitions,
one can verify that the adjoint of
``π``
is the mapping
``π' c = c_1 \mathbf{I}_N``,
for ``c β \mathbb{C}^1``,
where
``\mathbf{I}_N``
denotes the
``N Γ N`` identity matrix.
Here is the `LinearMapAO`
that includes the adjoint:
=#
back(y) = y[1] * I(N) # remember `y` is a 1-vector
π = LinearMapAA(forw, back, (1, N*N); idim = (N,N), odim = (1,))
# Here is a verification that the adjoint is correct (very important!):
@assert Matrix(π)' == Matrix(π')
Int8.(Matrix(π'))
include("../../../inc/reproduce.jl")
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 3691 | #=
# [Operator example: FFT](@id 03-fft)
This page illustrates
the "linear operator" feature
of the Julia package
[`LinearMapsAA`](https://github.com/JeffFessler/LinearMapsAA.jl)
for the case of a multi-dimensional FFT operation.
=#
#srcURL
# ### Setup
# Packages needed here.
using LinearMapsAA
using FFTW: fft, bfft, fft!, bfft!
using MIRTjim: jim, prompt
using LazyGrids: btime
using BenchmarkTools: @benchmark
using InteractiveUtils: versioninfo
# The following line is helpful when running this file as a script;
# this way it will prompt user to hit a key after each figure is displayed.
isinteractive() ? jim(:prompt, true) : prompt(:draw);
#=
## Overview
A 1D N-point discrete Fourier transform (DFT)
is a linear operation
that is naturally represented as a `N Γ N` matrix.
The multi-dimensional DFT
is a linear mapping
that could be represented as a matrix,
using the `vec(β
)` of its arguments,
but it is more naturally represented
as a linear operator ``A``.
For 2D images of size ``M Γ N``,
we can think the DFT
as an operator
``A`` that maps a ``M Γ N`` matrix into a ``M Γ N`` matrix of DFT coefficients.
In other words,
``A : \mathbb{C}^{M Γ N} \mapsto \mathbb{C}^{M Γ N}``.
The `LinearMapsAA` package
can represent such an operator easily.
=#
#=
We first define appropriate forward and adjoint functions.
We use `fft!` and `bfft!` to avoid unnecessary memory allocations.
=#
forw!(y, x) = fft!(copyto!(y, x)) # forward mapping function
back!(x, y) = bfft!(copyto!(x, y)) # adjoint mapping function
#=
Below is the operator definition for ``(M,N) = (8,16)``.
Because FFT returns complex numbers, we must use `T=ComplexF32` here
for `LinearMaps` to work properly.
=#
M,N = 16,8
T = ComplexF32
A = LinearMapAA(forw!, back!, (M*N, M*N); idim = (M,N), odim = (M,N), T)
#=
The `idim` argument specifies
that the input is a matrix of size `M Γ N`
and
the `odim` argument specifies
that the output is a matrix of size `(M,N)`.
=#
#=
Here is some verification
that applying this operator
to a matrix
produces a correct result:
=#
X = ones(M,N)
@assert A * X β M*N * ((1:M) .== 1)*((1:N) .== 1)' # Kronecker impulse
X = rand(T, M, N)
@assert A * X β fft(X)
#=
Although
``A`` here is *not* a matrix,
we can convert it to a matrix
(at least when ``M N`` is sufficiently small)
to perhaps understand it better:
=#
Amat = Matrix(A)
using MIRTjim: jim
jim(
jim(real(Amat)', "Real(A)"; prompt=false),
jim(imag(Amat)', "Imag(A)"; prompt=false),
)
#=
## Adjoint
Here is a verification that the
[adjoint](https://en.wikipedia.org/wiki/Adjoint)
of the operator
``A``
is working correctly.
=#
@assert Matrix(A)' β Matrix(A')
#=
Some users
might wonder if there is "overhead"
in using the overloaded linear mapping `A * x`
or `mul!(y, A, x)`
compared to directly calling
`fft!(copyto!(y), x)`.
Here are some timing tests
that confirm that `LinearMapsAA` does not incur overhead.
We deliberately choose very small `M,N`,
because any overhead will be most apparent
when the `fft` computation itself is fast.
=#
x = rand(ComplexF32, M, N)
y1 = similar(x)
y2 = similar(x)
mul!(y1, A, x)
forw!(y2, x)
@assert y1 == y2
mul!(y1, A', x)
back!(y2, x)
@assert y1 == y2
# time forward fft:
timer(t) = btime(t; unit=:ΞΌs)
t = @benchmark forw!($y2, $x) # 19.1 us (31 alloc, 2K)
timer(t)
# compare to `LinearMapsAA` version:
t = @benchmark mul!($y1, $A, $x) # 18.1 us (44 alloc, 4K)
timer(t)
# time backward fft:
t = @benchmark back!($y2, $x) # 19.443 ΞΌs (31 allocations: 2.12 KiB)
timer(t)
# compare to `LinearMapsAA` version:
t = @benchmark mul!($y1, $(A'), $x) # 17.855 ΞΌs (44 allocations: 4.00 KiB)
timer(t)
include("../../../inc/reproduce.jl")
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 1008 | #=
example/cuda.jl
Verify that this package works with CUDA arrays.
(This code can run only on a system with a NVidia GPU.)
=#
using CUDA: cu
import CUDA: allowscalar
using FFTW: fft, bfft, fft!, bfft!
using LinearMapsAA: LinearMapAA
using LinearAlgebra: mul!
allowscalar(false) # ensure no scalar operations
N = 8
T = ComplexF32
A = LinearMapAA(fft, bfft, (N, N), (name="fft",); T)
@assert Matrix(A') == Matrix(A)' # test the adjoint
x = randn(T, N)
y = A * x
xc = cu(x)
yc = A * xc
@assert Array(yc) β y
bc = A' * yc
b = A' * y
@assert Array(bc) β b
M,N = 16,8
T = ComplexF32
forw!(y,x) = fft!(copyto!(y,x))
back!(x,y) = bfft!(copyto!(x,y))
B = LinearMapAA(forw!, back!, (N*M, N*M), (name="fft",); idim = (M,N), odim = (M,N), T)
@assert Matrix(B') == Matrix(B)'
# test fft
x = randn(T, M, N)
y = similar(x)
mul!(y, B, x)
xc = cu(x)
yc = similar(xc)
mul!(yc, B, xc)
@assert Array(yc) β y
# test bfft
b = similar(x)
mul!(b, B', y)
bc = similar(yc)
mul!(bc, B', yc)
@assert Array(bc) β b
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 1168 | # LinearMapsAA_LinearOperators.jl
# Wrap a LinearMapAA around a LinearOperator or vice-versa
module LinearMapsAA_LinearOperators
# extended here
import LinearMapsAA: LinearMapAA, LinearOperator_from_AA
using LinearMapsAA: LinearMapAX, mul!
using LinearOperators: LinearOperator
"""
A = LinearMapAA(L::LinearOperator ; kwargs...)
Wrap a `LinearOperator` in a `LinearMapAX`.
Options are passed to `LinearMapAA` constructor.
"""
function LinearMapAA(L::LinearOperator ; kwargs...)
forw!(y, x) = mul!(y, L, x)
back!(x, y) = mul!(x, L', y)
return LinearMapAA(forw!, back!, size(L); kwargs...)
end
"""
L = LinearOperator_from_AA(A::LinearMapAX; symmetric, Hermitian)
Wrap a `LinearOperator` around a `LinearMapAX`.
The options `symmetric` and `hermitian` are `false` by default.
"""
function LinearOperator_from_AA(
A::LinearMapAX;
symmetric::Bool = false,
hermitian::Bool = false,
)
forw!(y, x) = mul!(y, A, x)
back!(x, y) = mul!(x, A', y)
return LinearOperator(
eltype(A),
size(A)...,
symmetric, hermitian,
forw!,
nothing, # transpose mul!
back!,
)
end
end # module
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 493 | """
`module LinearMapsAA`
Provides `AbstractArray` (actually `AbstractMatrix`)
or "Ann Arbor" version of `LinearMap` objects
"""
module LinearMapsAA
export LinearMapAA, LinearMapAM, LinearMapAO, LinearMapAX
Indexer = AbstractVector{Int}
include("types.jl")
include("multiply.jl")
include("ambiguity.jl")
include("kron.jl")
include("cat.jl")
include("getindex.jl")
#include("setindex.jl")
include("block_diag.jl")
include("lm-aa.jl")
include("identity.jl")
include("exts.jl")
end # module
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 1219 | #=
ambiguity.jl
Avoiding method ambiguities
This may be a bit of a whack-a-moleβ’ exercise...
=#
import LinearAlgebra
const Trans = LinearAlgebra.Transpose{<: Any, <: LinearAlgebra.RealHermSymComplexSym}
const Adjoi = LinearAlgebra.Adjoint{<: Any, <: LinearAlgebra.RealHermSymComplexHerm}
Base.:(*)(A::LinearMapAM, D::LinearAlgebra.Diagonal) = AM_M(A, D)
Base.:(*)(D::LinearAlgebra.Diagonal, B::LinearMapAM,) = M_AM(D, B)
Base.:(*)(A::LinearMapAM, B::LinearAlgebra.AbstractTriangular) = AM_M(A, B)
Base.:(*)(A::LinearAlgebra.AbstractTriangular, B::LinearMapAM) = M_AM(A, B)
Base.:(*)(A::LinearMapAM, B::Trans) = AM_M(A, B)
Base.:(*)(A::Trans, B::LinearMapAM) = M_AM(A, B)
Base.:(*)(A::LinearMapAM, B::Adjoi) = AM_M(A, B)
Base.:(*)(A::Adjoi, B::LinearMapAM) = M_AM(A, B)
# see https://github.com/Jutho/LinearMaps.jl/issues/118
Base.:(*)(A::LinearMapAM,
B::LinearAlgebra.Adjoint{<: Any, <: LinearAlgebra.AbstractRotation}) =
throw("AbstractRotation lacks size so * is unsupported")
#Base.:(*)(A::Given, B::LinearMapAM) = M_AM(A, B)
Base.:(*)(x::LinearAlgebra.AdjointAbsVec, A::LinearMapAM) = (A' * x')'
Base.:(*)(x::LinearAlgebra.TransposeAbsVec, A::LinearMapAM) =
transpose(transpose(A) * transpose(x))
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 1379 | #=
block_diag.jl
Like SparseArrays:blockdiag but slightly different name, just to be safe,
because SparseArrays are also an AbstractArray type.
Motivated by compressed sensing dynamic MRI
where each frame has different k-space sampling
2020-06-08 Jeff Fessler
=#
export block_diag
import LinearMaps # BlockDiagonalMap
using SparseArrays: blockdiag, sparse
same_idim(As::LinearMapAX...) = all(map(A -> A._idim == As[1]._idim, As))
same_odim(As::LinearMapAX...) = all(map(A -> A._odim == As[1]._odim, As))
"""
B = block_diag(As::LinearMapAX... ; tryop::Bool)
Make block diagonal `LinearMapAX` object from blocks.
Return a `LinearMapAM` unless `tryop` and all blocks have same `idim` and `odim`.
Default for `tryop` is `true` if all blocks are type `LinearMapAO`.
"""
block_diag(As::LinearMapAO... ; tryop::Bool = true) = block_diag(tryop, As...)
block_diag(As::LinearMapAX... ; tryop::Bool = false) = block_diag(tryop, As...)
function block_diag(tryop::Bool, As::LinearMapAX...)
B = LinearMaps.BlockDiagonalMap(map(A -> A._lmap, As)...)
nblock = length(As)
prop = (nblock = nblock,)
if (tryop && nblock > 1 && same_idim(As...) && same_odim(As...)) # operator version
return LinearMapAA(B ; prop=prop,
idim = (As[1]._idim..., nblock),
odim = (As[1]._odim..., nblock),
)
end
return LinearMapAA(B, prop)
end
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 4364 | #=
cat.jl
Concatenation support for LinearMapAX
2018-01-19, Jeff Fessler, University of Michigan
=#
export lmaa_hcat, lmaa_vcat, lmaa_hvcat
using LinearAlgebra: UniformScaling, I
#=
function warndim(A::LinearMapAX)
((length(A._idim) > 1) || (length(A._odim) > 1)) && @warn("dim ignored")
nothing
end
=#
# cat (hcat, vcat, hvcat) are tricky for avoiding type piracy
# It is especially hard to handle AbstractMatrix,
# so typically force the user to wrap it in LinearMap(AX) first.
#LMcat{T} = Union{LinearMapAM{T}, LinearMap{T}, UniformScaling{T},AbstractMatrix{T}}
LMcat{T} = Union{LinearMapAX{T}, LinearMap{T}, UniformScaling{T}} # settle
#LMelse{T} = Union{LinearMap{T},UniformScaling{T},AbstractMatrix{T}} # non AM
# convert to something suitable for LinearMap.*cat
function lm_promote(A::LMcat)
# @show typeof(A)
A isa LinearMapAX ? A._lmap :
A isa UniformScaling ? A : # leave unchanged - ok for LinearMaps.*cat
A # otherwise it is this
# throw("bug") # should only be only of LMcat types
# A isa AbstractMatrix ? LinearMap(A) :
# A isa LinearMap ?
end
# single-letter codes for cat objects, e.g., [A I A] becomes "AIA"
lm_code(::LinearMapAM) = "A"
lm_code(::LinearMapAO) = "O"
lm_code(::UniformScaling) = "I"
lm_code(::LinearMap) = "L"
#lm_code(::AbstractMatrix) = "M"
#lm_code(::Any) = "?"
# concatenate the single-letter codes, e.g., [A I A] becomes "AIA"
lm_name = As -> *(lm_code.(As)...)
# lm_name = As -> nothing
# these rely on LinearMap.*cat methods
"`B = lmaa_hcat(A1, A2, ...)` `hcat` of multiple objects"
lmaa_hcat(As::LMcat...) =
LinearMapAA(hcat(lm_promote.(As)...), (hcat=lm_name(As),))
"`B = lmaa_vcat(A1, A2, ...)` `vcat` of multiple objects"
lmaa_vcat(As::LMcat...) =
LinearMapAA(vcat(lm_promote.(As)...), (vcat=lm_name(As),))
"`B = lmaa_hvcat(rows, A1, A2, ...)` `hvcat` of multiple objects"
lmaa_hvcat(rows::NTuple{nr,Int} where {nr}, As::LMcat...) =
LinearMapAA(hvcat(rows, lm_promote.(As)...), (hvcat=lm_name(As),))
# a single leading LinearMapAM followed by others is clear
Base.hcat(A1::LinearMapAX, As::LMcat...) =
lmaa_hcat(A1, As...)
Base.vcat(A1::LinearMapAX, As::LMcat...) =
lmaa_vcat(A1, As...)
Base.hvcat(rows::NTuple{nr,Int} where {nr}, A1::LinearMapAX, As::LMcat...) =
lmaa_hvcat(rows, A1, As...)
# or in 2nd position, beyond that, user can use lmaa_*
#Base.hcat(A1::LMelse, A2::LinearMapAM, As::LMcat...) = # fails!?
Base.hcat(A1::UniformScaling, A2::LinearMapAX, As::LMcat...) =
lmaa_hcat(A1, A2, As...)
Base.vcat(A1::UniformScaling, A2::LinearMapAX, As::LMcat...) =
lmaa_vcat(A1, A2, As...)
Base.hvcat(rows::NTuple{nr,Int} where nr,
A1::UniformScaling, A2::LinearMapAX, As::LMcat...) =
lmaa_hvcat(rows, A1, A2, As...)
# special handling for solely AO collections
function _hcat(tryop::Bool, As::LinearMapAO...)
B = LinearMaps.hcat(map(A -> A._lmap, As)...)
nblock = length(As)
prop = (nblock = nblock,)
if (tryop && nblock > 1 && same_idim(As...) && same_odim(As...)) # operator version
return LinearMapAA(B ; prop=prop,
idim = (As[1]._idim..., nblock),
odim = As[1]._odim,
)
end
return LinearMapAA(B ; prop=prop)
end
function _vcat(tryop::Bool, As::LinearMapAO...)
B = LinearMaps.vcat(map(A -> A._lmap, As)...)
nblock = length(As)
prop = (nblock = nblock,)
if (tryop && nblock > 1 && same_idim(As...) && same_odim(As...)) # operator version
return LinearMapAA(B ; prop=prop,
idim = As[1]._idim,
odim = (As[1]._odim..., nblock),
)
end
return LinearMapAA(B ; prop=prop)
end
"""
hcat(As::LinearMapAO... ; tryop::Bool=true)
`hcat` with (by default) attempt to append `nblock` to `idim` if consistent blocks.
"""
Base.hcat(A1::LinearMapAO, As::LinearMapAO... ; tryop::Bool=true) =
_hcat(tryop, A1, As...)
"""
vcat(As::LinearMapAO... ; tryop::Bool=true)
`vcat` with (by default) attempt to append `nblock` to `odim` if consistent blocks.
"""
Base.vcat(A1::LinearMapAO, As::LinearMapAO... ; tryop::Bool=true) =
_vcat(tryop, A1, As...)
"""
hvcat(rows, As::LinearMapAO...)
`hvcat` that discards special `idim` and `odim` information (too hard!) # todo?
"""
Base.hvcat(rows::NTuple{nr,Int} where nr,
A1::LinearMapAO, As::LinearMapAO...) =
lmaa_hvcat(rows, undim(A1), undim.(As)...)
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 150 | # exts.jl
# methods defined in the extension(s)
export LinearOperator_from_AA
LinearOperator_from_AA() = throw("First run `using LinearOperators`")
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 2296 | #=
getindex.jl
Indexing support for LinearMapAX
2018-01-19, Jeff Fessler, University of Michigan
=#
# As of v0.11, rely on getindex of LM, including its restrictions to slicing
Base.getindex(A::LinearMapAX, args...) = Base.getindex(A._lmap, args...)
#=
# [end]
function Base.lastindex(A::LinearMapAX)
return prod(size(A._lmap))
end
# [?,end] and [end,?]
function Base.lastindex(A::LinearMapAX, d::Int)
return size(A._lmap, d)
end
# A[i,j]
function Base.getindex(A::LinearMapAX, i::Int, j::Int)
T = eltype(A)
e = zeros(T, size(A._lmap,2)); e[j] = one(T)
tmp = A._lmap * e
return tmp[i]
end
# A[:,j]
# it is crucial to provide this function rather than to inherit from
# Base.getindex(A::AbstractArray, ::Colon, ::Int)
# because Base.getindex does this by iterating (I think).
function Base.getindex(A::LinearMapAX, ::Colon, j::Int)
T = eltype(A)
e = zeros(T, size(A,2)); e[j] = one(T)
return A._lmap * e
end
# A[ii,j]
Base.getindex(A::LinearMapAX, ii::Indexer, j::Int) = A[:,j][ii]
# A[i,jj]
Base.getindex(A::LinearMapAX, i::Int, jj::Indexer) = A[i,:][jj]
# A[:,jj]
# this one is also important for efficiency
Base.getindex(A::LinearMapAX, ::Colon, jj::AbstractVector{Bool}) =
A[:,findall(jj)]
Base.getindex(A::LinearMapAX, ::Colon, jj::Indexer) =
hcat([A[:,j] for j in jj]...)
# A[ii,:]
# trick: cannot use A' for a FunctionMap with no fc
function Base.getindex(A::LinearMapAX, ii::Indexer, ::Colon)
if (:fc in propertynames(A._lmap)) && isnothing(A._lmap.fc)
return hcat([A[ii,j] for j in 1:size(A,2)]...) # very slow!
else
return A'[:,ii]'
end
end
# A[ii,jj]
Base.getindex(A::LinearMapAX, ii::Indexer, jj::Indexer) = A[:,jj][ii,:]
# A[k]
function Base.getindex(A::LinearMapAX, k::Int)
c = CartesianIndices(size(A._lmap))[k] # is there a more elegant way?
return A[c[1], c[2]]
end
# A[kk]
Base.getindex(A::LinearMapAX, kk::AbstractVector{Bool}) = A[findall(kk)]
Base.getindex(A::LinearMapAX, kk::Indexer) = [A[k] for k in kk]
# A[i,:]
# trick: one row slice returns a 1D ("column") vector
Base.getindex(A::LinearMapAX, i::Int, ::Colon) = A[[i],:][:]
# A[:,:] = Matrix(A)
Base.getindex(A::LinearMapAX, ::Colon, ::Colon) = Matrix(A._lmap)
# A[:]
Base.getindex(A::LinearMapAX, ::Colon) = A[:,:][:]
=#
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 327 | # identity.jl
import LinearAlgebra: UniformScaling
"""
*(I, X) = X
*(J, X) = J.Ξ» * X
Extends the effect of `I::UniformScaling` and scaled versions thereof
to also apply to `X::AbstractArray` instead of just to `Vector` and `Matrix` types.
"""
Base.:(*)(J::UniformScaling, X::AbstractArray) = J.Ξ» == 1 ? X : J.Ξ» * X
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 1596 | #=
kron.jl
Kronecker product
2018-01-19, Jeff Fessler, University of Michigan
=#
# export LinearMapAA_test_kron # testing
using LinearAlgebra: I, Diagonal
# kron (requires LM 2.6.0)
"""
kron(A::LinearMapAX, M::AbstractMatrix)
kron(M::AbstractMatrix, A::LinearMapAX)
kron(A::LinearMapAX, B::LinearMapAX)
Kronecker products
Returns a `LinearMapAO` with appropriate `idim` and `odim`
if either argument is a `LinearMapAO`
else returns a `LinearMapAM`
"""
Base.kron(A::LinearMapAM, M::AbstractMatrix) =
LinearMapAA(kron(A._lmap, M), A._prop)
Base.kron(M::AbstractMatrix, A::LinearMapAM) =
LinearMapAA(kron(M, A._lmap), A._prop)
Base.kron(A::LinearMapAM, D::Diagonal{<: Number}) =
LinearMapAA(kron(A._lmap, D), A._prop)
Base.kron(D::Diagonal{<: Number}, A::LinearMapAM) =
LinearMapAA(kron(D, A._lmap), A._prop)
Base.kron(A::LinearMapAM, B::LinearMapAM) =
LinearMapAA(kron(A._lmap, B._lmap) ;
prop = (kron=nothing, props=(A._prop, B._prop)),
)
Base.kron(A::LinearMapAO, B::LinearMapAO) =
LinearMapAA(kron(A._lmap, B._lmap) ;
prop = (kron=nothing, props=(A._prop, B._prop)),
odim = (B._odim..., A._odim...),
idim = (B._idim..., A._idim...),
)
Base.kron(M::AbstractMatrix, A::LinearMapAO) =
LinearMapAA(kron(M, A._lmap) ; prop = A._prop,
odim = (A._odim..., size(M,1)),
idim = (A._idim..., size(M,2)),
)
Base.kron(A::LinearMapAO, M::AbstractMatrix) =
LinearMapAA(kron(A._lmap, M) ; prop = A._prop,
odim = (size(M,1), A._odim...),
idim = (size(M,2), A._idim...),
)
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 4198 | #=
lm-aa
Core methods for LinearMapAA objects.
2019-08-07 Jeff Fessler, University of Michigan
=#
using LinearMaps: LinearMap
using LinearAlgebra: UniformScaling, I
import LinearAlgebra: issymmetric, ishermitian, isposdef
#import LinearAlgebra: mul! #, lmul!, rmul!
import SparseArrays: sparse
export redim, undim
# Matrix
Base.Matrix(A::LinearMapAX) = Matrix(A._lmap)
# ndims
# Base.ndims(A::LinearMapAX) = ndims(A._lmap) # 2 for AbstractMatrix
Base.ndims(A::LinearMapAO) = ndims(A._lmap) # 2
"""
show(io::IO, A::LinearMapAX)
show(io::IO, ::MIME"text/plain", A::LinearMapAX)
Pretty printing for `display`
"""
function Base.show(io::IO, A::LinearMapAX) # short version
print(io, isa(A, LinearMapAM) ? "LinearMapAM" : "LinearMapAO",
": $(size(A,1)) Γ $(size(A,2))")
end
# multi-line version:
function Base.show(io::IO, ::MIME"text/plain", A::LinearMapAX{T,Do,Di}) where {T,Do,Di}
show(io, A)
print(io, " odim=$(A._odim) idim=$(A._idim) T=$T Do=$Do Di=$Di")
(A._prop != NamedTuple()) && (print(io, "\nprop = "); show(io, A._prop))
print(io, "\nmap = $(A._lmap)\n")
end
# size
Base.size(A::LinearMapAX) = size(A._lmap)
Base.size(A::LinearMapAX, d::Int) = size(A._lmap, d)
"""
redim(A::LinearMapAX ; idim::Dims=A._idim, odim::Dims=A._odim)
"Reinterpret" the `idim` and `odim` of `A`
"""
function redim(A::LinearMapAX{T} ;
idim::Dims=A._idim, odim::Dims=A._odim) where {T}
prod(idim) == prod(A._idim) || throw("incompatible idim")
prod(odim) == prod(A._odim) || throw("incompatible odim")
return LinearMapAA(A._lmap ; prop=A._prop, T=T, idim=idim, odim=odim)
end
"""
undim(A::LinearMapAX)
"Reinterpret" the `idim` and `odim` of `A` to be of AM type
"""
undim(A::LinearMapAX{T}) where {T} =
LinearMapAA(A._lmap ; prop=A._prop, T=T)
# adjoint
Base.adjoint(A::LinearMapAX) = LinearMapAA(adjoint(A._lmap) ;
prop=A._prop, idim=A._odim, odim=A._idim, operator=isa(A,LinearMapAO))
# transpose
Base.transpose(A::LinearMapAX) = LinearMapAA(transpose(A._lmap) ;
prop=A._prop, idim=A._odim, odim=A._idim, operator=isa(A,LinearMapAO))
# eltype
Base.eltype(A::LinearMapAX) = eltype(A._lmap)
# LinearMap algebraic properties
issymmetric(A::LinearMapAX) = issymmetric(A._lmap)
#ishermitian(A::LinearMapAX{<:Real}) = issymmetric(A._lmap)
ishermitian(A::LinearMapAX) = ishermitian(A._lmap)
isposdef(A::LinearMapAX) = isposdef(A._lmap)
# comparison of LinearMapAX objects, sufficient but not necessary
Base.:(==)(A::LinearMapAX, B::LinearMapAX) =
eltype(A) == eltype(B) &&
A._lmap == B._lmap && A._prop == B._prop &&
A._idim == B._idim && A._odim == B._odim
# convert to sparse
sparse(A::LinearMapAX) = sparse(A._lmap)
# add or subtract objects (with compatible idim,odim)
function Base.:(+)(A::LinearMapAX, B::LinearMapAX)
(A._idim != B._idim) && throw("idim mismatch in +")
(A._odim != B._odim) && throw("odim mismatch in +")
LinearMapAA(A._lmap + B._lmap ;
idim=A._idim, odim=A._odim,
prop = (sum=nothing,props=(A._prop,B._prop)),
operator = isa(A, LinearMapAO) & isa(B, LinearMapAO),
)
end
# Allow LMAA + AM only if Do=Di=1
function Base.:(+)(A::LinearMapAX, B::AbstractMatrix)
(length(A._idim) != 1 || length(A._odim) != 1) && throw("use redim")
LinearMapAA(A._lmap + LinearMap(B) ; prop=A._prop,
operator = isa(A, LinearMapAO),
)
end
# But allow LMAA + I for any Do,Di
Base.:(+)(A::LinearMapAX, B::UniformScaling) = # A + I -> A + I(N)
LinearMapAA(A._lmap + B(size(A,2)) ;
prop = (Aprop=A._prop, Iscale=B(size(A,2))[1]),
idim = A._idim,
odim = A._odim,
operator = isa(A, LinearMapAO),
)
Base.:(+)(A::AbstractMatrix, B::LinearMapAX) = B + A
Base.:(-)(A::LinearMapAX, B::LinearMapAX) = A + (-1)*B
Base.:(-)(A::LinearMapAX, B::AbstractMatrix) = A + (-1)*B
Base.:(-)(A::AbstractMatrix, B::LinearMapAX) = A + (-1)*B
# A.?
Base.getproperty(A::LinearMapAX, s::Symbol) =
(s in LMAAkeys) ? getfield(A, s) :
# s == :m ? size(A._lmap, 1) :
haskey(A._prop, s) ? getfield(A._prop, s) :
throw("unknown key $s")
Base.propertynames(A::LinearMapAX) = (propertynames(A._prop)..., LMAAkeys...)
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 7884 | #=
multiply.jl
Multiplication of a LinearMapAX object with other things
2020-06-16 add 5-arg mul!
2020-06-27 Jeff Fessler
=#
export mul!
using LinearMaps
using LinearAlgebra: UniformScaling, I
import LinearAlgebra: mul! #, lmul!, rmul!
#import LinearAlgebra # AdjointAbsVec
# multiply with I or s*I (identity or scaled identity)
Base.:(*)(A::LinearMapAX, B::UniformScaling{Bool}) = B.Ξ» ? A : (A * B.Ξ»)
Base.:(*)(A::LinearMapAX, B::UniformScaling) = (B.Ξ» == 1) ? A : (A * B.Ξ»)
Base.:(*)(B::UniformScaling{Bool}, A::LinearMapAX) = B.Ξ» ? A : (B.Ξ» * A)
Base.:(*)(B::UniformScaling, A::LinearMapAX) = (B.Ξ» == 1) ? A : (B.Ξ» * A)
# multiply with scalars
Base.:(*)(s::Number, A::LinearMapAX) =
LinearMapAA((s*I) * A._lmap ; prop=A._prop, idim=A._idim, odim=A._odim,
operator = isa(A, LinearMapAO))
Base.:(*)(A::LinearMapAX, s::Number) =
LinearMapAA(A._lmap * (s*I) ; prop=A._prop, idim=A._idim, odim=A._odim,
operator = isa(A, LinearMapAO))
# multiply LMAX objects, if compatible
Base.:(*)(A::LinearMapAO{Ta,Do,D}, B::LinearMapAO{Tb,D,Di}) where {Ta,Tb,Do,D,Di} =
lm_obj_mul(A, B)
Base.:(*)(A::LinearMapAO{T,Do,1}, B::LinearMapAM) where {T,Do} = lm_obj_mul(A, B)
Base.:(*)(A::LinearMapAM, B::LinearMapAO{T,1,Di}) where {T,Di} = lm_obj_mul(A, B)
Base.:(*)(A::LinearMapAM, B::LinearMapAM) = lm_obj_mul(A, B)
function lm_obj_mul(A::LinearMapAX, B::LinearMapAX)
(A._idim != B._odim) && throw("dim mismatch")
LinearMapAA(A._lmap * B._lmap ;
prop = (prod=(A._prop,B._prop),),
idim = B._idim, odim = A._odim,
operator = isa(A, LinearMapAO) | isa(B, LinearMapAO),
)
end
# multiply with a matrix
# subtle: AM * Matrix and Matrix * AM yield a new AM
# whereas AO * M and M * AO yield a matrix of numbers!
function AM_M(A::LinearMapAM, B::AbstractMatrix{<:Number})
(A._idim == (size(B,1),)) || throw("$(A._idim) * $(size(B,1)) mismatch")
LinearMapAA(A._lmap * LinearMap(B) ; prop=A._prop, odim=A._odim)
end
function M_AM(A::AbstractMatrix{<:Number}, B::LinearMapAM)
(B._odim == (size(A,2),)) || throw("$(B._odim) * $(size(A,1)) mismatch")
LinearMapAA(LinearMap(A) * B._lmap ; prop=B._prop, idim=B._idim)
end
Base.:(*)(A::LinearMapAM, B::AbstractMatrix{<:Number}) = AM_M(A, B)
Base.:(*)(A::AbstractMatrix{<:Number}, B::LinearMapAM) = M_AM(A, B)
# LMAM case is easy!
# multiply with vectors (in-place)
# pass to lmam_mul! to handle composite maps (products) effectively
# 5-arg mul! requires julia 1.3 or later
# mul!(y, A, x, Ξ±, Ξ²) β‘ y .= A*(Ξ±*x) + Ξ²*y
mul!(y::AbstractVector, A::LinearMapAM, x::AbstractVector) =
lm_mul!(y, A._lmap, x, 1, 0)
# mul!(y, A._lmap, x)
mul!(y::AbstractVector, A::LinearMapAM, x::AbstractVector, Ξ±::Number, Ξ²::Number) =
lm_mul!(y, A._lmap, x, Ξ±, Ξ²)
# mul!(y, A._lmap, x, Ξ±, Ξ²)
# treat LinearMaps.CompositeMap as special case for in-place operations
function lm_mul!(y::AbstractVector{<:Number}, Lm::LinearMaps.CompositeMap,
x::AbstractVector{<:Number}, Ξ±::Number, Ξ²::Number)
LinearMaps.mul!(y, Lm, x, Ξ±, Ξ²) # todo: composite buffer
end
# 5-arg mul! for any other type
lm_mul!(y::AbstractVector{<:Number}, Lm::LinearMap,
x::AbstractVector{<:Number}, Ξ±::Number, Ξ²::Number) =
LinearMaps.mul!(y, Lm, x, Ξ±, Ξ²)
# with array
#=
these are unused because AM * array becomes a new AM
mul!(Y::AbstractArray, A::LinearMapAM, X::AbstractArray, Ξ±::Number, Ξ²::Number) =
lmao_mul!(Y, A._lmap, X, Ξ±, Ξ² ; idim=A._idim, odim=A._odim)
mul!(Y::AbstractArray, A::LinearMapAM, X::AbstractArray) =
LinearMapsAA.mul!(Y, A, X, 1, 0)
=#
# LMAO case
# 3-arg O*X
mul!(Y::AbstractArray, A::LinearMapAO, X::AbstractArray) =
mul!(Y, A, X, 1, 0)
# 3-arg X*O
mul!(Y::AbstractArray, X::AbstractArray, A::LinearMapAO) =
mul!(Y, X, A, 1, 0)
# 5-arg O*X
mul!(Y::AbstractArray, A::LinearMapAO, X::AbstractArray, Ξ±::Number, Ξ²::Number) =
lmao_mul!(Y, A._lmap, X, Ξ±, Ξ² ; idim=A._idim, odim=A._odim)
# 5-arg X*O (todo: test complex case)
mul!(Y::AbstractArray, X::AbstractArray, A::LinearMapAO, Ξ±::Number, Ξ²::Number) =
lmao_mul!(Y, A._lmap', X, Ξ±, Ξ² ; idim=A._odim, odim=A._idim) # note!
"""
lmao_mul!(Y, A, X, Ξ±, Ξ² ; idim, odim)
Core routine for 5-arg multiply.
If `A._idim = (2,3,4)` and `A._odim = (5,6)` and
if input `X` has size `(2,3,4, 7,8)`
then output `Y` will have size `(5,6, 7,8)`
"""
function lmao_mul!(Y::AbstractArray, Lm::LinearMap, X::AbstractArray,
Ξ±::Number, Ξ²::Number ;
idim = (size(Lm,2),),
odim = (size(Lm,1),),
)
Di = length(idim)
Do = length(odim)
(Di > ndims(X) || (idim != size(X)[1:Di])) &&
throw("idim=$(idim) vs size(RHS)=$(size(X))")
(Do > ndims(Y) || (odim != size(Y)[1:Do])) &&
throw("odim=$(odim) vs size(LHS)=$(size(Y))")
size(X)[(Di+1):end] == size(Y)[(Do+1):end] ||
throw("size(LHS)=$(size(Y)) vs size(RHS)=$(size(X))")
x = reshape(X, prod(idim), :)
y = reshape(Y, prod(odim), :)
K = size(x,2)
size(y,2) == K || throw("mismatch $(size(y,2)) K=$K")
for k=1:K
xk = selectdim(x,2,k)
yk = selectdim(y,2,k)
lm_mul!(yk, Lm, xk, Ξ±, Ξ²)
end
return Y
end
"""
mul!(yv, AO::LinearMapAO, xv, Ξ±, Ξ²)
Fancy 5-arg multiply when `yv` and `xv` are each a `Vector` of AbstractArrays.
Basically does `mul!(yv[i], A, xv[i], Ξ±, Ξ²)` for `i in 1:length(xv)`.
"""
Base.@propagate_inbounds function mul!(
yv::AbstractVector{<:AbstractArray},
A::LinearMapAO,
xv::AbstractVector{<:AbstractArray},
Ξ±::Number, Ξ²::Number
)
@boundscheck (length(xv) == length(yv) ||
throw("vector length mismatch $(length(xv)) $(length(yv))"))
for i in 1:length(xv)
@inbounds mul!(yv[i], A, xv[i], Ξ±, Ξ²)
end
return yv
end
"""
*(A::LinearMapAO, xv::AbstractVector{<:AbstractArray}) = [A * x for x in xv]
Fancy multiply when `xv` is a `Vector` of `AbstractArray`s of appropriate size.
"""
Base.:(*)(A::LinearMapAO, xv::AbstractVector{<:AbstractArray}) = [A * x for x in xv]
# multiply by array, with allocation
Base.:(*)(A::LinearMapAO, X::AbstractArray) = lmax_mul(A, X)
Base.:(*)(X::AbstractArray, A::LinearMapAO) = lmax_mul(A', X) # note!
#=
# this next line caused ambiguous method errors:
# Base.:(*)(A::LinearMapAM, X::AbstractArray) = lmax_mul(A, X)
# so i resort to this awful kludge:
Base.:(*)(A::LinearMapAM, X::AbstractArray{T,4}) where {T} = lmax_mul(A, X)
nah, too difficult, so revert to the AM*M returning an object, per above
=#
function lmax_mul(A::LinearMapAX{T}, X::AbstractArray{<:Number}) where {T}
Di = length(A._idim)
Do = length(A._odim)
(Di > ndims(X) || (A._idim != size(X)[1:Di])) &&
throw("idim=$(A._idim) vs size(RHS)=$(size(X))")
extra = size(X)[(Di+1):end]
Ty = promote_type(T, eltype(X))
Y = similar(X, Ty, A._odim..., extra...) # allocate
lmao_mul!(Y, A._lmap, X, 1, 0; idim=A._idim, odim=A._odim)
end
# multiply with vector
# O*v
Base.:(*)(A::LinearMapAO{T,Do,1}, v::AbstractVector{<:Number}) where {T,Do} =
reshape(A._lmap * v, A._odim)
# u'*O (no, use general X*O above because unclear what this would mean)
#Base.:(*)(u::LinearAlgebra.AdjointAbsVec, A::LinearMapAO) =
# reshape(A._lmap' * u', A._idim)
# A*v
Base.:(*)(A::LinearMapAM, v::AbstractVector{<:Number}) =
A._lmap * v
# u'*A (nah, not worth it)
#Base.:(*)(u::LinearAlgebra.AdjointAbsVec, A::LinearMapAM) =
# (A._lmap' * u')'
#= bad kludge
LMAAmanyFromOne = Union{
LinearMapAA{T,2,1},
LinearMapAA{T,3,1},
LinearMapAA{T,4,1},
} where {T}
Base.:(*)(A::LMAAmanyFromOne, v::AbstractVector{<:Number}) where {T} =
reshape(A._lmap * v, A._odim)
Base.:(*)(A::LinearMapAA, v::AbstractVector{<:Number}) where {T} =
reshape(A._lmap * v, A._odim)
=#
#= these are pointless; see multiplication with scalars above
lmul!(s::Number, A::LinearMapAA) = lmul!(s, A._lmap)
rmul!(A::LinearMapAA, s::Number) = rmul!(A._lmap, s)
=#
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 5035 | #=
types.jl
Types and constructors for LinearMapAA objects.
2026-06-27 Jeff Fessler, University of Michigan
=#
using LinearMaps: LinearMap
LMAAkeys = (:_lmap, :_prop, :_idim, :_odim) # reserved
"""
struct LinearMapAM{T,Do,Di,LM,P} <: AbstractMatrix{T}
"matrix" version that is quite akin to a matrix in its behavior
"""
struct LinearMapAM{T,Do,Di,LM,P} <: AbstractMatrix{T}
_lmap::LM # "L"
_prop::P # user-defined "named properties" accessible via A.name
_idim::Dims{Di} # "input" dimensions, always (size(L,2),)
_odim::Dims{Do} # "output" dimensions, always (size(L,1),)
end
"""
struct LinearMapAO{T,Do,Di,LM,P}
"Tensor" version that can map from arrays to arrays.
(It is not a subtype of `AbstractArray`.)
"""
struct LinearMapAO{T,Do,Di,LM,P} # LM <: LinearMap, P <: NamedTuple
_lmap::LM # "L"
_prop::P # user-defined "named properties" accessible via A.name
_idim::Dims{Di} # "input" dimensions, often (size(L,2),)
_odim::Dims{Do} # "output" dimensions, often (size(L,1),)
end
"""
struct LinearMapAX{T,Do,Di,LM,P}
Union of `LinearMapAM` and `LinearMapAO`
because most operations apply to both AM and AO types.
* `T` : `eltype`
* `Do` : output dimensionality
* `Di` : input dimensionality
* `LM` : `LinearMap` type
* `P` : `NamedTuple` type
"""
LinearMapAX{T,Do,Di,LM,P} =
Union{
LinearMapAM{T,Do,Di,LM,P},
LinearMapAO{T,Do,Di,LM,P},
} where {T,Do,Di,LM,P}
# constructors
"""
B = LinearMapAO(A::LinearMapAX)
Make an AO from an AM, despite `idim` and `odim` being 1D,
for expert users who want `B*X` to be an `Array`.
Somewhat an opposite of `undim`.
"""
LinearMapAO(A::LinearMapAX{T,Do,Di,LM,P}) where {T,Do,Di,LM,P} =
LinearMapAO{T,Do,Di,LM,P}(A._lmap, A._prop, A._idim, A._odim)
"""
A = LinearMapAA(L::LinearMap ; ...)
Constructor for `LinearMapAM` or `LinearMapAO` given a `LinearMap`.
# Options
- `prop::NamedTuple = NamedTuple()`;
cannot include the fields `_lmap`, `_prop`, `_idim`, `_odim`
- `T::Type = eltype(L)`
- `idim::Dims = (size(L,2),)`
- `odim::Dims = (size(L,1),)`
- `operator::Bool` by default: `false` if both `idim` & `odim` are 1D.
Output `A` is `LinearMapAO` if `operator` is `true`, else `LinearMapAM`.
"""
function LinearMapAA(
L::LM ;
prop::P = NamedTuple(),
T::Type{<:Number} = eltype(L),
idim::Dims{Di} = (size(L,2),),
odim::Dims{Do} = (size(L,1),),
operator::Bool = length(idim) > 1 || length(odim) > 1,
) where {Di, Do, LM <: LinearMap, P <: NamedTuple}
size(L,2) == prod(idim) ||
throw(DimensionMismatch("size2=$(size(L,2)) vs idim=$idim"))
size(L,1) == prod(odim) ||
throw(DimensionMismatch("size1=$(size(L,1)) vs odim=$odim"))
length(intersect(propertynames(prop), LMAAkeys)) > 0 &&
throw("invalid property field among $(propertynames(prop))")
return operator ?
LinearMapAO{T,Do,Di,LM,P}(L, prop, idim, odim) :
LinearMapAM{T,Do,Di,LM,P}(L, prop, idim, odim)
end
# for backwards compatibility:
LinearMapAA(L, prop::NamedTuple ; kwargs...) =
LinearMapAA(L::LinearMap ; prop, kwargs...)
"""
A = LinearMapAA(L::AbstractMatrix ; ...)
Constructor given an `AbstractMatrix`.
"""
LinearMapAA(L::AbstractMatrix ; kwargs...) =
LinearMapAA(LinearMap(L) ; kwargs...)
_ismutating(f) = first(methods(f)).nargs == 3
"""
A = LinearMapAA(f::Function, fc::Function, D::Dims{2} [, prop::NamedTuple)]
; T::Type = Float32, idim::Dims, odim::Dims)
Constructor given forward `f` and adjoint function `fc`.
"""
function LinearMapAA(
f::Function,
fc::Function,
D::Dims{2} ;
T::Type{<:Number} = Float32,
idim::Dims = (D[2],),
odim::Dims = (D[1],),
kwargs...,
)
if idim == (D[2],) && odim == (D[1],)
fnew = f
fcnew = fc
else
fnew = _ismutating(f) ?
(y,x) -> f(reshape(y,odim), reshape(x,idim)) :
x -> reshape(f(reshape(x,idim)), odim)
fcnew = _ismutating(fc) ?
(x,y) -> fc(reshape(x,idim), reshape(y,odim)) :
y -> reshape(fc(reshape(y,odim)), idim)
end
LinearMapAA(LinearMap{T}(fnew, fcnew, D[1], D[2]) ;
idim=idim, odim=odim, kwargs...)
end
LinearMapAA(f::Function, fc::Function, D::Dims{2}, prop::NamedTuple ; kwargs...) =
LinearMapAA(f, fc, D ; prop=prop, kwargs...)
"""
A = LinearMapAA(f::Function, D::Dims{2} [, prop::NamedTuple]; kwargs...)
Constructor given just forward function `f`.
"""
function LinearMapAA(f::Function, D::Dims{2} ;
T::Type{<:Number} = Float32,
idim::Dims = (D[2],),
odim::Dims = (D[1],),
kwargs...,
)
if idim == (D[2],) && odim == (D[1],)
fnew = f
else
fnew = _ismutating(f) ?
(y,x) -> f(reshape(y,odim), reshape(x,idim)) :
x -> reshape(f(reshape(x,idim)), odim)
end
LinearMapAA(LinearMap{T}(fnew, D[1], D[2]) ;
idim=idim, odim=odim, kwargs...)
end
LinearMapAA(f::Function, D::Dims{2}, prop::NamedTuple ; kwargs...) =
LinearMapAA(f, D ; prop=prop, kwargs...)
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 1841 | # ambiguity.jl
# tests needed only because of code added to resolve method ambiguities
using LinearAlgebra: Diagonal, UpperTriangular
using LinearAlgebra: Adjoint, Transpose, Symmetric
using LinearAlgebra: TransposeAbsVec, AdjointAbsVec
using LinearAlgebra: givens
import LinearAlgebra
using LinearMapsAA: LinearMapAA
using Test: @test, @testset, @test_throws
M = rand(2,2)
A = LinearMapAA(M)
@testset "Diagonal" begin
D = Diagonal(1:2)
@test Matrix(A * D) == M * D
@test Matrix(D * A) == D * M
end
@testset "UpperTri" begin
U = UpperTriangular(M)
@test Matrix(A * U) β M * U
@test Matrix(U * A) β U * M
end
@testset "TransposeVec" begin
xt = Transpose(1:2)
@test xt isa TransposeAbsVec
@test xt * M β xt * A
end
@testset "AdjointVec" begin
r = Adjoint(1:2)
@test r isa AdjointAbsVec
@test r * M β r * A
end
@testset "Transpose" begin
# work-around per
# https://github.com/Jutho/LinearMaps.jl/issues/147
LinearAlgebra.isposdef(A::Transpose) = LinearAlgebra.isposdef(parent(A))
S = LinearAlgebra.Symmetric(M)
T = LinearAlgebra.Transpose(S)
@test Matrix(A * T) β M * T # failed prior to isposdef overload
@test Matrix(T * A) β T * M
end
@testset "Adjoint" begin
C = rand(ComplexF32, 2, 2)
H = LinearAlgebra.Hermitian(C)
J = Adjoint(H)
LinearAlgebra.isposdef(A::Adjoint) = LinearAlgebra.isposdef(parent(A))
@test Matrix(A * J) β M * J
@test Matrix(J * A) β J * M
end
@testset "AbsRot" begin
G, _ = givens(1., 2., 3, 4)
R = LinearAlgebra.Rotation([G, G])
AR = adjoint(R); # semicolon needed, otherwise "show" error!
# size(AR) # fails because AR is size-less and not an AbstractMatrix
AR isa Adjoint{<:Any,<:LinearAlgebra.AbstractRotation} # true
# ones(4,4) * AR # works
@test_throws DimensionMismatch A * AR
end
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 957 | # block_diag.jl
# test
using LinearMapsAA: LinearMapAA, LinearMapAM, LinearMapAO, block_diag
using SparseArrays: blockdiag, sparse
using Test: @test, @testset
M1 = rand(3,2)
M2 = rand(5,4)
M = [M1 zeros(size(M1,1),size(M2,2));
zeros(size(M2,1),size(M1,2)) M2]
A1 = LinearMapAA(M1) # WrappedMap
A2 = LinearMapAA(x -> M2*x, y -> M2'y, size(M2), T=eltype(M2)) # FunctionMap
B = block_diag(A1, A2)
@testset "block_diag for AM" begin
@test Matrix(B) == M
@test Matrix(B)' == Matrix(B')
end
# test LMAO
@testset "block_diag for AO" begin
Ao = LinearMapAA(M2 ; odim=(1,5))
@test block_diag(A1, A1) isa LinearMapAM
@test block_diag(A1, A1 ; tryop=true) isa LinearMapAO
@test block_diag(A1, Ao) isa LinearMapAM
Bo = block_diag(Ao, Ao)
@test Bo isa LinearMapAO
Md = blockdiag(sparse(M2), sparse(M2))
X = rand(4,2)
Yo = Bo * X
Yd = Md * vec(X)
@test vec(Yo) β Yd
@test Matrix(Bo)' == Matrix(Bo')
end
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 5189 | # cat.jl
# test
using LinearMaps: LinearMap
using LinearMapsAA: LinearMapAA, LinearMapAM, LinearMapAO, LinearMapAX
using LinearMapsAA: redim, undim
using LinearAlgebra: I
using Test: @test, @testset
# test
#=
this approach using eval() works only in the global scope!
N = 6
forw = x -> [cumsum(x); 0] # non-square to stress test
back = y -> reverse(cumsum(reverse(y[1:N])))
prop = (name="cumsum", extra=1)
A = LinearMapAA(forw, back, (N+1, N), prop)
list1 = [
:([A I]), :([I A]), :([2*A 3*A]),
:([A; I]), :([I; A]), :([2*A; 3*A]),
:([A A I]), :([A I A]), :([2*A 3*A 4*A]),
:([A; A; I]), :([A; I; A]), :([2*A; 3*A; 4*A]),
:([I A I]), :([I A A]),
:([I; A; I]), :([I; A; A]),
# :([I I A]), :([I; I; A]), # unsupported
:([A A; A A]), :([A I; 2A 3I]), :([I A; 2I 3A]),
# :([I A; A I]), :([A I; I A]), # weird sizes
:([A I A; 2A 3I 4A]), :([I A I; 2I 3A 4I]),
# :([A I A; I A A]), :([I A 2A; 3A 4I 5A]), # weird
# :([I I A; I A I]), # unsupported
:([A A I; 2A 3A 4I]),
:([A I I; 2A 3I 4I]),
]
M = Matrix(A)
list2 = [
:([M I]), :([I M]), :([2*M 3*M]),
:([M; I]), :([I; M]), :([2*M; 3*M]),
:([M M I]), :([M I M]), :([2*M 3*M 4*M]),
:([M; M; I]), :([M; I; M]), :([2*M; 3*M; 4*M]),
:([I M I]), :([I M M]),
:([I; M; I]), :([I; M; M]),
# :([I I M]), :([I; I; M]), # unsupported
:([M M; M M]), :([M I; 2M 3I]), :([I M; 2I 3M]),
# :([I M; M I]), :([M I; I M]), # weird sizes
:([M I M; 2M 3I 4M]), :([I M I; 2I 3M 4I]),
# :([M I M; I M M]), :([I M 2M; 3M 4I 5M]), # weird
# :([I I M; I M I]), # unsupported
:([M M I; 2M 3M 4I]),
:([M I I; 2M 3I 4I]),
]
length(list1) != length(list2) && throw("bug")
for ii in 1:length(list1)
e1 = list1[ii]
b1 = eval(e1)
e2 = list2[ii]
b2 = eval(e2)
@test b1 isa LinearMapAX
end
=#
"""
LinearMapAA_test_cat(A::LinearMapAM)
test hcat vcat hvcat
"""
function LinearMapAA_test_cat(A::LinearMapAM)
Lm = LinearMap{eltype(A)}(x -> A*x, y -> A'*y, size(A,1), size(A,2))
M = Matrix(A)
# LinearMaps supports *cat of LM and UniformScaling only in v2.6.1
# but see: https://github.com/Jutho/LinearMaps.jl/pull/71
# B0 = [M Lm] # fails!
#=
# cannot get cat with AbstractMatrix to work
M1 = reshape(1:35, N+1, N-1)
H2 = [A M1]
@test H2 isa LinearMapAX
@test Matrix(H2) == [Matrix(A) H2]
H1 = [M1 A]
@test H1 isa LinearMapAX
@test Matrix(H1) == [M1 Matrix(A)]
M2 = reshape(1:(3*N), 3, N)
V1 = [M2; A]
@test V1 isa LinearMapAX
@test Matrix(V1) == [M2; Matrix(A)]
V2 = [A; M2]
@test V2 isa LinearMapAX
@test Matrix(V2) == [Matrix(A); M2]
=#
fun0 = A -> [
[A I], [I A], [2A 3A],
[A; I], [I; A], [2A; 3A],
[A A I], [A I A], [2A 3A 4A],
[A; A; I], [A; I; A], [2A; 3A; 4A],
[I A I], [I A A],
[I; A; I], [I; A; A],
# [I I A], [I; I; A], # unsupported
[A A; A A], [A I; 2A 3I], [I A; 2I 3A],
# [I A; A I], [A I; I A], # weird sizes
[A I A; 2A 3I 4A], [I A I; 2I 3A 4I],
# [A I A; I A A], [I A 2A; 3A 4I 5A], # weird
# [I I A; I A I], # unsupported
[A A I; 2A 3A 4I],
[A I I; 2A 3I 4I],
# [A Lm], # need one LinearMap test for codecov (see below)
]
list1 = fun0(A)
list2 = fun0(M)
if true # need one LinearMap test for codecov
push!(list1, [A Lm])
push!(list2, [M M]) # trick because [M Lm] fails
end
for ii in 1:length(list1)
b1 = list1[ii]
b2 = list2[ii]
@test b1 isa LinearMapAX
@test b2 isa AbstractMatrix
@test Matrix(b1) == b2
@test Matrix(b1') == Matrix(b1)'
end
true
end
"""
LinearMapAA_test_cat(A::LinearMapAO)
test hcat vcat hvcat for AO
"""
function LinearMapAA_test_cat(A::LinearMapAO)
M = Matrix(A)
@testset "cat AO" begin
H = [A A]
V = [A; A]
B = [A 2A; 3A 4A]
@test H isa LinearMapAO
@test V isa LinearMapAO
@test B isa LinearMapAM # !!
@test Matrix(H) == [M M]
@test Matrix(V) == [M; M]
@test Matrix(B) == [M 2M; 3M 4M]
end
@testset "cat OI" begin
@test [A I] isa LinearMapAM
@test [A; I] isa LinearMapAM
@test [A A; I I] isa LinearMapAM
end
@testset "cat AO mixed" begin
B = redim(A, idim=(1,A._idim...)) # force incompatible dim
@test [A B] isa LinearMapAM
@test [A; B] isa LinearMapAM
Z = [A undim(A) I A._lmap] # Matrix(B)]
@test Z isa LinearMapAM
@test Z.hcat == "OAIL"
end
true
end
N = 6; M = 8 # non-square to stress test
forw = x -> [cumsum(x); 0; 0]
back = y -> reverse(cumsum(reverse(y[1:N])))
A = LinearMapAA(forw, back, (M, N))
@test LinearMapAA_test_cat(A)
forw = x -> [cumsum(x ; dims=2) [0] [0]]
back = y -> reverse(cumsum(reverse(y[[1],1:N] ; dims=2) ; dims=2) ; dims=2)
O = LinearMapAA(forw, back, (M, N) ; idim=(1,N), odim=(1,M))
@test LinearMapAA_test_cat(O)
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 1362 | # cuda.jl
# Test that CUDA arrays work properly.
using LinearMaps: LinearMap
using LinearMapsAA: LinearMapAA
using CUDA: CuArray
import CUDA
using Test: @test
if CUDA.functional()
@info "testing CUDA"
CUDA.allowscalar(false)
nx, ny, nz = 5, 7, 6
idim = (nx, ny, nz)
odim = (nx, ny, nz, 2)
x = rand(Float32, idim)
forw1 = x -> cat(x, x, dims=4)
back1 = y -> y[:,:,:,1] + y[:,:,:,2]
forwv = x -> vec(forw1(reshape(x,idim)))
backv = y -> vec(back1(reshape(y,odim)))
O = LinearMapAA(forw1, back1, (prod(odim), prod(idim)); odim, idim)
L = LinearMap(forwv, backv, prod(odim), prod(idim))
A = LinearMapAA(forwv, backv, (prod(odim), prod(idim)))
# check adjoint
@test Matrix(O') == Matrix(O)'
@test Matrix(A') == Matrix(A)'
@test Matrix(L') == Matrix(L)'
# check forward
@test L * vec(x) == vec(O * x)
@test A * vec(x) == vec(O * x)
# check back
y = O * x
@test L' * vec(y) β vec(O' * y)
@test A' * vec(y) β vec(O' * y)
# finally with CUDA arrays
xg = CuArray(x)
yo = O * xg
yl = L * vec(xg)
ya = A * vec(xg)
@test yl == vec(yo)
@test ya == vec(yo)
xo = O' * yo
xl = L' * vec(yo)
xa = A' * vec(yo)
@test xl == vec(xo)
@test xa == vec(xo)
else
@warn "no CUDA test"
@info "One must test CUDA separately"
end
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 1965 | # getindex.jl
# test
using LinearMapsAA: LinearMapAA, LinearMapAX
using Test: @test, @test_throws, @testset
_slice(a, b) = (a == :) || (b == :) # only slicing supported as of LM 3.7 !
"""
LinearMapAA_test_getindex(A::LinearMapAX)
tests for `getindex`
"""
function LinearMapAA_test_getindex(A::LinearMapAX)
B = Matrix(A)
@test all(size(A) .>= (4,4)) # required by tests
tf1 = [false; trues(size(A,1)-1)]
tf2 = [false; trues(size(A,2)-2); false]
ii1 = (3, 2:4, [2,4], :, tf1)
ii2 = (2, 3:4, [1,4], :, tf2)
for i2 in ii2, i1 in ii1
if _slice(i1, i2)
@test B[i1,i2] == A[i1,i2]
else
@test_throws ErrorException B[i1,i2] == A[i1,i2]
end
end
L = A._lmap
test_adj = !((:fc in propertynames(L)) && isnothing(L.fc))
if test_adj
for i1 in ii2, i2 in ii1
if _slice(i1, i2)
@test B'[i1,i2] == A'[i1,i2]
else
@test_throws ErrorException B'[i1,i2] == A'[i1,i2]
end
end
end
true
end
function LinearMapAA_test_getindex_scalar(A::LinearMapAX)
# "end"
@test B[3,end-1] == A[3,end-1]
@test B[end-2,3] == A[end-2,3]
if test_adj
@test B'[3,end-1] == A'[3,end-1]
end
# [?]
@test B[1] == A[1]
@test B[7] == A[7]
if test_adj
@test B'[3] == A'[3]
end
@test B[end] == A[end] # lastindex
kk = [k in [3,5] for k = 1:length(A)] # Bool
@test B[kk] == A[kk]
# Some tests could rely on the fact that LinearMapAM <: AbstractMatrix,
# by inheriting from general Base.getindex, but all are provided here.
@test B[[1, 3, 4]] == A[[1, 3, 4]]
@test B[4:7] == A[4:7]
true
end
N = 6; M = 8 # non-square to stress test
forw = x -> [cumsum(x); 0; 0]
back = y -> reverse(cumsum(reverse(y[1:N])))
A = LinearMapAA(forw, back, (M, N))
@test LinearMapAA_test_getindex(A)
# @test LinearMapAA_test_getindex_scalar(A) # no!
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 188 | # identity.jl
# test
using Test: @test, @testset
using LinearAlgebra: I
@testset "identity" begin
X = rand(2,3,4) # AbstractArray
@test I * X === X
@test (5I) * X == 5*X
end
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 1422 | # kron.jl
# test
using LinearMapsAA: LinearMapAA, LinearMapAM, LinearMapAO
using LinearAlgebra: I, Diagonal
using Test: @test, @testset
M1 = rand(ComplexF64, 3, 3)
M2 = rand(ComplexF64, 2, 2)
M12 = kron(M1, M2)
A1 = LinearMapAA(M1)
A2 = LinearMapAA(M2)
@testset "kron basics" begin
@test kron(A1, A1) isa LinearMapAM
for pair in ((A1,A2), (A1,M2), (M1,A2)) # all combinations
AAk = kron(pair[1], pair[2])
@test AAk isa LinearMapAM
@test Matrix(AAk) == M12
@test Matrix(AAk)' == Matrix(AAk')
end
end
A3 = LinearMapAA(M1 ; odim=(1,size(M1,1)))
A4 = LinearMapAA(M2 ; idim=(size(M2,2),1))
@testset "kron(I,A)" begin
K = kron(I(2), A4)
M = kron(I(2), M2)
@test K isa LinearMapAO
@test Matrix(K) == M
@test Matrix(K') == Matrix(K)'
end
@testset "kron(A,I)" begin
K = kron(A4, I(2))
M = kron(M2, I(2))
@test K isa LinearMapAO
@test Matrix(K) == M
@test Matrix(K') == Matrix(K)'
end
@testset "kron(Ao,M)" begin
@test kron(A3, M2) isa LinearMapAO
@test kron(M1, A4) isa LinearMapAO
end
@testset "kron(Ao,Bo)" begin
K = kron(A3, A4)
M = kron(M1, M2)
@test K isa LinearMapAO
@test Matrix(K) == M
@test Matrix(K') == Matrix(K)'
end
@testset "kron(A,D)" begin
D = Diagonal(1:3)
K = kron(A1, D)
@test Matrix(K) == kron(M1, D)
K = kron(D, A1)
@test Matrix(K) == kron(D, M1)
end
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 5147 | # multiply.jl
#export LinearMapAA_test_vmul # testing
#export LinearMapAA_test_mul # testing
using LinearMapsAA: LinearMapAA, LinearMapAM, LinearMapAO, mul!
using Test: @test, @testset
"""
LinearMapAA_test_vmul(A::LinearMapAX)
Tests for multiply by vector, scalar, and Matrix
"""
LinearMapAA_test_vmul
function LinearMapAA_test_vmul(A::LinearMapAM)
B = Matrix(A)
(M,N) = size(A)
u = rand(M)
v = rand(N)
@testset "A*v" begin
Bv = B * v
Bpu = B' * u
y = A * v
x = A' * u
@test isapprox(Bv, y)
@test isapprox(Bpu, x)
mul!(y, A, v)
mul!(x, A', u)
@test isapprox(Bv, y)
@test isapprox(Bpu, x)
end
#= nah
@testset "u'*A" begin
uB = u' * B
x = u' * A
@test isapprox(uB, x)
mul!(x, u', A)
@test isapprox(uB, x)
end
=#
@testset "A*X" begin
X = rand(N,2)
BX = B * X
Y = A * X
@test Y isa LinearMapAM
Y = Matrix(Y)
@test isapprox(BX, Y)
Y .= 0
# mul!(Y, A, X) # doesn't work because A*X is AM
# @test isapprox(BX, Y)
end
@testset "X*A" begin
X = rand(2,M)
XB = X * B
Y = X * A
@test Y isa LinearMapAM
Y = Matrix(Y)
@test isapprox(XB, Y)
Y .= 0
# mul!(Y, X, A) # doesn't work because X*A is AM
# @test isapprox(XB, Y)
end
@testset "5-arg" begin
y1 = randn(M)
y2 = copy(y1)
mul!(y1, A, v, 2, 3)
mul!(y2, B, v, 2, 3)
@test isapprox(y1, y2)
x1 = randn(N)
x2 = copy(x1)
mul!(x1, A', u, 4, 3)
mul!(x2, B', u, 4, 3)
@test isapprox(x1, x2)
end
@testset "*s" begin
s = 4.2
C = s * A
@test isapprox(Matrix(C), s * B)
C = A * s
@test isapprox(Matrix(C), B * s)
end
#=
s = 4.2
C = deepcopy(A)
lmul!(s, C)
@test isapprox(s * B * v, C * v)
C = deepcopy(A)
rmul!(C, s)
@test isapprox(s * B * v, C * v)
=#
true
end
function LinearMapAA_test_vmul(A::LinearMapAO)
B = Matrix(A)
(M,N) = size(A)
u = rand(M)
v = rand(N)
u = reshape(u, A._odim)
v = reshape(v, A._idim)
@testset "A*v" begin
Bv = reshape(B * v[:], A._odim)
Bpu = reshape(B' * u[:], A._idim)
y = A * v
x = A' * u
@test isapprox(Bv, y)
@test isapprox(Bpu, x)
mul!(y, A, v)
mul!(x, A', u)
@test isapprox(Bv, y)
@test isapprox(Bpu, x)
A1 = redim(A ; idim = (N,))
y1 = A1 * vec(v)
@test y1 β y
end
#= nah
@testset "u'*A" begin
uB = reshape(u[:]' * B, A._idim)
x = u' * A
@test isapprox(uB, x)
mul!(x, u', A)
@test isapprox(uB, x)
end
=#
@testset "A*X" begin
K = 2
X = rand(A._idim..., K)
BX = reshape(B * reshape(X, :, K), A._odim..., K)
Y = A * X
@test Y isa AbstractArray
@test isapprox(BX, Y)
Y .= 0
mul!(Y, A, X)
@test isapprox(BX, Y)
# 5-arg
Y1 = copy(Y)
Y2 = copy(Y)
mul!(Y1, A, X, 2, 3)
mul!(reshape(Y2,:,K), B, reshape(X,:,K), 2, 3)
Y2 = reshape(Y2, A._odim..., K)
@test isapprox(Y1, Y2)
end
# todo: should eventually test complex X*A as well
@testset "X*A" begin
K = 2
X = rand(A._odim..., K)
XB = reshape(X, :, K)' * B
XB = reshape(XB', A._idim..., K)
Y = X * A
@test Y isa AbstractArray
@test isapprox(XB, Y)
Y .= 0
mul!(Y, X, A)
@test isapprox(XB, Y)
# 5-arg
Y1 = copy(Y)
Y2 = copy(Y)
mul!(Y1, X, A, 2, 3)
mul!(reshape(Y2,:,K), B', reshape(X,:,K), 2, 3)
Y2 = reshape(Y2, A._idim..., K)
@test isapprox(Y1, Y2)
end
@testset "*s" begin
s = 4.2
C = s * A
@test isapprox(Matrix(C), s * B)
C = A * s
@test isapprox(Matrix(C), B * s)
end
true
end
# object multiplication
function LinearMapAA_test_mul( ;
A::LinearMapAO = LinearMapAA(rand(6,4) ; odim=(2,3), idim=(1,4)),
)
(M,N) = size(A)
@testset "O*O" begin
@test A'*A isa LinearMapAO
end
@testset "O*M" begin
B = LinearMapAA(rand(N,3)) # AM
O = redim(A ; idim=(N,))
@test O*B isa LinearMapAO
end
@testset "M*O" begin
B = LinearMapAA(rand(3,M)) # AM
O = redim(A ; odim=(M,))
@test B*O isa LinearMapAO
end
true
end
# Test multiplication of an AO by a Vector of Arrays (v0.9.0)
@testset "mul! Vector{Array}" begin
M = randn(6,4)
O = LinearMapAA(M ; odim=(2,3), idim=(1,4))
x1 = randn(O._idim)
x2 = randn(O._idim)
x3 = cat(dims=3, x1, x2)
xv = [x1, x3]
yv1 = map(x -> O * x, xv)
yv2 = [O * x1, cat(dims=3, O*x1, O*x2)]
@test yv1 == yv2
mul!(yv2, O, xv, 1, 0)
@test yv1 == yv2
mul!(yv2, O, xv)
@test yv1 == yv2
yv2 = O * xv
@test yv1 == yv2
end
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 801 | # test/runtests.jl
using LinearMapsAA: LinearMapsAA
using Test: @test, @testset, @test_broken, detect_ambiguities
function test_ambig(str::String)
@testset "ambiguities-$str" begin
tmp = detect_ambiguities(LinearMapsAA)
# @show tmp
@test length(tmp) == 0
end
end
include("multiply.jl")
list = [
"ambiguity"
"identity"
"kron"
"cat"
"getindex"
#"setindex"
"block_diag"
"tests"
"wrap-linop"
]
for file in list
@testset "$file" begin
include("$file.jl")
end
end
test_ambig("before cuda")
#=
using CUDA causes an import of StaticArrays that leads to a method ambiguity
=#
@testset "cuda" begin
include("cuda.jl")
end
@testset "ambiguities" begin
tmp = detect_ambiguities(LinearMapsAA)
@show tmp # todo
@test_broken length(tmp) == 0
end
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 2174 | # setindex.jl
# test setindex! (deprecated)
using LinearMapsAA: LinearMapAA, LinearMapAM
using Test: @test
"""
`LinearMapAA_test_setindex(A::LinearMapAM)`
"""
function LinearMapAA_test_setindex(A::LinearMapAM)
@test all(size(A) .>= (4,4)) # required by tests
tf1 = [false; trues(size(A,1)-1)]
tf2 = [false; trues(size(A,2)-2); false]
ii1 = (3, 2:4, [2,4], :, tf1)
ii2 = (2, 3:4, [1,4], :, tf2)
# test all [?,?] combinations with array "X"
for i2 in ii2
for i1 in ii1
B = deepcopy(A)
X = 2 .+ A[i1,i2].^2 # values must differ from A[ii,jj]
B[i1,i2] = X
Am = Matrix(A)
Bm = Matrix(B)
Am[i1,i2] = X
@test isapprox(Am, Bm)
end
end
# test all [?,?] combinations with scalar "s"
for i2 in ii2
for i1 in ii1
B = deepcopy(A)
s = maximum(abs.(A[:])) + 2
B[i1,i2] = s
Am = Matrix(A)
Bm = Matrix(B)
if (i1 == Colon() || ndims(i1) > 0) || (i2 == Colon() || ndims(i2) > 0)
Am[i1,i2] .= s
else
Am[i1,i2] = s
end
@test isapprox(Am, Bm)
end
end
# others not supported for now
set1 = (3, ) # [3], [2,4], 2:4, (1:length(A)) .== 2), end
for s1 in set1
B = deepcopy(A)
X = 2 .+ A[s1].^2 # values must differ from A[ii,jj]
B[s1] = X
Am = Matrix(A)
Bm = Matrix(B)
Am[s1] = X
@test isapprox(Am, Bm)
end
# insanity below here
# A[:] = s
B = deepcopy(A)
B[:] = 5
Am = Matrix(A)
Am[:] .= 5
Bm = Matrix(B)
@test Bm == Am
# A[:] = v
B = deepcopy(A)
v = 1:length(A)
B[:] = v
Am = Matrix(A)
Am[:] .= v
Bm = Matrix(B)
@test Bm == Am
# A[:,:]
B = deepcopy(A)
B[:,:] = 6
Am = Matrix(A)
Am[:,:] .= 6
Bm = Matrix(B)
@test Bm == Am
true
end
N = 6; M = 8 # non-square to stress test
forw = x -> [cumsum(x); 0; 0]
back = y -> reverse(cumsum(reverse(y[1:N])))
A = LinearMapAA(forw, back, (M, N))
@test LinearMapAA_test_setindex(A)
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 5480 | # tests
using LinearMaps: LinearMap
using LinearMapsAA: LinearMapAA, LinearMapAM, LinearMapAO, LinearMapAX
using LinearAlgebra: issymmetric, ishermitian, isposdef, I
using SparseArrays: sparse
using Test: @test, @testset, @test_throws
#B = 1:6
#L = LinearMap(x -> B*x, y -> B'*y, 6, 1)
B = reshape(1:6, 6, 1)
@test Matrix(LinearMapAA(B)) == B
# ensure that "show" is concise even for big `prop`
L = LinearMapAA(LinearMap(ones(3,4)), (a=1:3, b=ones(99,99)))
show(isinteractive() ? stdout : devnull, L)
N = 6; M = N+1 # non-square to stress test
forw = x -> [cumsum(x); 0]
back = y -> reverse(cumsum(reverse(y[1:N])))
prop = (name="cumsum", extra=1)
@test LinearMapAA(forw, (M, N)) isa LinearMapAX
@test LinearMapAA(forw, (M, N), prop ; T=Float64) isa LinearMapAX
L = LinearMap{Float32}(forw, back, M, N)
A = LinearMapAA(L, prop)
Lm = Matrix(L)
show(isinteractive() ? stdout : devnull, "text/plain", A)
@testset "basics" begin
@test A._lmap == LinearMapAA(L)._lmap
# @test A == LinearMapAA(forw, back, M, N, prop)
@test A._prop == LinearMapAA(forw, back, (M, N), prop)._prop
@test A._lmap == LinearMapAA(forw, back, (M, N), prop)._lmap
@test A == LinearMapAA(forw, back, (M, N), prop)
@test A._lmap == LinearMapAA(forw, back, (M, N))._lmap
@test LinearMapAA(forw, back, (M, N)) isa LinearMapAX
end
@testset "symmetry" begin
@test issymmetric(A) == false
@test ishermitian(A) == false
@test ishermitian(im * A) == false
@test isposdef(A) == false
@test issymmetric(A' * A) == true
end
@testset "convert" begin
@test Matrix(LinearMapAA(L, prop)) == Lm
@test Matrix(LinearMapAA(L)) == Lm
@test Matrix(sparse(A)) == Lm
end
@testset "getproperty" begin
@test :name β propertynames(A)
@test A._prop == prop
@test A.name == prop.name
@test eltype(A) == eltype(L)
@test Base.eltype(A) == eltype(L) # codecov
@test ndims(A) == 2
@test size(A) == size(L)
@test redim(A) isa LinearMapAX
end
@testset "deepcopy" begin
B = deepcopy(A)
@test B == A
# @test !(B === A) # irrelevant now that struct is immutable
end
@testset "throw" begin
@test_throws String A.bug
@test_throws DimensionMismatch LinearMapAA(L ; idim=(0,0))
@test_throws String LinearMapAA(L, (_prop=0,))
end
@testset "transpose" begin
@test Matrix(A)' == Matrix(A')
@test Matrix(A)' == Matrix(transpose(A))
end
@testset "wrap" begin # WrappedMap vs FunctionMap
M1 = rand(3,2)
A1w = LinearMapAA(M1)
A1f = LinearMapAA(x -> M1*x, y -> M1'y, size(M1), T=eltype(M1))
@test Matrix(A1w) == M1
@test Matrix(A1f) == M1
end
Ao = LinearMapAA(A._lmap ; odim=(1,size(A,1)), idim=(size(A,2),1))
@testset "vmul" begin
@test LinearMapAA_test_vmul(A)
@test LinearMapAA_test_vmul(A*A'*A) # CompositeMap
@test LinearMapAA_test_vmul(Ao) # AO type
@test ndims(Ao) == 2
end
# add / subtract
@testset "add" begin
@test 2A + 6A isa LinearMapAX
@test 7A - 2A isa LinearMapAX
@test Matrix(2A + 6A) == 8 * Matrix(A)
@test Matrix(7A - 2A) == 5 * Matrix(A)
@test Matrix(7A - 2*ones(size(A))) == 7 * Matrix(A) - 2*ones(size(A))
@test Matrix(3*ones(size(A)) - 5A) == 3*ones(size(A)) - 5 * Matrix(A)
@test_throws String @show A + redim(A ; idim=(3,2)) # mismatch dim
end
# add identity
@testset "+I" begin
@test Matrix(A'A - 7I) == Matrix(A'A) - 7I
end
# multiply with identity
@testset "*I" begin
@test Matrix(A * 6I) == 6 * Matrix(A)
@test Matrix(7I * A) == 7 * Matrix(A)
@test Matrix((false*I) * A) == zeros(size(A))
@test Matrix(A * (false*I)) == zeros(size(A))
@test 1.0I * A === A
@test A * 1.0I === A
@test I * A === A
@test A * I === A
end
# multiply
@testset "*" begin
D = A * A'
@test D isa LinearMapAX
@test Matrix(D) == Lm * Lm'
@test issymmetric(D) == true
E = A * Lm'
@test E isa LinearMapAX
@test Matrix(E) == Lm * Lm'
F = Lm' * A
@test F isa LinearMapAX
@test Matrix(F) == Lm' * Lm
@test LinearMapAA_test_getindex(F)
@test LinearMapAA_test_mul()
end
# AO FunctionMap complex
@testset "AO FM C" begin
T = ComplexF16
c = T(2im)
forw! = (y,x) -> copyto!(y,x) .*= c
back! = (x,y) -> copyto!(x,y) .*= conj(c)
dims = (2,3)
O = LinearMapAA(forw!, back!, (1,1).*prod(dims) ;
T=T, idim=dims, odim=dims)
x = rand(T, dims)
@test O*x == c*x
@test O'*x == conj(c)*x
@test Matrix(O') == Matrix(O)'
end
# non-adjoint version
#= no longer supported, for consistency with LM
@testset "non-adjoint" begin
Af = LinearMapAA(forw, (M, N))
@test Matrix(Af) == Lm
@test LinearMapAA_test_getindex(Af)
# @test LinearMapAA_test_setindex(Af)
end
=#
@testset "AO for 1D" begin
B = LinearMapAO(A)
@test B isa LinearMapAO
X = rand(N,2)
Y = B * X
@test Y isa AbstractArray
@test Y β Lm * X
Z = B' * Y
@test Z isa AbstractArray
@test Z β Lm' * Y
end
# FunctionMap for multi-dimensional AO
@testset "AO FM 2D" begin
forw = x -> [cumsum(x; dims=2); zeros(2,size(x,2))]
back = y -> reverse(cumsum(reverse(y[1:(end-2),:]; dims=2); dims=2); dims=2)
A = LinearMapAA(forw, (4*3, 2*3) ; idim=(2,3), odim=(4,3))
@test A isa LinearMapAO
A = LinearMapAA(forw, back, (4*3, 2*3) ; idim=(2,3), odim=(4,3))
@test A isa LinearMapAO
@test Matrix(A') == Matrix(A)'
A = undim(A) # ensure that undim works
@test A isa LinearMapAM
@test Matrix(A') == Matrix(A)'
end
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | code | 788 | # wrap-linop.jl
# test wrapping of a LinearMapAX in a LinearOperator and vice-versa
using LinearMapsAA: LinearMapAA, LinearMapAM, LinearOperator_from_AA
using LinearOperators: LinearOperator
using Test: @test, @testset
forw! = cumsum!
back! = (x, y) -> reverse!(cumsum!(x, reverse!(copyto!(x, y))))
N = 9
T = Float32
L = LinearOperator(
T, N, N, false, false, forw!,
nothing, # transpose mul!
back!,
)
x = rand(N)
y = L * x
@test y == cumsum(x)
@test Matrix(L)' == Matrix(L')
A = LinearMapAA(L) # wrap LinearOperator
@test A isa LinearMapAM
@test Matrix(A)' == Matrix(A')
@test A * x == cumsum(x)
B = LinearMapAA(forw!, back!, (N, N); T)
L = LinearOperator_from_AA(B) # wrap LinearMapAM
@test L isa LinearOperator
@test Matrix(L)' == Matrix(L')
@test L * x == cumsum(x)
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | docs | 14906 | # LinearMapsAA.jl
https://github.com/JeffFessler/LinearMapsAA.jl
[![action status][action-img]][action-url]
[![build status][build-img]][build-url]
[![pkgeval status][pkgeval-img]][pkgeval-url]
[![codecov.io][codecov-img]][codecov-url]
[![license][license-img]][license-url]
[![docs stable][docs-stable-img]][docs-stable-url]
[![docs dev][docs-dev-img]][docs-dev-url]
This package is an overlay for the package
[`LinearMaps.jl`](https://github.com/Jutho/LinearMaps.jl)
that allows one to represent linear operations
(like the FFT)
as a object that appears to the user like a matrix
but internally uses user-defined fast computations
for operations, especially multiplication.
With this package,
you can write and debug code
(especially for iterative algorithms)
using a small matrix `A`,
and then later replace it with a `LinearMapAX` object.
The extra `AA` in the package name here has two meanings.
- `LinearMapAM` is a subtype of `AbstractArray{T,2}`, i.e.,
[conforms to (some of) the requirements of an `AbstractMatrix`](https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-array)
type.
- The package was developed in Ann Arbor, Michigan :)
As of `v0.6`,
the package produces objects of two types:
* `LinearMapAM` (think "Matrix") that is a subtype of `AbstractMatrix`.
* `LinearMapAO` (think "Operator") that is not a subtype of `AbstractMatrix`.
* The general type `LinearMapAX` is a `Union` of both.
* To convert a `LinearMapAM` to a `LinearMapAO`,
use `redim` or `LinearMapAO(A)`
* To convert a `LinearMapAO` to a `LinearMapAM`, use `undim`.
## Examples
```julia
N = 6
L = LinearMap(cumsum, y -> reverse(cumsum(reverse(y))), N)
A = LinearMapAA(L) # version with no properties
A = LinearMapAA(L, (name="cumsum",))) # version with a NamedTuple of properties
Matrix(L), Matrix(A) # both the same 6 x 6 lower triangular matrix
A.name # returns "cumsum" here
```
Here is a more interesting example for signal processing.
```julia
using LinearMapsAA
using FFTW: fft, bfft
N = 8
A = LinearMapAA(fft, bfft, (N, N), (name="fft",), T=ComplexF32)
@show A[:,2]
```
For more details see the examples
in the
[documentation](https://jefffessler.github.io/LinearMapsAA.jl/dev/).
## Features shared with `LinearMap` objects
#### Object combinations
A `LinearMapAX` object supports all of the features of a `LinearMap`.
In particular, if `A` and `B` are both `LinearMapAX` objects
of appropriate sizes,
then the following each make new `LinearMapAX` objects:
- Multiplication: `A * B`
- Linear combination: `A + B`, `A - B`, `3A - 7B`
- Kronecker products: `kron(A, B)`
- Concatenation: `[A B]` `[A; B]` `[I A I]` `[A B; 2A 3I]` etc.
Caution: currently some shorthand concatenations are unsupported,
like `[I I A]`, though one can accomplish that one using
`lmaa_hcat(I, I, A)`
#### Conversions
Conversion to other data types
(may require lots of memory if `A` is big):
- Convert to sparse: `sparse(A)`
- Convert to dense matrix: `Matrix(A)`.
#### Avoiding memory allocations
Like `LinearMap` objects,
both types of `LinearMapAX` objects support `mul!`
for storing the results in a previously allocated output array,
to avoid new memory allocations.
The basic syntax is to replace
`y = A * x` with
`mul!(y, A, x)`.
To make the code look more like the math,
use the `InplaceOps` package:
```julia
using InplaceOps
@! y = A * x # shorthand for mul!(y, A, x)
```
## Features unique to `LinearMapsAA`
A bonus feature provided by `LinearMapsAA`
is that a user can include a `NamedTuple` of properties
with it, and then retrieve those later
using the `A.key` syntax like one would do with a struct (composite type).
The nice folks over at `LinearMaps.jl`
[helped get me started](https://github.com/Jutho/LinearMaps.jl/issues/53)
with this feature.
Often linear operators are associated
with some properties,
e.g.,
a wavelet transform arises
from some mother wavelet,
and it can be convenient
to carry those properties with the object itself.
Currently
the properties are lost when one combines
two or more `LinearMapAA` objects by adding, multiplying, concatenating, etc.
The following features are provided
by a `LinearMapAX` object
due to its `getindex` support:
- Columns or rows slicing: `A[:,5]`, `A[end,:]`etc. return a 1D vector
- Elements: `A[4,5]` (returns a scalar)
- Portions: `A[4:6,5:8]` (returns a dense matrix)
- Linear indexing: `A[2:9]` (returns a 1D vector)
- Convert to matrix: `A[:,:]` (if memory permits)
- Convert to vector: `A[:]` (if memory permits).
## Operator support
A `LinearMapAO` object
represents a linear mapping
from some input array size
into some output array size
specified by the `idim` and `odim` options.
Here is a (simplified) example for 2D MRI,
where the operator maps a 2D input array
into a 1D output vector:
```julia
using FFTW: fft, bfft
using LinearMapsAA
embed = (v, samp) -> setindex!(fill(zero(eltype(v)),size(samp)), v, samp)
N = (128,64) # image size
samp = rand(N...) .< 0.8 # random sampling pattern
K = sum(samp) # number of k-space samples
A = LinearMapAA(x -> fft(x)[samp], y -> bfft(embed(y,samp)),
(K, prod(N)) ; prop = (name="fft",), T=ComplexF32, idim=N, odim=(K,))
x = rand(N...)
z = A' * (A * x) # result is a 2D array!
typeof(A) # LinearMapAO{ComplexF32, 1, 2}
```
For more details see FFT example in the
[documentation](https://jefffessler.github.io/LinearMapsAA.jl/dev/).
The adjoint of this `LinearMapAO` object
maps a 1D vector of k-space samples
into a 2D image array.
Multiplying a `M Γ N` matrix times a `N Γ K` matrix
can be thought of as multiplying the matrix
by each of the `K` columns,
yielding a `M Γ K` result.
Generalizing this to higher dimensional arrays,
if `A::LinearMapAO`
has "input dimensions" `idim=(2,3)`
and "output dimensions" `odim=(4,5,6)`
and you do `A*X` where `X::AbstractArray` has dimension `(2,3,7,8)`,
then the output will be an `Array` of dimension `(4,5,6,7,8)`.
In other words, it works block-wise.
(If you really want a new `LinearMapAO`, rather than an `Array`,
then you must first wrap `X` in a `LinearMapAO`.)
This behavior deliberately departs from the non-`Matrix` like behavior
in `LinearMaps` where `A*X` produces a new `LinearMap`.
Here is a corresponding example (not useful; just for illustration).
```julia
using LinearMapsAA
idim = (2,3)
odim = (4,5,6)
forward = x -> repeat(reshape(x, (idim[1],1,idim[2])) ; outer=(2,5,2))
A = LinearMapAA(forward,
(prod(odim), prod(idim)) ; prop = (name="test",), idim, odim)
x = rand(idim..., 7, 8)
y = A * x
```
In the spirit of such generality,
this package overloads `*` for `LinearAlgebra.I`
(and for `UniformScaling` objects more generally)
such that
`I * X == X`
even when `X` is an array of more than two dimensions.
(The original `LinearAlgebra.I` can only multiply
vectors and matrices,
which suffices for matrix algebra,
but not for general linear algebra.)
Caution:
The `LinearMapAM` type should be quite stable now,
whereas `LinearMapAO` is new in `v0.6`.
The conversions `redim` and `undim`
are probably not thoroughly tested.
The safe bet is to use all
`LinearMapAM` objects
or all
`LinearMapAO` objects
rather than trying to mix and match.
## Historical note about `getindex`
An `AbstractArray`
must support a `getindex` operation.
The maintainers of the `LinearMaps.jl` package
[originally did not wish to add `getindex` there](https://github.com/Jutho/LinearMaps.jl/issues/38),
so this package added that feature
(while avoiding "type piracy").
Eventually,
partial `getindex` support,
[specifically slicing](https://github.com/JuliaLinearAlgebra/LinearMaps.jl/pull/165),
was added in
[v3.7](https://github.com/JuliaLinearAlgebra/LinearMaps.jl/releases/tag/v3.7.0)
there.
As of v0.11,
this package uses that `getindex` implementation
and also supports only slicing.
This is a breaking change that could be easily reverted,
so please submit an issue if you have a use case
for more general use of `getindex`.
## Historical note about `setindex!`
The
[Julia manual section on the `AbstractArray` interface](https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-array)
implies that an `AbstractArray`
should support a `setindex!` operation.
Versions of this package prior to v0.8.0
provided that capability,
mainly for completeness
and as a proof of principle,
solely for the `LinearMapAM` type.
However,
the reality is that many sub-types of `AbstractArray`
in the Julia ecosystem,
such as `LinearAlgebra.Diagonal`,
understandably do *not* support `setindex!`,
and it there seems to be no use
for it here either.
Supporting `setindex!` seems impossible with a concrete type
for a function map,
so it is no longer supported.
The key code is relegated to the `archive` directory.
## Related packages
[`LinearOperators.jl`](https://github.com/JuliaSmoothOptimizers/LinearOperators.jl)
also provides `getindex`-like features,
but slicing there always returns another operator,
unlike with a matrix.
In contrast,
a `LinearMapAM` object is designed to behave
akin to a matrix,
except for operations like `svd` and `pinv`
that are unsuitable for large-scale problems.
However, one can try
[`Arpack.svds(A)`](https://julialinearalgebra.github.io/Arpack.jl/latest/index.html#Arpack.svds)
to compute a few SVD components.
[`LazyArrays.jl`](https://github.com/JuliaArrays/LazyArrays.jl)
and
[`BlockArrays.jl`](https://github.com/JuliaArrays/BlockArrays.jl)
also have some related features,
but only for arrays,
not linear operators defined by functions,
so `LinearMaps` is more comprehensive.
[`LazyAlgebra.jl`](https://github.com/emmt/LazyAlgebra.jl)
also has many related features, and supports nonlinear mappings.
[`SciML/SciMLOperators.jl`](https://github.com/SciML/SciMLOperators.jl)
seems to be designed for "matrix-free" operators
that are functions of some possibly changing parameters.
This package provides similar functionality
as the `Fatrix` / `fatrix` object in the
[Matlab version of MIRT](https://github.com/JeffFessler/mirt).
In particular,
the `odim` and `idim` features of those objects
are similar to those here.
[`FunctionOperators.jl`](https://github.com/hakkelt/FunctionOperators.jl)
supports `inDims` and `outDims` features.
[`JOLI.jl`](https://github.com/slimgroup/JOLI.jl)
Being a sub-type of `AbstractArray` can be useful
for other purposes,
such as using the nice
[Kronecker.jl](https://github.com/MichielStock/Kronecker.jl)
package.
Will this list keep growing,
or will the community settle
on some common `AbstractLinearMap` base?
## Inter-operability
To promote inter-operability of different linear mapping packages,
this package provides methods
for wrapping other operator types into `LinearMapAX` types.
The syntax is simply
`LinearMapAA(L; kwargs...)`
where `L` can be any of the following types currently:
* `AbstractMatrix` (including `Matrix`, `SparseMatrixCSC`, `Diagonal`, among many others)
* `LinearMap` from
[`LinearMaps.jl`](https://github.com/Jutho/LinearMaps.jl)
* `LinearOperator` from
[`LinearOperators.jl`](https://github.com/JuliaSmoothOptimizers/LinearOperators.jl).
Submit an issue or make a PR if there are other operator types
that one would like to have supported.
To minimize package dependencies,
the wrapping code for a `LinearOperator` uses
[package extensions](https://docs.julialang.org/en/v1/manual/code-loading/#man-extensions).
## Multiplication properties
It can help developers and users
to know how multiplication operations should behave.
| Type | Shorthand |
| :--- | :---: |
| `LinearMapAO` | `O` |
| `LinearMapAM` | `M` |
| `LinearMap` | `L` |
| `AbstractVector` | `v` |
| `AbstractMatrix` | `X` |
| `AbstractArray` | `A` |
| `LinearAlgebra.I` | `I` |
For `left * right` multiplication the results are as follows.
| Left | Right | Result |
| :---: | :---: | :---: |
| `M` | `v` | `v` |
| `v'` | `M` | `v'` |
| `M` | `X` | `X` |
| `X` | `M` | `X` |
| `M` | `M` | `M` |
| `M` | `L` | `M` |
| `L` | `M` | `M` |
| `O` | `A` | `A` |
| `A` | `O` | `A` |
| `O` | `O` | `O` |
| `I` | `A` | `A` |
The following subset of the above operations also work
for the in-place version `mul!(result, left, right)`:
| Left | Right | Result |
| :---: | :---: | :---: |
| `M` | `v` | `v` |
| `v'` | `M` | `v'` |
| `M` | `X` | `X` |
| `X` | `M` | `X` |
| `O` | `A` | `A` |
| `A` | `O` | `A` |
There is one more special multiplication property.
If `O` is a `LinearMapAO` and `xv` is `Vector` of `AbstractArrays`,
then `O * xv` is equivalent to `[O * x for x in xv]`.
This is useful, for example,
in dynamic imaging
where one might store a video sequence
as a vector of 2D images,
rather than as a 3D array.
There is also a corresponding
[5-argument `mul!`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.mul!).
Each array in the `Vector` `xv`
must be compatible with multiplication on the left by `O`.
## Credits
This software was developed at the
[University of Michigan](https://umich.edu/)
by
[Jeff Fessler](https://web.eecs.umich.edu/~fessler)
and his
[group](https://web.eecs.umich.edu/~fessler/group),
with substantial inspiration drawn
from the `LinearMaps` package.
## Compatibility
* Version 0.2.0 tested with Julia 1.1 and 1.2
* Version 0.3.0 requires Julia 1.3
* Version 0.6.0 assumes Julia 1.4
* Version 0.7.0 assumes Julia 1.6
* Version 0.11.0 assumes Julia 1.9
## Getting started
This package is registered in the
[`General`](https://github.com/JuliaRegistries/General) registry,
so you can install it at the REPL with `] add LinearMapAA`.
Here are
[detailed installation instructions](https://github.com/JeffFessler/MIRT.jl/blob/main/doc/start.md).
This package is included in the
Michigan Image Reconstruction Toolbox
[`MIRT.jl`](https://github.com/JeffFessler/MIRT.jl)
and is exported there
so that MIRT users can use it
without "separate" installation.
<!-- URLs -->
[action-img]: https://github.com/JeffFessler/LinearMapsAA.jl/workflows/Unit%20test/badge.svg
[action-url]: https://github.com/JeffFessler/LinearMapsAA.jl/actions
[build-img]: https://github.com/JeffFessler/LinearMapsAA.jl/workflows/CI/badge.svg?branch=main
[build-url]: https://github.com/JeffFessler/LinearMapsAA.jl/actions?query=workflow%3ACI+branch%3Amain
[pkgeval-img]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/L/LinearMapsAA.svg
[pkgeval-url]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/L/LinearMapsAA.html
[codecov-img]: https://codecov.io/github/JeffFessler/LinearMapsAA.jl/coverage.svg?branch=main
[codecov-url]: https://codecov.io/github/JeffFessler/LinearMapsAA.jl?branch=main
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://JeffFessler.github.io/LinearMapsAA.jl/stable
[docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg
[docs-dev-url]: https://JeffFessler.github.io/LinearMapsAA.jl/dev
[license-img]: https://img.shields.io/badge/license-MIT-brightgreen.svg
[license-url]: LICENSE
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | docs | 417 | ```@meta
CurrentModule = LinearMapsAA
```
# LinearMapsAA.jl Documentation
## Contents
```@contents
```
## Overview
Currently the main documentation for
[(LinearMapsAA)](https://github.com/JeffFessler/LinearMapsAA.jl)
is in the README file therein.
See also the documentation for the underlying
[(LinearMaps)](https://github.com/Jutho/LinearMaps.jl)
package.
See the Example(s) tab for one non-trivial example.
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.12.0 | 3540b82a4228ab6352b41d713c876ff08c059ee5 | docs | 92 | ## Methods list
```@index
```
## Methods usage
```@autodocs
Modules = [LinearMapsAA]
```
| LinearMapsAA | https://github.com/JeffFessler/LinearMapsAA.jl.git |
|
[
"MIT"
] | 0.4.6 | 4693424929b4ec7ad703d68912a6ad6eff103cfe | code | 191 | module FreqTables
using CategoricalArrays
using Tables
using NamedArrays
using Missings
include("freqtable.jl")
export freqtable, proptable, prop, Name
end # module
| FreqTables | https://github.com/nalimilan/FreqTables.jl.git |
|
[
"MIT"
] | 0.4.6 | 4693424929b4ec7ad703d68912a6ad6eff103cfe | code | 11890 | import Base.ht_keyindex
# Cf. https://github.com/JuliaStats/StatsBase.jl/issues/135
struct UnitWeights <: AbstractVector{Int} end
Base.getindex(w::UnitWeights, ::Integer...) = 1
Base.getindex(w::UnitWeights, ::AbstractVector) = w
# About the type inference limitation which prompts this workaround, see
# https://github.com/JuliaLang/julia/issues/10880
Base.@pure eltypes(T) = Tuple{map(eltype, T.parameters)...}
Base.@pure vectypes(T) = Tuple{map(U -> Vector{U}, T.parameters)...}
# Internal function needed for now so that n is inferred
function _freqtable(x::Tuple,
skipmissing::Bool = false,
weights::AbstractVector{<:Real} = UnitWeights(),
subset::Union{Nothing, AbstractVector{Int}, AbstractVector{Bool}} = nothing)
n = length(x)
n == 0 && throw(ArgumentError("at least one argument must be provided"))
if !isa(subset, Nothing)
x = map(y -> y[subset], x)
weights = weights[subset]
end
l = map(length, x)
vtypes = eltypes(typeof(x))
for i in 1:n
if l[1] != l[i]
error("arguments are not of the same length: $l")
end
end
if !isa(weights, UnitWeights) && length(weights) != l[1]
error("'weights' (length $(length(weights))) must be of the same length as vectors (length $(l[1]))")
end
d = Dict{vtypes, eltype(weights)}()
for (i, el) in enumerate(zip(x...))
index = ht_keyindex(d, el)
if index > 0
@inbounds d.vals[index] += weights[i]
else
@inbounds d[el] = weights[i]
end
end
if skipmissing
filter!(p -> !any(ismissing, p[1]), d)
end
keyvec = collect(keys(d))
dimnames = Vector{Vector}(undef, n)
for i in 1:n
s = Set{vtypes.parameters[i]}()
for j in 1:length(keyvec)
push!(s, keyvec[j][i])
end
# convert() is needed for Union{T, Missing}, which currently gives a Vector{Any}
# which breaks inference of the return type
dimnames[i] = convert(Vector{vtypes.parameters[i]}, unique(s))
try
sort!(dimnames[i])
catch err
err isa MethodError || rethrow(err)
end
end
a = zeros(eltype(weights), map(length, dimnames)...)::Array{eltype(weights), n}
na = NamedArray(a, tuple(dimnames...)::vectypes(vtypes), ntuple(i -> "Dim$i", n))
for (k, v) in d
na[Name.(k)...] = v
end
na
end
"""
freqtable(x::AbstractVector...;
skipmissing::Bool = false,
weights::AbstractVector{<:Real} = UnitWeights(),
subset::Union{Nothing, AbstractVector{Int}, AbstractVector{Bool}} = nothing])
freqtable(t, cols::Union{Symbol, AbstractString}...;
skipmissing::Bool = false,
weights::AbstractVector{<:Real} = UnitWeights(),
subset::Union{Nothing, AbstractVector{Int}, AbstractVector{Bool}} = nothing])
Create frequency table from vectors or table columns.
`t` can be any type of table supported by the [Tables.jl](https://github.com/JuliaData/Tables.jl) interface.
**Examples**
```jldoctest
julia> freqtable([1, 2, 2, 3, 4, 3])
4-element Named Array{Int64,1}
Dim1 β
βββββββΌββ
1 β 1
2 β 2
3 β 2
4 β 1
julia> df = DataFrame(x=[1, 2, 2, 2], y=[1, 2, 1, 2]);
julia> freqtable(df, :x, :y)
2Γ2 Named Array{Int64,2}
x β² y β 1 2
βββββββΌβββββ
1 β 1 0
2 β 1 2
julia> freqtable(df, :x, :y, subset=df.x .> 1)
1Γ2 Named Array{Int64,2}
x β² y β 1 2
βββββββΌβββββ
2 β 1 2
```
"""
freqtable(x::AbstractVector...;
skipmissing::Bool = false,
weights::AbstractVector{<:Real} = UnitWeights(),
subset::Union{Nothing, AbstractVector{Int}, AbstractVector{Bool}} = nothing) =
_freqtable(x, skipmissing, weights, subset)
# Internal function needed for now so that n is inferred
function _freqtable(x::NTuple{n, AbstractCategoricalVector}, skipmissing::Bool = false,
weights::AbstractVector{<:Real} = UnitWeights(),
subset::Union{Nothing, AbstractVector{Int}, AbstractVector{Bool}} = nothing) where n
n == 0 && throw(ArgumentError("at least one argument must be provided"))
if !isa(subset, Nothing)
x = map(y -> y[subset], x)
weights = weights[subset]
end
len = map(length, x)
allowsmissing = map(v -> eltype(v) >: Missing, x)
lev = map(x) do v
l = eltype(v) >: Missing && !skipmissing ? [levels(v); missing] : levels(v)
CategoricalArray{eltype(v)}(l)
end
dims = map(length, lev)
for i in 1:n
if len[1] != len[i]
error(string("arguments are not of the same length: ", tuple(len...)))
end
end
if !isa(weights, UnitWeights) && length(weights) != len[1]
error("'weights' (length $(length(weights))) must be of the same length as vectors (length $(len[1]))")
end
sizes = cumprod([dims...])
a = zeros(eltype(weights), dims)
missingpossible = any(allowsmissing)
@inbounds for i in 1:len[1]
ref = Int(x[1].refs[i])
miss = missingpossible & (ref <= 0)
el = ifelse(miss, dims[1], ref)
anymiss = miss
for j in 2:n
ref = Int(x[j].refs[i])
miss = missingpossible & (ref <= 0)
el += (ifelse(miss, dims[j], ref) - 1) * sizes[j - 1]
anymiss |= miss
end
if !(missingpossible && skipmissing && anymiss)
a[el] += weights[i]
end
end
NamedArray(a, lev, ntuple(i -> "Dim$i", n))
end
freqtable(x::AbstractCategoricalVector...; skipmissing::Bool = false,
weights::AbstractVector{<:Real} = UnitWeights(),
subset::Union{Nothing, AbstractVector{Int}, AbstractVector{Bool}} = nothing) =
_freqtable(x, skipmissing, weights, subset)
function freqtable(t, cols::Union{Symbol, AbstractString}...; args...)
all_cols = Tables.columns(t)
a = freqtable((Tables.getcolumn(all_cols, Symbol(y)) for y in cols)...; args...)
colsβ² = all(x -> x isa AbstractString, cols) ? cols : Symbol.(cols)
setdimnames!(a, colsβ²)
a
end
"""
prop(tbl::AbstractArray{<:Number};
margins = nothing)
Create a table of proportions from an array `tbl`.
If `margins` is `nothing` (the default), proportions over the whole `tbl` are computed.
If `margins` is an `Integer`, or an iterable of `Integer`s, proportions
sum to `1` over dimensions specified by `margins`.
In particular for a two-dimensional array, when `margins` is `1` row proportions are
calculated, and when `margins` is `2` column proportions are calculated.
This function does not check that `tbl` contains only non-negative values.
Calculating `sum(proptable(..., margins=margins), dims=dims)` with `dims` equal to the complement
of `margins` produces an array containing only `1.0` (see last example below).
**Examples**
```jldoctest
julia> prop([1 2; 3 4])
2Γ2 Array{Float64,2}:
0.1 0.2
0.3 0.4
julia> prop([1 2; 3 4], margins=1)
2Γ2 Array{Float64,2}:
0.333333 0.666667
0.428571 0.571429
julia> prop([1 2; 3 4], margins=2)
2Γ2 Array{Float64,2}:
0.25 0.333333
0.75 0.666667
julia> prop([1 2; 3 4], margins=(1, 2))
2Γ2 Array{Float64,2}:
1.0 1.0
1.0 1.0
julia> pt = prop(reshape(1:12, (2, 2, 3)), margins=3)
2Γ2Γ3 Array{Float64,3}:
[:, :, 1] =
0.1 0.3
0.2 0.4
[:, :, 2] =
0.192308 0.269231
0.230769 0.307692
[:, :, 3] =
0.214286 0.261905
0.238095 0.285714
julia> sum(pt, dims=(1, 2))
1Γ1Γ3 Array{Float64,3}:
[:, :, 1] =
1.0
[:, :, 2] =
1.0
[:, :, 3] =
1.0
```
"""
function prop(tbl::AbstractArray{<:Number,N}; margins=nothing) where N
if margins === nothing
return tbl / sum(tbl)
else
lo, hi = extrema(margins)
(lo < 1 || hi > N) && throw(ArgumentError("margins must be a valid dimension"))
return tbl ./ sum(tbl, dims=tuple(setdiff(1:N, margins)...)::NTuple{N-length(margins),Int})
end
end
"""
proptable(x::AbstractVector...;
margins = nothing,
skipmissing::Bool = false,
weights::AbstractVector{<:Real} = UnitWeights(),
subset::Union{Nothing, AbstractVector{Int}, AbstractVector{Bool}} = nothing])
proptable(t, cols::Union{Symbol, AbstractString}...;
margins = nothing,
skipmissing::Bool = false,
weights::AbstractVector{<:Real} = UnitWeights(),
subset::Union{Nothing, AbstractVector{Int}, AbstractVector{Bool}} = nothing])
Create a frequency table of proportions from vectors or table columns.
This is equivalent to calling `prop(freqtable(...), margins=margins)`.
`t` can be any type of table supported by the [Tables.jl](https://github.com/JuliaData/Tables.jl)
interface.
If `margins` is `nothing` (the default), proportions over the whole table are computed.
If `margins` is an `Integer`, or an iterable of `Integer`s, proportions
sum to `1` over dimensions specified by `margins`.
In particular for a two-dimensional array, when `margins` is `1` row proportions are
calculated, and when `margins` is `2` column proportions are calculated.
Calculating `sum(proptable(..., margins=margins), dims=dims)` with `dims` equal to the complement
of `margins` produces an array containing only `1.0` (see last example below).
**Examples**
```jldoctest
julia> proptable([1, 2, 2, 3, 4, 3])
4-element Named Array{Float64,1}
Dim1 β
βββββββΌβββββββββ
1 β 0.166667
2 β 0.333333
3 β 0.333333
4 β 0.166667
julia> df = DataFrame(x=[1, 2, 2, 2, 1, 1], y=[1, 2, 1, 2, 2, 2], z=[1, 1, 1, 2, 2, 1]);
julia> proptable(df, :x, :y)
2Γ2 Named Array{Float64,2}
x β² y β 1 2
βββββββΌβββββββββββββββββββ
1 β 0.166667 0.333333
2 β 0.166667 0.333333
julia> proptable(df, :x, :y, subset=df.x .> 1)
1Γ2 Named Array{Float64,2}
x β² y β 1 2
βββββββΌβββββββββββββββββββ
2 β 0.333333 0.666667
julia> proptable([1, 2, 2, 2], [1, 1, 1, 2], margins=1)
2Γ2 Named Array{Float64,2}
Dim1 β² Dim2 β 1 2
βββββββββββββΌβββββββββββββββββββ
1 β 1.0 0.0
2 β 0.666667 0.333333
julia> proptable([1, 2, 2, 2], [1, 1, 1, 2], margins=2)
2Γ2 Named Array{Float64,2}
Dim1 β² Dim2 β 1 2
βββββββββββββΌβββββββββββββββββββ
1 β 0.333333 0.0
2 β 0.666667 1.0
julia> proptable([1, 2, 2, 2], [1, 1, 1, 2], margins=(1,2))
2Γ2 Named Array{Float64,2}
Dim1 β² Dim2 β 1 2
βββββββββββββΌβββββββββ
1 β 1.0 NaN
2 β 1.0 1.0
julia> proptable(df.x, df.y, df.z)
2Γ2Γ2 Named Array{Float64,3}
[:, :, Dim3=1] =
Dim1 β² Dim2 β 1 2
βββββββββββββΌβββββββββββββββββββ
1 β 0.166667 0.166667
2 β 0.166667 0.166667
[:, :, Dim3=2] =
Dim1 β² Dim2 β 1 2
βββββββββββββΌβββββββββββββββββββ
1 β 0.0 0.166667
2 β 0.0 0.166667
julia> pt = proptable(df.x, df.y, df.z, margins=(1,2))
2Γ2Γ2 Named Array{Float64,3}
[:, :, Dim3=1] =
Dim1 β² Dim2 β 1 2
βββββββββββββΌβββββββββ
1 β 1.0 0.5
2 β 1.0 0.5
[:, :, Dim3=2] =
Dim1 β² Dim2 β 1 2
βββββββββββββΌβββββββββ
1 β 0.0 0.5
2 β 0.0 0.5
julia> sum(pt, dims=3)
2Γ2Γ1 Named Array{Float64,3}
[:, :, Dim3=sum(Dim3)] =
Dim1 β² Dim2 β 1 2
βββββββββββββΌβββββββββ
1 β 1.0 1.0
2 β 1.0 1.0
```
"""
proptable(x::AbstractVector...;
margins = nothing,
skipmissing::Bool = false,
weights::AbstractVector{<:Real} = UnitWeights(),
subset::Union{Nothing, AbstractVector{Int}, AbstractVector{Bool}} = nothing) =
prop(freqtable(x...,
skipmissing=skipmissing, weights=weights, subset=subset), margins=margins)
proptable(t, cols::Union{Symbol, AbstractString}...; margins=nothing, kwargs...) =
prop(freqtable(t, cols...; kwargs...), margins=margins)
| FreqTables | https://github.com/nalimilan/FreqTables.jl.git |
|
[
"MIT"
] | 0.4.6 | 4693424929b4ec7ad703d68912a6ad6eff103cfe | code | 8233 | using FreqTables
using Test
using NamedArrays
x = repeat(["a", "b", "c", "d"], outer=[100]);
# Values not in order to test discrepancy between index and levels with CategoricalArray
y = repeat(["D", "C", "A", "B"], inner=[10], outer=[10]);
tab = @inferred freqtable(x)
@test tab == [100, 100, 100, 100]
@test names(tab) == [["a", "b", "c", "d"]]
@test @inferred prop(tab) == [0.25, 0.25, 0.25, 0.25]
tab = @inferred freqtable(y)
@test tab == [100, 100, 100, 100]
@test names(tab) == [["A", "B", "C", "D"]]
tab = @inferred freqtable(x, y)
@test tab == [30 20 20 30;
30 20 20 30;
20 30 30 20;
20 30 30 20]
@test names(tab) == [["a", "b", "c", "d"], ["A", "B", "C", "D"]]
pt = @inferred prop(tab)
@test pt == [0.075 0.05 0.05 0.075;
0.075 0.05 0.05 0.075;
0.05 0.075 0.075 0.05;
0.05 0.075 0.075 0.05]
pt = @inferred prop(tab, margins=2)
@test pt == [0.3 0.2 0.2 0.3;
0.3 0.2 0.2 0.3;
0.2 0.3 0.3 0.2;
0.2 0.3 0.3 0.2]
pt = @inferred prop(tab, margins=1)
@test pt == [0.3 0.2 0.2 0.3;
0.3 0.2 0.2 0.3;
0.2 0.3 0.3 0.2;
0.2 0.3 0.3 0.2]
pt = @inferred prop(tab, margins=(1, 2))
@test pt == [1.0 1.0 1.0 1.0;
1.0 1.0 1.0 1.0;
1.0 1.0 1.0 1.0;
1.0 1.0 1.0 1.0]
tbl = @inferred prop(rand(5, 5, 5, 5), margins=(1, 2))
sumtbl = sum(tbl, dims=(3,4))
@test all(x -> x β 1.0, sumtbl)
@test_throws MethodError prop()
@test_throws MethodError prop(("a","b"))
@test_throws MethodError prop((1, 2))
@test_throws MethodError prop([1,2,3], "a")
@test_throws MethodError prop([1,2,3], 1, 2)
@test_throws ArgumentError prop([1,2,3], margins=2)
@test_throws ArgumentError prop([1,2,3], margins=0)
tab = @inferred freqtable(x, y,
subset=1:20,
weights=repeat([1, .5], outer=[10]))
@test tab == [2.0 3.0
1.0 1.5
3.0 2.0
1.5 1.0]
@test names(tab) == [["a", "b", "c", "d"], ["C", "D"]]
pt = @inferred prop(tab)
@test pt == [4 6; 2 3; 6 4; 3 2] / 30.0
pt = @inferred prop(tab, margins=2)
@test pt == [8 12; 4 6; 12 8; 6 4] / 30.0
pt = @inferred prop(tab, margins=1)
@test pt == [6 9; 6 9; 9 6; 9 6] / 15.0
pt = @inferred prop(tab, margins=(1, 2))
@test pt == [1.0 1.0; 1.0 1.0; 1.0 1.0; 1.0 1.0]
using CategoricalArrays
cx = CategoricalArray(x)
cy = CategoricalArray(y)
tab = @inferred freqtable(cx)
@test tab == [100, 100, 100, 100]
@test names(tab) == [["a", "b", "c", "d"]]
tab = @inferred freqtable(cy)
@test tab == [100, 100, 100, 100]
@test names(tab) == [["A", "B", "C", "D"]]
tab = @inferred freqtable(cx, cy)
@test tab == [30 20 20 30;
30 20 20 30;
20 30 30 20;
20 30 30 20]
@test names(tab) == [["a", "b", "c", "d"], ["A", "B", "C", "D"]]
tab = @inferred freqtable(cx, cy,
subset=1:20,
weights=repeat([1, .5], outer=[10]))
@test tab == [0.0 0.0 2.0 3.0
0.0 0.0 1.0 1.5
0.0 0.0 3.0 2.0
0.0 0.0 1.5 1.0]
@test names(tab) == [["a", "b", "c", "d"], ["A", "B", "C", "D"]]
const β
= isequal
mx = Array{Union{String, Missing}}(x)
my = Array{Union{String, Missing}}(y)
mx[1] = missing
my[[1, 10, 20, 400]] .= missing
mcx = categorical(mx)
mcy = categorical(my)
tab = @inferred freqtable(mx)
tabc = @inferred freqtable(mcx)
@test tab == tabc == [99, 100, 100, 100, 1]
@test names(tab) β
names(tabc) β
[["a", "b", "c", "d", missing]]
tab = @inferred freqtable(my)
tabc = @inferred freqtable(mcy)
@test tab == tabc == [100, 99, 99, 98, 4]
@test names(tab) β
names(tabc) β
[["A", "B", "C", "D", missing]]
tab = @inferred freqtable(mx, my)
tabc = @inferred freqtable(mcx, mcy)
@test tab == tabc == [30 20 20 29 0;
30 20 20 29 1;
20 30 30 20 0;
20 29 29 20 2;
0 0 0 0 1]
@test names(tab) β
names(tabc) β
[["a", "b", "c", "d", missing],
["A", "B", "C", "D", missing]]
tab = @inferred freqtable(mx, skipmissing=true)
tabc = @inferred freqtable(mcx, skipmissing=true)
@test tab == tabc == [99, 100, 100, 100]
@test names(tab) β
names(tabc) β
[["a", "b", "c", "d"]]
tab = @inferred freqtable(my, skipmissing=true)
tabc = @inferred freqtable(mcy, skipmissing=true)
@test names(tab) β
names(tabc) β
[["A", "B", "C", "D"]]
@test tab == tabc == [100, 99, 99, 98]
tab = @inferred freqtable(mx, my, skipmissing=true)
tabc = @inferred freqtable(mcx, mcy, skipmissing=true)
@test tab == tabc == [30 20 20 29;
30 20 20 29;
20 30 30 20;
20 29 29 20]
using DataFrames
for docat in [false, true]
iris = DataFrame(SepalLength=[4.8, 4.3, 5.8, 5.7, 5.4, 5.7, 5.7, 6.2,
5.1, 5.7, 6.3, 5.8, 7.1, 6.3, 6.5, 7.6, 4.9],
SepalWidth=[3, 3, 4, 4.4, 3.9, 3, 2.9, 2.9, 2.5, 2.8,
3.3, 2.7, 3, 2.9, 3, 3, 2.5],
Species=["Iris-setosa", "Iris-setosa", "Iris-setosa",
"Iris-setosa", "Iris-setosa", "Iris-versicolor",
"Iris-versicolor", "Iris-versicolor", "Iris-versicolor",
"Iris-versicolor", "Iris-virginica", "Iris-virginica",
"Iris-virginica", "Iris-virginica", "Iris-virginica",
"Iris-virginica", "Iris-virginica"])
if docat
iris.LongSepal = categorical(iris.SepalLength .> 5.0)
else
iris.LongSepal = iris.SepalLength .> 5.0
end
for cols in ((:Species, :LongSepal), ("Species", "LongSepal"),
("Species", :LongSepal), (:Species, "LongSepal"))
tab = freqtable(iris, cols...)
@test tab == [2 3
0 5
1 6]
if all(x -> x isa AbstractString, cols)
@test dimnames(tab) == ["Species", "LongSepal"]
else
@test dimnames(tab) == [:Species, :LongSepal]
end
@test names(tab) == [["Iris-setosa", "Iris-versicolor", "Iris-virginica"], [false, true]]
@test (names(tab, 2) isa CategoricalArray) == docat
end
tab = freqtable(iris, :Species, :LongSepal, subset=iris.SepalWidth .< 3.8)
@test tab == [2 0
0 5
1 6]
@test names(tab[1:2, :]) == [["Iris-setosa", "Iris-versicolor"], [false, true]]
@test (names(tab, 2) isa CategoricalArray) == docat
iris_nt = (Species = iris.Species, LongSepal = iris.LongSepal)
@test freqtable(iris, :Species, :LongSepal) == freqtable(iris_nt, :Species, :LongSepal)
@test_throws ArgumentError freqtable(iris)
@test_throws ArgumentError freqtable(nothing, :Species, :LongSepal)
end
# Issue #5
@test @inferred freqtable([Set(1), Set(2)]) == [1, 1]
@test @inferred freqtable([Set(1), Set(2)], [Set(1), Set(2)]) == [1 0; 0 1]
@test_throws ArgumentError freqtable()
@test_throws ArgumentError freqtable(DataFrame())
# Integer dimension
using NamedArrays
df = DataFrame(A = 101:103, B = ["x","y","y"]);
intft = freqtable(df, :A, :B)
@test names(intft) == [[101,102,103],["x","y"]]
@test intft == [1 0;
0 1;
0 1]
@test_throws BoundsError intft[101,"x"]
@test intft[Name(101),"x"] == 1
# proptable
df = DataFrame(x = [1, 2, 1, 2], y = [1, 1, 2, 2], z = ["a", "a", "c", "d"])
for cols in ((:x, :z), ("x", "z"), ("x", :z), (:x, "z"))
tab = proptable(df, cols...)
if all(x -> x isa AbstractString, cols)
@test dimnames(tab) == ["x", "z"]
else
@test dimnames(tab) == [:x, :z]
end
@test tab == [0.25 0.25 0.0
0.25 0.0 0.25]
@test names(tab) == [[1, 2], ["a", "c", "d"]]
end
tab = proptable(df, :x, :z, margins=1)
@test tab == [0.5 0.5 0.0
0.5 0.0 0.5]
tab = proptable(df, :x, :y, margins=(1,2))
@test tab == [1.0 1.0
1.0 1.0]
@test names(tab) == [[1, 2], [1, 2]]
@test_throws ArgumentError proptable(df)
@test_throws ArgumentError proptable(nothing, :x, :y)
@test_throws MethodError proptable(df, :x, :y, 1, 2)
| FreqTables | https://github.com/nalimilan/FreqTables.jl.git |
|
[
"MIT"
] | 0.4.6 | 4693424929b4ec7ad703d68912a6ad6eff103cfe | docs | 3380 | # FreqTables
[](https://github.com/nalimilan/FreqTables.jl/actions?query=workflow%3ACI+branch%3Amaster)
[](https://coveralls.io/github/nalimilan/FreqTables.jl?branch=master)
This package allows computing one- or multi-way frequency tables (a.k.a. contingency or pivot tables) from
any type of vector or array. It includes support for [`CategoricalArray`](https://github.com/JuliaData/CategoricalArrays.jl)
and [`Tables.jl`](https://github.com/JuliaData/Tables.jl) compliant objects, as well as for weighted counts.
Tables are represented as [`NamedArray`](https://github.com/davidavdav/NamedArrays.jl/) objects.
```julia
julia> using FreqTables
julia> x = repeat(["a", "b", "c", "d"], outer=[100]);
julia> y = repeat(["A", "B", "C", "D"], inner=[10], outer=[10]);
julia> tbl = freqtable(x)
4-element Named Array{Int64,1}
Dim1 β
βββββββΌββββ
a β 100
b β 100
c β 100
d β 100
julia> prop(tbl)
4-element Named Array{Float64,1}
Dim1 β
βββββββΌβββββ
a β 0.25
b β 0.25
c β 0.25
d β 0.25
julia> freqtable(x, y)
4Γ4 Named Array{Int64,2}
Dim1 β² Dim2 β A B C D
βββββββββββββΌβββββββββββββββ
a β 30 20 30 20
b β 30 20 30 20
c β 20 30 20 30
d β 20 30 20 30
julia> tbl2 = freqtable(x, y, subset=1:20)
4Γ2 Named Array{Int64,2}
Dim1 β² Dim2 β A B
βββββββββββββΌβββββ
a β 3 2
b β 3 2
c β 2 3
d β 2 3
julia> prop(tbl2, margins=2)
4Γ2 Named Array{Float64,2}
Dim1 β² Dim2 β A B
βββββββββββββΌβββββββββ
a β 0.3 0.2
b β 0.3 0.2
c β 0.2 0.3
d β 0.2 0.3
julia> freqtable(x, y, subset=1:20, weights=repeat([1, .5], outer=[10]))
4Γ2 Named Array{Float64,2}
Dim1 β² Dim2 β A B
βββββββββββββΌβββββββββ
a β 3.0 2.0
b β 1.5 1.0
c β 2.0 3.0
d β 1.0 1.5
```
For convenience, when working with tables (like e.g. a `DataFrame`) one can pass a table object and columns as symbols:
```julia
julia> using DataFrames, CSV
julia> iris = DataFrame(CSV.File(joinpath(dirname(pathof(DataFrames)), "../docs/src/assets/iris.csv")));
julia> iris.LongSepal = iris.SepalLength .> 5.0;
julia> freqtable(iris, :Species, :LongSepal)
3Γ2 Named Array{Int64,2}
Species β² LongSepal β false true
βββββββββββββββββββββΌβββββββββββββ
setosa β 28 22
versicolor β 3 47
virginica β 1 49
julia> freqtable(iris, :Species, :LongSepal, subset=iris.PetalLength .< 4.0)
2Γ2 Named Array{Int64,2}
Species β² LongSepal β false true
βββββββββββββββββββββΌβββββββββββββ
setosa β 28 22
versicolor β 3 8
```
Note that when one of the input variables contains integers, `Name(i)` has to be used
when indexing into the table to prevent `i` to be interpreted as a numeric index:
```julia
julia> df = DataFrame(A = 101:103, B = ["x","y","y"]);
julia> ft = freqtable(df, :A, :B)
3Γ2 Named Array{Int64,2}
Dim1 β² Dim2 β x y
βββββββββββββΌβββββ
101 β 1 0
102 β 0 1
103 β 0 1
julia> ft[Name(101), "x"]
1
julia> ft[101,"x"]
ERROR: BoundsError: attempt to access 10Γ2 Array{Int64,2} at index [101, 1]
```
| FreqTables | https://github.com/nalimilan/FreqTables.jl.git |
|
[
"MIT"
] | 0.3.0 | e7f8a3e4bafabc4154558c1f3cd6f3e5915a534f | code | 404 | using Documenter, ImageGather, DocumenterCitations
bib = CitationBibliography(joinpath(@__DIR__, "cig-refs.bib"); style = :authoryear)
makedocs(;sitename="Image gather tools",
doctest=false, clean=true,
authors="Mathias Louboutin",
pages = Any["Home" => "index.md"],
plugins=[bib])
deploydocs(repo="github.com/slimgroup/ImageGather.jl",
devbranch="main") | ImageGather | https://github.com/slimgroup/ImageGather.jl.git |
|
[
"MIT"
] | 0.3.0 | e7f8a3e4bafabc4154558c1f3cd6f3e5915a534f | code | 3531 | # Author: Mathias Louboutin
# Date: June 2021
#
using JUDI, LinearAlgebra, Images, PyPlot, DSP, ImageGather, SlimPlotting
# Set up model structure
n = (601, 333) # (x,y,z) or (x,z)
d = (15., 15.)
o = (0., 0.)
# Velocity [km/s]
v = ones(Float32,n) .+ 0.5f0
for i=1:12
v[:,25*i+1:end] .= 1.5f0 + i*.25f0
end
v0 = imfilter(v, Kernel.gaussian(5))
v0_low = .95f0 .* imfilter(v, Kernel.gaussian(5))
v0_high = 1.05f0 .* imfilter(v, Kernel.gaussian(5))
# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
m0 = (1f0 ./ v0).^2
m0_low = (1f0 ./ v0_low).^2
m0_high = (1f0 ./ v0_high).^2
dm = vec(m - m0)
# Setup info and model structure
nsrc = 51 # number of sources
model = Model(n, d, o, m; nb=40)
model0 = Model(n, d, o, m0; nb=40)
model0_low = Model(n, d, o, m0_low; nb=40)
model0_high = Model(n, d, o, m0_high; nb=40)
# Set up receiver geometry
nxrec = 401
xrec = range(0f0, stop=(n[1] -1)*d[1], length=nxrec)
yrec = 0f0
zrec = range(20f0, stop=20f0, length=nxrec)
# receiver sampling and recording time
timeR = 4000f0 # receiver recording time [ms]
dtR = 4f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dtR, t=timeR, nsrc=nsrc)
# Set up source geometry (cell array with source locations for each shot)
xsrc = convertToCell(range(0f0, stop=(n[1] -1)*d[1], length=nsrc))
ysrc = convertToCell(range(0f0, stop=0f0, length=nsrc))
zsrc = convertToCell(range(20f0, stop=20f0, length=nsrc))
# source sampling and number of time steps
timeS = 4000f0 # ms
dtS = 4f0 # ms
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtS, t=timeS)
# setup wavelet
f0 = 0.015f0 # kHz
wavelet = ricker_wavelet(timeS, dtS, f0)
q = judiVector(srcGeometry, wavelet)
###################################################################################################
opt = Options(space_order=16)
# Setup operators
F = judiModeling(model, srcGeometry, recGeometry; options=opt)
# Nonlinear modeling
dD = F*q
# Common surface offset image gather
offsets = 0f0:150f0:8000f0
CIG = surface_gather(model0, q, dD; offsets=offsets, options=opt)
CIG_low = surface_gather(model0_low, q, dD; offsets=offsets, options=opt);
CIG_high = surface_gather(model0_high, q, dD; offsets=offsets, options=opt);
cc = 1e-1
figure(figsize=(20, 10))
subplot(231)
plot_simage(CIG[301, :, :], d; cmap="Greys", new_fig=false)
title("Good velocity (CDP=4.5km)")
subplot(232)
plot_simage(CIG_low[301, :, :], d; cmap="Greys", new_fig=false)
title("Low velocity (CDP=4.5km)")
subplot(233)
plot_simage(CIG_high[301, :, :], d; cmap="Greys", new_fig=false)
title("High velocity (CDP=4.5km)")
subplot(234)
plot_simage(CIG[101, :, :], d; cmap="Greys", new_fig=false)
subplot(235)
plot_simage(CIG_low[101, :, :], d; cmap="Greys", new_fig=false)
subplot(236)
plot_simage(CIG_high[101, :, :], d; cmap="Greys", new_fig=false)
savefig("./docs/img/cig_cdp.png", bbox_inches="tight")
# Plot gathers as a pseudo rtm image
cig_rtm_good = hcat([CIG[i, :, 1:25] for i=1:20:n[1]]...)
cig_rtm_low = hcat([CIG_low[i, :, 1:25] for i=1:20:n[1]]...)
cig_rtm_high = hcat([CIG_high[i, :, 1:25] for i=1:20:n[1]]...)
figure(figsize=(20, 10))
subplot(131)
plot_simage(cig_rtm_good, d; cmap="Greys", new_fig=false)
xticks([])
title("Good velocity")
subplot(132)
plot_simage(cig_rtm_low, d; cmap="Greys", new_fig=false)
xticks([])
title("Low velocity")
subplot(133)
plot_simage(cig_rtm_high, d; cmap="Greys", new_fig=false)
xticks([])
title("High velocity")
savefig("./docs/img/cig_line.png", bbox_inches="tight")
| ImageGather | https://github.com/slimgroup/ImageGather.jl.git |
|
[
"MIT"
] | 0.3.0 | e7f8a3e4bafabc4154558c1f3cd6f3e5915a534f | code | 2267 | # Author: Mathias Louboutin
# Date: June 2021
#
using JUDI, LinearAlgebra, Images, PyPlot, DSP, ImageGather, Printf
# Set up model structure
n = (301, 151) # (x,y,z) or (x,z)
d = (10., 10.)
o = (0., 0.)
# Velocity [km/s]
v = 1.5f0 .* ones(Float32,n)
v[:, 76:end] .= 2.5f0
v0 = imfilter(v, Kernel.gaussian(5))
# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
m0 = (1f0 ./ v0).^2
# Setup info and model structure
nsrc = 1 # number of sources
model = Model(n, d, o, m; nb=40)
model0 = Model(n, d, o, m0; nb=40)
dm = model.m - model0.m
# Set up receiver geometry
nxrec = 151
xrec = range(0f0, stop=(n[1] -1)*d[1], length=nxrec)
yrec = 0f0
zrec = range(20f0, stop=20f0, length=nxrec)
# receiver sampling and recording time
timeD = 2000f0 # receiver recording time [ms]
dtD = 4f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dtD, t=timeD, nsrc=nsrc)
# Set up source geometry (cell array with source locations for each shot)
xsrc = 1500f0
ysrc = 0f0
zsrc = 20f0
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtD, t=timeD)
# setup wavelet
f0 = 0.015f0 # kHz
wavelet = ricker_wavelet(timeD, dtD, f0)
q = diff(judiVector(srcGeometry, wavelet))
###################################################################################################
opt = Options(space_order=4, isic=false, sum_padding=true)
# Setup operators
F = judiModeling(model, srcGeometry, recGeometry; options=opt)
J0 = judiJacobian(F(model0), q)
# Nonlinear modeling
dD = J0*dm
rtm = J0'*dD
# Common surface offset image gather
offsets = -40f0:model.d[1]:40f0
# offsets = [0f0]
J = judiExtendedJacobian(F(model0), q, offsets)
Jz = judiExtendedJacobian(F(model0), q, offsets, dims=:z)
ssodm = J'*dD
ssodmz = Jz'*dD
ssor = zeros(Float32, size(ssodm)...)
for h=1:size(ssor, 1)
ssor[h, :, :] .= dm.data
end
dDe = J*ssor
dDez= Jz*ssor
# @show norm(dDe - dD), norm(ssor[:] - dm[:])
a, b = dot(dD, dDe), dot(ssodm[:], ssor[:])
@printf(" <F x, y> : %2.5e, <x, F' y> : %2.5e, rel-error : %2.5e, ratio : %2.5e \n", a, b, (a - b)/(a + b), a/b)
a, b = dot(dD, dDez), dot(ssodmz[:], ssor[:])
@printf(" <F x, y> : %2.5e, <x, F' y> : %2.5e, rel-error : %2.5e, ratio : %2.5e \n", a, b, (a - b)/(a + b), a/b)
| ImageGather | https://github.com/slimgroup/ImageGather.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.